Programs & Examples On #Wsh

For questions relating to Windows Script Host (WSH), a language-independent scripting host for the Windows operating system. It allows scripts to be run from both the graphical Windows desktop (via WScript.exe) and the command prompt (via CScript.exe).

"rm -rf" equivalent for Windows?

You can install GnuWin32 and use *nix commands natively on windows. I install this before I install anything else on a minty fresh copy of windows. :)

how can I check if a file exists?

Start with this:

Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(path)) Then
   msg = path & " exists."
Else
   msg = path & " doesn't exist."
End If

Taken from the documentation.

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

Run it under a different user name, using "runas" or by scheduling it under a different user in Windows Scheduled Tasks.

VBScript: Using WScript.Shell to Execute a Command Line Program That Accesses Active Directory

Taking Shiraz's idea and running with it...

In your application, are you explicitly defining a domain User Account and Password to access AD?

When you are executing the application explicitly it may be inherently using your credentials (your currently logged in domain account) to interrogate AD. However, when calling the application from the script, I'm not sure if the application is in the System context.

A VBScript example would be as follows:

  Dim objConnection As ADODB.Connection
    Set objConnection = CreateObject("ADODB.Connection")
    objConnection.Provider = "ADsDSOObject"
    objConnection.Properties("User ID") = "MyDomain\MyAccount"
    objConnection.Properties("Password") = "MyPassword"
    objConnection.Open "Active Directory Provider"

If this works, of course it would be best practice to create and use a service account specifically for this task, and to deny interactive login to that account.

Can I pass an argument to a VBScript (vbs file launched with cscript)?

Inside of VBS you can access parameters with

Wscript.Arguments(0)
Wscript.Arguments(1)

and so on. The number of parameter:

Wscript.Arguments.Count

C# Threading - How to start and stop a thread

Thread th = new Thread(function1);
th.Start();
th.Abort();

void function1(){
//code here
}

A column-vector y was passed when a 1d array was expected

use below code:

model = forest.fit(train_fold, train_y.ravel())

if you are still getting slap by error as identical as below ?

Unknown label type: %r" % y

use this code:

y = train_y.ravel()
train_y = np.array(y).astype(int)
model = forest.fit(train_fold, train_y)

How to create an empty file with Ansible?

Building on the accepted answer, if you want the file to be checked for permissions on every run, and these changed accordingly if the file exists, or just create the file if it doesn't exist, you can use the following:

- stat: path=/etc/nologin
  register: p

- name: create fake 'nologin' shell
  file: path=/etc/nologin 
        owner=root
        group=sys
        mode=0555
        state={{ "file" if  p.stat.exists else "touch"}}

Failed linking file resources

Sometimes it happen what you copy paste code from another project fro example you copy

<android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="256dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@android:color/white"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:itemTextColor="@color/colorDrawerItems"
        app:menu="@menu/activity_main_drawer" />

Unfortunately Android studio not always show dependency error, but what happen is that class NavigationView is missing because implementation 'com.android.support:design not added to the project

How to determine an interface{} value's "real" type?

Your example does work. Here's a simplified version.

package main

import "fmt"

func weird(i int) interface{} {
    if i < 0 {
        return "negative"
    }
    return i
}

func main() {
    var i = 42
    if w, ok := weird(7).(int); ok {
        i += w
    }
    if w, ok := weird(-100).(int); ok {
        i += w
    }
    fmt.Println("i =", i)
}

Output:
i = 49

It uses Type assertions.

How to create a thread?

Update The currently suggested way to start a Task is simply using Task.Run()

Task.Run(() => foo());

Note that this method is described as the best way to start a task see here

Previous answer

I like the Task Factory from System.Threading.Tasks. You can do something like this:

Task.Factory.StartNew(() => 
{
    // Whatever code you want in your thread
});

Note that the task factory gives you additional convenience options like ContinueWith:

Task.Factory.StartNew(() => {}).ContinueWith((result) => 
{
    // Whatever code should be executed after the newly started thread.
});

Also note that a task is a slightly different concept than threads. They nicely fit with the async/await keywords, see here.

console.log(result) returns [object Object]. How do I get result.name?

Try adding JSON.stringify(result) to convert the JS Object into a JSON string.

From your code I can see you are logging the result in error which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).

Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.

How to convert InputStream to FileInputStream

You need something like:

    URL resource = this.getClass().getResource("/path/to/resource.res");
    File is = null;
    try {
        is = new File(resource.toURI());
    } catch (URISyntaxException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        FileInputStream input = new FileInputStream(is);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

But it will work only within your IDE, not in runnable JAR. I had same problem explained here.

Permission denied (publickey,keyboard-interactive)

You need to change the sshd_config file in the remote server (probably in /etc/ssh/sshd_config).

Change

PasswordAuthentication no

to

PasswordAuthentication yes

And then restart the sshd daemon.

Loop over html table and get checked checkboxes (JQuery)

use .filter(':has(:checkbox:checked)' ie:

$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
 $('#out').append(this.id);
});

How should I store GUID in MySQL tables?

I would store it as a char(36).

Is there an opposite of include? for Ruby Arrays?

Here you go:

unless @players.include?(p.name)
  ...
end

You might have a look at the Ruby Style Guide for more info on similar techniques.

How do you split and unsplit a window/view in Eclipse IDE?

This is possible with the menu items Window>Editor>Toggle Split Editor.

Current shortcut for splitting is:

Azerty keyboard:

  • Ctrl + _ for split horizontally, and
  • Ctrl + { for split vertically.

Qwerty US keyboard:

  • Ctrl + Shift + - (accessing _) for split horizontally, and
  • Ctrl + Shift + [ (accessing {) for split vertically.

MacOS - Qwerty US keyboard:

  • + Shift + - (accessing _) for split horizontally, and
  • + Shift + [ (accessing {) for split vertically.

On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:

  • Alt + ASCII code + Ctrl then release Alt

Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.

Example of vertical split:

https://bugs.eclipse.org/bugs/attachment.cgi?id=238285

PS:

  • The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
  • The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
  • The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.

No newline after div?

Quoting Mr Initial Man from here:

Instead of this:

<div id="Top" class="info"></div><a href="#" class="a_info"></a>

Use this:

<span id="Top" class="info"></span><a href="#" class="a_info"></a>

Also, you could use this:

<div id="Top" class="info"><a href="#" class="a_info"></a></div>

And gostbustaz:

If you absoultely must use a <div>, you can set

div {
    display: inline;
}

in your stylesheet.

Of course, that essentially makes the <div> a <span>.

What are the best PHP input sanitizing functions?

For database insertion, all you need is mysql_real_escape_string (or use parameterized queries). You generally don't want to alter data before saving it, which is what would happen if you used htmlentities. That would lead to a garbled mess later on when you ran it through htmlentities again to display it somewhere on a webpage.

Use htmlentities when you are displaying the data on a webpage somewhere.

Somewhat related, if you are sending submitted data somewhere in an email, like with a contact form for instance, be sure to strip newlines from any data that will be used in the header (like the From: name and email address, subect, etc)

$input = preg_replace('/\s+/', ' ', $input);

If you don't do this it's just a matter of time before the spam bots find your form and abuse it, I've learned the hard way.

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

How to use the "required" attribute with a "radio" input field

TL;DR: Set the required attribute for at least one input of the radio group.


Setting required for all inputs is more clear, but not necessary (unless dynamically generating radio-buttons).

To group radio buttons they must all have the same name value. This allows only one to be selected at a time and applies required to the whole group.

_x000D_
_x000D_
<form>_x000D_
  Select Gender:<br>_x000D_
_x000D_
  <label>_x000D_
    <input type="radio" name="gender" value="male" required>_x000D_
    Male_x000D_
  </label><br>_x000D_
_x000D_
  <label>_x000D_
    <input type="radio" name="gender" value="female">_x000D_
    Female_x000D_
  </label><br>_x000D_
_x000D_
  <label>_x000D_
    <input type="radio" name="gender" value="other">_x000D_
    Other_x000D_
  </label><br>_x000D_
_x000D_
  <input type="submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Also take note of:

To avoid confusion as to whether a radio button group is required or not, authors are encouraged to specify the attribute on all the radio buttons in a group. Indeed, in general, authors are encouraged to avoid having radio button groups that do not have any initially checked controls in the first place, as this is a state that the user cannot return to, and is therefore generally considered a poor user interface.

Source

How to get all possible combinations of a list’s elements?

I agree with Dan H that Ben indeed asked for all combinations. itertools.combinations() does not give all combinations.

Another issue is, if the input iterable is big, it is perhaps better to return a generator instead of everything in a list:

iterable = range(10)
for s in xrange(len(iterable)+1):
  for comb in itertools.combinations(iterable, s):
    yield comb

Postgresql SELECT if string contains

SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' LIKE '%' || "tag_name" || '%';

tag_name should be in quotation otherwise it will give error as tag_name doest not exist

Unit testing private methods in C#

You can use PrivateObject Class

Class target = new Class();
PrivateObject obj = new PrivateObject(target);
var retVal = obj.Invoke("PrivateMethod");
Assert.AreEqual(expectedVal, retVal);

Note: PrivateObject and PrivateType are not available for projects targeting netcoreapp2.0 - GitHub Issue 366

Only read selected columns

Say the data are in file data.txt, you can use the colClasses argument of read.table() to skip columns. Here the data in the first 7 columns are "integer" and we set the remaining 6 columns to "NULL" indicating they should be skipped

> read.table("data.txt", colClasses = c(rep("integer", 7), rep("NULL", 6)), 
+            header = TRUE)
  Year Jan Feb Mar Apr May Jun
1 2009 -41 -27 -25 -31 -31 -39
2 2010 -41 -27 -25 -31 -31 -39
3 2011 -21 -27  -2  -6 -10 -32

Change "integer" to one of the accepted types as detailed in ?read.table depending on the real type of data.

data.txt looks like this:

$ cat data.txt 
"Year" "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
2009 -41 -27 -25 -31 -31 -39 -25 -15 -30 -27 -21 -25
2010 -41 -27 -25 -31 -31 -39 -25 -15 -30 -27 -21 -25
2011 -21 -27 -2 -6 -10 -32 -13 -12 -27 -30 -38 -29

and was created by using

write.table(dat, file = "data.txt", row.names = FALSE)

where dat is

dat <- structure(list(Year = 2009:2011, Jan = c(-41L, -41L, -21L), Feb = c(-27L, 
-27L, -27L), Mar = c(-25L, -25L, -2L), Apr = c(-31L, -31L, -6L
), May = c(-31L, -31L, -10L), Jun = c(-39L, -39L, -32L), Jul = c(-25L, 
-25L, -13L), Aug = c(-15L, -15L, -12L), Sep = c(-30L, -30L, -27L
), Oct = c(-27L, -27L, -30L), Nov = c(-21L, -21L, -38L), Dec = c(-25L, 
-25L, -29L)), .Names = c("Year", "Jan", "Feb", "Mar", "Apr", 
"May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), class = "data.frame",
row.names = c(NA, -3L))

If the number of columns is not known beforehand, the utility function count.fields will read through the file and count the number of fields in each line.

## returns a vector equal to the number of lines in the file
count.fields("data.txt", sep = "\t")
## returns the maximum to set colClasses
max(count.fields("data.txt", sep = "\t"))

How to center Font Awesome icons horizontally?

Add your own flavour of the font awesome style

[class^="icon-"], [class*=" icon-"] {
    display: inline-block;
    width: 100%;
}

which along with your

td i {
    text-align:center;
}

should center just the icons.

For div to extend full height

Did you remember setting the height of the html and body tags in your CSS? This is generally how I've gotten DIVs to extend to full height:


<html>
  <head>
    <style type="text/css">

      html,body { height: 100%; margin: 0px; padding: 0px; }
      #full { background: #0f0; height: 100% }

    </style>
  </head>
  <body>
    <div id="full">
    </div>
  </body>
</html>



Difference between VARCHAR2(10 CHAR) and NVARCHAR2(10)

I don't think answer from Vincent Malgrat is correct. When NVARCHAR2 was introduced long time ago nobody was even talking about Unicode.

Initially Oracle provided VARCHAR2 and NVARCHAR2 to support localization. Common data (include PL/SQL) was hold in VARCHAR2, most likely US7ASCII these days. Then you could apply NLS_NCHAR_CHARACTERSET individually (e.g. WE8ISO8859P1) for each of your customer in any country without touching the common part of your application.

Nowadays character set AL32UTF8 is the default which fully supports Unicode. In my opinion today there is no reason anymore to use NLS_NCHAR_CHARACTERSET, i.e. NVARCHAR2, NCHAR2, NCLOB. Note, there are more and more Oracle native functions which do not support NVARCHAR2, so you should really avoid it. Maybe the only reason is when you have to support mainly Asian characters where AL16UTF16 consumes less storage compared to AL32UTF8.

How do I parse command line arguments in Java?

I've used JOpt and found it quite handy: http://jopt-simple.sourceforge.net/

The front page also provides a list of about 8 alternative libraries, check them out and pick the one that most suits your needs.

How can I check if a value is of type Integer?

if (x % 1 == 0)
    // x is an integer

Here x is a numeric primitive: short, int, long, float or double

Check for database connection, otherwise display message

very basic:

<?php 
$username = 'user';
$password = 'password';
$server = 'localhost'; 
// Opens a connection to a MySQL server
$connection = mysql_connect ($server, $username, $password) or die('try again in some minutes, please');
//if you want to suppress the error message, substitute the connection line for:
//$connection = @mysql_connect($server, $username, $password) or die('try again in some minutes, please');
?>

result:

Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'user'@'localhost' (using password: YES) in /home/user/public_html/zdel1.php on line 6 try again in some minutes, please

as per Wrikken's recommendation below, check out a complete error handler for more complex, efficient and elegant solutions: http://www.php.net/manual/en/function.set-error-handler.php

NSArray + remove item from array

NSMutableArray *arrayThatYouCanRemoveObjects = [NSMutableArray arrayWithArray:your_array];

[arrayThatYouCanRemoveObjects removeObjectAtIndex:your_object_index];

[your_array release];

 your_array = [[NSArray arrayWithArray: arrayThatYouCanRemoveObjects] retain];

that's about it

if you dont own your_array(i.e it's autoreleased) remove the release & retain messages

Delete all local git branches

If you work with NodeJS, I wrote this command:

npx git-clear-branch

The command clears all of your local branch except master and current branch.

Doctrine - How to print out the real sql, not just the prepared statement?

To print out an SQL query in Doctrine, use:

$query->getResult()->getSql();

How do I convert this list of dictionaries to a csv file?

In python 3 things are a little different, but way simpler and less error prone. It's a good idea to tell the CSV your file should be opened with utf8 encoding, as it makes that data more portable to others (assuming you aren't using a more restrictive encoding, like latin1)

import csv
toCSV = [{'name':'bob','age':25,'weight':200},
         {'name':'jim','age':31,'weight':180}]
with open('people.csv', 'w', encoding='utf8', newline='') as output_file:
    fc = csv.DictWriter(output_file, 
                        fieldnames=toCSV[0].keys(),

                       )
    fc.writeheader()
    fc.writerows(toCSV)
  • Note that csv in python 3 needs the newline='' parameter, otherwise you get blank lines in your CSV when opening in excel/opencalc.

Alternatively: I prefer use to the csv handler in the pandas module. I find it is more tolerant of encoding issues, and pandas will automatically convert string numbers in CSVs into the correct type (int,float,etc) when loading the file.

import pandas
dataframe = pandas.read_csv(filepath)
list_of_dictionaries = dataframe.to_dict('records')
dataframe.to_csv(filepath)

Note:

  • pandas will take care of opening the file for you if you give it a path, and will default to utf8 in python3, and figure out headers too.
  • a dataframe is not the same structure as what CSV gives you, so you add one line upon loading to get the same thing: dataframe.to_dict('records')
  • pandas also makes it much easier to control the order of columns in your csv file. By default, they're alphabetical, but you can specify the column order. With vanilla csv module, you need to feed it an OrderedDict or they'll appear in a random order (if working in python < 3.5). See: Preserving column order in Python Pandas DataFrame for more.

Using variable in SQL LIKE statement

I had also problem using local variables in LIKE.
Important is to know: how long is variable.
Below, ORDER_NO is 50 characters long, so You can not use: LIKE @ORDER_NO, because in the end will be spaces.
You need to trim right side of the variable first.
Like this:

DECLARE @ORDER_NO char(50)
SELECT @ORDER_NO = 'OR/201910/0012%'

SELECT * FROM orders WHERE ord_no LIKE RTRIM(@ORDER_NO)

Error related to only_full_group_by when executing a query in MySql

Addition of lines (mention below) in file : /etc/mysql/my.cnf

[mysqld]
sql_mode = STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

Work fine for me. Server version: 5.7.18-0ubuntu0.16.04.1 - (Ubuntu)

Check if certain value is contained in a dataframe column in pandas

You can simply use this:

'07311954' in df.date.values which returns True or False


Here is the further explanation:

In pandas, using in check directly with DataFrame and Series (e.g. val in df or val in series ) will check whether the val is contained in the Index.

BUT you can still use in check for their values too (instead of Index)! Just using val in df.col_name.values or val in series.values. In this way, you are actually checking the val with a Numpy array.

And .isin(vals) is the other way around, it checks whether the DataFrame/Series values are in the vals. Here vals must be set or list-like. So this is not the natural way to go for the question.

How to vertically align an image inside a div

Solution using a table and table cells

Sometimes it should be solved by displaying as table/table-cell. For example, a fast title screen. It is a recommended way by W3 also. I recommend you check this link called Centering a block or image from W3C.org.

The tips used here are:

  • Absolute positioning container displayed as table
  • Vertical aligned to center content displayed as table-cell

_x000D_
_x000D_
.container {_x000D_
    position: absolute;_x000D_
    display: table;_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
}_x000D_
.content {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="content">_x000D_
    <h1 style="text-align:center">Peace in the world</h1>_x000D_
 </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Personally I actually disagree about use helpers for this purpose.

Remove all child elements of a DOM node in JavaScript

element.textContent = '';

It's like innerText, except standard. It's a bit slower than removeChild(), but it's easier to use and won't make much of a performance difference if you don't have too much stuff to delete.

Initialize/reset struct to zero/null

I believe you can just assign the empty set ({}) to your variable.

struct x instance;

for(i = 0; i < n; i++) {
    instance = {};
    /* Do Calculations */
}

How to Lazy Load div background images

I know it's not related to the image load but here what I did in one of the job interview test.

HTML

<div id="news-feed">Scroll to see News (Newest First)</div>

CSS

article {
   margin-top: 500px;
   opacity: 0;
   border: 2px solid #864488;
   padding: 5px 10px 10px 5px;
   background-image: -webkit-gradient(
   linear,
   left top,
   left bottom,
   color-stop(0, #DCD3E8),
   color-stop(1, #BCA3CC)
   );
   background-image: -o-linear-gradient(bottom, #DCD3E8 0%, #BCA3CC 100%);
   background-image: -moz-linear-gradient(bottom, #DCD3E8 0%, #BCA3CC 100%);
   background-image: -webkit-linear-gradient(bottom, #DCD3E8 0%, #BCA3CC 100%);
   background-image: -ms-linear-gradient(bottom, #DCD3E8 0%, #BCA3CC 100%);
   background-image: linear-gradient(to bottom, #DCD3E8 0%, #BCA3CC 100%);
   color: gray;
   font-family: arial;    
}

article h4 {
   font-family: "Times New Roman";
   margin: 5px 1px;
}

.main-news {
   border: 5px double gray;
   padding: 15px;
}

JavaScript

var newsData,
    SortData = '',
    i = 1;

$.getJSON("http://www.stellarbiotechnologies.com/media/press-releases/json", function(data) {

   newsData = data.news;

   function SortByDate(x,y) {
     return ((x.published == y.published) ? 0 : ((x.published < y.published) ? 1 : -1 ));
   }

   var sortedNewsData = newsData.sort(SortByDate);

   $.each( sortedNewsData, function( key, val ) {
     SortData += '<article id="article' + i + '"><h4>Published on: ' + val.published + '</h4><div  class="main-news">' + val.title + '</div></article>';
     i++;    
   });

   $('#news-feed').append(SortData);
});

$(window).scroll(function() {

   var $window = $(window),
       wH = $window.height(),
       wS = $window.scrollTop() + 1

   for (var j=0; j<$('article').length;j++) {
      var eT = $('#article' + j ).offset().top,
          eH = $('#article' + j ).outerHeight();

          if (wS > ((eT + eH) - (wH))) {
             $('#article' + j ).animate({'opacity': '1'}, 500);
          }
    }

});

I am sorting the data by Date and then doing lazy load on window scroll function.

I hope it helps :)

Demo

How can I make a .NET Windows Forms application that only runs in the System Tray?

Simply add

this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;

to your form object. You will see only an icon at system tray.

Maintaining href "open in new tab" with an onClick handler in React

The answer from @gunn is correct, target="_blank makes the link open in a new tab.

But this can be a security risk for you page; you can read about it here. There is a simple solution for that: adding rel="noopener noreferrer".

<a style={{display: "table-cell"}} href = "someLink" target = "_blank" 
rel = "noopener noreferrer">text</a>

align right in a table cell with CSS

Don't forget about CSS3's 'nth-child' selector. If you know the index of the column you wish to align text to the right on, you can just specify

table tr td:nth-child(2) {
    text-align: right;
}

In cases with large tables this can save you a lot of extra markup!

here's a fiddle for ya.... https://jsfiddle.net/w16c2nad/

How to pass 2D array (matrix) in a function in C?

I don't know what you mean by "data dont get lost". Here's how you pass a normal 2D array to a function:

void myfunc(int arr[M][N]) { // M is optional, but N is required
  ..
}

int main() {
  int somearr[M][N];
  ...
  myfunc(somearr);
  ...
}

How do I start/stop IIS Express Server?

Open Task Manager and Kill both of these processes. They will autostart back up. Then try debugging your project again.

enter image description here

Trying to get property of non-object MySQLi result

$sql = "SELECT * FROM table";
$result = $conn->query($sql);

if (!$result) {
    trigger_error('Invalid query: ' . $conn->error);
}

check the error with mysqli_error() function

probably your query has some faults.

When using a Settings.settings file in .NET, where is the config actually stored?

Assuming that you're talking about desktop and not web applications:

When you add settings to a project, VS creates a file named app.config in your project directory and stores the settings in that file. It also builds the Settings.cs file that provides the static accessors to the individual settings.

At compile time, VS will (by default; you can change this) copy the app.config to the build directory, changing its name to match the executable (e.g. if your executable is named foo.exe, the file will be named foo.exe.config), which is the name the .NET configuration manager looks for when it retrieves settings at runtime.

If you change a setting through the VS settings editor, it will update both app.config and Settings.cs. (If you look at the property accessors in the generated code in Settings.cs, you'll see that they're marked with an attribute containing the default value of the setting that's in your app.config file.) If you change a setting by editing the app.config file directly, Settings.cs won't be updated, but the new value will still be used by your program when you run it, because app.config gets copied to foo.exe.config at compile time. If you turn this off (by setting the file's properties), you can change a setting by directly editing the foo.exe.config file in the build directory.

Then there are user-scoped settings.

Application-scope settings are read-only. Your program can modify and save user-scope settings, thus allowing each user to have his/her own settings. These settings aren't stored in the foo.exe.config file (since under Vista, at least, programs can't write to any subdirectory of Program Files without elevation); they're stored in a configuration file in the user's application data directory.

The path to that file is %appdata%\%publisher_name%\%program_name%\%version%\user.config, e.g. C:\Users\My Name\AppData\Local\My_Company\My_Program.exe\1.0.0\user.config. Note that if you've given your program a strong name, the strong name will be appended to the program name in this path.

What characters are forbidden in Windows and Linux directory names?

For anyone looking for a regex:

const BLACKLIST = /[<>:"\/\\|?*]/g;

How to get featured image of a product in woocommerce

get_the_post_thumbnail function returns html not url of featured image. You should use get_post_thumbnail_id to get post id of featured image and then use wp_get_attachment_image_src to get url of featured image.

Try this:

<?php
$args = array( 'post_type' => 'product', 'posts_per_page' => 80, 'product_cat' => 'profiler', 'orderby' => 'rand' );

$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
    <div class="dvThumb col-xs-4 col-sm-3 col-md-3 profiler-select profiler<?php echo the_title(); ?>" data-profile="<?php echo $loop->post->ID; ?>">
        <?php $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($loop->post->ID)); ?>
        <?php if($featured_image) { ?>
        <img src="<?php $featured_image[0]; ?>" data-id="<?php echo $loop->post->ID; ?>">
        <?php } ?>
        <p><?php the_title(); ?></p>
        <span class="price"><?php echo $product->get_price_html(); ?></span>
    </div>
<?php endwhile; ?>

How should I escape strings in JSON?

StringEscapeUtils.escapeJavaScript / StringEscapeUtils.escapeEcmaScript should do the trick too.

Get the decimal part from a double

var result = number.ToString().Split(System.Globalization.NumberDecimalSeparator)[2]

Returns it as a string (but you can always cast that back to an int), and assumes the number does have a "." somewhere.

Spring Boot Program cannot find main class

I had similar kind of problem while I was adding spring security dependency to my project , then I deleted my target folder and used maven update again . It's worked for me.

Ternary operator in AngularJS templates

There it is : ternary operator got added to angular parser in 1.1.5! see the changelog

Here is a fiddle showing new ternary operator used in ng-class directive.

ng-class="boolForTernary ? 'blue' : 'red'"

Counting number of characters in a file through shell script

awk only

awk 'BEGIN{FS=""}{for(i=1;i<=NF;i++)c++}END{print "total chars:"c}' file

shell only

var=$(<file)
echo ${#var}

Ruby(1.9+)

ruby -0777 -ne 'print $_.size' file

How to execute 16-bit installer on 64-bit Win7?

I am mostly posting this in case someone comes along and is not aware that VB2005 and VB2008 have update utilities that convert older VB versions to it's format. Especially since no one bothered to point that fact out.

Points taken, but maintenance of this VB6 product is unavoidable. It would also be costly in man-hours to replace the Sheridan controls with native ones. Simply developing on a 32-bit machine would be a better alternative than doing that. I would like to install everything on Win7 64-bit ideally. – CJ7

Have you tried utilizing the code upgrade functionality of VB Express 2005+?

If not, 1. Make a copy of your code - folder and all. 2. Import the project into VB express 2005. This will activate the update wizard. 3. Debug and get the app running. 4. Create a new installer utilizing MS free tool. 5. You now have a 32 bit application with a 32 bit installer.

Until you do this, you will never know how difficult or hard it will be to update and modernize the program. It is quite possible that the wizard will update the Sheridan controls to the VB 2005 controls. Again, you will not know if it does and how well it does it until you try it.

Alternatively, stick with the 32 Bit versions of Windows 7 and 8. I have Windows 7 x64 and a program that will not run. However, the program will run in Windows 7 32 bit as well as Windows 8 RC 32 bit. Under Windows 8 RC 32, I was prompted to enable 16 bit emulation which I did and the program rand quite fine afterwords.

error::make_unique is not a member of ‘std’

This happens to me while working with XCode (I'm using the most current version of XCode in 2019...). I'm using, CMake for build integration. Using the following directive in CMakeLists.txt fixed it for me:

set(CMAKE_CXX_STANDARD 14).

Example:

cmake_minimum_required(VERSION 3.14.0)
set(CMAKE_CXX_STANDARD 14)

# Rest of your declarations...

rake assets:precompile RAILS_ENV=production not working as required

To explain the problem, your error is as follows:

LoadError: cannot load such file -- uglifier
      (in /home/cool_tech/cool_tech/app/assets/javascripts/application.js)

This means somewhere in application.js, your app is referencing uglifier (probably in the manifest area at the top of the file). To fix the issue, you either need to remove the reference to uglifier, or make sure the uglifier file is present in your app, hence the answers you've been provided


Fix

If you've had no luck with adding the gem to your GemFile, a quick fix would be to remove any reference to uglifier in your application.js manifest. This, of course, will be temporary, but will at least allow you to precompile your assets

How to determine CPU and memory consumption from inside a process?

On linux, you cannot/shouldnot get "Total Available Physical Memory" with SysInfo's freeram or by doing some arithmetic on totalram. The recommended way to do this is by reading proc/meminfo, quoting https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773:

Many load balancing and workload placing programs check /proc/meminfo to estimate how much free memory is available. They generally do this by adding up "free" and "cached", which was fine ten years ago, but is pretty much guaranteed to be wrong today.

It is more convenient to provide such an estimate in /proc/meminfo. If things change in the future, we only have to change it in one place.

One way to do it is as https://stackoverflow.com/a/350039/7984460 suggest: read the file, and use fscanf to grab the line (but instead of going for MemTotal, go for MemAvailable)

Likewise, if you want to get the total amounf of physical memory used, depending on what you mean by "use", you might not want to subtract freeram from totalram, but subtract memavailable from memtotal to get what top/htop tell you.

Converting double to string with N decimals, dot as decimal separator, and no thousand separator

You can use

value.ToString(CultureInfo.InvariantCulture)

to get exact double value without putting precision.

how to remove the bold from a headline?

<h1><span style="font-weight:bold;">THIS IS</span> A HEADLINE</h1>

But be sure that h1 is marked with

font-weight:normal;

You can also set the style with a id or class attribute.

src absolute path problem

I think because C would be seen the C drive on the client pc, it wont let you. And if it could do this, it would be a big security hole.

Can you force a React component to rerender without calling setState?

We can use this.forceUpdate() as below.

       class MyComponent extends React.Component {



      handleButtonClick = ()=>{
          this.forceUpdate();
     }


 render() {

   return (
     <div>
      {Math.random()}
        <button  onClick={this.handleButtonClick}>
        Click me
        </button>
     </div>
    )
  }
}

 ReactDOM.render(<MyComponent /> , mountNode);

The Element 'Math.random' part in the DOM only gets updated even if you use the setState to re-render the component.

All the answers here are correct supplementing the question for understanding..as we know to re-render a component with out using setState({}) is by using the forceUpdate().

The above code runs with setState as below.

 class MyComponent extends React.Component {



             handleButtonClick = ()=>{
                this.setState({ });
              }


        render() {
         return (
  <div>
    {Math.random()}
    <button  onClick={this.handleButtonClick}>
      Click me
    </button>
  </div>
)
  }
 }

ReactDOM.render(<MyComponent /> , mountNode);

OAuth2 and Google API: access token expiration time?

You shouldn't design your application based on specific lifetimes of access tokens. Just assume they are (very) short lived.

However, after a successful completion of the OAuth2 installed application flow, you will get back a refresh token. This refresh token never expires, and you can use it to exchange it for an access token as needed. Save the refresh tokens, and use them to get access tokens on-demand (which should then immediately be used to get access to user data).

EDIT: My comments above notwithstanding, there are two easy ways to get the access token expiration time:

  1. It is a parameter in the response (expires_in)when you exchange your refresh token (using /o/oauth2/token endpoint). More details.
  2. There is also an API that returns the remaining lifetime of the access_token:

    https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}

    This will return a json array that will contain an expires_in parameter, which is the number of seconds left in the lifetime of the token.

Closing database connections in Java

It is always better to close the database/resource objects after usage. Better close the connection, resultset and statement objects in the finally block.

Until Java 7, all these resources need to be closed using a finally block. If you are using Java 7, then for closing the resources, you can do as follows.

try(Connection con = getConnection(url, username, password, "org.postgresql.Driver");
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery(sql);
) {

    // Statements
}
catch(....){}

Now, the con, stmt and rs objects become part of try block and Java automatically closes these resources after use.

"pip install unroll": "python setup.py egg_info" failed with error code 1

pip3 install --upgrade setuptools WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip. Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.

******To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.******

use python3 -m pip "command" eg: python3 -m pip install --user pyqt5

how to rename an index in a cluster?

Starting with ElasticSearch 7.4, the best method to rename an index is to copy the index using the newly introduced Clone Index API, then to delete the original index using the Delete Index API.

The main advantage of the Clone Index API over the use of the Snapshot API or the Reindex API for the same purpose is speed, since the Clone Index API hardlinks segments from the source index to the target index, without reprocessing any of its content (on filesystems that support hardlinks, obviously; otherwise, files are copied at the file system level, which is still much more efficient that the alternatives). Clone Index also guarantee that the target index is identical in every point to the source index (that is, there is no need to manually copy settings and mappings, contrary to the Reindex approach), and doesn't require a local snapshot directory be configured.

Side note: even though this procedure is much faster than previous solutions, it still implies down time. There are real use cases that justify renaming indices (for example, as a step in a split, shrink or backup workflow), but renaming indices should not be part of day-to-day operations. If your workflow requires frequent index renaming, then you should consider using Indices Aliases instead.

Here is an example of a complete sequence of operations to rename index source_index to target_index. It can be executed using some ElasticSearch specific console, such as the one integrated in Kibana. See this gist for an alternative version of this example, using curl instead of an Elastic Search console.

# Make sure the source index is actually open
POST /source_index/_open

# Put the source index in read-only mode
PUT /source_index/_settings
{
  "settings": {
    "index.blocks.write": "true"
  }
}

# Clone the source index to the target name, and set the target to read-write mode
POST /source_index/_clone/target_index
{
  "settings": {
    "index.blocks.write": null 
  }
}

# Wait until the target index is green;
# it should usually be fast (assuming your filesystem supports hard links).
GET /_cluster/health/target_index?wait_for_status=green&timeout=30s

# If it appears to be taking too much time for the cluster to get back to green,
# the following requests might help you identify eventual outstanding issues (if any)
GET /_cat/indices/target_index
GET /_cat/recovery/target_index
GET /_cluster/allocation/explain

# Delete the source index
DELETE /source_index

What is the equivalent of Java static methods in Kotlin?

All static member and function should be inside companion block

  companion object {
    @JvmStatic
    fun main(args: Array<String>) {
    }

    fun staticMethod() {
    }
  }

Is it possible to set a custom font for entire of application?

As of Android O this is now possible to define directly from the XML and my bug is now closed!

See here for details

TL;DR:

First you must add your fonts to the project

Second you add a font family, like so:

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:fontStyle="normal"
        android:fontWeight="400"
        android:font="@font/lobster_regular" />
    <font
        android:fontStyle="italic"
        android:fontWeight="400"
        android:font="@font/lobster_italic" />
</font-family>

Finally, you can use the font in a layout or style:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/lobster"/>

<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
    <item name="android:fontFamily">@font/lobster</item>
</style>

Enjoy!

jQuery ajax success error

I had the same problem;

textStatus = 'error'
errorThrown = (empty)
xhr.status = 0

That fits my problem exactly. It turns out that when I was loading the HTML-page from my own computer this problem existed, but when I loaded the HTML-page from my webserver it went alright. Then I tried to upload it to another domain, and again the same error occoured. Seems to be a cross-domain problem. (in my case at least)

I have tried calling it this way also:

var request = $.ajax({
url: "http://crossdomain.url.net/somefile.php", dataType: "text",
crossDomain: true,
xhrFields: {
withCredentials: true
}
});

but without success.

This post solved it for me: jQuery AJAX cross domain

Check folder size in Bash

You can do:

du -h your_directory

which will give you the size of your target directory.

If you want a brief output, du -hcs your_directory is nice.

Parsing JSON string in Java

To convert your JSON string to hashmap you can make use of this :

HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;

Use this class :) (handles even lists , nested lists and json)

public class Utility {

    public static Map<String, Object> jsonToMap(Object json) throws JSONException {

        if(json instanceof JSONObject)
            return _jsonToMap_((JSONObject)json) ;

        else if (json instanceof String)
        {
            JSONObject jsonObject = new JSONObject((String)json) ;
            return _jsonToMap_(jsonObject) ;
        }
        return null ;
    }


   private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
        Map<String, Object> retMap = new HashMap<String, Object>();

        if(json != JSONObject.NULL) {
            retMap = toMap(json);
        }
        return retMap;
    }


    private static Map<String, Object> toMap(JSONObject object) throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator<String> keysItr = object.keys();
        while(keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = object.get(key);

            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            map.put(key, value);
        }
        return map;
    }


    public static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            list.add(value);
        }
        return list;
    }
}

"Sources directory is already netbeans project" error when opening a project from existing sources

This happened to me when I tried to import an Eclipse project in a brand new NetBeans 7.2.1 install on Ubuntu 12.04LTS.

I mistakenly selected the import projects from workspace (the first option in the import wizard's opening pane) on the first attempt, and it opened the project in the original Eclipse workspace path (which was on a usb stick).

From this, I then realized that I actually need the second option - import project ignoring project dependencies, which lets you specifically choose source and destination folders. After closing the project, I tried to import again with the proper option, but it didn't work. From then on nothing I did helped - restart the IDE, move the source folder, nothing. There was no nbproject folder in the project or /var/cache in the user folder to delete (in-fact there was no nbproject folder in the whole file-system).

Since restart didn't work, I'm guessing that there is a garbage project entry somewhere which Nb reads (See Martin Frické answer above).

After googling along the lines of 'netbeans clear memory project cache' with no success, I opted to reinstall NetBeans -

sudo /usr/local/netbeans-7.2.1/uninstall
sudo ./netbeans-7.2.1-ml-javase-linux.sh

which solved it.

Use of PUT vs PATCH methods in REST API real life scenarios

The difference between PUT and PATCH is that:

  1. PUT is required to be idempotent. In order to achieve that, you have to put the entire complete resource in the request body.
  2. PATCH can be non-idempotent. Which implies it can also be idempotent in some cases, such as the cases you described.

PATCH requires some "patch language" to tell the server how to modify the resource. The caller and the server need to define some "operations" such as "add", "replace", "delete". For example:

GET /contacts/1
{
  "id": 1,
  "name": "Sam Kwee",
  "email": "[email protected]",
  "state": "NY",
  "zip": "10001"
}

PATCH /contacts/1
{
 [{"operation": "add", "field": "address", "value": "123 main street"},
  {"operation": "replace", "field": "email", "value": "[email protected]"},
  {"operation": "delete", "field": "zip"}]
}

GET /contacts/1
{
  "id": 1,
  "name": "Sam Kwee",
  "email": "[email protected]",
  "state": "NY",
  "address": "123 main street",
}

Instead of using explicit "operation" fields, the patch language can make it implicit by defining conventions like:

in the PATCH request body:

  1. The existence of a field means "replace" or "add" that field.
  2. If the value of a field is null, it means delete that field.

With the above convention, the PATCH in the example can take the following form:

PATCH /contacts/1
{
  "address": "123 main street",
  "email": "[email protected]",
  "zip":
}

Which looks more concise and user-friendly. But the users need to be aware of the underlying convention.

With the operations I mentioned above, the PATCH is still idempotent. But if you define operations like: "increment" or "append", you can easily see it won't be idempotent anymore.

Printing Batch file results to a text file

For showing result of batch file in text file, you can use

this command

chdir > test.txt

This command will redirect result to test.txt.

When you open test.txt you will found current path of directory in test.txt

BEGIN - END block atomic transactions in PL/SQL

BEGIN-END blocks are the building blocks of PL/SQL, and each PL/SQL unit is contained within at least one such block. Nesting BEGIN-END blocks within PL/SQL blocks is usually done to trap certain exceptions and handle that special exception and then raise unrelated exceptions. Nevertheless, in PL/SQL you (the client) must always issue a commit or rollback for the transaction.

If you wish to have atomic transactions within a PL/SQL containing transaction, you need to declare a PRAGMA AUTONOMOUS_TRANSACTION in the declaration block. This will ensure that any DML within that block can be committed or rolledback independently of the containing transaction.

However, you cannot declare this pragma for nested blocks. You can only declare this for:

  • Top-level (not nested) anonymous PL/SQL blocks
  • List item
  • Local, standalone, and packaged functions and procedures
  • Methods of a SQL object type
  • Database triggers

Reference: Oracle

Parse JSON from JQuery.ajax success data

One of the way you can ensure that this type of mistake (using string instead of json) doesn't happen is to see what gets printed in the alert. When you do

alert(data)

if data is a string, it will print everything that is contains. However if you print is json object. you will get the following response in the alert

[object Object]

If this the response then you can be sure that you can use this as an object (json in this case).

Thus, you need to convert your string into json first, before using it by doing this:

JSON.parse(data)

How can I tell if a DOM element is visible in the current viewport?

All the answers here are determining if the element is fully contained within the viewport, not just visible in some way. For example, if only half of an image is visible at the bottom of the view, the solutions here will fail, considering that "outside".

I had a use case where I'm doing lazy loading via IntersectionObserver, but due to animations that occur during pop-in, I didn't want to observe any images that were already intersected on page load. To do that, I used the following code:

const bounding = el.getBoundingClientRect();
const isVisible = (0 < bounding.top && bounding.top < (window.innerHeight || document.documentElement.clientHeight)) ||
        (0 < bounding.bottom && bounding.bottom < (window.innerHeight || document.documentElement.clientHeight));

This is basically checking to see if either the top or bottom bound is independently in the viewport. The opposite end may be outside, but as long as one end is in, it's "visible" at least partially.

Swift: Testing optionals for nil

From swift programming guide

If Statements and Forced Unwrapping

You can use an if statement to find out whether an optional contains a value. If an optional does have a value, it evaluates to true; if it has no value at all, it evaluates to false.

So the best way to do this is

// swift > 3
if xyz != nil {}

and if you are using the xyz in if statement.Than you can unwrap xyz in if statement in constant variable .So you do not need to unwrap every place in if statement where xyz is used.

if let yourConstant = xyz{
      //use youtConstant you do not need to unwrap `xyz`
}

This convention is suggested by apple and it will be followed by devlopers.

invalid types 'int[int]' for array subscript

What to change? Aside from the 3 or 4 dimensional array problem, you should get rid of the magic numbers (10 and 9).

const int DIM_SIZE = 10;
int myArray[DIM_SIZE][DIM_SIZE][DIM_SIZE];

for (int i = 0; i < DIM_SIZE; ++i){
    for (int t = 0; t < DIM_SIZE; ++t){            
        for (int x = 0; x < DIM_SIZE; ++x){

'const string' vs. 'static readonly string' in C#

Here is a good breakdown of the pros and cons:

So, it appears that constants should be used when it is very unlikely that the value will ever change, or if no external apps/libs will be using the constant. Static readonly fields should be used when run-time calculation is required, or if external consumers are a factor.

How do I make the scrollbar on a div only visible when necessary?

You can try with below one:

  <div style="width: 100%; height: 100%; overflow-x: visible; overflow-y: scroll;">Text</div>

Array of an unknown length in C#

Use an ArrayList if in .NET 1.x, or a List<yourtype> if in .NET 2.0 or 3.x.

Search for them in System.Collections and System.Collections.Generics.

Best way to deploy Visual Studio application that can run without installing

First you need to publish the file by:

  1. BUILD -> PUBLISH or by right clicking project on Solution Explorer -> properties -> publish or select project in Solution Explorer and press Alt + Enter NOTE: if you are using Visual Studio 2013 then in properties you have to go to BUILD and then you have to disable define DEBUG constant and define TRACE constant and you are ready to go. Representation

  2. Save your file to a particular folder. Find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj). In Visual Studio they are in the Application Files folder and inside that you just need the .exe and dll files. (You have to delete ClickOnce and other files and then make this folder a zip file and distribute it.)

NOTE: The ClickOnce application does install the project to system, but it has one advantage. You DO NOT require administrative privileges here to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

Youtube - downloading a playlist - youtube-dl

Your link is not a playlist.

A proper playlist URL looks like this:

https://www.youtube.com/playlist?list=PLHSdFJ8BDqEyvUUzm6R0HxawSWniP2c9K

Your URL is just the first video OF a certain playlist. It contains https://www.youtube.com/watch? instead of https://www.youtube.com/playlist?.

Pick the playlist by clicking on the title of the playlist on the right side in the list of videos and use this URL.

How to make lists contain only distinct element in Python?

The characteristics of sets in Python are that the data items in a set are unordered and duplicates are not allowed. If you try to add a data item to a set that already contains the data item, Python simply ignores it.

>>> l = ['a', 'a', 'bb', 'b', 'c', 'c', '10', '10', '8','8', 10, 10, 6, 10, 11.2, 11.2, 11, 11]
>>> distinct_l = set(l)
>>> print(distinct_l)
set(['a', '10', 'c', 'b', 6, 'bb', 10, 11, 11.2, '8'])

How to restart Jenkins manually?

If you want to just reload the configuration file, one can do

    <jenkins_url>/reload

This is quicker if you have made some small change in the configuration file, like config.xml directly in the file system or made copies of the job through the filesystem (not through the browser).

how to make a full screen div, and prevent size to be changed by content?

Here is my Solution, I think will better to use vh (viewport height) and vw for (viewport width), units regarding to the height and width of the current viewport

_x000D_
_x000D_
function myFunction() {
  var element = document.getElementById("main");
  element.classList.add("container");
}
_x000D_
.container{
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  background-color: #333;
  margin: 0; 
  padding: 0; 
}
_x000D_
<div id="main"></div>
<button onclick="myFunction()">Try it</button>
_x000D_
_x000D_
_x000D_

jQuery $(".class").click(); - multiple elements, click event once

I think you add click event five times. Try to count how many times you do this.

console.log('add click event')
$(".addproduct").click(function(){ });

Toggle Checkboxes on/off

I think it's simpler to just trigger a click:

$("#select-all-teammembers").click(function() {
    $("input[name=recipients\\[\\]]").trigger('click');
});                 

How to edit CSS style of a div using C# in .NET

Add the runat="server" attribute to it so you have:

<div id="formSpinner" runat="server">
    <img src="images/spinner.gif">
    <p>Saving...</p>
</div>

That way you can access the class attribute by using:

formSpinner.Attributes["class"] = "classOfYourChoice";

It's also worth mentioning that the asp:Panel control is virtually synonymous (at least as far as rendered markup is concerned) with div, so you could also do:

<asp:Panel id="formSpinner" runat="server">
    <img src="images/spinner.gif">
    <p>Saving...</p>
</asp:Panel>

Which then enables you to write:

formSpinner.CssClass = "classOfYourChoice";

This gives you more defined access to the property and there are others that may, or may not, be of use to you.

Make the console wait for a user input to close

The problem with Java console input is that it's buffered input, and requires an enter key to continue.

There are these two discussions: Detecting and acting on keyboard direction keys in Java and Java keyboard input parsing in a console app

The latter of which used JLine to get his problem solved.

I personally haven't used it.

Angles between two n-dimensional vectors in Python

Note: all of the other answers here will fail if the two vectors have either the same direction (ex, (1, 0, 0), (1, 0, 0)) or opposite directions (ex, (-1, 0, 0), (1, 0, 0)).

Here is a function which will correctly handle these cases:

import numpy as np

def unit_vector(vector):
    """ Returns the unit vector of the vector.  """
    return vector / np.linalg.norm(vector)

def angle_between(v1, v2):
    """ Returns the angle in radians between vectors 'v1' and 'v2'::

            >>> angle_between((1, 0, 0), (0, 1, 0))
            1.5707963267948966
            >>> angle_between((1, 0, 0), (1, 0, 0))
            0.0
            >>> angle_between((1, 0, 0), (-1, 0, 0))
            3.141592653589793
    """
    v1_u = unit_vector(v1)
    v2_u = unit_vector(v2)
    return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))

Assert that a method was called in a Python unit test

I'm not aware of anything built-in. It's pretty simple to implement:

class assertMethodIsCalled(object):
    def __init__(self, obj, method):
        self.obj = obj
        self.method = method

    def called(self, *args, **kwargs):
        self.method_called = True
        self.orig_method(*args, **kwargs)

    def __enter__(self):
        self.orig_method = getattr(self.obj, self.method)
        setattr(self.obj, self.method, self.called)
        self.method_called = False

    def __exit__(self, exc_type, exc_value, traceback):
        assert getattr(self.obj, self.method) == self.called,
            "method %s was modified during assertMethodIsCalled" % self.method

        setattr(self.obj, self.method, self.orig_method)

        # If an exception was thrown within the block, we've already failed.
        if traceback is None:
            assert self.method_called,
                "method %s of %s was not called" % (self.method, self.obj)

class test(object):
    def a(self):
        print "test"
    def b(self):
        self.a()

obj = test()
with assertMethodIsCalled(obj, "a"):
    obj.b()

This requires that the object itself won't modify self.b, which is almost always true.

Redirecting new tab on button click.(Response.Redirect) in asp.net C#

Wouldn't you be better off with

<asp:HyperLink ID="HyperLink1" runat="server" 
            NavigateUrl="CMS_1.aspx" 
            Target="_blank">
    Click here
</asp:HyperLink>

Because, to replicate your desired behavior on an asp:Button, you have to call window.open on the OnClientClick event of the button which looks a lot less cleaner than the above solution. Plus asp:HyperLink is there to handle scenarios like this.

If you want to replicate this using an asp:Button, do this.

<asp:Button ID="btn" runat="Server" 
        Text="SUBMIT"
        OnClientClick="javascript:return openRequestedPopup();"/>

JavaScript function.

var windowObjectReference;

function openRequestedPopup() {
    windowObjectReference = window.open("CMS_1.aspx",
              "DescriptiveWindowName",
              "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");
}

How to upgrade safely php version in wamp server

For someone who need to update the PHP version in WAMP, I can recommend this http://wampserver.aviatechno.net/

I had a problems with updating too, but on this website are Wampserver addons like new php version (php 7.1.4 etc.) And you don't have to manually edit files like php.ini or phpForApache.

Enjoy!

Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"

Your not applying Date formator. rather you are just parsing the date. to get output in this format

yyyy-MM-dd HH:mm:ss.SSSSSS

we have to use format() method here is full example:- Here is full example:- it will take Date in this format yyyy-MM-dd HH:mm:ss.SSSSSS and as result we will get output as same as this format yyyy-MM-dd HH:mm:ss.SSSSSS

 import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//TODO OutPut should LIKE in this format yyyy-MM-dd HH:mm:ss.SSSSSS.
public class TestDateExample {

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

    SimpleDateFormat changeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");

    java.util.Date temp = changeFormat.parse("2012-07-10 14:58:00.000000");
     Date thisDate = changeFormat.parse("2012-07-10 14:58:00.000000");  
    System.out.println(thisDate);
    System.out.println("----------------------------"); 
    System.out.println("After applying formating :");
    String strDateOutput = changeFormat.format(temp);
    System.out.println(strDateOutput);

}

}

Working example screen

Set initial value in datepicker with jquery?

This simple example works for me...

HTML

<input type="text" id="datepicker">

JavaScript

var $datepicker = $('#datepicker');
$datepicker.datepicker();
$datepicker.datepicker('setDate', new Date());

I was able to create this by simply looking @ the manual and reading the explanation of setDate:

.datepicker( "setDate" , date )
Sets the current date for the datepicker. The new date may be a Date object or a string in the current date format (e.g. '01/26/2009'), a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null to clear the selected date.

Causes of getting a java.lang.VerifyError

java.lang.VerifyError means your compiled bytecode is referring to something that Android cannot find. This verifyError Issues me only with kitkat4.4 and lesser version not in above version of that even I ran the same build in both Devices. when I used jackson json parser of older version it shows java.lang.verifyerror

compile 'com.fasterxml.jackson.core:jackson-databind:2.2.+'
compile 'com.fasterxml.jackson.core:jackson-core:2.2.+'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.2.+'

Then I have changed the Dependancy to the latest version 2.2 to 2.7 without the core library, then it works. which means the Methods and other contents of core is migrated to the latest version of Databind2.7. This fix my Issues.

compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.0-rc3'
compile 'com.fasterxml.jackson.core:jackson-databind:2.7.0-rc3'

Java, Simplified check if int array contains int

Guava offers additional methods for primitive types. Among them a contains method which takes the same arguments as yours.

public boolean contains(final int[] array, final int key) {
    return Ints.contains(array, key);
}

You might as well statically import the guava version.

See Guava Primitives Explained

Angular: Cannot Get /

See this answer here. You need to redirect all routes that Node is not using to Angular:

app.get('*', function(req, res) {
  res.sendfile('./server/views/index.html')
})

How to make JQuery-AJAX request synchronous

The below is a working example. Add async:false.

const response = $.ajax({
                    type:"POST",
                    dataType:"json",
                    async:false, 
                    url:"your-url",
                    data:{"data":"data"}                        
                });                   
 console.log("response: ", response);

How to replace ${} placeholders in a text file?

Sed!

Given template.txt:

The number is ${i}
The word is ${word}

we just have to say:

sed -e "s/\${i}/1/" -e "s/\${word}/dog/" template.txt

Thanks to Jonathan Leffler for the tip to pass multiple -e arguments to the same sed invocation.

jQuery Datepicker localization

You can do like this

 $.datepicker.regional['fr'] = {clearText: 'Effacer', clearStatus: '',
    closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
    prevText: '&lt;Préc', prevStatus: 'Voir le mois précédent',
    nextText: 'Suiv&gt;', nextStatus: 'Voir le mois suivant',
    currentText: 'Courant', currentStatus: 'Voir le mois courant',
    monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
    'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
    monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
    'Jul','Aoû','Sep','Oct','Nov','Déc'],
    monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
    weekHeader: 'Sm', weekStatus: '',
    dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
    dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
    dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
    dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
    dateFormat: 'dd/mm/yy', firstDay: 0, 
    initStatus: 'Choisir la date', isRTL: false};
 $.datepicker.setDefaults($.datepicker.regional['fr']);

Bootstrap radio button "checked" flag

You have to use active in the label to make it work as mentioned above. But you can use checked="checked" and it will work too. It's not necessary but it's more legible and makes more sense as it is more html format compliance.

How to convert C++ Code to C

This is an old thread but apparently the C++ Faq has a section (Archived 2013 version) on this. This apparently will be updated if the author is contacted so this will probably be more up to date in the long run, but here is the current version:

Depends on what you mean. If you mean, Is it possible to convert C++ to readable and maintainable C-code? then sorry, the answer is No — C++ features don't directly map to C, plus the generated C code is not intended for humans to follow. If instead you mean, Are there compilers which convert C++ to C for the purpose of compiling onto a platform that yet doesn't have a C++ compiler? then you're in luck — keep reading.

A compiler which compiles C++ to C does full syntax and semantic checking on the program, and just happens to use C code as a way of generating object code. Such a compiler is not merely some kind of fancy macro processor. (And please don't email me claiming these are preprocessors — they are not — they are full compilers.) It is possible to implement all of the features of ISO Standard C++ by translation to C, and except for exception handling, it typically results in object code with efficiency comparable to that of the code generated by a conventional C++ compiler.

Here are some products that perform compilation to C:

  • Comeau Computing offers a compiler based on Edison Design Group's front end that outputs C code.
  • LLVM is a downloadable compiler that emits C code. See also here and here. Here is an example of C++ to C conversion via LLVM.
  • Cfront, the original implementation of C++, done by Bjarne Stroustrup and others at AT&T, generates C code. However it has two problems: it's been difficult to obtain a license since the mid 90s when it started going through a maze of ownership changes, and development ceased at that same time and so it doesn't get bug fixes and doesn't support any of the newer language features (e.g., exceptions, namespaces, RTTI, member templates).

  • Contrary to popular myth, as of this writing there is no version of g++ that translates C++ to C. Such a thing seems to be doable, but I am not aware that anyone has actually done it (yet).

Note that you typically need to specify the target platform's CPU, OS and C compiler so that the generated C code will be specifically targeted for this platform. This means: (a) you probably can't take the C code generated for platform X and compile it on platform Y; and (b) it'll be difficult to do the translation yourself — it'll probably be a lot cheaper/safer with one of these tools.

One more time: do not email me saying these are just preprocessors — they are not — they are compilers.

How to pass a view's onClick event to its parent on Android?

This answer is similar to Alexander Ukhov's answer, except that it uses touch events rather than click events. Those event allow the parent to display the proper pressed states (e.g., ripple effect). This answer is also in Kotlin instead of Java.

view.setOnTouchListener { view, motionEvent ->
    (view.parent as View).onTouchEvent(motionEvent)
}

Text file in VBA: Open/Find Replace/SaveAs/Close File

This code will open and read lines of complete text file That variable "ReadedData" Holds the text line in memory

Open "C:\satheesh\myfile\Hello.txt" For Input As #1

do until EOF(1)   

       Input #1, ReadedData
loop**

How are iloc and loc different?

Label vs. Location

The main distinction between the two methods is:

  • loc gets rows (and/or columns) with particular labels.

  • iloc gets rows (and/or columns) at integer locations.

To demonstrate, consider a series s of characters with a non-monotonic integer index:

>>> s = pd.Series(list("abcdef"), index=[49, 48, 47, 0, 1, 2]) 
49    a
48    b
47    c
0     d
1     e
2     f

>>> s.loc[0]    # value at index label 0
'd'

>>> s.iloc[0]   # value at index location 0
'a'

>>> s.loc[0:1]  # rows at index labels between 0 and 1 (inclusive)
0    d
1    e

>>> s.iloc[0:1] # rows at index location between 0 and 1 (exclusive)
49    a

Here are some of the differences/similarities between s.loc and s.iloc when passed various objects:

<object> description s.loc[<object>] s.iloc[<object>]
0 single item Value at index label 0 (the string 'd') Value at index location 0 (the string 'a')
0:1 slice Two rows (labels 0 and 1) One row (first row at location 0)
1:47 slice with out-of-bounds end Zero rows (empty Series) Five rows (location 1 onwards)
1:47:-1 slice with negative step Four rows (labels 1 back to 47) Zero rows (empty Series)
[2, 0] integer list Two rows with given labels Two rows with given locations
s > 'e' Bool series (indicating which values have the property) One row (containing 'f') NotImplementedError
(s>'e').values Bool array One row (containing 'f') Same as loc
999 int object not in index KeyError IndexError (out of bounds)
-1 int object not in index KeyError Returns last value in s
lambda x: x.index[3] callable applied to series (here returning 3rd item in index) s.loc[s.index[3]] s.iloc[s.index[3]]

loc's label-querying capabilities extend well-beyond integer indexes and it's worth highlighting a couple of additional examples.

Here's a Series where the index contains string objects:

>>> s2 = pd.Series(s.index, index=s.values)
>>> s2
a    49
b    48
c    47
d     0
e     1
f     2

Since loc is label-based, it can fetch the first value in the Series using s2.loc['a']. It can also slice with non-integer objects:

>>> s2.loc['c':'e']  # all rows lying between 'c' and 'e' (inclusive)
c    47
d     0
e     1

For DateTime indexes, we don't need to pass the exact date/time to fetch by label. For example:

>>> s3 = pd.Series(list('abcde'), pd.date_range('now', periods=5, freq='M')) 
>>> s3
2021-01-31 16:41:31.879768    a
2021-02-28 16:41:31.879768    b
2021-03-31 16:41:31.879768    c
2021-04-30 16:41:31.879768    d
2021-05-31 16:41:31.879768    e

Then to fetch the row(s) for March/April 2021 we only need:

>>> s3.loc['2021-03':'2021-04']
2021-03-31 17:04:30.742316    c
2021-04-30 17:04:30.742316    d

Rows and Columns

loc and iloc work the same way with DataFrames as they do with Series. It's useful to note that both methods can address columns and rows together.

When given a tuple, the first element is used to index the rows and, if it exists, the second element is used to index the columns.

Consider the DataFrame defined below:

>>> import numpy as np 
>>> df = pd.DataFrame(np.arange(25).reshape(5, 5),  
                      index=list('abcde'), 
                      columns=['x','y','z', 8, 9])
>>> df
    x   y   z   8   9
a   0   1   2   3   4
b   5   6   7   8   9
c  10  11  12  13  14
d  15  16  17  18  19
e  20  21  22  23  24

Then for example:

>>> df.loc['c': , :'z']  # rows 'c' and onwards AND columns up to 'z'
    x   y   z
c  10  11  12
d  15  16  17
e  20  21  22

>>> df.iloc[:, 3]        # all rows, but only the column at index location 3
a     3
b     8
c    13
d    18
e    23

Sometimes we want to mix label and positional indexing methods for the rows and columns, somehow combining the capabilities of loc and iloc.

For example, consider the following DataFrame. How best to slice the rows up to and including 'c' and take the first four columns?

>>> import numpy as np 
>>> df = pd.DataFrame(np.arange(25).reshape(5, 5),  
                      index=list('abcde'), 
                      columns=['x','y','z', 8, 9])
>>> df
    x   y   z   8   9
a   0   1   2   3   4
b   5   6   7   8   9
c  10  11  12  13  14
d  15  16  17  18  19
e  20  21  22  23  24

We can achieve this result using iloc and the help of another method:

>>> df.iloc[:df.index.get_loc('c') + 1, :4]
    x   y   z   8
a   0   1   2   3
b   5   6   7   8
c  10  11  12  13

get_loc() is an index method meaning "get the position of the label in this index". Note that since slicing with iloc is exclusive of its endpoint, we must add 1 to this value if we want row 'c' as well.

Not able to launch IE browser using Selenium2 (Webdriver) with Java

It needs to set same Security level in all zones. To do that follow the steps below:

  1. Open IE
  2. Go to Tools -> Internet Options -> Security
  3. Set all zones (Internet, Local intranet, Trusted sites, Restricted sites) to the same protected mode, enabled or disabled should not matter.

Finally, set Zoom level to 100% by right clicking on the gear located at the top right corner and enabling the status-bar. Default zoom level is now displayed at the lower right.

System.Security.SecurityException when writing to Event Log

try below in web.config

 <system.web>

<trust level="Full"/>

</system.web>

Convert string to date in bash

This worked for me :

date -d '20121212 7 days'
date -d '12-DEC-2012 7 days'
date -d '2012-12-12 7 days'
date -d '2012-12-12 4:10:10PM 7 days'
date -d '2012-12-12 16:10:55 7 days'

then you can format output adding parameter '+%Y%m%d'

OSError: [Errno 8] Exec format error

OSError: [Errno 8] Exec format error can happen if there is no shebang line at the top of the shell script and you are trying to execute the script directly. Here's an example that reproduces the issue:

>>> with open('a','w') as f: f.write('exit 0') # create the script
... 
>>> import os
>>> os.chmod('a', 0b111101101) # rwxr-xr-x make it executable                       
>>> os.execl('./a', './a')     # execute it                                            
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/os.py", line 312, in execl
    execv(file, args)
OSError: [Errno 8] Exec format error

To fix it, just add the shebang e.g., if it is a shell script; prepend #!/bin/sh at the top of your script:

>>> with open('a','w') as f: f.write('#!/bin/sh\nexit 0')
... 
>>> os.execl('./a', './a')

It executes exit 0 without any errors.


On POSIX systems, shell parses the command line i.e., your script won't see spaces around = e.g., if script is:

#!/usr/bin/env python
import sys
print(sys.argv)

then running it in the shell:

$ /usr/local/bin/script hostname = '<hostname>' -p LONGLIST

produces:

['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']

Note: no spaces around '='. I've added quotes around <hostname> to escape the redirection metacharacters <>.

To emulate the shell command in Python, run:

from subprocess import check_call

cmd = ['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']
check_call(cmd)

Note: no shell=True. And you don't need to escape <> because no shell is run.

"Exec format error" might indicate that your script has invalid format, run:

$ file /usr/local/bin/script

to find out what it is. Compare the architecture with the output of:

$ uname -m

Concatenate two string literals

The difference between a string (or to be precise, std::string) and a character literal is that for the latter there is no + operator defined. This is why the second example fails.

In the first case, the compiler can find a suitable operator+ with the first argument being a string and the second a character literal (const char*) so it used that. The result of that operation is again a string, so it repeats the same trick when adding "!" to it.

HTML button onclick event

Having trouble with a button onclick event in jsfiddle?

If so see Onclick event not firing on jsfiddle.net

Get value from SimpleXMLElement Object

you can convert array with this function

function xml2array($xml){
$arr = array();

foreach ($xml->children() as $r)
{
    $t = array();
    if(count($r->children()) == 0)
    {
        $arr[$r->getName()] = strval($r);
    }
    else
    {
        $arr[$r->getName()][] = xml2array($r);
    }
}
return $arr;
}

Check if image exists on server using JavaScript?

You could use something like:

function imageExists(image_url){

    var http = new XMLHttpRequest();

    http.open('HEAD', image_url, false);
    http.send();

    return http.status != 404;

}

Obviously you could use jQuery/similar to perform your HTTP request.

$.get(image_url)
    .done(function() { 
        // Do something now you know the image exists.

    }).fail(function() { 
        // Image doesn't exist - do something else.

    })

android edittext onchange listener

As far as I can think bout it, there's only two ways you can do it. How can you know the user has finished writing a word? Either on focus lost, or clicking on an "ok" button. There's no way on my mind you can know the user pressed the last character...

So call onFocusChange(View v, boolean hasFocus) or add a button and a click listener to it.

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

It's in this package (Ubuntu 19.04):

  sudo apt install g++-6

Change the color of a bullet in a html list?

You could use CSS to attain this. By specifying the list in the color and style of your choice, you can then also specify the text as a different color.

Follow the example at http://www.echoecho.com/csslists.htm.

How to parse a date?

In response to: "How to convert Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México)) to dd-MM-yy in Java?", it was marked how duplicate

Try this: With java.util.Date, java.text.SimpleDateFormat, it's a simple solution.

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

    String fecha = "Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México))";
    Date f = new Date(fecha);

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    sdf.setTimeZone(TimeZone.getTimeZone("-5GMT"));
    fecha = sdf.format(f);
    System.out.println(fecha);
}

Installing Apache Maven Plugin for Eclipse

Eclipse > Help > Eclipse Marketplace...

Search for m2e

Install Maven Integration for Eclipse (Juno and newer). [It works for Indigo also]

Can't find file executable in your configured search path for gnc gcc compiler

Disable vertical scroll bar on div overflow: auto

Add the following:

body{
overflow-y:hidden;
}

Inserting Image Into BLOB Oracle 10g

You cannot access a local directory from pl/sql. If you use bfile, you will setup a directory (create directory) on the server where Oracle is running where you will need to put your images.

If you want to insert a handful of images from your local machine, you'll need a client side app to do this. You can write your own, but I typically use Toad for this. In schema browser, click onto the table. Click the data tab, and hit + sign to add a row. Double click the BLOB column, and a wizard opens. The far left icon will load an image into the blob:

enter image description here

SQL Developer has a similar feature. See the "Load" link below:

enter image description here

If you need to pull images over the wire, you can do it using pl/sql, but its not straight forward. First, you'll need to setup ACL list access (for security reasons) to allow a user to pull over the wire. See this article for more on ACL setup.

Assuming ACL is complete, you'd pull the image like this:

declare
    l_url varchar2(4000) := 'http://www.oracleimg.com/us/assets/12_c_navbnr.jpg';
    l_http_request   UTL_HTTP.req;
    l_http_response  UTL_HTTP.resp;
    l_raw RAW(2000);
    l_blob BLOB;
begin
   -- Important: setup ACL access list first!

    DBMS_LOB.createtemporary(l_blob, FALSE);

    l_http_request  := UTL_HTTP.begin_request(l_url);
    l_http_response := UTL_HTTP.get_response(l_http_request);

  -- Copy the response into the BLOB.
  BEGIN
    LOOP
      UTL_HTTP.read_raw(l_http_response, l_raw, 2000);
      DBMS_LOB.writeappend (l_blob, UTL_RAW.length(l_raw), l_raw);
    END LOOP;
  EXCEPTION
    WHEN UTL_HTTP.end_of_body THEN
      UTL_HTTP.end_response(l_http_response);
  END;

  insert into my_pics (pic_id, pic) values (102, l_blob);
  commit;

  DBMS_LOB.freetemporary(l_blob); 
end;

Hope that helps.

Use images instead of radio buttons

Example:

Heads up! This solution is CSS-only.

Credit-card selector, the MasterCard on the modded demo is hovered.

I recommend you take advantage of CSS3 to do that, by hidding the by-default input radio button with CSS3 rules:

.options input{
    margin:0;padding:0;
    -webkit-appearance:none;
       -moz-appearance:none;
            appearance:none;
}

I just make an example a few days ago.

Good way to encapsulate Integer.parseInt()

Maybe someone is looking for a more generic approach, since Java 8 there is the Package java.util.function that allows to define Supplier Functions. You could have a function that takes a supplier and a default value as follows:

public static <T> T tryGetOrDefault(Supplier<T> supplier, T defaultValue) {
    try {
        return supplier.get();
    } catch (Exception e) {
        return defaultValue;
    }
}

With this function, you can execute any parsing method or even other methods that could throw an Exception while ensuring that no Exception can ever be thrown:

Integer i = tryGetOrDefault(() -> Integer.parseInt(stringValue), 0);
Long l = tryGetOrDefault(() -> Long.parseLong(stringValue), 0l);
Double d = tryGetOrDefault(() -> Double.parseDouble(stringValue), 0d);

String Array object in Java

Currently you can't access the arrays named name and country, because they are member variables of your Athelete class.

Based on what it looks like you're trying to do, this will not work.

These arrays belong in your main class.

How to get the last N rows of a pandas DataFrame?

How to get the last N rows of a pandas DataFrame?

If you are slicing by position, __getitem__ (i.e., slicing with[]) works well, and is the most succinct solution I've found for this problem.

pd.__version__
# '0.24.2'

df = pd.DataFrame({'A': list('aaabbbbc'), 'B': np.arange(1, 9)})
df

   A  B
0  a  1
1  a  2
2  a  3
3  b  4
4  b  5
5  b  6
6  b  7
7  c  8

df[-3:]

   A  B
5  b  6
6  b  7
7  c  8

This is the same as calling df.iloc[-3:], for instance (iloc internally delegates to __getitem__).


As an aside, if you want to find the last N rows for each group, use groupby and GroupBy.tail:

df.groupby('A').tail(2)

   A  B
1  a  2
2  a  3
5  b  6
6  b  7
7  c  8

Excluding Maven dependencies

Global exclusions look like they're being worked on, but until then...

From the Sonatype maven reference (bottom of the page):

Dependency management in a top-level POM is different from just defining a dependency on a widely shared parent POM. For starters, all dependencies are inherited. If mysql-connector-java were listed as a dependency of the top-level parent project, every single project in the hierarchy would have a reference to this dependency. Instead of adding in unnecessary dependencies, using dependencyManagement allows you to consolidate and centralize the management of dependency versions without adding dependencies which are inherited by all children. In other words, the dependencyManagement element is equivalent to an environment variable which allows you to declare a dependency anywhere below a project without specifying a version number.

As an example:

  <dependencies>
    <dependency>
      <groupId>commons-httpclient</groupId>
      <artifactId>commons-httpclient</artifactId>
      <version>3.1</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>3.0.5.RELEASE</version>
    </dependency>
  </dependencies>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <exclusions>
          <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
          </exclusion>
        </exclusions>
      </dependency>
      <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <exclusions>
          <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
          </exclusion>
        </exclusions>
      </dependency>
    </dependencies>
  </dependencyManagement>

It doesn't make the code less verbose overall, but it does make it less verbose where it counts. If you still want it less verbose you can follow these tips also from the Sonatype reference.

How to select a single column with Entity Framework?

You can use LINQ's .Select() to do that. In your case it would go something like:

string Name = yourDbContext
  .MyTable
  .Where(u => u.UserId == 1)
  .Select(u => u.Name)
  .SingleOrDefault(); // This is what actually executes the request and return a response

If you are expecting more than one entry in response, you can use .ToList() instead, to execute the request. Something like this, to get the Name of everyone with age 30:

string[] Names = yourDbContext
  .MyTable
  .Where(u => u.Age == 30)
  .Select(u => u.Name)
  .ToList();

Storing query results into a variable and modifying it inside a Stored Procedure

Or you can use one SQL-command instead of create and call stored procedure

INSERT INTO [order_cart](orId,caId)
OUTPUT inserted.*
SELECT
   (SELECT MAX(orId) FROM [order]) as orId,
   (SELECT MAX(caId) FROM [cart]) as caId;

OR operator in switch-case?

dude do like this

    case R.id.someValue :
    case R.id.someOtherValue :
       //do stuff

This is same as using OR operator between two values Because of this case operator isn't there in switch case

Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave

Reassigning the path Xcode is configured with worked for me.

sudo xcode-select -switch /Applications/Xcode.app

You'll then likely be prompted (after trying a command) to agree to the license agreement.

SHOW PROCESSLIST in MySQL command: sleep

Sleep meaning that thread is do nothing. Time is too large beacuse anthor thread query,but not disconnect server, default wait_timeout=28800;so you can set values smaller,eg 10. also you can kill the thread.

SQL QUERY replace NULL value in a row with a value from the previous known value

Here is the Oracle solution (10g or higher). It uses the analytic function last_value() with the ignore nulls option, which substitutes the last non-null value for the column.

SQL> select *
  2  from mytable
  3  order by id
  4  /

        ID    SOMECOL
---------- ----------
         1          3
         2
         3          5
         4
         5
         6          2

6 rows selected.

SQL> select id
  2         , last_value(somecol ignore nulls) over (order by id) somecol
  3  from mytable
  4  /

        ID    SOMECOL
---------- ----------
         1          3
         2          3
         3          5
         4          5
         5          5
         6          2

6 rows selected.

SQL>

How to parse freeform street/postal address out of text, and into components

There are many street address parsers. They come in two basic flavors - ones that have databases of place names and street names, and ones that don't.

A regular expression street address parser can get up to about a 95% success rate without much trouble. Then you start hitting the unusual cases. The Perl one in CPAN, "Geo::StreetAddress::US", is about that good. There are Python and Javascript ports of that, all open source. I have an improved version in Python which moves the success rate up slightly by handling more cases. To get the last 3% right, though, you need databases to help with disambiguation.

A database with 3-digit ZIP codes and US state names and abbreviations is a big help. When a parser sees a consistent postal code and state name, it can start to lock on to the format. This works very well for the US and UK.

Proper street address parsing starts from the end and works backwards. That's how the USPS systems do it. Addresses are least ambiguous at the end, where country names, city names, and postal codes are relatively easy to recognize. Street names can usually be isolated. Locations on streets are the most complex to parse; there you encounter things such as "Fifth Floor" and "Staples Pavillion". That's when a database is a big help.

How to call another components function in angular2

  1. Add injectable decorator to component2(or any component which have the method)
@Injectable({
    providedIn: 'root'
})
  1. Inject into component1 (the component from where component2 method will be called)
constructor(public comp2 : component2) { }
  1. Define method in component1 from where component2 method is called
method1()
{
    this.comp2.method2();
}

component 1 and component 2 code below.

import {Component2} from './Component2';

@Component({
  selector: 'sel-comp1',
  templateUrl: './comp1.html',
  styleUrls: ['./comp1.scss']
})
export class Component1 implements OnInit {
  show = false;
  constructor(public comp2: Component2) { }
method1()
 {
   this.comp2.method2(); 
  }
}


@Component({
  selector: 'sel-comp2',
  templateUrl: './comp2.html',
  styleUrls: ['./comp2.scss']
})
export class Component2 implements OnInit {
  method2()
{
  alert('called comp2 method from comp1');
}

Pass array to where in Codeigniter Active Record

Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with AND if appropriate,

$this->db->where_in()
ex :  $this->db->where_in('id', array('1','2','3'));

Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with OR if appropriate

$this->db->or_where_in()
ex :  $this->db->where_in('id', array('1','2','3'));

How to wrap text of HTML button with fixed width?

white-space: normal;
word-wrap: break-word;

Mine works with both

count distinct values in spreadsheet

Not exactly what the user asked, but an easy way to just count unique values:

Google introduced a new function to count unique values in just one step, and you can use this as an input for other formulas:

=COUNTUNIQUE(A1:B10)

Accessing the logged-in user in a template

You can access user data directly in the twig template without requesting anything in the controller. The user is accessible like that : app.user.

Now, you can access every property of the user. For example, you can access the username like that : app.user.username.

Warning, if the user is not logged, the app.user is null.

If you want to check if the user is logged, you can use the is_granted twig function. For example, if you want to check if the user has ROLE_ADMIN, you just have to do is_granted("ROLE_ADMIN").

So, in every of your pages you can do :

{% if is_granted("ROLE") %}
    Hi {{ app.user.username }}
{% endif %}

C++ array initialization

Yes, this form of initialization is supported by all C++ compilers. It is a part of C++ language. In fact, it is an idiom that came to C++ from C language. In C language = { 0 } is an idiomatic universal zero-initializer. This is also almost the case in C++.

Since this initalizer is universal, for bool array you don't really need a different "syntax". 0 works as an initializer for bool type as well, so

bool myBoolArray[ARRAY_SIZE] = { 0 };

is guaranteed to initialize the entire array with false. As well as

char* myPtrArray[ARRAY_SIZE] = { 0 };

in guaranteed to initialize the whole array with null-pointers of type char *.

If you believe it improves readability, you can certainly use

bool myBoolArray[ARRAY_SIZE] = { false };
char* myPtrArray[ARRAY_SIZE] = { nullptr };

but the point is that = { 0 } variant gives you exactly the same result.

However, in C++ = { 0 } might not work for all types, like enum types, for example, which cannot be initialized with integral 0. But C++ supports the shorter form

T myArray[ARRAY_SIZE] = {};

i.e. just an empty pair of {}. This will default-initialize an array of any type (assuming the elements allow default initialization), which means that for basic (scalar) types the entire array will be properly zero-initialized.

Regular Expression: Any character that is NOT a letter or number

Have you tried str = str.replace(/\W|_/g,''); it will return a string without any character and you can specify if any especial character after the pipe bar | to catch them as well.

var str = "1324567890abc§$)% John Doe #$@'.replace(/\W|_/g, ''); it will return str = 1324567890abcJohnDoe

or look for digits and letters and replace them for empty string (""):

var str = "1324567890abc§$)% John Doe #$@".replace(/\w|_/g, ''); it will return str = '§$)% #$@';

What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?

Assuming here you're referring to the javax.inject.Inject annotation. @Inject is part of the Java CDI (Contexts and Dependency Injection) standard introduced in Java EE 6 (JSR-299), read more. Spring has chosen to support using the @Inject annotation synonymously with their own @Autowired annotation.

So, to answer your question, @Autowired is Spring's own annotation. @Inject is part of a Java technology called CDI that defines a standard for dependency injection similar to Spring. In a Spring application, the two annotations works the same way as Spring has decided to support some JSR-299 annotations in addition to their own.

MySQL: Grant **all** privileges on database

I had this challenge when working on MySQL Ver 8.0.21

I wanted to grant permissions of a database named my_app_db to the root user running on localhost host.

But when I run the command:

use my_app_db;

GRANT ALL PRIVILEGES ON my_app_db.* TO 'root'@'localhost';

I get the error:

ERROR 1064 (42000): 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 'my_app_db.* TO 'root'@'localhost'' at line 1>

Here's how I fixed:

Login to your MySQL console. You can change root to the user you want to login with:

mysql -u root -p

Enter your mysql root password

Next, list out all the users and their host on the MySQL server. Unlike PostgreSQL this is often stored in the mysql database. So we need to select the mysql database first:

use mysql;
SELECT user, host FROM user;

Note: if you don't run the use mysql, you get the no database selected error.

This should give you an output of this sort:

+------------------+-----------+
| user             | host      |
+------------------+-----------+
| mysql.infoschema | localhost |
| mysql.session    | localhost |
| mysql.sys        | localhost |
| root             | localhost |
+------------------+-----------+
4 rows in set (0.00 sec)

Next, based on the information gotten from the list, grant privileges to the user that you want. We will need to first select the database before granting permission to it. For me, I am using the root user that runs on the localhost host:

use my_app_db;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';

Note: The GRANT ALL PRIVILEGES ON database_name.* TO 'root'@'localhost'; command may not work for modern versions of MySQL. Most modern versions of MyQL replace the database_name with * in the grant privileges command after you select the database that you want to use.

You can then exit the MySQL console:

exit

That's it.

I hope this helps

Center Contents of Bootstrap row container

I solved this by doing the following:

<body class="container-fluid">
    <div class="row">
        <div class="span6" style="float: none; margin: 0 auto;">
           ....
        </div>
    </div>
</body>

Close Current Tab

Try this:

window.open('', '_self').close();

Can two or more people edit an Excel document at the same time?

yes if it is SharePoint 2010 and above by using the Office feature co-authoring

Python json.loads shows ValueError: Extra data

One-liner for your problem:

data = [json.loads(line) for line in open('tweets.json', 'r')]

JPanel vs JFrame in Java

You should not extend the JFrame class unnecessarily (only if you are adding extra functionality to the JFrame class)

JFrame:

JFrame extends Component and Container.

It is a top level container used to represent the minimum requirements for a window. This includes Borders, resizability (is the JFrame resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Events like windowClose, windowOpened etc.

JPanel:

JPanel extends Component, Container and JComponent

It is a generic class used to group other Components together.

  • It is useful when working with LayoutManagers e.g. GridLayout f.i adding components to different JPanels which will then be added to the JFrame to create the gui. It will be more manageable in terms of Layout and re-usability.

  • It is also useful for when painting/drawing in Swing, you would override paintComponent(..) and of course have the full joys of double buffering.

A Swing GUI cannot exist without a top level container like (JWindow, Window, JFrame Frame or Applet), while it may exist without JPanels.

How to set -source 1.7 in Android Studio and Gradle

Java 7 support was added at build tools 19. You can now use features like the diamond operator, multi-catch, try-with-resources, strings in switches, etc. Add the following to your build.gradle.

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.0"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 19
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

Gradle 1.7+, Android gradle plugin 0.6.+ are required.

Note, that only try with resources require minSdkVersion 19. Other features works on previous platforms.

Link to android gradle plugin user guide

Link to see how source vs target are different

How to get input field value using PHP

For global use, you may use:

$val = $_REQUEST['subject'];

and to add yo your session, simply

session_start();
$_SESSION['subject'] =  $val;

And you dont need jQuery in this case.

What do the different readystates in XMLHttpRequest mean, and how can I use them?

kieron's answer contains w3schools ref. to which nobody rely , bobince's answer gives link , which actually tells native implementation of IE ,

so here is the original documentation quoted to rightly understand what readystate represents :

The XMLHttpRequest object can be in several states. The readyState attribute must return the current state, which must be one of the following values:

UNSENT (numeric value 0)
The object has been constructed.

OPENED (numeric value 1)
The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.

HEADERS_RECEIVED (numeric value 2)
All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.

LOADING (numeric value 3)
The response entity body is being received.

DONE (numeric value 4)
The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).

Please Read here : W3C Explaination Of ReadyState

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

I was also facing this issue

Error- Windows cannot find 'http://127.0.01:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

After some research work, I found out that my HTTPPORT ie. 8080 was occupied by Apace HTTP Server and hence connection by OracleServiceXE could not be established.

What I did to solve this issue was :

  1. Go to Windows -> Services, found out Apache2.4 and manually stopped it to free my 8080 port.
  2. Clicked on Start Database, and I received message :

The OracleServiceXE service is starting.............. The OracleServiceXE service was started successfully.

  1. Manually entered http://127.0.0.1:8080/apex/f?p=4950 url to my browser which auto redirected me to http://127.0.0.1:8080/apex/f?p=4950:1:3763261197573303

That's it my issue got resolved.

In order to remember this new url and make sure that next time whenever I hit Get Started I should be redirected to http://127.0.0.1:8080/apex/f?p=4950:1:3763261197573303 instead of http://127.0.0.1:8080/apex/f?p=4950, what I did was :

  1. Browse to Directory:\OracleDatabase\app\oracle\product\11.2.0\server and search for Get_Started.html.
  2. Right Click on Get_Started.html and select Properties
  3. Modify your url and click Apply

Hope this Helps.

Best practices for copying files with Maven

I can only assume that your ${project.server.config} property is something custom defined and is outside of the standard directory layout.

If so, then I'd use the copy task.

MongoDB or CouchDB - fit for production?

We are currently using MongoDB in production as the caching layer as well as storage engine for product importing and manipulating product data. We are an eCommerce company managing over two million products (100+ million attributes), spanning 10+ distributors and without MongoDB, this task would be nearing impossible.

Setting Django up to use MySQL

If you are using python3.x then Run below command

pip install mysqlclient

Then change setting.py like

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'DB',
     'USER': 'username',
    'PASSWORD': 'passwd',
  }
  }

SQL to LINQ Tool

Bill Horst's - Converting SQL to LINQ is a very good resource for this task (as well as LINQPad).

LINQ Tools has a decent list of tools as well but I do not believe there is anything else out there that can do what Linqer did.


Generally speaking, LINQ is a higher-level querying language than SQL which can cause translation loss when trying to convert SQL to LINQ. For one, LINQ emits shaped results and SQL flat result sets. The issue here is that an automatic translation from SQL to LINQ will often have to perform more transliteration than translation - generating examples of how NOT to write LINQ queries. For this reason, there are few (if any) tools that will be able to reliably convert SQL to LINQ. Analogous to learning C# 4 by first converting VB6 to C# 4 and then studying the resulting conversion.

best way to get the key of a key/value javascript object

I was having the same problem and this is what worked

//example of an Object
var person = {
    firstName:"John",
    lastName:"Doe",
    age:50,
    eyeColor:"blue"
};

//How to access a single key or value
var key = Object.keys(person)[0];
var value = person.firstName;

Android appcompat v7:23

Original answer:

I too tried to change the support library to "23". When I changed the targetSdkVersion to 23, Android Studio reported the following error:

This support library should not use a lower version (22) than the targetSdkVersion (23)

I simply changed:

compile 'com.android.support:appcompat-v7:23.0.0'

to

compile 'com.android.support:appcompat-v7:+'

Although this fixed my issue, you should not use dynamic versions. After a few hours the new support repository was available and it is currently 23.0.1.


Pro tip:

You can use double quotes and create a ${supportLibVersion} variable for simplicity. Example:

ext {
    supportLibVersion = '23.1.1'
}

compile "com.android.support:appcompat-v7:${supportLibVersion}"
compile "com.android.support:design:${supportLibVersion}"
compile "com.android.support:palette-v7:${supportLibVersion}"
compile "com.android.support:customtabs:${supportLibVersion}"
compile "com.android.support:gridlayout-v7:${supportLibVersion}"

source: https://twitter.com/manidesto/status/669195097947377664

Using an image caption in Markdown Jekyll

Andrew's @andrew-wei answer works great. You can also chain a few together, depending on what you are trying to do. This, for example, gets you an image with alt, title and caption with a line break and bold and italics in different parts of the caption:

img + br + strong {margin-top: 5px; margin-bottom: 7px; font-style:italic; font-size: 12px; }
img + br + strong + em {margin-top: 5px; margin-bottom: 7px; font-size: 12px; font-style:italic;}

With the following <img> markdown:

![description](https://img.jpg "description")
***Image:*** *description*

How to split a string by spaces in a Windows batch file?

Three possible solutions to iterate through the words of the string:

Version 1:

@echo off & setlocal
set s=AAA BBB CCC DDD EEE FFF
for %%a in (%s%) do echo %%a

Version 2:

@echo off & setlocal
set s=AAA BBB CCC DDD EEE FFF
set t=%s%
:loop
for /f "tokens=1*" %%a in ("%t%") do (
   echo %%a
   set t=%%b
   )
if defined t goto :loop

Version 3:

@echo off & setlocal
set s=AAA BBB CCC DDD EEE FFF
call :sub1 %s%
exit /b
:sub1
if "%1"=="" exit /b
echo %1
shift
goto :sub1

Version 1 does not work when the string contains wildcard characters like '*' or '?'.

Versions 1 and 3 treat characters like '=', ';' or ',' as word separators. These characters have the same effect as the space character.

How to detect the OS from a Bash script?

For my .bashrc, I use the following code:

platform='unknown'
unamestr=`uname`
if [[ "$unamestr" == 'Linux' ]]; then
   platform='linux'
elif [[ "$unamestr" == 'FreeBSD' ]]; then
   platform='freebsd'
fi

Then I do somethings like:

if [[ $platform == 'linux' ]]; then
   alias ls='ls --color=auto'
elif [[ $platform == 'freebsd' ]]; then
   alias ls='ls -G'
fi

It's ugly, but it works. You may use case instead of if if you prefer.

Block direct access to a file over http but allow php script access

Are the files on the same server as the PHP script? If so, just keep the files out of the web root and make sure your PHP script has read permissions for wherever they're stored.

Expand a random range from 1–5 to 1–7

int rand7()
{
    int zero_one_or_two = ( rand5() + rand5() - 1 ) % 3 ;
    return rand5() + zero_one_or_two ;
}

Returning a boolean value in a JavaScript function

You could simplify this a lot:

  • Check whether one is not empty
  • Check whether they are equal

This will result in this, which will always return a boolean. Your function also should always return a boolean, but you can see it does a little better if you simplify your code:

function validatePassword()
{
   var password = document.getElementById("password");
   var confirm_password = document.getElementById("password_confirm");

   return password.value !== "" && password.value === confirm_password.value;
       //       not empty       and              equal
}

simple vba code gives me run time error 91 object variable or with block not set

Also you are trying to set value2 using Set keyword, which is not required. You can directly use rng.value2 = 1

below test code for ref.

Sub test()
    Dim rng As Range
    Set rng = Range("A1")
    rng.Value2 = 1
End Sub

findViewByID returns null

In my case, I was using ExpandableListView and I had set android:transcriptMode="normal". This was causing few children in expandable group to disappear and I used to get NULL exception when ever I used scroll the list.

How to wait for all threads to finish, using ExecutorService?

You could use this code:

public class MyTask implements Runnable {

    private CountDownLatch countDownLatch;

    public MyTask(CountDownLatch countDownLatch {
         this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
         try {
             //Do somethings
             //
             this.countDownLatch.countDown();//important
         } catch (InterruptedException ex) {
              Thread.currentThread().interrupt();
         }
     }
}

CountDownLatch countDownLatch = new CountDownLatch(NUMBER_OF_TASKS);
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
for (int i = 0; i < NUMBER_OF_TASKS; i++){
     taskExecutor.execute(new MyTask(countDownLatch));
}
countDownLatch.await();
System.out.println("Finish tasks");

How to convert a String to JsonObject using gson library

String emailData = {"to": "[email protected]","subject":"User details","body": "The user has completed his training"
}

// Java model class
public class EmailData {
    public String to;
    public String subject;
    public String body;
}

//Final Data
Gson gson = new Gson();  
EmailData emaildata = gson.fromJson(emailData, EmailData.class);

What does "Git push non-fast-forward updates were rejected" mean?

A fast-forward update is where the only changes one one side are after the most recent commit on the other side, so there doesn't need to be any merging. This is saying that you need to merge your changes before you can push.

ENOENT, no such file or directory

  1. First try npm install ,if the issue is not yet fixed try the following one after the other.
  2. npm cache clean ,then
  3. npm install -g npm,then npm install,Finally
  4. ng serve --o to run the project. Hope this will help....

Adding elements to object

 function addValueInObject(value, object, key) {

        var addMoreOptions = eval('{"'  + key + '":' +  value + '}');

        if(addMoreOptions != null) {
            var textObject = JSON.stringify(object);
            textObject = textObject.substring(1,textObject.length-1);
            var AddElement = JSON.stringify(addMoreOptions);
            object = eval('{' + textObject +','+  AddElement.substring(1,AddElement.length-1) + '}');
        }
        return object;
    }

addValueInObject('sdfasfas', yourObject, 'keyname');

OR:

var obj = {'key':'value'};

obj.key2 = 'value2';

How to drop all stored procedures at once in SQL Server database?

ANSI compliant, without cursor

DECLARE @SQL national character varying(MAX) 
SET @SQL= ''

SELECT @SQL= @SQL+ N'DROP PROCEDURE "' + REPLACE(SPECIFIC_SCHEMA, N'"', N'""') + N'"."' + REPLACE(SPECIFIC_NAME, N'"', N'""') + N'"; '
FROM INFORMATION_SCHEMA.ROUTINES 

WHERE (1=1) 
AND ROUTINE_TYPE = 'PROCEDURE' 
AND ROUTINE_NAME NOT IN 
(
     'dt_adduserobject'
    ,'dt_droppropertiesbyid'
    ,'dt_dropuserobjectbyid'
    ,'dt_generateansiname'
    ,'dt_getobjwithprop'
    ,'dt_getobjwithprop_u'
    ,'dt_getpropertiesbyid'
    ,'dt_getpropertiesbyid_u'
    ,'dt_setpropertybyid'
    ,'dt_setpropertybyid_u'
    ,'dt_verstamp006'
    ,'dt_verstamp007'

    ,'sp_helpdiagrams'
    ,'sp_creatediagram'
    ,'sp_alterdiagram'
    ,'sp_renamediagram'
    ,'sp_dropdiagram'

    ,'sp_helpdiagramdefinition'
    ,'fn_diagramobjects'
    ,'sp_upgraddiagrams'
) 


ORDER BY SPECIFIC_NAME 


-- PRINT @SQL
EXEC(@SQL) 

Without cursor, non-ansi compliant:

DECLARE @sql NVARCHAR(MAX) = N''
, @lineFeed NVARCHAR(2) = CHAR(13) + CHAR(10) ;

SELECT @sql = @sql + N'DROP PROCEDURE ' + QUOTENAME(SPECIFIC_SCHEMA) + N'.' + QUOTENAME(SPECIFIC_NAME) + N';' + @lineFeed
FROM INFORMATION_SCHEMA.ROUTINES 
WHERE ROUTINE_TYPE = 'PROCEDURE' 
-- AND SPECIFIC_NAME LIKE 'sp[_]RPT[_]%'


AND ROUTINE_NAME NOT IN 
( 
    SELECT name FROM sys.procedures WHERE is_ms_shipped <> 0 
) 


ORDER BY SPECIFIC_NAME 


-- PRINT @sql 
EXECUTE(@sql)

How to decrypt hash stored by bcrypt

You can use the password_verify function with the PHP. It verifies that a password matches with the hash

password_verify ( string $password , string $hash ) : bool

more details: https://www.php.net/manual/en/function.password-verify.php

Page redirect after certain time PHP

You can try this:

header('Refresh: 10; URL=http://yoursite.com/page.php');

Where 10 is in seconds.

Android Debug Bridge (adb) device - no permissions

The output of ls -al /usr/bin/adb should show that it is owned by user root and group root. You can use Linux ACL (Access Control Lists) to give your local user permissions for adb as follows:

setfacl -m "u:userName:rwx" /usr/bin/adb

This is preferable to setting the SUID bit on /usr/bin/adb and also limits the users who can use adb to userName and root.

How to install older version of node.js on Windows?

run:

npm install -g [email protected]

- or whatever version you want after the @ symbol (This works as of 2019)

How do I find the length/number of items present for an array?

I'm not sure that i know exactly what you mean.

But to get the length of an initialized array,

doesn't strlen(string) work ??

How to change date format in JavaScript

Try -

var monthNames = [ "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December" ];

var newDate = new Date(form.startDate.value);
var formattedDate = monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear();

Is it possible to use Java 8 for Android development?

UPDATE 2019/10/28

Android Studio 4.0 solves this issue.

The D8 compiler patches a backport of the Java 8 native APIs into your APK at compile time and your app will use that code, instead of the native APIs, at runtime. The process is called desugaring.

The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked

I had the same issue (EF Core) while setting up xUnit tests. What 'fixed' it for me in testing was looping through the change tracker entities after setting up the seed data.

  • at the bottom of the SeedAppDbContext() method.

I set up a Test Mock Context:

/// <summary>
/// Get an In memory version of the app db context with some seeded data
/// </summary>
public static AppDbContext GetAppDbContext(string dbName)
{
    //set up the options to use for this dbcontext
    var options = new DbContextOptionsBuilder<AppDbContext>()
        .UseInMemoryDatabase(databaseName: dbName)
        //.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
        .Options;

    var dbContext = new AppDbContext(options);
    dbContext.SeedAppDbContext();
    return dbContext;
}

Extension method to add some seed data:

  • and detach entities in foreach loop at bottom of method.
    public static void SeedAppDbContext(this AppDbContext appDbContext)
    {
       // add companies
       var c1 = new Company() { Id = 1, CompanyName = "Fake Company One", ContactPersonName = "Contact one", eMail = "[email protected]", Phone = "0123456789", AdminUserId = "" };
       c1.Address = new Address() { Id = 1, AddressL1 = "Field Farm", AddressL2 = "Some Lane", City = "some city", PostalCode = "AB12 3CD" };
       appDbContext.CompanyRecords.Add(c1);
                        
       var nc1 = new Company() { Id = 2, CompanyName = "Test Company 2", ContactPersonName = "Contact two", eMail = "[email protected]", Phone = "0123456789", Address = new Address() { }, AdminUserId = "" };
       nc1.Address = new Address() { Id = 2, AddressL1 = "The Barn", AddressL2 = "Some Lane", City = "some city", PostalCode = "AB12 3CD" };
       appDbContext.CompanyRecords.Add(nc1);

       //....and so on....
            
       //last call to commit everything to the memory db
       appDbContext.SaveChanges();

       //and then to detach everything 
       foreach (var entity in appDbContext.ChangeTracker.Entries())
       {
           entity.State = EntityState.Detached;
       }
    }

The controller put method

The .ConvertTo<>() Method is an extension method from ServiceStack

 [HttpPut]
public async Task<IActionResult> PutUpdateCompany(CompanyFullDto company)
{
    if (0 == company.Id)
        return BadRequest();
    try
    {
        Company editEntity = company.ConvertTo<Company>();
        
        //Prior to detaching an error thrown on line below (another instance with id)
        var trackedEntity = _appDbContext.CompanyRecords.Update(editEntity);
        

        await _appDbContext.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException dbError)
    {
        if (!CompanyExists(company.Id))
            return NotFound();
        else
            return BadRequest(dbError);
    }
    catch (Exception Error)
    {
        return BadRequest(Error);
    }
    return Ok();
}

and the test:

    [Fact]
    public async Task PassWhenEditingCompany()
    {
        var _appDbContext = AppDbContextMocker.GetAppDbContext(nameof(CompaniesController));
        var _controller = new CompaniesController(null, _appDbContext);

        //Arrange
        const string companyName = "Fake Company One";
        const string contactPerson = "Contact one";

        const string newCompanyName = "New Fake Company One";
        const string newContactPersonName = "New Contact Person";

        //Act
        var getResult = _controller.GetCompanyById(1);
        var getEntity = (getResult.Result.Result as OkObjectResult).Value;
        var entityDto = getEntity as CompanyFullDto;


        //Assert
        Assert.Equal(companyName, entityDto.CompanyName);
        Assert.Equal(contactPerson, entityDto.ContactPersonName);
        Assert.Equal(1, entityDto.Id);

        //Arrange
        Company entity = entityDto.ConvertTo<Company>();
        entity.CompanyName = newCompanyName;
        entity.ContactPersonName = newContactPersonName;
        CompanyFullDto entityDtoUpd = entity.ConvertTo<CompanyFullDto>();

        //Act
        var result = await _controller.PutUpdateCompany(entityDtoUpd) as StatusCodeResult;

        //Assert           
        Assert.True(result.StatusCode == 200);

        //Act
        getResult = _controller.GetCompanyById(1);
        getEntity = (getResult.Result.Result as OkObjectResult).Value;
        
        entityDto = getEntity as CompanyFullDto;
        
        //Assert
        Assert.Equal(1, entityDto.Id); // didn't add a new record
        Assert.Equal(newCompanyName, entityDto.CompanyName); //updated the name
        Assert.Equal(newContactPersonName, entityDto.ContactPersonName); //updated the contact

//make sure to dispose of the _appDbContext otherwise running the full test will fail.
_appDbContext.Dispose();
    }

How to remove Left property when position: absolute?

In the future one would use left: unset; for unsetting the value of left.

As of today 4 nov 2014 unset is only supported in Firefox.

Read more about unset in MDN.

My guess is we'll be able to use it around year 2022 when IE 11 is properly phased out.

Checking to see if a DateTime variable has had a value assigned

do you mean like so:

DateTime datetime = new DateTime();

if (datetime == DateTime.MinValue)
{
    //unassigned
}

or you could use Nullable

DateTime? datetime = null;

 if (!datetime.HasValue)
 {
     //unassigned
 }

Get a list of numbers as input from the user

In Python 3.x, use this.

a = [int(x) for x in input().split()]

Example

>>> a = [int(x) for x in input().split()]
3 4 5
>>> a
[3, 4, 5]
>>> 

How can I display the current branch and folder path in terminal?

The git package installed on your system includes bash files to aid you in creating an informative prompt. To create colors, you will need to insert terminal escape sequences into your prompt. And, the final ingredient is to update your prompt after each command gets executed by using the built-in variable PROMPT_COMMAND.

Edit your ~/.bashrc to include the following, and you should get the prompt in your question, modulo some color differences.

#
# Git provides a bash file to create an informative prompt. This is its standard
# location on Linux. On Mac, you should be able to find it under your Git
# installation. If you are unable to find the file, I have a copy of it on my GitHub.
#
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/40-git-prompt.sh
#
source /usr/share/git/completion/git-prompt.sh

#
# Next, we need to define some terminal escape sequences for colors. For a fuller
# list of colors, and an example how to use them, see my bash color file on my GitHub
# and my coniguration for colored man pages.
#
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/10-colors.sh
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/40-less.sh
#
color_start='\e['
color_end='m'
color_reset='\e[0m'
color_bg_blue='44'

#
# To get a fancy git prompt, it's not sufficient to set PS1. Instead, we set PROMPT_COMMAND,
# a built in Bash variable that gets evaluated before each render of the prompt.
#
export PROMPT_COMMAND="PS1=\"\${color_start}\${color_bg_blue}\${color_end}\u@\h [\w\$(__git_ps1 \" - %s\")]\${color_reset}\n\$ \""

#
# If you find that the working directory that appears in the prompt is ofter too long,
# then trim it.
#
export PROMPT_DIRTRIM=3

How do I include a JavaScript script file in Angular and call a function from that script?

Refer the scripts inside the angular-cli.json (angular.json when using angular 6+) file.

"scripts": [
    "../path" 
 ];

then add in typings.d.ts (create this file in src if it does not already exist)

declare var variableName:any;

Import it in your file as

import * as variable from 'variableName';

How do I increase the cell width of the Jupyter/ipython notebook in my browser?

If you don't want to change your default settings, and you only want to change the width of the current notebook you're working on, you can enter the following into a cell:

from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))

How to download an entire directory and subdirectories using wget?

You can use this in a shell:

wget -r -nH --cut-dirs=7 --reject="index.html*" \
      http://abc.tamu.edu/projects/tzivi/repository/revisions/2/raw/tzivi/

The Parameters are:

-r recursively download

-nH (--no-host-directories) cuts out hostname 

--cut-dirs=X (cuts out X directories)

How to comment out a block of Python code in Vim

Frankly I use a tcomment plugin for that link. It can handle almost every syntax. It defines nice movements, using it with some text block matchers specific for python makes it a powerful tool.

Java - How to convert type collection into ArrayList?

As other people have mentioned, ArrayList has a constructor that takes a collection of items, and adds all of them. Here's the documentation:

http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html#ArrayList%28java.util.Collection%29

So you need to do:

ArrayList<MyNode> myNodeList = new ArrayList<MyNode>(this.getVertices());

However, in another comment you said that was giving you a compiler error. It looks like your class MyGraph is a generic class. And so getVertices() actually returns type V, not type myNode.

I think your code should look like this:

public V getNode(int nodeId){
        ArrayList<V> myNodeList = new ArrayList<V>(this.getVertices());
        return myNodeList(nodeId);
}

But, that said it's a very inefficient way to extract a node. What you might want to do is store the nodes in a binary tree, then when you get a request for the nth node, you do a binary search.

Taskkill /f doesn't kill a process

I had the exact same issue, found this fix on another site: powershell.exe "Get-Process processname| Stop-Process" it worked for me and I was in the same boat where I had to restart, the /T would not work.

Django template how to look up a dictionary value with a variable

env: django 2.1.7

view:

dict_objs[query_obj.id] = {'obj': query_obj, 'tag': str_tag}
return render(request, 'obj.html', {'dict_objs': dict_objs})

template:

{% for obj_id,dict_obj in dict_objs.items %}
<td>{{ dict_obj.obj.obj_name }}</td>
<td style="display:none">{{ obj_id }}</td>
<td>{{ forloop.counter }}</td>
<td>{{ dict_obj.obj.update_timestamp|date:"Y-m-d H:i:s"}}</td>

Detect Android phone via Javascript / jQuery

js version, catches iPad too:

var is_mobile = /mobile|android/i.test (navigator.userAgent);

How to change package name in flutter?

Change App Package Name easily using change_app_package_name package

just add the above package in dev dependencies

dev_dependencies:
  flutter_test:
    sdk: flutter
  change_app_package_name: ^0.1.2

and run the following command, replace "com.new.package.name" with your new package name

flutter pub run change_app_package_name:main com.new.package.name

Package Link on Pub Dev

screenshot of Package