Programs & Examples On #Cdma

Code division multiple access (CDMA): the channel access method. Also common name for mobile phone standards cdmaOne, CDMA2000...

How to display Woocommerce product price by ID number on a custom page?

If you have the product's ID you can use that to create a product object:

$_product = wc_get_product( $product_id );

Then from the object you can run any of WooCommerce's product methods.

$_product->get_regular_price();
$_product->get_sale_price();
$_product->get_price();

Update
Please review the Codex article on how to write your own shortcode.

Integrating the WooCommerce product data might look something like this:

function so_30165014_price_shortcode_callback( $atts ) {
    $atts = shortcode_atts( array(
        'id' => null,
    ), $atts, 'bartag' );

    $html = '';

    if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
         $_product = wc_get_product( $atts['id'] );
         $html = "price = " . $_product->get_price();
    }
    return $html;
}
add_shortcode( 'woocommerce_price', 'so_30165014_price_shortcode_callback' );

Your shortcode would then look like [woocommerce_price id="99"]

How to get the device's IMEI/ESN programmatically in android?

For those looking for a Kotlin version, you can use something like this;

private fun telephonyService() {
    val telephonyManager = getSystemService(TELEPHONY_SERVICE) as TelephonyManager
    val imei = if (android.os.Build.VERSION.SDK_INT >= 26) {
        Timber.i("Phone >= 26 IMEI")
        telephonyManager.imei
    } else {
        Timber.i("Phone IMEI < 26")
        telephonyManager.deviceId
    }

    Timber.i("Phone IMEI $imei")
}

NOTE: You must wrap telephonyService() above with a permission check using checkSelfPermission or whatever method you use.

Also add this permission in the manifest file;

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

How to get textLabel of selected row in swift?

In my case I made small changes, when i search the value in tabelview select (didSelectRowAtIndexPath) the cell its return the index of the cell so im get problem in move one viewControler to another.By using this method i found a solution to redirect to a new viewControler

let indexPath = tableView.indexPathForSelectedRow!
let currentCellValue = tableView.cellForRow(at: indexPath!)! as UITableViewCell
let textLabelText = currentCellValue.textLabel!.text
print(textLabelText) 

Plot Normal distribution with Matplotlib

Note: This solution is using pylab, not matplotlib.pyplot

You may try using hist to put your data info along with the fitted curve as below:

import numpy as np
import scipy.stats as stats
import pylab as pl

h = sorted([186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180])  #sorted

fit = stats.norm.pdf(h, np.mean(h), np.std(h))  #this is a fitting indeed

pl.plot(h,fit,'-o')

pl.hist(h,normed=True)      #use this to draw histogram of your data

pl.show()                   #use may also need add this 

enter image description here

change <audio> src with javascript

with jQuery:

 $("#playerSource").attr("src", "new_src");

    var audio = $("#player");      

    audio[0].pause();
    audio[0].load();//suspends and restores all audio element

    if (isAutoplay) 
        audio[0].play();

Passing multiple variables to another page in url

Use & for this. Using & you can put as many variables as you want!

$url = "http://localhost/main.php?event_id=".$event_id."&email=".$email;

How to know installed Oracle Client is 32 bit or 64 bit?

One thing that was super easy and worked well for me was doing a TNSPing from a cmd prompt:

TNS Ping Utility for 32-bit Windows: Version 11.2.0.3.0 - Production on 13-MAR-2015 16:35:32

TSQL select into Temp table from dynamic sql

declare @sql varchar(100);

declare @tablename as varchar(100);

select @tablename = 'your_table_name';

create table #tmp 
    (col1 int, col2 int, col3 int);

set @sql = 'select aa, bb, cc from ' + @tablename;

insert into #tmp(col1, col2, col3) exec( @sql );

select * from #tmp;

For each row in an R dataframe

You can try this, using apply() function

> d
  name plate value1 value2
1    A    P1      1    100
2    B    P2      2    200
3    C    P3      3    300

> f <- function(x, output) {
 wellName <- x[1]
 plateName <- x[2]
 wellID <- 1
 print(paste(wellID, x[3], x[4], sep=","))
 cat(paste(wellID, x[3], x[4], sep=","), file= output, append = T, fill = T)
}

> apply(d, 1, f, output = 'outputfile')

What's an object file in C?

  1. An Object file is the compiled file itself. There is no difference between the two.

  2. An executable file is formed by linking the Object files.

  3. Object file contains low level instructions which can be understood by the CPU. That is why it is also called machine code.

  4. This low level machine code is the binary representation of the instructions which you can also write directly using assembly language and then process the assembly language code (represented in English) into machine language (represented in Hex) using an assembler.

Here's a typical high level flow for this process for code in High Level Language such as C

--> goes through pre-processor

--> to give optimized code, still in C

--> goes through compiler

--> to give assembly code

--> goes through an assembler

--> to give code in machine language which is stored in OBJECT FILES

--> goes through Linker

--> to get an executable file.

This flow can have some variations for example most compilers can directly generate the machine language code, without going through an assembler. Similarly, they can do the pre-processing for you. Still, it is nice to break up the constituents for a better understanding.

Reading a text file in MATLAB line by line

You cannot read text strings with csvread. Here is another solution:

fid1 = fopen('test.csv','r'); %# open csv file for reading
fid2 = fopen('new.csv','w'); %# open new csv file
while ~feof(fid1)
    line = fgets(fid1); %# read line by line
    A = sscanf(line,'%*[^,],%f,%f'); %# sscanf can read only numeric data :(
    if A(2)<4.185 %# test the values
        fprintf(fid2,'%s',line); %# write the line to the new file
    end
end
fclose(fid1);
fclose(fid2);

Optimistic vs. Pessimistic locking

Optimistic Locking is a strategy where you read a record, take note of a version number (other methods to do this involve dates, timestamps or checksums/hashes) and check that the version hasn't changed before you write the record back. When you write the record back you filter the update on the version to make sure it's atomic. (i.e. hasn't been updated between when you check the version and write the record to the disk) and update the version in one hit.

If the record is dirty (i.e. different version to yours) you abort the transaction and the user can re-start it.

This strategy is most applicable to high-volume systems and three-tier architectures where you do not necessarily maintain a connection to the database for your session. In this situation the client cannot actually maintain database locks as the connections are taken from a pool and you may not be using the same connection from one access to the next.

Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking but requires you to be careful with your application design to avoid Deadlocks. To use pessimistic locking you need either a direct connection to the database (as would typically be the case in a two tier client server application) or an externally available transaction ID that can be used independently of the connection.

In the latter case you open the transaction with the TxID and then reconnect using that ID. The DBMS maintains the locks and allows you to pick the session back up through the TxID. This is how distributed transactions using two-phase commit protocols (such as XA or COM+ Transactions) work.

How to cast int to enum in C++?

Test castEnum = static_cast<Test>(a-1); will cast a to A. If you don't want to substruct 1, you can redefine the enum:

enum Test
{
    A:1, B
};

In this case Test castEnum = static_cast<Test>(a); could be used to cast a to A.

Immutable vs Mutable types

Difference between Mutable and Immutable objects

Definitions

Mutable object: Object that can be changed after creating it.
Immutable object: Object that cannot be changed after creating it.

In python if you change the value of the immutable object it will create a new object.

Mutable Objects

Here are the objects in Python that are of mutable type:

  1. list
  2. Dictionary
  3. Set
  4. bytearray
  5. user defined classes

Immutable Objects

Here are the objects in Python that are of immutable type:

  1. int
  2. float
  3. decimal
  4. complex
  5. bool
  6. string
  7. tuple
  8. range
  9. frozenset
  10. bytes

Some Unanswered Questions

Questions: Is string an immutable type?
Answer: yes it is, but can you explain this: Proof 1:

a = "Hello"
a +=" World"
print a

Output

"Hello World"

In the above example the string got once created as "Hello" then changed to "Hello World". This implies that the string is of the mutable type. But it is not when we check its identity to see whether it is of a mutable type or not.

a = "Hello"
identity_a = id(a)
a += " World"
new_identity_a = id(a)
if identity_a != new_identity_a:
    print "String is Immutable"

Output

String is Immutable

Proof 2:

a = "Hello World"
a[0] = "M"

Output

TypeError 'str' object does not support item assignment

Questions: Is Tuple an immutable type?
Answer: yes, it is. Proof 1:

tuple_a = (1,)
tuple_a[0] = (2,)
print a

Output

'tuple' object does not support item assignment

Delete last char of string

strgroupids = strgroupids.Remove(strgroupids.Length - 1);

MSDN:

String.Remove(Int32):

Deletes all the characters from this string beginning at a specified position and continuing through the last position

How do you format an unsigned long long int using printf?

%d--> for int

%u--> for unsigned int

%ld--> for long int or long

%lu--> for unsigned long int or long unsigned int or unsigned long

%lld--> for long long int or long long

%llu--> for unsigned long long int or unsigned long long

How to get date, month, year in jQuery UI datepicker?

what about that simple way)

$(document).ready ->
 $('#datepicker').datepicker( dateFormat: 'yy-mm-dd',  onSelect: (dateStr) ->
    alert dateStr # yy-mm-dd
    #OR
    alert $("#datepicker").val(); # yy-mm-dd

Removing specific rows from a dataframe

DF[ ! ( ( DF$sub ==1 & DF$day==2) | ( DF$sub ==3 & DF$day==4) ) , ]   # note the ! (negation)

Or if sub is a factor as suggested by your use of quotes:

DF[ ! paste(sub,day,sep="_") %in% c("1_2", "3_4"), ]

Could also use subset:

subset(DF,  ! paste(sub,day,sep="_") %in% c("1_2", "3_4") )

(And I endorse the use of which in Dirk's answer when using "[" even though some claim it is not needed.)

How to get the last row of an Oracle a table

You can do it like this:

SELECT * FROM (SELECT your_table.your_field, versions_starttime
               FROM your_table
               VERSIONS BETWEEN TIMESTAMP MINVALUE AND MAXVALUE)
WHERE ROWNUM = 1;

Or:

SELECT your_field,ora_rowscn,scn_to_timestamp(ora_rowscn) from your_table WHERE ROWNUM = 1;

Comparing the contents of two files in Sublime Text

View - Layout and View - Groups will do in latest Sublime 3

eg:

Shift+Alt+2 --> creates 2 columns

Ctrl+2 --> move selected file to column 2

This is for side by side comparison. For actual diff, there is the diff function other already mentioned. Unfortunately, I can't find a way to make columns scroll at the same time, which would be a nice feature.

How to perform Unwind segue programmatically?

Here's a complete answer with Objective C and Swift:

1) Create an IBAction unwind segue in your destination view controller (where you want to segue to). Anywhere in the implementation file.

// Objective C

    - (IBAction)unwindToContainerVC:(UIStoryboardSegue *)segue {

    }

// Swift

 @IBAction func unwindToContainerVC(segue: UIStoryboardSegue) {

    }

2) On the source view controller (the controller you're segueing from), ^ + drag from "Name of activity" to exit. You should see the unwind segue created in step 1 in the popup. (If you don't see it, review step one). Pick unwindToContainerVC: from the popup, or whatever you named your method to connect your source controller to the unwind IBAction.

enter image description here

3) Select the segue in the source view controller's document outline of the storyboard (it will be listed near the bottom), and give it an identifier.

enter image description here

4) Call the unwind segue using this method from source view controller, substituting your unwind segue name.

// Objective C

[self performSegueWithIdentifier:@"unwindToContainerVC" sender:self];

// Swift

self.performSegueWithIdentifier("unwindToContainerVC", sender: self)

NB. Use the sourceViewController property of the segue parameter on the unwind method to access any exposed properties on the source controller. Also, notice that the framework handles dismissing the source controller. If you'd like to confirm this add a dealloc method to the source controller with a log message that should fire once it has been killed. If dealloc doesn't fire you may have a retain cycle.

Removing multiple files from a Git repo that have already been deleted from disk

You can use git add -u <filenames> to stage the deleted files only.

For example, if you deleted the files templates/*.tpl, then use git add -u templates/*.tpl.

The -u is required in order to refer to files that exist in the repository but no longer exist in the working directory. Otherwise, the default of git add is to look for the files in the working directory, and if you specify files you've deleted there, it won't find them.

How to send email from SQL Server?

You can send email natively from within SQL Server using Database Mail. This is a great tool for notifying sysadmins about errors or other database events. You could also use it to send a report or an email message to an end user. The basic syntax for this is:

EXEC msdb.dbo.sp_send_dbmail  
@recipients='[email protected]',
@subject='Testing Email from SQL Server',
@body='<p>It Worked!</p><p>Email sent successfully</p>',
@body_format='HTML',
@from_address='Sender Name <[email protected]>',
@reply_to='[email protected]'

Before use, Database Mail must be enabled using the Database Mail Configuration Wizard, or sp_configure. A database or Exchange admin might need to help you configure this. See http://msdn.microsoft.com/en-us/library/ms190307.aspx and http://www.codeproject.com/Articles/485124/Configuring-Database-Mail-in-SQL-Server for more information.

Get value of a string after last slash in JavaScript

String path ="AnyDirectory/subFolder/last.htm";
int pos = path.lastIndexOf("/") + 1;

path.substring(pos, path.length()-pos) ;

Now you have the last.htm in the path string.

What does /p mean in set /p?

For future reference, you can get help for any command by using the /? switch, which should explain what switches do what.

According to the set /? screen, the format for set /p is SET /P variable=[promptString] which would indicate that the p in /p is "prompt." It just prints in your example because <nul passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.

/L in for /L generates a List of numbers.

From ping /?:

Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
            [-r count] [-s count] [[-j host-list] | [-k host-list]]
            [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name

Options:
    -t             Ping the specified host until stopped.
                   To see statistics and continue - type Control-Break;
                   To stop - type Control-C.
    -a             Resolve addresses to hostnames.
    -n count       Number of echo requests to send.
    -l size        Send buffer size.
    -f             Set Don't Fragment flag in packet (IPv4-only).
    -i TTL         Time To Live.
    -v TOS         Type Of Service (IPv4-only. This setting has been deprecated
                   and has no effect on the type of service field in the IP Header).
    -r count       Record route for count hops (IPv4-only).
    -s count       Timestamp for count hops (IPv4-only).
    -j host-list   Loose source route along host-list (IPv4-only).
    -k host-list   Strict source route along host-list (IPv4-only).
    -w timeout     Timeout in milliseconds to wait for each reply.
    -R             Use routing header to test reverse route also (IPv6-only).
    -S srcaddr     Source address to use.
    -4             Force using IPv4.
    -6             Force using IPv6.

jQuery autohide element after 5 seconds

$(function() {
    // setTimeout() function will be fired after page is loaded
    // it will wait for 5 sec. and then will fire
    // $("#successMessage").hide() function
    setTimeout(function() {
        $("#successMessage").hide('blind', {}, 500)
    }, 5000);
});

Note: In order to make you jQuery function work inside setTimeout you should wrap it inside

function() { ... }

updating nodejs on ubuntu 16.04

According to official docs to install node on Debian and Ubuntu based distributions:

node v12 (Old)

curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
sudo apt-get install -y nodejs

node v14 (For new users: install this one):

curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs

node v15 (Current version):

curl -sL https://deb.nodesource.com/setup_15.x | sudo -E bash -
sudo apt-get install -y nodejs

Other older versions: Just replace the desired version number in the link above.

Optional: install build tools

To compile and install native packages

sudo apt-get install -y build-essential

To update node to the latest version just:

sudo apt update
sudo apt upgrade

To keep npm updated

sudo npm i -g npm

To find out other versions try npm info npm and in versions find your desired version and replace [version-tag] with that version tag in npm i -g npm@[version-tag]

And I also recommend trying yarn instead of npm

Count number of columns in a table row

Count all td in table1:

_x000D_
_x000D_
console.log(_x000D_
table1.querySelectorAll("td").length_x000D_
)
_x000D_
<table id="table1">_x000D_
<tr>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<table>
_x000D_
_x000D_
_x000D_

Count all td into each tr of table1.

_x000D_
_x000D_
table1.querySelectorAll("tr").forEach(function(e){_x000D_
 console.log( e.querySelectorAll("td").length )_x000D_
})
_x000D_
<table id="table1">_x000D_
<tr>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<table>
_x000D_
_x000D_
_x000D_

How to make a machine trust a self-signed Java application

I was having the same issue. So I went to the Java options through Control Panel. Copied the web address that I was having an issue with to the exceptions and it was fixed.

Git - remote: Repository not found

I had the same issue after I set up 2FA on my repo. If you recently set up 2FA on your account, here's what I did to solve it:

Generate a personal access token

Go to Settings -> Developer Settings -> Personal Access Tokens on your GitHub account. Generate a new personal access token. Make sure to check all repo-access related permissions.

Delete all GitHub authentication configuration (from keychain for Mac)

You'll need to sign in afresh using the generated Personal Access Token, so clear all previous authentication details from your laptop. For mac, open keychain and delete all github.com related details from the login/passwords section.

Sign in to your terminal with your GitHub username and PAT as password.

If you've set up 2FA on your account, you won't be able to authenticate using your GitHub password from the terminal. Now, attempt to push to a GitHub repo to trigger a need for authentication. A request to enter your GitHub username will pop up on your terminal. Enter your username, and when prompted for a password, use the generated Personal Access Token as password.

These exact steps solved the problem for me.

Visual Studio Code cannot detect installed git

Follow this :

1. File > Preferences > setting
2. In search type -> git path
3. Now scroll down a little > you will see "Git:path" section.
4. Click "Edit in settings.json".
5. Now just paste this path there "C:\\Program Files\\Git\\mingw64\\libexec\\git-core\\git.exe"

Restart VSCode and open new terminal in VSCode and try "git version"


In case still problem exists :

1. Inside terminal click on terminal options (1:Poweshell)
2. Select default shell
3. Select bash

open new terminal and change terminal option to 2:Bash Again try "git version" - this should work :)


MemoryStream - Cannot access a closed Stream

Since .net45 you can use the LeaveOpen constructor argument of StreamWriter and still use the using statement. Example:

using (var ms = new MemoryStream())
{
    using (var sw = new StreamWriter(ms, Encoding.UTF8, 1024, true))
    {
        sw.WriteLine("data");
        sw.WriteLine("data 2");    
    }

    ms.Position = 0;
    using (var sr = new StreamReader(ms))
    {
        Console.WriteLine(sr.ReadToEnd());
    }
}

Delete the first five characters on any line of a text file in Linux with sed

sed 's/^.\{,5\}//' file.dat worked like a charm for me

Why shouldn't I use mysql_* functions in PHP?

Because (amongst other reasons) it's much harder to ensure the input data is sanitized. If you use parametrized queries, as one does with PDO or mysqli you can entirely avoid the risk.

As an example, someone could use "enhzflep); drop table users" as a username. The old functions will allow executing multiple statements per query, so something like that nasty bugger can delete a whole table.

If one were to use PDO of mysqli, the user-name would end-up being "enhzflep); drop table users".

See bobby-tables.com.

restrict edittext to single line

android:maxLines="1"
android:inputType="text"

Add the above code to have a single line in EditText tag in your layout.

android:singleLine="true" is deprecated

This constant was deprecated in API level 3.

This attribute is deprecated. Use maxLines instead to change the layout of a static text, and use the textMultiLine flag in the inputType attribute instead for editable text views (if both singleLine and inputType are supplied, the inputType flags will override the value of singleLine).

Access cell value of datatable

You can also try (first cell in 4th column):

dt.Rows[0][3]

Text-decoration: none not working

Try placing your text-decoration: none; on your a:hover css.

Where can I read the Console output in Visual Studio 2015

The simple way is using System.Diagnostics.Debug.WriteLine()

Your can then read what you're writing to the output by clicking the menu "DEBUG" -> "Windows" -> "Output".

htons() function in socket programing

It has to do with the order in which bytes are stored in memory. The decimal number 5001 is 0x1389 in hexadecimal, so the bytes involved are 0x13 and 0x89. Many devices store numbers in little-endian format, meaning that the least significant byte comes first. So in this particular example it means that in memory the number 5001 will be stored as

0x89 0x13

The htons() function makes sure that numbers are stored in memory in network byte order, which is with the most significant byte first. It will therefore swap the bytes making up the number so that in memory the bytes will be stored in the order

0x13 0x89

On a little-endian machine, the number with the swapped bytes is 0x8913 in hexadecimal, which is 35091 in decimal notation. Note that if you were working on a big-endian machine, the htons() function would not need to do any swapping since the number would already be stored in the right way in memory.

The underlying reason for all this swapping has to do with the network protocols in use, which require the transmitted packets to use network byte order.

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

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

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

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

SQL Server - stop or break execution of a SQL script

You can alter the flow of execution using GOTO statements:

IF @ValidationResult = 0
BEGIN
    PRINT 'Validation fault.'
    GOTO EndScript
END

/* our code */

EndScript:

How to check if a variable exists in a FreeMarker template?

I think a lot of people are wanting to be able to check to see if their variable is not empty as well as if it exists. I think that checking for existence and emptiness is a good idea in a lot of cases, and makes your template more robust and less prone to silly errors. In other words, if you check to make sure your variable is not null AND not empty before using it, then your template becomes more flexible, because you can throw either a null variable or an empty string into it, and it will work the same in either case.

<#if p?? && p?has_content>1</#if>

Let's say you want to make sure that p is more than just whitespace. Then you could trim it before checking to see if it has_content.

<#if p?? && p?trim?has_content>1</#if>

UPDATE

Please ignore my suggestion -- has_content is all that is needed, as it does a null check along with the empty check. Doing p?? && p?has_content is equivalent to p?has_content, so you may as well just use has_content.

Displaying splash screen for longer than default seconds

This works...

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Load Splash View Controller first
    self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"Splash"];
    self.window.rootViewController = viewController;
    [self.window makeKeyAndVisible];

    // Load other stuff that requires time

    // Now load the main View Controller that you want
}

asp.net: How can I remove an item from a dropdownlist?

You can use the

myDropDown.Items.Remove(ListItem li);

or

myDropDown.Items.RemoveAt(int index);

to remove it using C#.

Getting XML Node text value with Java DOM

If you are open to vtd-xml, which excels at both performance and memory efficiency, below is the code to do what you are looking for...in both XPath and manual navigation... the overall code is much concise and easier to understand ...

import com.ximpleware.*;
public class queryText {
    public static void main(String[] s) throws VTDException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", true))
            return;
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        // first manually navigate
        if(vn.toElement(VTDNav.FC,"tag")){
            int i= vn.getText();
            if (i!=-1){
                System.out.println("text ===>"+vn.toString(i));
            }
            if (vn.toElement(VTDNav.NS,"tag")){
                i=vn.getText();
                System.out.println("text ===>"+vn.toString(i));
            }
        }

        // second version use XPath
        ap.selectXPath("/add/tag/text()");
        int i=0;
        while((i=ap.evalXPath())!= -1){
            System.out.println("text node ====>"+vn.toString(i));
        }
    }
}

How to create Android Facebook Key Hash?

Easy way

By using this website you can get Hash Key by Converting SHA1 key to Hash Key for Facebook.

SQL where datetime column equals today's date?

Can you try this?

SELECT [Title], [Firstname], [Surname], [Company_name], [Interest] 
FROM [dbo].[EXTRANET_users] 
WHERE CAST(Submission_date AS DATE) = CAST(GETDATE() AS DATE)

T-SQL doesn't really have the "implied" casting like C# does - you need to explicitly use CAST (or CONVERT).

Also, use GETDATE() or CURRENT_TIMESTAMP to get the "now" date and time.

Update: since you're working against SQL Server 2000 - none of those approaches so far work. Try this instead:

SELECT [Title], [Firstname], [Surname], [Company_name], [Interest] 
FROM [dbo].[EXTRANET_users] 
WHERE DATEADD(dd, 0, DATEDIFF(dd, 0, submission_date)) = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))

How to fix date format in ASP .NET BoundField (DataFormatString)?

The following links will help you:

In Client side design page you can try this: {0:G}

OR

You can convert that datetime format inside the query itself from the database:

C++ JSON Serialization

Using quicktype, you can generate C++ serializers and deserializers from JSON sample data.

For example, given the sample JSON:

{
  "breed": "Boxer",
  "age": 5,
  "tail_length": 6.5
}

quicktype generates:

#include "json.hpp"

namespace quicktype {
    using nlohmann::json;

    struct Dog {
        int64_t age;
        std::string breed;
        double tail_length;
    };


    inline json get_untyped(const json &j, const char *property) {
        if (j.find(property) != j.end()) {
            return j.at(property).get<json>();
        }
        return json();
    }
}

namespace nlohmann {

    inline void from_json(const json& _j, struct quicktype::Dog& _x) {
        _x.age = _j.at("age").get<int64_t>();
        _x.breed = _j.at("breed").get<std::string>();
        _x.tail_length = _j.at("tail_length").get<double>();
    }

    inline void to_json(json& _j, const struct quicktype::Dog& _x) {
        _j = json{{"age", _x.age}, {"breed", _x.breed}, {"tail_length", _x.tail_length}};
    }
}

To parse the Dog JSON data, include the code above, install Boost and json.hpp, then do:

Dog dog = nlohmann::json::parse(jsonString);

How do you copy and paste into Git Bash

on my keyboard insert is located on the same key as a Printscreen. unfortunately, ctrl + ins doesn't work for me , so i descoved the following working combinations for me:

FN + CTRL + PRT SC - for copy

FN + SHIFT + PRT SC - for insert

How to while loop until the end of a file in Python without checking for empty line?

for line in f

reads all file to a memory, and that can be a problem.

My offer is to change the original source by replacing stripping and checking for empty line. Because if it is not last line - You will receive at least newline character in it ('\n'). And '.strip()' removes it. But in last line of a file You will receive truely empty line, without any characters. So the following loop will not give You false EOF, and You do not waste a memory:

with open("blablabla.txt", "r") as fl_in:
   while True:
      line = fl_in.readline()

        if not line:
            break

      line = line.strip()
      # do what You want

two divs the same line, one dynamic width, one fixed

I've had success with using white-space: nowrap; on the outer container, display: inline-block; on the inner containers, and then (in my case since I wanted the second one to word-wrap) white-space: normal; on the inner ones.

fatal: Not a valid object name: 'master'

You need to commit at least one time on master before creating a new branch.

PHP: Split string into array, like explode with no delimiter

Try this:

    $str = '546788';
    $char_array = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);

How to install all required PHP extensions for Laravel?

Laravel Server Requirements mention that BCMath, Ctype, JSON, Mbstring, OpenSSL, PDO, Tokenizer, and XML extensions are required. Most of the extensions are installed and enabled by default.

You can run the following command in Ubuntu to make sure the extensions are installed.

sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip

PHP version specific installation (if PHP 7.4 installed)

sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring

You may need other PHP extensions for your composer packages. Find from links below.

PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)

PHP extensions for Ubuntu 18.04 LTS (Bionic)

PHP extensions for Ubuntu 16.04 LTS (Xenial)

What is the => assignment in C# in a property signature

You can even write this:

    private string foo = "foo";

    private string bar
    {
        get => $"{foo}bar";
        set
        {
            foo = value;
        }
    }

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

There is another option: with syntax. To use the OPs example, this would look like:

with data as (
  select 'value1' name from dual
  union all
  select 'value2' name from dual
  union all
...
  select 'value10000+' name from dual)
select field1, field2, field3 
from table1 t1
inner join data on t1.name = data.name;

I ran into this problem. In my case I had a list of data in Java where each item had an item_id and a customer_id. I have two tables in the DB with subscriptions to items respective customers. I want to get a list of all subscriptions to the items or to the customer for that item, together with the item id.

I tried three variants:

  1. Multiple selects from Java (using tuples to get around the limit)
  2. With-syntax
  3. Temporary table

Option 1: Multiple Selects from Java

Basically, I first

select item_id, token 
from item_subs 
where (item_id, 0) in ((:item_id_0, 0)...(:item_id_n, 0))

Then

select cus_id, token 
from cus_subs 
where (cus_id, 0) in ((:cus_id_0, 0)...(:cus_id_n, 0))

Then I build a Map in Java with the cus_id as the key and a list of items as value, and for each found customer subscription I add (to the list returned from the first select) an entry for all relevant items with that item_id. It's much messier code

Option 2: With-syntax

Get everything at once with an SQL like

with data as (
  select :item_id_0 item_id, :cus_id_0 cus_id
  union all
  ...
  select :item_id_n item_id, :cus_id_n cus_id )
select I.item_id item_id, I.token token
from item_subs I
inner join data D on I.item_id = D.item_id
union all
select D.item_id item_id, C.token token
from cus_subs C
inner join data D on C.cus_id = D.cus_id

Option 3: Temporary table

Create a global temporary table with three fields: rownr (primary key), item_id and cus_id. Insert all the data there then run a very similar select to option 2, but linking in the temporary table instead of the with data

Performance

This is not a fully-scientific performance analysis.

  • I'm running against a development database, with slightly over 1000 rows in my data set that I want to find subscriptions for.
  • I've only tried one data set.
  • I'm not in the same physical location as my DB server. It's not that far away, but I do notice if I try from home over the VPN then it's all much slower, even though it's the same distance (and it's not my home internet that's the problem).
  • I was testing the full call, so my API calls another (also running in the same instance in dev) which also connects to to the DB to get the initial data set. But that is the same in all three cases.

YMMV.

That said, the temporary table option was much slower. As in double so slow. I was getting 14-15 seconds for option 1, 15-16 for option 2 and 30 for option 3.

I'll try them again from the same network as the DB server and check if that changes things when I get the chance.

Shortest distance between a point and a line segment

Solution for dart and flutter:

import 'dart:math' as math;
 class Utils {
   static double shortestDistance(Point p1, Point p2, Point p3){
      double px = p2.x - p1.x;
      double py = p2.y - p1.y;
      double temp = (px*px) + (py*py);
      double u = ((p3.x - p1.x)*px + (p3.y - p1.y)* py) /temp;
      if(u>1){
        u=1;
      }
      else if(u<0){
        u=0;
      }
      double x = p1.x + u*px;
      double y = p1.y + u*py;
      double dx = x - p3.x;
      double dy = y - p3.y;
      double dist = math.sqrt(dx*dx+dy*dy);
      return dist;
   }
}

class Point {
  double x;
  double y;
  Point(this.x, this.y);
}

path.join vs path.resolve with __dirname

const absolutePath = path.join(__dirname, some, dir);

vs.

const absolutePath = path.resolve(__dirname, some, dir);

path.join will concatenate __dirname which is the directory name of the current file concatenated with values of some and dir with platform-specific separator.

Whereas

path.resolve will process __dirname, some and dir i.e. from right to left prepending it by processing it.

If any of the values of some or dir corresponds to a root path then the previous path will be omitted and process rest by considering it as root

In order to better understand the concept let me explain both a little bit more detail as follows:-

The path.join and path.resolve are two different methods or functions of the path module provided by nodejs.

Where both accept a list of paths but the difference comes in the result i.e. how they process these paths.

path.join concatenates all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path. While the path.resolve() process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.

When no arguments supplied

The following example will help you to clearly understand both concepts:-

My filename is index.js and the current working directory is E:\MyFolder\Pjtz\node

const path = require('path');

console.log("path.join() : ", path.join());
// outputs .
console.log("path.resolve() : ", path.resolve());
// outputs current directory or equivalent to __dirname

Result

? node index.js
path.join() :  .
path.resolve() :  E:\MyFolder\Pjtz\node

path.resolve() method will output the absolute path whereas the path.join() returns . representing the current working directory if nothing is provided

When some root path is passed as arguments

const path=require('path');

console.log("path.join() : " ,path.join('abc','/bcd'));
console.log("path.resolve() : ",path.resolve('abc','/bcd'));

Result i

? node index.js
path.join() :  abc\bcd
path.resolve() :  E:\bcd

path.join() only concatenates the input list with platform-specific separator while the path.resolve() process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.

Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

While the above solutions should work in 90% of the cases, but if you are still reading this answer!!! You are probably trying to connect to a different server than intended. It may be due to a configuration file pointing to a different SQL server than the actual server you think you are trying to connecting to.

Happened to me atleast.

What are some resources for getting started in operating system development?

Minix is a lot smaller, and designed for learning purposes, and the book to go with it is a good one too.

Update: I guess Minix 3 is a bit of a different goal, but Minix 2 (and of course the first version) were for teaching purposes.

open_basedir restriction in effect. File(/) is not within the allowed path(s):

If you are running a PHP IIS stack and have this error, it is usually a quick permission fix.

If you administer the windows server yourself and have access, try this FIRST:

Navigate to the folder that is giving you grief on writing to and right click it > open properties > security.

See what users have access to the folder, which ones have read only and which have full. Do you have a group that is blocking write?

The fix will be specific to your IIS setup, are you using Anonymous Authentication with specific user IUSR or with the Application Pool identity?

At any rate, you are going to end up adding a new full write permission for one of IUSR, IIS_IUSRS, or your application pool identity - like I said, this is going to vary depending on your setup and how you want to do it, you can go down the google rabbit hole on this one (one such post - IIS_IUSRS and IUSR permissions in IIS8) For me, i use anon with my app pool identity so i can get away with MACHINE_NAME\IIS_IUSRS with full read/write on any temp or upload folders.

I do not need to add anything extra to my open_basedir = in the php.ini.

break statement in "if else" - java

The issue is that you are trying to have multiple statements in an if without using {}. What you currently have is interpreted like:

if( choice==5 )
{
    System.out.println( ... );
}
break;
else
{
    //...
}

You really want:

if( choice==5 )
{
    System.out.println( ... );
    break;
}
else
{
    //...
}

Also, as Farce has stated, it would be better to use else if for all the conditions instead of if because if choice==1, it will still go through and check if choice==5, which would fail, and it will still go into your else block.

if( choice==1 )
    //...
else if( choice==2 )
    //...
else if( choice==3 )
    //...
else if( choice==4 )
    //...
else if( choice==5 )
{
    //...
}
else
    //...

A more elegant solution would be using a switch statement. However, break only breaks from the most inner "block" unless you use labels. So you want to label your loop and break from that if the case is 5:

LOOP:
for(;;)
{
    System.out.println("---> Your choice: ");
    choice = input.nextInt();
    switch( choice )
    {
        case 1:
            playGame();
            break;
        case 2:
            loadGame();
            break;
        case 2:
            options();
            break;
        case 4:
            credits();
            break;
        case 5:
            System.out.println("End of Game\n Thank you for playing with us!");
            break LOOP;
        default:
            System.out.println( ... );
    }
}

Instead of labeling the loop, you could also use a flag to tell the loop to stop.

bool finished = false;
while( !finished )
{
    switch( choice )
    {
        // ...
        case 5:
            System.out.println( ... )
            finished = true;
            break;
        // ...
    }
}

How to determine the screen width in terms of dp or dip at runtime in Android?

How about using this instead ?

final DisplayMetrics displayMetrics=getResources().getDisplayMetrics();
final float screenWidthInDp=displayMetrics.widthPixels/displayMetrics.density;
final float screenHeightInDp=displayMetrics.heightPixels/displayMetrics.density;

How to undo a git pull?

git reflog show should show you the history of HEAD. You can use that to figure out where you were before the pull. Then you can reset your HEAD to that commit.

How to enable CORS in ASP.net Core WebAPI

Because you have a very simple CORS policy (Allow all requests from XXX domain), you don't need to make it so complicated. Try doing the following first (A very basic implementation of CORS).

If you haven't already, install the CORS nuget package.

Install-Package Microsoft.AspNetCore.Cors

In the ConfigureServices method of your startup.cs, add the CORS services.

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(); // Make sure you call this previous to AddMvc
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

Then in your Configure method of your startup.cs, add the following :

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // Make sure you call this before calling app.UseMvc()
    app.UseCors(
        options => options.WithOrigins("http://example.com").AllowAnyMethod()
    );

    app.UseMvc();
}

Now give it a go. Policies are for when you want different policies for different actions (e.g. different hosts or different headers). For your simple example you really don't need it. Start with this simple example and tweak as you need to from there.

Further reading : http://dotnetcoretutorials.com/2017/01/03/enabling-cors-asp-net-core/

Oracle - Why does the leading zero of a number disappear when converting it TO_CHAR

I was looking for a way to format numbers without leading or trailing spaces, periods, zeros (except one leading zero for numbers less than 1 that should be present).

This is frustrating that such most usual formatting can't be easily achieved in Oracle.

Even Tom Kyte only suggested long complicated workaround like this:

case when trunc(x)=x
    then to_char(x, 'FM999999999999999999')
    else to_char(x, 'FM999999999999999.99')
end x

But I was able to find shorter solution that mentions the value only once:

rtrim(to_char(x, 'FM999999999999990.99'), '.')

This works as expected for all possible values:

select 
    to_char(num, 'FM99.99') wrong_leading_period,
    to_char(num, 'FM90.99') wrong_trailing_period,
    rtrim(to_char(num, 'FM90.99'), '.') correct
from (
  select num from (select 0.25 c1, 0.1 c2, 1.2 c3, 13 c4, -70 c5 from dual)
  unpivot (num for dummy in (c1, c2, c3, c4, c5))
) sampledata;

    | WRONG_LEADING_PERIOD | WRONG_TRAILING_PERIOD | CORRECT |
    |----------------------|-----------------------|---------|
    |                  .25 |                  0.25 |    0.25 |
    |                   .1 |                   0.1 |     0.1 |
    |                  1.2 |                   1.2 |     1.2 |
    |                  13. |                   13. |      13 |
    |                 -70. |                  -70. |     -70 |

Still looking for even shorter solution.

There is a shortening approarch with custom helper function:

create or replace function str(num in number) return varchar2
as
begin
    return rtrim(to_char(num, 'FM999999999999990.99'), '.');
end;

But custom pl/sql functions have significant performace overhead that is not suitable for heavy queries.

How can I take an UIImage and give it a black border?

//you need to import

QuartzCore/QuartzCore.h

& then for ImageView in border

[imageView.layer setBorderColor: [[UIColor blackColor] CGColor]];

[imageView.layer setBorderWidth: 2.0];

[imageView.layer setCornerRadius: 5.0];

How to get different colored lines for different plots in a single figure?

Matplot colors your plot with different colors , but incase you wanna put specific colors

    import matplotlib.pyplot as plt
    import numpy as np
            
    x = np.arange(10)
            
    plt.plot(x, x)
    plt.plot(x, 2 * x,color='blue')
    plt.plot(x, 3 * x,color='red')
    plt.plot(x, 4 * x,color='green')
    plt.show()

Does Java read integers in little endian or big endian?

There are no unsigned integers in Java. All integers are signed and in big endian.

On the C side the each byte has tne LSB at the start is on the left and the MSB at the end.

It sounds like you are using LSB as Least significant bit, are you? LSB usually stands for least significant byte. Endianness is not bit based but byte based.

To convert from unsigned byte to a Java integer:

int i = (int) b & 0xFF;

To convert from unsigned 32-bit little-endian in byte[] to Java long (from the top of my head, not tested):

long l = (long)b[0] & 0xFF;
l += ((long)b[1] & 0xFF) << 8;
l += ((long)b[2] & 0xFF) << 16;
l += ((long)b[3] & 0xFF) << 24;

Check folder size in Bash

if you just want to see the aggregate size of the folder and probably in MB or GB format, please try the below script

$du -s --block-size=M /path/to/your/directory/

Spark Kill Running Application

First use:

yarn application -list

Note down the application id Then to kill use:

yarn application -kill application_id

Setting Camera Parameters in OpenCV/Python

If anyone is still wondering what the value in CV_CAP_PROP_EXPOSURE might be:

Depends. For my cheap webcam I have to enter the desired value directly, e.g. 0.1 for 1/10s. For my expensive industrial camera I have to enter -5 to get an exposure time of 2^-5s = 1/32s.

How to change the icon of .bat file programmatically?

i recommand to use BAT to EXE converter for your desires

Why does this AttributeError in python occur?

The default namespace in Python is "__main__". When you use import scipy, Python creates a separate namespace as your module name. The rule in Pyhton is: when you want to call an attribute from another namespaces you have to use the fully qualified attribute name.

Error renaming a column in MySQL

Lone Ranger is very close... in fact, you also need to specify the datatype of the renamed column. For example:

ALTER TABLE `xyz` CHANGE `manufacurerid` `manufacturerid` INT;

Remember :

  • Replace INT with whatever your column data type is (REQUIRED)
  • Tilde/ Backtick (`) is optional

textarea's rows, and cols attribute in CSS

width and height are used when going the css route.

<!DOCTYPE html>
<html>
    <head>
        <title>Setting Width and Height on Textareas</title>
        <style>
            .comments { width: 300px; height: 75px }
        </style>
    </head>
    <body>
        <textarea class="comments"></textarea>
    </body>
</html>

Android – Listen For Incoming SMS Messages

In case you want to handle intent on opened activity, you can use PendintIntent (Complete steps below):

public class SMSReciver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        final Bundle bundle = intent.getExtras();
        try {
            if (bundle != null) {
                final Object[] pdusObj = (Object[]) bundle.get("pdus");
                for (int i = 0; i < pdusObj.length; i++) {
                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();
                    String senderNum = phoneNumber;
                    String message = currentMessage.getDisplayMessageBody();
                    try {
                        if (senderNum.contains("MOB_NUMBER")) {
                            Toast.makeText(context,"",Toast.LENGTH_SHORT).show();

                            Intent intentCall = new Intent(context, MainActivity.class);
                            intentCall.putExtra("message", currentMessage.getMessageBody());

                            PendingIntent pendingIntent= PendingIntent.getActivity(context, 0, intentCall, PendingIntent.FLAG_UPDATE_CURRENT);
                            pendingIntent.send();
                        }
                    } catch (Exception e) {
                    }
                }
            }
        } catch (Exception e) {
        }
    }
} 

manifest:

<activity android:name=".MainActivity"
            android:launchMode="singleTask"/>
<receiver android:name=".SMSReciver">
            <intent-filter android:priority="1000">
                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
        </receiver>

onNewIntent:

 @Override
         protected void onNewIntent(Intent intent) {
                super.onNewIntent(intent);
                Toast.makeText(this, "onNewIntent", Toast.LENGTH_SHORT).show();

                onSMSReceived(intent.getStringExtra("message"));

            }

permissions:

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />

Service Reference Error: Failed to generate code for the service reference

"Reuse types" is not always the problem when this error occurs.

When adding a reference to an older service, click 'advanced' and there 'Add Web Reference'. Now link to your wsdl and everything should be working.

Installing Bootstrap 3 on Rails App

Twitter now has a sass-ready version of bootstrap with gem included, so it is easier than ever to add it to Rails.

Simply add to your gemfile the following:

gem 'sass-rails', '>= 3.2' # sass-rails needs to be higher than 3.2
gem 'bootstrap-sass', '~> 3.1.1'

bundle install and restart your server to make the files available through the pipeline.

There is also support for compass and sass-only: https://github.com/twbs/bootstrap-sass

VBA code to set date format for a specific column as "yyyy-mm-dd"

You are applying the formatting to the workbook that has the code, not the added workbook. You'll want to get in the habit of fully qualifying sheet and range references. The code below does that and works for me in Excel 2010:

Sub test()
Dim wb As Excel.Workbook
Set wb = Workbooks.Add
With wb.Sheets(1)
    .Range("A1") = "Acctdate"
    .Range("B1") = "Ledger"
    .Range("C1") = "CY"
    .Range("D1") = "BusinessUnit"
    .Range("E1") = "OperatingUnit"
    .Range("F1") = "LOB"
    .Range("G1") = "Account"
    .Range("H1") = "TreatyCode"
    .Range("I1") = "Amount"
    .Range("J1") = "TransactionCurrency"
    .Range("K1") = "USDEquivalentAmount"
    .Range("L1") = "KeyCol"
    .Range("A2", "A50000").Value = Me.TextBox3.Value
    .Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"
End With
End Sub

How to cast the size_t to double or int C++

You can use Boost numeric_cast.

This throws an exception if the source value is out of range of the destination type, but it doesn't detect loss of precision when converting to double.

Whatever function you use, though, you should decide what you want to happen in the case where the value in the size_t is greater than INT_MAX. If you want to detect it use numeric_cast or write your own code to check. If you somehow know that it cannot possibly happen then you could use static_cast to suppress the warning without the cost of a runtime check, but in most cases the cost doesn't matter anyway.

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

  • Update your support library to last version

  • Open Manifest File , and add it into Manifest File

  • <uses-sdk tools:overrideLibrary="android.support.v17.leanback"/>

  • And add for recyclerview in >> build.gradle Module app :

  • compile 'com.android.support:recyclerview-v7:25.3.1'

  • And click : Sync Now

JQuery Parsing JSON array

getJSON() will also parse the JSON for you after fetching, so from then on, you are working with a simple Javascript array ([] marks an array in JSON). The documentation also has examples on how to handle the fetched data.

You can get all the values in an array using a for loop:

$.getJSON("url_with_json_here", function(data){
    for (var i = 0, len = data.length; i < len; i++) {
        console.log(data[i]);
    }
});

Check your console to see the output (Chrome, Firefox/Firebug, IE).

jQuery also provides $.each() for iterations, so you could also do this:

$.getJSON("url_with_json_here", function(data){
    $.each(data, function (index, value) {
        console.log(value);
    });
});

how to install python distutils

If you are in a scenario where you are using one of the latest versions of Ubuntu (or variants like Linux Mint), one which comes with Python 3.8, then you will NOT be able to have Python3.7 distutils, alias not be able to use pip or pipenv with Python 3.7, see: How to install python-distutils for old python versions

Obviously using Python3.8 is no problem.

Unused arguments in R

I had the same problem as you. I had a long list of arguments, most of which were irrelevant. I didn't want to hard code them in. This is what I came up with

library(magrittr)
do_func_ignore_things <- function(data, what){
    acceptable_args <- data[names(data) %in% (formals(what) %>% names)]
    do.call(what, acceptable_args %>% as.list)
}

do_func_ignore_things(c(n = 3, hello = 12, mean = -10), "rnorm")
# -9.230675 -10.503509 -10.927077

how to permit an array with strong parameters

It should be like

params.permit(:id => [])

Also since rails version 4+ you can use:

params.permit(id: [])

How do I check that a Java String is not all whitespaces?

If you are only checking for whitespace and don't care about null then you can use org.apache.commons.lang.StringUtils.isWhitespace(String str),

StringUtils.isWhitespace(String str);

(Checks if the String contains only whitespace.)

If you also want to check for null(including whitespace) then

StringUtils.isBlank(String str);

Session timeout in ASP.NET

Do you have anything in machine.config that might be taking effect? Setting the session timeout in web.config should override any settings in IIS or machine.config, however, if you have a web.config file somewhere in a subfolder in your application, that setting will override the one in the root of your application.

Also, if I remember correctly, the timeout in IIS only affects .asp pages, not .aspx. Are you sure your session code in web.config is correct? It should look something like:

<sessionState
    mode="InProc"
    stateConnectionString="tcpip=127.0.0.1:42424"
    stateNetworkTimeout="60"
    sqlConnectionString="data source=127.0.0.1;Integrated Security=SSPI"
    cookieless="false"
    timeout="60"
/>

How do I alter the precision of a decimal column in Sql Server?

ALTER TABLE `tableName` CHANGE  `columnName` DECIMAL(16,1) NOT NULL;

I uses This for the alterration

Delete all Duplicate Rows except for One in MySQL?

Editor warning: This solution is computationally inefficient and may bring down your connection for a large table.

NB - You need to do this first on a test copy of your table!

When I did it, I found that unless I also included AND n1.id <> n2.id, it deleted every row in the table.

  1. If you want to keep the row with the lowest id value:

    DELETE n1 FROM names n1, names n2 WHERE n1.id > n2.id AND n1.name = n2.name
    
  2. If you want to keep the row with the highest id value:

    DELETE n1 FROM names n1, names n2 WHERE n1.id < n2.id AND n1.name = n2.name
    

I used this method in MySQL 5.1

Not sure about other versions.


Update: Since people Googling for removing duplicates end up here
Although the OP's question is about DELETE, please be advised that using INSERT and DISTINCT is much faster. For a database with 8 million rows, the below query took 13 minutes, while using DELETE, it took more than 2 hours and yet didn't complete.

INSERT INTO tempTableName(cellId,attributeId,entityRowId,value)
    SELECT DISTINCT cellId,attributeId,entityRowId,value
    FROM tableName;

.NET Core vs Mono

This is one of my favorite topics and the content here was just amazing. I was thinking if it would be worth while or effective to compare the methods available in Runtime vs. Mono. I hope I got my terms right, but I think you know what I mean. In order to have a somewhat better understanding of what each Runtime supports currently, would it make sense to compare the methods they provide? I realize implementations may vary, and I have not considered the Framework Class libraries or the slew of other libraries available in one environment vs. the other. I also realize someone might have already done this work even more efficiently. I would be most grateful if you would let me know so I can review it. I feel doing a diff between the outcome of such activity would be of value, and wanted to see how more experienced developers feel about it, and would they provide useful guidance. While back I was playing with reflection, and wrote some lines that traverse the .net directory, and list the assemblies.

missing private key in the distribution certificate on keychain

I got into this situation ("Missing private key.") after Xcode failed to create new distribution certificate - an unknown error occurred.

Then, I struggled to obtain the private key or to generate new certificate. From the certificate manager in Xcode I got strange errors like "The passphrase you entered is wrong". But it did not even ask me for any passphrase.

What helped me was:

  1. Revoke all not-working distribution certificates at developer.apple.com
  2. Restart my Mac

After that, Xcode was able to create new distribution certificate and no private key was missing.

Lesson learned: Restart your Mac as much as your Windows ;)

Enter export password to generate a P12 certificate

The selected answer apparently does not work anymore in 2019 (at least for me).

I was trying to export a certificate using openssl (version 1.1.0) and the parameter -password doesn't work.

According to that link in the original answer (the same info is in man openssl), openssl has two parameter for passwords and they are -passin for the input parts and -passout for output files.

For the -export command, I used -passin for the password of my key file and -passout to create a new password for my P12 file.

So the complete command without any prompt was like below:

openssl pkcs12 -export -in /tmp/MyCert.crt -inkey /tmp/MyKey.key -out /tmp/MyP12.p12 -name alias -passin pass:keypassphrase -passout pass:certificatepassword

If you does not want a password, you can use pass: like below:

openssl pkcs12 -export -in /tmp/MyCert.crt -inkey /tmp/MyKey.key -out /tmp/MyP12.p12 -name alias -passin pass: -passout pass:

It will works fine with a key without password and the output certificate will be created without password too.

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?

enter image description here

This examples shows calling a method

  1. Defined in Child widget from Parent widget.
  2. Defined in Parent widget from Child widget.

class ParentPage extends StatefulWidget {
  @override
  _ParentPageState createState() => _ParentPageState();
}

class _ParentPageState extends State<ParentPage> {
  final GlobalKey<ChildPageState> _key = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Parent")),
      body: Center(
        child: Column(
          children: <Widget>[
            Expanded(
              child: Container(
                color: Colors.grey,
                width: double.infinity,
                alignment: Alignment.center,
                child: RaisedButton(
                  child: Text("Call method in child"),
                  onPressed: () => _key.currentState.methodInChild(), // calls method in child
                ),
              ),
            ),
            Text("Above = Parent\nBelow = Child"),
            Expanded(
              child: ChildPage(
                key: _key,
                function: methodInParent,
              ),
            ),
          ],
        ),
      ),
    );
  }

  methodInParent() => Fluttertoast.showToast(msg: "Method called in parent", gravity: ToastGravity.CENTER);
}

class ChildPage extends StatefulWidget {
  final Function function;

  ChildPage({Key key, this.function}) : super(key: key);

  @override
  ChildPageState createState() => ChildPageState();
}

class ChildPageState extends State<ChildPage> {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.teal,
      width: double.infinity,
      alignment: Alignment.center,
      child: RaisedButton(
        child: Text("Call method in parent"),
        onPressed: () => widget.function(), // calls method in parent
      ),
    );
  }

  methodInChild() => Fluttertoast.showToast(msg: "Method called in child");
}

How To Auto-Format / Indent XML/HTML in Notepad++

For those who don't know, npp has a lot of support from plugins and other projects. You can download those plugins from SourceForge.

enter image description here

You need XML Tools to format your text in n++

After you have downloaded XML Tools ..

Exit Notepad++

Go To C:\Program File\Notepad++ .... Your N++ installed folder.

  1. Place below files from xml tools which you downloaded in the npp root folder by copy replace

enter image description here

  1. Go To ..\Plugins subfolder and place below downloaded file

enter image description here

Restart and enjoy!!!

Ctrl + Alt + Shft + B to format.

Google maps API V3 method fitBounds()

I have the same problem that you describe although I'm building up my LatLngBounds as proposed by above. The problem is that things are async and calling map.fitBounds() at the wrong time may leave you with a result like in the Q. The best way I found is to place the call in an idle handler like this:

google.maps.event.addListenerOnce(map, 'idle', function() {
    map.fitBounds(markerBounds);
});

Free FTP Library

You may consider FluentFTP, previously known as System.Net.FtpClient.

It is released under The MIT License and available on NuGet (FluentFTP).

Case insensitive string compare in LINQ-to-SQL

The following 2-stage approach works for me (VS2010, ASP.NET MVC3, SQL Server 2008, Linq to SQL):

result = entRepos.FindAllEntities()
    .Where(e => e.EntitySearchText.Contains(item));

if (caseSensitive)
{
    result = result
        .Where(e => e.EntitySearchText.IndexOf(item, System.StringComparison.CurrentCulture) >= 0);
}

Using jQuery how to get click coordinates on the target element

Try this:

jQuery(document).ready(function(){
   $("#special").click(function(e){
      $('#status2').html(e.pageX +', '+ e.pageY);
   }); 
})

Here you can find more info with DEMO

In Java, how do you determine if a thread is running?

To be precise,

Thread.isAlive() returns true if the thread has been started (may not yet be running) but has not yet completed its run method.

Thread.getState() returns the exact state of the thread.

How should I set the default proxy to use default credentials?

From .NET 2.0 you shouldn't need to do this. If you do not explicitly set the Proxy property on a web request it uses the value of the static WebRequest.DefaultWebProxy. If you wanted to change the proxy being used by all subsequent WebRequests, you can set this static DefaultWebProxy property.

The default behaviour of WebRequest.DefaultWebProxy is to use the same underlying settings as used by Internet Explorer.

If you wanted to use different proxy settings to the current user then you would need to code

WebRequest webRequest = WebRequest.Create("http://stackoverflow.com/");
webRequest.Proxy = new WebProxy("http://proxyserver:80/",true);

or

WebRequest.DefaultWebProxy = new WebProxy("http://proxyserver:80/",true);

You should also remember the object model for proxies includes the concept that the proxy can be different depending on the destination hostname. This can make things a bit confusing when debugging and checking the property of webRequest.Proxy. Call

webRequest.Proxy.GetProxy(new Uri("http://google.com.au")) to see the actual details of the proxy server that would be used.

There seems to be some debate about whether you can set webRequest.Proxy or WebRequest.DefaultWebProxy = null to prevent the use of any proxy. This seems to work OK for me but you could set it to new DefaultProxy() with no parameters to get the required behaviour. Another thing to check is that if a proxy element exists in your applications config file, the .NET Framework will NOT use the proxy settings in Internet Explorer.

The MSDN Magazine article Take the Burden Off Users with Automatic Configuration in .NET gives further details of what is happening under the hood.

Why does git status show branch is up-to-date when changes exist upstream?

Trivial answer yet accurate in some cases, such as the one that brought me here. I was working in a repo which was new for me and I added a file which was not seen as new by the status.

It ends up that the file matched a pattern in the .gitignore file.

Importing variables from another file?

script1.py

title="Hello world"

script2.py is where we using script1 variable

Method 1:

import script1
print(script1.title)

Method 2:

from script1 import title
print(title)

C/C++ maximum stack size of program

(Added 26 Sept. 2020)

On 24 Oct. 2009, as @pixelbeat first pointed out here, Bruno Haible empirically discovered the following default thread stack sizes for several systems. He said that in a multithreaded program, "the default thread stack size is:"

- glibc i386, x86_64    7.4 MB
- Tru64 5.1             5.2 MB
- Cygwin                1.8 MB
- Solaris 7..10           1 MB
- MacOS X 10.5          460 KB
- AIX 5                  98 KB
- OpenBSD 4.0            64 KB
- HP-UX 11               16 KB

Note that the above units are all in MB and KB (base 1000 numbers), NOT MiB and KiB (base 1024 numbers). I've proven this to myself by verifying the 7.4 MB case.

He also stated that:

32 KB is more than you can safely allocate on the stack in a multithreaded program

And he said:

And the default stack size for sigaltstack, SIGSTKSZ, is

  • only 16 KB on some platforms: IRIX, OSF/1, Haiku.
  • only 8 KB on some platforms: glibc, NetBSD, OpenBSD, HP-UX, Solaris.
  • only 4 KB on some platforms: AIX.

Bruno

He wrote the following simple Linux C program to empirically determine the above values. You can run it on your system today to quickly see what your maximum thread stack size is, or you can run it online on GDBOnline here: https://onlinegdb.com/rkO9JnaHD.

Explanation: It simply creates a single new thread, so as to check the thread stack size and NOT the program stack size, in case they differ, then it has that thread repeatedly allocate 128 bytes of memory on the stack (NOT the heap), using the Linux alloca() call, after which it writes a 0 to the first byte of this new memory block, and then it prints out how many total bytes it has allocated. It repeats this process, allocating 128 more bytes on the stack each time, until the program crashes with a Segmentation fault (core dumped) error. The last value printed is the estimated maximum thread stack size allowed for your system.

Important note: alloca() allocates on the stack: even though this looks like dynamic memory allocation onto the heap, similar to a malloc() call, alloca() does NOT dynamically allocate onto the heap. Rather, alloca() is a specialized Linux function to "pseudo-dynamically" (I'm not sure what I'd call this, so that's the term I chose) allocate directly onto the stack as though it was statically-allocated memory. Stack memory used and returned by alloca() is scoped at the function-level, and is therefore "automatically freed when the function that called alloca() returns to its caller." That's why its static scope isn't exited and memory allocated by alloca() is NOT freed each time a for loop iteration is completed and the end of the for loop scope is reached. See man 3 alloca for details. Here's the pertinent quote (emphasis added):

DESCRIPTION
The alloca() function allocates size bytes of space in the stack frame of the caller. This temporary space is automatically freed when the function that called alloca() returns to its caller.

RETURN VALUE
The alloca() function returns a pointer to the beginning of the allocated space. If the allocation causes stack overflow, program behavior is undefined.

Here is Bruno Haible's program from 24 Oct. 2009, copied directly from the GNU mailing list here:

Again, you can run it live online here.

// By Bruno Haible
// 24 Oct. 2009
// Source: https://lists.gnu.org/archive/html/bug-coreutils/2009-10/msg00262.html

// =============== Program for determining the default thread stack size =========

#include <alloca.h>
#include <pthread.h>
#include <stdio.h>
void* threadfunc (void*p) {
  int n = 0;
  for (;;) {
    printf("Allocated %d bytes\n", n);
    fflush(stdout);
    n += 128;
    *((volatile char *) alloca(128)) = 0;
  }
}

int main()
{
  pthread_t thread;
  pthread_create(&thread, NULL, threadfunc, NULL);
  for (;;) {}
}

When I run it on GDBOnline using the link above, I get the exact same results each time I run it, as both a C and a C++17 program. It takes about 10 seconds or so to run. Here are the last several lines of the output:

Allocated 7449856 bytes
Allocated 7449984 bytes
Allocated 7450112 bytes
Allocated 7450240 bytes
Allocated 7450368 bytes
Allocated 7450496 bytes
Allocated 7450624 bytes
Allocated 7450752 bytes
Allocated 7450880 bytes
Segmentation fault (core dumped)

So, the thread stack size is ~7.45 MB for this system, as Bruno mentioned above (7.4 MB).

I've made a few changes to the program, mostly just for clarity, but also for efficiency, and a bit for learning.

Summary of my changes:

  1. [learning] I passed in BYTES_TO_ALLOCATE_EACH_LOOP as an argument to the threadfunc() just for practice passing in and using generic void* arguments in C.

  2. [efficiency] I made the main thread sleep instead of wastefully spinning.

  3. [clarity] I added more-verbose variable names, such as BYTES_TO_ALLOCATE_EACH_LOOP and bytes_allocated.

  4. [clarity] I changed this:

     *((volatile char *) alloca(128)) = 0;
    

    to this:

     volatile uint8_t * byte_buff = 
             (volatile uint8_t *)alloca(BYTES_TO_ALLOCATE_EACH_LOOP);
     byte_buff[0] = 0;
    

Here is my modified test program, which does exactly the same thing as Bruno's, and even has the same results:

You can run it online here, or download it from my repo here. If you choose to run it locally from my repo, here's the build and run commands I used for testing:

  1. Build and run it as a C program:

     mkdir -p bin && \
     gcc -Wall -Werror -g3 -O3 -std=c11 -pthread -o bin/tmp \
     onlinegdb--empirically_determine_max_thread_stack_size_GS_version.c && \
     time bin/tmp
    
  2. Build and run it as a C++ program:

     mkdir -p bin && \
     g++ -Wall -Werror -g3 -O3 -std=c++17 -pthread -o bin/tmp \
     onlinegdb--empirically_determine_max_thread_stack_size_GS_version.c && \
     time bin/tmp
    

It takes < 0.5 seconds to run locally on a fast computer with a thread stack size of ~7.4 MB.

Here's the program:

// =============== Program for determining the default thread stack size =========

// Modified by Gabriel Staples, 26 Sept. 2020

// Originally by Bruno Haible
// 24 Oct. 2009
// Source: https://lists.gnu.org/archive/html/bug-coreutils/2009-10/msg00262.html

#include <alloca.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h> // sleep

/// Thread function to repeatedly allocate memory within a thread, printing
/// the total memory allocated each time, until the program crashes. The last
/// value printed before the crash indicates how big a thread's stack size is.
void* threadfunc(void* bytes_to_allocate_each_loop)
{
    const uint32_t BYTES_TO_ALLOCATE_EACH_LOOP =
            *(uint32_t*)bytes_to_allocate_each_loop;

    uint32_t bytes_allocated = 0;
    while (true)
    {
        printf("bytes_allocated = %u\n", bytes_allocated);
        fflush(stdout);
        // NB: it appears that you don't necessarily need `volatile` here,
        // but you DO definitely need to actually use (ex: write to) the
        // memory allocated by `alloca()`, as we do below, or else the
        // `alloca()` call does seem to get optimized out on some systems,
        // making this whole program just run infinitely forever without
        // ever hitting the expected segmentation fault.
        volatile uint8_t * byte_buff =
                (volatile uint8_t *)alloca(BYTES_TO_ALLOCATE_EACH_LOOP);
        byte_buff[0] = 0;
        bytes_allocated += BYTES_TO_ALLOCATE_EACH_LOOP;
    }
}

int main()
{
    const uint32_t BYTES_TO_ALLOCATE_EACH_LOOP = 128;

    pthread_t thread;
    pthread_create(&thread, NULL, threadfunc,
                   (void*)(&BYTES_TO_ALLOCATE_EACH_LOOP));
    while (true)
    {
        const unsigned int SLEEP_SEC = 10000;
        sleep(SLEEP_SEC);
    }

    return 0;
}

Sample output (same results as Bruno Haible's original program):

bytes_allocated = 7450240                                                                                                                                                        
bytes_allocated = 7450368                                                                                                                                                        
bytes_allocated = 7450496                                                                                                                                                        
bytes_allocated = 7450624                                                                                                                                                        
bytes_allocated = 7450752                                                                                                                                                        
bytes_allocated = 7450880                                                                                                                                                        
Segmentation fault (core dumped) 

How to check iOS version?

  1. From the the Home Screen, tap Settings > General > About.
  2. The software version of your device should appear on this screen.
  3. Check whether the version number is greater than 3.1.3.

Render a string in HTML and preserve spaces and linebreaks

I was trying the white-space: pre-wrap; technique stated by pete but if the string was continuous and long it just ran out of the container, and didn't warp for whatever reason, didn't have much time to investigate.. but if you too are having the same problem, I ended up using the <pre> tags and the following css and everything was good to go..

pre {
font-size: inherit;
color: inherit;
border: initial;
padding: initial;
font-family: inherit;
}

Mock HttpContext.Current in Test Init Method

HttpContext.Current returns an instance of System.Web.HttpContext, which does not extend System.Web.HttpContextBase. HttpContextBase was added later to address HttpContext being difficult to mock. The two classes are basically unrelated (HttpContextWrapper is used as an adapter between them).

Fortunately, HttpContext itself is fakeable just enough for you do replace the IPrincipal (User) and IIdentity.

The following code runs as expected, even in a console application:

HttpContext.Current = new HttpContext(
    new HttpRequest("", "http://tempuri.org", ""),
    new HttpResponse(new StringWriter())
    );

// User is logged in
HttpContext.Current.User = new GenericPrincipal(
    new GenericIdentity("username"),
    new string[0]
    );

// User is logged out
HttpContext.Current.User = new GenericPrincipal(
    new GenericIdentity(String.Empty),
    new string[0]
    );

Checking if a website is up via Python

Here's my solution using PycURL and validators

import pycurl, validators


def url_exists(url):
    """
    Check if the given URL really exists
    :param url: str
    :return: bool
    """
    if validators.url(url):
        c = pycurl.Curl()
        c.setopt(pycurl.NOBODY, True)
        c.setopt(pycurl.FOLLOWLOCATION, False)
        c.setopt(pycurl.CONNECTTIMEOUT, 10)
        c.setopt(pycurl.TIMEOUT, 10)
        c.setopt(pycurl.COOKIEFILE, '')
        c.setopt(pycurl.URL, url)
        try:
            c.perform()
            response_code = c.getinfo(pycurl.RESPONSE_CODE)
            c.close()
            return True if response_code < 400 else False
        except pycurl.error as err:
            errno, errstr = err
            raise OSError('An error occurred: {}'.format(errstr))
    else:
        raise ValueError('"{}" is not a valid url'.format(url))

Defining private module functions in python

This question was not fully answered, since module privacy is not purely conventional, and since using import may or may not recognize module privacy, depending on how it is used.

If you define private names in a module, those names will be imported into any script that uses the syntax, 'import module_name'. Thus, assuming you had correctly defined in your example the module private, _num, in a.py, like so..

#a.py
_num=1

..you would be able to access it in b.py with the module name symbol:

#b.py
import a
...
foo = a._num # 1

To import only non-privates from a.py, you must use the from syntax:

#b.py
from a import *
...
foo = _num # throws NameError: name '_num' is not defined

For the sake of clarity, however, it is better to be explicit when importing names from modules, rather than importing them all with a '*':

#b.py
from a import name1 
from a import name2
...

Padding characters in printf

I think this is the simplest solution. Pure shell builtins, no inline math. It borrows from previous answers.

Just substrings and the ${#...} meta-variable.

A="[>---------------------<]";

# Strip excess padding from the right
#

B="A very long header"; echo "${A:0:-${#B}} $B"
B="shrt hdr"          ; echo "${A:0:-${#B}} $B"

Produces

[>----- A very long header
[>--------------- shrt hdr


# Strip excess padding from the left
#

B="A very long header"; echo "${A:${#B}} $B"
B="shrt hdr"          ; echo "${A:${#B}} $B"

Produces

-----<] A very long header
---------------<] shrt hdr

How to save and load numpy.array() data properly?

np.fromfile() has a sep= keyword argument:

Separator between items if file is a text file. Empty (“”) separator means the file should be treated as binary. Spaces (” ”) in the separator match zero or more whitespace characters. A separator consisting only of spaces must match at least one whitespace.

The default value of sep="" means that np.fromfile() tries to read it as a binary file rather than a space-separated text file, so you get nonsense values back. If you use np.fromfile('markers.txt', sep=" ") you will get the result you are looking for.

However, as others have pointed out, np.loadtxt() is the preferred way to convert text files to numpy arrays, and unless the file needs to be human-readable it is usually better to use binary formats instead (e.g. np.load()/np.save()).

How to transform numpy.matrix or array to scipy sparse matrix

There are several sparse matrix classes in scipy.

bsr_matrix(arg1[, shape, dtype, copy, blocksize]) Block Sparse Row matrix
coo_matrix(arg1[, shape, dtype, copy]) A sparse matrix in COOrdinate format.
csc_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Column matrix
csr_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Row matrix
dia_matrix(arg1[, shape, dtype, copy]) Sparse matrix with DIAgonal storage
dok_matrix(arg1[, shape, dtype, copy]) Dictionary Of Keys based sparse matrix.
lil_matrix(arg1[, shape, dtype, copy]) Row-based linked list sparse matrix

Any of them can do the conversion.

import numpy as np
from scipy import sparse
a=np.array([[1,0,1],[0,0,1]])
b=sparse.csr_matrix(a)
print(b)

(0, 0)  1
(0, 2)  1
(1, 2)  1

See http://docs.scipy.org/doc/scipy/reference/sparse.html#usage-information .

Pandas - Plotting a stacked Bar Chart

Maybe you can use pandas crosstab function

test5 = pd.crosstab(index=faultdf['Site Name'], columns=faultdf[''Abuse/NFF''])

test5.plot(kind='bar', stacked=True)

Extract directory path and filename

You can simply do:

base=$(basename "$fspec")

How to download the latest artifact from Artifactory repository?

In case you need to download an artifact in a Dockerfile, instead of using wget or curl or the likes you can simply use the 'ADD' directive:

ADD ${ARTIFACT_URL} /opt/app/app.jar

Of course, the tricky part is determining the ARTIFACT_URL, but there's enough about that in all the other answers.

However, Docker best practises strongly discourage using ADD for this purpose and recommend using wget or curl.

How to check the version before installing a package using apt-get?

The following might work well enough:

aptitude versions ^hylafax+

See more in aptitude(8)

How to use a RELATIVE path with AuthUserFile in htaccess?

Let's take an example.

Your application is located in /var/www/myApp on some Linux server

.htaccess : /var/www/myApp/.htaccess

htpasswdApp : /var/www/myApp/htpasswdApp. (You're free to use any name for .htpasswd file)

To use relative path in .htaccess:

AuthType Digest
AuthName myApp
AuthUserFile "htpasswdApp"
Require valid-user

But it will search for file in server_root directory. Not in document_root.

In out case, when application is located at /var/www/myApp :

document_root is /var/www/myApp

server_root is /etc/apache2 //(just in our example, because of we using the linux server)

You can redefine it in your apache configuration file ( /etc/apache2/apache2.conf), but I guess it's a bad idea.

So to use relative file path in your /var/www/myApp/.htaccess you should define the password's file in your server_root.

I prefer to do it by follow command:

sudo ln -s /var/www/myApp/htpasswdApp /etc/apache2/htpasswdApp

You're free to copy my command, use a hard link instead of symbol,or copy a file to your server_root.

Jackson and generic type reference

This is a well-known problem with Java type erasure: T is just a type variable, and you must indicate actual class, usually as Class argument. Without such information, best that can be done is to use bounds; and plain T is roughly same as 'T extends Object'. And Jackson will then bind JSON Objects as Maps.

In this case, tester method needs to have access to Class, and you can construct

JavaType type = mapper.getTypeFactory().
  constructCollectionType(List.class, Foo.class)

and then

List<Foo> list = mapper.readValue(new File("input.json"), type);

Should I return EXIT_SUCCESS or 0 from main()?

0 is, by definition, a magic number. EXIT_SUCCESS is almost universally equal to 0, happily enough. So why not just return/exit 0?

exit(EXIT_SUCCESS); is abundantly clear in meaning.

exit(0); on the other hand, is counterintuitive in some ways. Someone not familiar with shell behavior might assume that 0 == false == bad, just like every other usage of 0 in C. But no - in this one special case, 0 == success == good. For most experienced devs, not going to be a problem. But why trip up the new guy for absolutely no reason?

tl;dr - if there's a defined constant for your magic number, there's almost never a reason not to used the constant in the first place. It's more searchable, often clearer, etc. and it doesn't cost you anything.

A child container failed during start java.util.concurrent.ExecutionException

This issue might also be caused by a broken Maven repository.

I observe the SEVERE: A child container failed during start message from time to time when working with Eclipse. My Eclipse workspace has several projects. Some of the projects have common external dependencies. If Maven repository is empty (or I add new dependencies into pom.xml files), Eclipse starts downloading libraries specified in pom.xml into Maven repository. And Eclipse does that in parallel for several projects in the workspace. It might happen that several Eclipse threads would be downloading the same file simultaneously into the same place in Maven repository. As a result, this file becomes corrupted.

So, this is how you could resolve the issue.

  1. Close your Eclipse.
  2. If you know which specific jar-file is broken in Maven repository, then delete that file.
  3. If you do not know which file is broken in Maven repository, then delete the whole repository (rm -rf $HOME/.m2).
  4. For each project, run mvn package in the command line. It is important to run the command for each project one-by-one, not in parallel; thus, you ensure that only one instance of Maven runs each time.
  5. Open your Eclipse.

What does the exclamation mark do before the function?

! is a logical NOT operator, it's a boolean operator that will invert something to its opposite.

Although you can bypass the parentheses of the invoked function by using the BANG (!) before the function, it will still invert the return, which might not be what you wanted. As in the case of an IEFE, it would return undefined, which when inverted becomes the boolean true.

Instead, use the closing parenthesis and the BANG (!) if needed.

// I'm going to leave the closing () in all examples as invoking the function with just ! and () takes away from what's happening.

(function(){ return false; }());
=> false

!(function(){ return false; }());
=> true

!!(function(){ return false; }());
=> false

!!!(function(){ return false; }());
=> true

Other Operators that work...

+(function(){ return false; }());
=> 0

-(function(){ return false; }());
=> -0

~(function(){ return false; }());
=> -1

Combined Operators...

+!(function(){ return false; }());
=> 1

-!(function(){ return false; }());
=> -1

!+(function(){ return false; }());
=> true

!-(function(){ return false; }());
=> true

~!(function(){ return false; }());
=> -2

~!!(function(){ return false; }());
=> -1

+~(function(){ return false; }());
+> -1

Does it make sense to use Require.js with Angular.js?

It makes sense to use requirejs with angularjs if you plan on lazy loading controllers and directives etc, while also combining multiple lazy dependencies into single script files for much faster lazy loading. RequireJS has an optimisation tool that makes the combining easy. See http://ify.io/using-requirejs-with-optimisation-for-lazy-loading-angularjs-artefacts/

Is there a simple way to delete a list element by value?

Maybe your solutions works with ints, but It Doesnt work for me with dictionarys.

In one hand, remove() has not worked for me. But maybe it works with basic Types. I guess the code bellow is also the way to remove items from objects list.

In the other hand, 'del' has not worked properly either. In my case, using python 3.6: when I try to delete an element from a list in a 'for' bucle with 'del' command, python changes the index in the process and bucle stops prematurely before time. It only works if You delete element by element in reversed order. In this way you dont change the pending elements array index when you are going through it

Then, Im used:

c = len(list)-1
for element in (reversed(list)):
    if condition(element):
        del list[c]
    c -= 1
print(list)

where 'list' is like [{'key1':value1'},{'key2':value2}, {'key3':value3}, ...]

Also You can do more pythonic using enumerate:

for i, element in enumerate(reversed(list)):
    if condition(element):
        del list[(i+1)*-1]
print(list)

What’s the best way to reload / refresh an iframe?

<script type="text/javascript">
  top.frames['DetailFrame'].location = top.frames['DetailFrame'].location;
</script> 

How do I close a tkinter window?

Illumination in case of confusion...

def quit(self):
    self.destroy()
    exit()

A) destroy() stops the mainloop and kills the window, but leaves python running

B) exit() stops the whole process

Just to clarify in case someone missed what destroy() was doing, and the OP also asked how to "end" a tkinter program.

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

Check if file exists and whether it contains a specific string

Instead of storing the output of grep in a variable and then checking whether the variable is empty, you can do this:

if grep -q "poet" $file_name
then
    echo "poet was found in $file_name"
fi

============

Here are some commonly used tests:

   -d FILE
          FILE exists and is a directory
   -e FILE
          FILE exists
   -f FILE
          FILE exists and is a regular file
   -h FILE
          FILE exists and is a symbolic link (same as -L)
   -r FILE
          FILE exists and is readable
   -s FILE
          FILE exists and has a size greater than zero
   -w FILE
          FILE exists and is writable
   -x FILE
          FILE exists and is executable
   -z STRING
          the length of STRING is zero

Example:

if [ -e "$file_name" ] && [ ! -z "$used_var" ]
then
    echo "$file_name exists and $used_var is not empty"
fi

Docker-compose: node_modules not present in a volume after npm install succeeds

If you want the node_modules folder available to the host during development, you could install the dependencies when you start the container instead of during build-time. I do this to get syntax highlighting working in my editor.

Dockerfile

# We're using a multi-stage build so that we can install dependencies during build-time only for production.

# dev-stage
FROM node:14-alpine AS dev-stage
WORKDIR /usr/src/app
COPY package.json ./
COPY . .
# `yarn install` will run every time we start the container. We're using yarn because it's much faster than npm when there's nothing new to install
CMD ["sh", "-c", "yarn install && yarn run start"]

# production-stage
FROM node:14-alpine AS production-stage
WORKDIR /usr/src/app
COPY package.json ./
RUN yarn install
COPY . .

.dockerignore

Add node_modules to .dockerignore to prevent it from being copied when the Dockerfile runs COPY . .. We use volumes to bring in node_modules.

**/node_modules

docker-compose.yml

node_app:
    container_name: node_app
    build:
        context: ./node_app
        target: dev-stage # `production-stage` for production
    volumes:
        # For development:
        #   If node_modules already exists on the host, they will be copied
        #   into the container here. Since `yarn install` runs after the
        #   container starts, this volume won't override the node_modules.
        - ./node_app:/usr/src/app
        # For production:
        #   
        - ./node_app:/usr/src/app
        - /usr/src/app/node_modules

Creating and playing a sound in swift

works in Xcode 9.2

if let soundURL = Bundle.main.url(forResource: "note1", withExtension: "wav") {
   var mySound: SystemSoundID = 0
   AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
   // Play
    AudioServicesPlaySystemSound(mySound);
 }

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

ran across this page and several like it all talking about the GIT_DISCOVERY_ACROSS_FILESYSTEM not set message. In my case our sys admin had decided that the apache2 directory needed to be on a mounted filesystem in case the disk for the server stopped working and had to get rebuilt. I found this with a simple df command:

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:48:43)--> df -h
Filesystem                           Size  Used Avail Use% Mounted on
<snip>
/dev/mapper/vgraid-lvapache           63G   54M   60G   1% /etc/apache2
<snip>

To fix this I just put the following in the root user's shell (as they are the only ones who need to be looking at etckeeper revisions:

export GIT_DISCOVERY_ACROSS_FILESYSTEM=1

and all was well and good...much joy.

More notes:

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:48:54)--> export GIT_DISCOVERY_ACROSS_FILESYSTEM=0

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:57:35)--> git status
On branch master
nothing to commit, working tree clean

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:57:40)--> touch apache2/me

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:57:45)--> git status
On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)

    apache2/me

nothing added to commit but untracked files present (use "git add" to track)

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:57:47)--> cd apache2

-->  UBIk  <--:root@ns1:[/etc/apache2]
--PRODUCTION--(16:57:50)--> git status
fatal: Not a git repository (or any parent up to mount point /etc/apache2)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).
-->  UBIk  <--:root@ns1:[/etc/apache2]
--PRODUCTION--(16:57:52)--> export GIT_DISCOVERY_ACROSS_FILESYSTEM=1

-->  UBIk  <--:root@ns1:[/etc/apache2]
--PRODUCTION--(16:58:59)--> git status
On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)

    me

nothing added to commit but untracked files present (use "git add" to track)

Hopefully that will help someone out somewhere... -wc

The most efficient way to remove first N elements in a list?

l = [1, 2, 3, 4, 5]
del l[0:3] # Here 3 specifies the number of items to be deleted.

This is the code if you want to delete a number of items from the list. You might as well skip the zero before the colon. It does not have that importance. This might do as well.

l = [1, 2, 3, 4, 5]
del l[:3] # Here 3 specifies the number of items to be deleted.

Why do Twitter Bootstrap tables always have 100% width?

Bootstrap 3:

Why fight it? Why not simply control your table width using the bootstrap grid?

<div class="row">
    <div class="col-sm-6">
        <table></table>
    </div>
</div>

This will create a table that is half (6 out of 12) of the width of the containing element.

I sometimes use inline styles as per the other answers, but it is discouraged.

Bootstrap 4:

Bootstrap 4 has some nice helper classes for width like w-25, w-50, w-75, w-100, and w-auto. This will make the table 50% width:

<table class="w-50"></table>

Here's the doc: https://getbootstrap.com/docs/4.0/utilities/sizing/

Vue - Deep watching an array of objects and calculating the change?

Your comparison function between old value and new value is having some issue. It is better not to complicate things so much, as it will increase your debugging effort later. You should keep it simple.

The best way is to create a person-component and watch every person separately inside its own component, as shown below:

<person-component :person="person" v-for="person in people"></person-component>

Please find below a working example for watching inside person component. If you want to handle it on parent side, you may use $emit to send an event upwards, containing the id of modified person.

_x000D_
_x000D_
Vue.component('person-component', {_x000D_
    props: ["person"],_x000D_
    template: `_x000D_
        <div class="person">_x000D_
            {{person.name}}_x000D_
            <input type='text' v-model='person.age'/>_x000D_
        </div>`,_x000D_
    watch: {_x000D_
        person: {_x000D_
            handler: function(newValue) {_x000D_
                console.log("Person with ID:" + newValue.id + " modified")_x000D_
                console.log("New age: " + newValue.age)_x000D_
            },_x000D_
            deep: true_x000D_
        }_x000D_
    }_x000D_
});_x000D_
_x000D_
new Vue({_x000D_
    el: '#app',_x000D_
    data: {_x000D_
        people: [_x000D_
          {id: 0, name: 'Bob', age: 27},_x000D_
          {id: 1, name: 'Frank', age: 32},_x000D_
          {id: 2, name: 'Joe', age: 38}_x000D_
        ]_x000D_
    }_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<body>_x000D_
    <div id="app">_x000D_
        <p>List of people:</p>_x000D_
        <person-component :person="person" v-for="person in people"></person-component>_x000D_
    </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

C++ Compare char array with string

There is more stable function, also gets rid of string folding.

// Add to C++ source
bool string_equal (const char* arg0, const char* arg1)
{
    /*
     * This function wraps string comparison with string pointers
     * (and also works around 'string folding', as I said).
     * Converts pointers to std::string
     * for make use of string equality operator (==).
     * Parameters use 'const' for prevent possible object corruption.
     */
    std::string var0 = (std::string) arg0;
    std::string var1 = (std::string) arg1;
    if (var0 == var1)
    {
        return true;
    }
    else
    {
        return false;
    }
}

And add declaration to header

// Parameters use 'const' for prevent possible object corruption.
bool string_equal (const char* arg0, const char* arg1);

For usage, just place an 'string_equal' call as condition of if (or ternary) statement/block.

if (string_equal (var1, "dev"))
{
    // It is equal, do what needed here.
}
else
{
    // It is not equal, do what needed here (optional).
}

Source: sinatramultimedia/fl32 codec (it's written by myself)

Why is this error, 'Sequence contains no elements', happening?

Check again. Use debugger if must. My guess is that for some item in userResponseDetails this query finds no elements:

.Where(y => y.ResponseId.Equals(item.ResponseId))

so you can't call

.First()

on it. Maybe try

.FirstOrDefault()

if it solves the issue.

Do NOT return NULL value! This is purely so that you can see and diagnose where problem is. Handle these cases properly.

Write to custom log file from a Bash script

logger logs to syslog facilities. If you want the message to go to a particular file you have to modify the syslog configuration accordingly. You could add a line like this:

local7.*   -/var/log/mycustomlog

and restart syslog. Then you can log like this:

logger -p local7.info "information message"
logger -p local7.err "error message"

and the messages will appear in the desired logfile with the correct log level.

Without making changes to the syslog configuration you could use logger like this:

logger -s "foo bar" >> /var/log/mycustomlog

That would instruct logger to print the message to STDERR as well (in addition to logging it to syslog), so you could redirect STDERR to a file. However, it would be utterly pointless, because the message is already logged via syslog anyway (with the default priority user.notice).

How can I get current location from user in iOS

In Swift (for iOS 8+).

Info.plist

First things first. You need to add your descriptive string in the info.plist file for the keys NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription depending on what kind of service you are requesting

Code

import Foundation
import CoreLocation

class LocationManager: NSObject, CLLocationManagerDelegate {
    
    let manager: CLLocationManager
    var locationManagerClosures: [((userLocation: CLLocation) -> ())] = []
    
    override init() {
        self.manager = CLLocationManager()
        super.init()
        self.manager.delegate = self
    }
    
    //This is the main method for getting the users location and will pass back the usersLocation when it is available
    func getlocationForUser(userLocationClosure: ((userLocation: CLLocation) -> ())) {
        
        self.locationManagerClosures.append(userLocationClosure)
        
        //First need to check if the apple device has location services availabel. (i.e. Some iTouch's don't have this enabled)
        if CLLocationManager.locationServicesEnabled() {
            //Then check whether the user has granted you permission to get his location
            if CLLocationManager.authorizationStatus() == .NotDetermined {
                //Request permission
                //Note: you can also ask for .requestWhenInUseAuthorization
                manager.requestWhenInUseAuthorization()
            } else if CLLocationManager.authorizationStatus() == .Restricted || CLLocationManager.authorizationStatus() == .Denied {
                //... Sorry for you. You can huff and puff but you are not getting any location
            } else if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
                // This will trigger the locationManager:didUpdateLocation delegate method to get called when the next available location of the user is available
                manager.startUpdatingLocation()
            }
        }
        
    }
    
    //MARK: CLLocationManager Delegate methods
    
    @objc func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        if status == .AuthorizedAlways || status == .AuthorizedWhenInUse {
            manager.startUpdatingLocation()
        }
    }
    
    func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
        //Because multiple methods might have called getlocationForUser: method there might me multiple methods that need the users location.
        //These userLocation closures will have been stored in the locationManagerClosures array so now that we have the users location we can pass the users location into all of them and then reset the array.
        let tempClosures = self.locationManagerClosures
        for closure in tempClosures {
            closure(userLocation: newLocation)
        }
        self.locationManagerClosures = []
    }
}

Usage

self.locationManager = LocationManager()
self.locationManager.getlocationForUser { (userLocation: CLLocation) -> () in
            print(userLocation)
        }

How to replace a substring of a string

By regex i think this is java, the method replaceAll() returns a new String with the substrings replaced, so try this:

String teste = "abcd=0; efgh=1";

String teste2 = teste.replaceAll("abcd", "dddd");

System.out.println(teste2);

Output:

dddd=0; efgh=1

Replace last occurrence of character in string

Another super clear way of doing this could be as follows:

let modifiedString = originalString
   .split('').reverse().join('')
   .replace('_', '')
   .split('').reverse().join('')

How to update MySql timestamp column to current timestamp on PHP?

Use this query:

UPDATE `table` SET date_date=now();

Sample code can be:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

mysql_query("UPDATE `table` SET date_date=now()");

mysql_close($con);
?>

Is it worth using Python's re.compile?

I agree with Honest Abe that the match(...) in the given examples are different. They are not a one-to-one comparisons and thus, outcomes are vary. To simplify my reply, I use A, B, C, D for those functions in question. Oh yes, we are dealing with 4 functions in re.py instead of 3.

Running this piece of code:

h = re.compile('hello')                   # (A)
h.match('hello world')                    # (B)

is same as running this code:

re.match('hello', 'hello world')          # (C)

Because, when looked into the source re.py, (A + B) means:

h = re._compile('hello')                  # (D)
h.match('hello world')

and (C) is actually:

re._compile('hello').match('hello world')

So, (C) is not the same as (B). In fact, (C) calls (B) after calling (D) which is also called by (A). In other words, (C) = (A) + (B). Therefore, comparing (A + B) inside a loop has same result as (C) inside a loop.

George's regexTest.py proved this for us.

noncompiled took 4.555 seconds.           # (C) in a loop
compiledInLoop took 4.620 seconds.        # (A + B) in a loop
compiled took 2.323 seconds.              # (A) once + (B) in a loop

Everyone's interest is, how to get the result of 2.323 seconds. In order to make sure compile(...) only get called once, we need to store the compiled regex object in memory. If we are using a class, we could store the object and reuse when every time our function get called.

class Foo:
    regex = re.compile('hello')
    def my_function(text)
        return regex.match(text)

If we are not using class (which is my request today), then I have no comment. I'm still learning to use global variable in Python, and I know global variable is a bad thing.

One more point, I believe that using (A) + (B) approach has an upper hand. Here are some facts as I observed (please correct me if I'm wrong):

  1. Calls A once, it will do one search in the _cache followed by one sre_compile.compile() to create a regex object. Calls A twice, it will do two searches and one compile (because the regex object is cached).

  2. If the _cache get flushed in between, then the regex object is released from memory and Python need to compile again. (someone suggest that Python won't recompile.)

  3. If we keep the regex object by using (A), the regex object will still get into _cache and get flushed somehow. But our code keep a reference on it and the regex object will not be released from memory. Those, Python need not to compile again.

  4. The 2 seconds differences in George's test compiledInLoop vs compiled is mainly the time required to build the key and search the _cache. It doesn't mean the compile time of regex.

  5. George's reallycompile test show what happen if it really re-do the compile every time: it will be 100x slower (he reduced the loop from 1,000,000 to 10,000).

Here are the only cases that (A + B) is better than (C):

  1. If we can cache a reference of the regex object inside a class.
  2. If we need to calls (B) repeatedly (inside a loop or multiple times), we must cache the reference to regex object outside the loop.

Case that (C) is good enough:

  1. We cannot cache a reference.
  2. We only use it once in a while.
  3. In overall, we don't have too many regex (assume the compiled one never get flushed)

Just a recap, here are the A B C:

h = re.compile('hello')                   # (A)
h.match('hello world')                    # (B)
re.match('hello', 'hello world')          # (C)

Thanks for reading.

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

I have solved this issue about $ sudo docker run hello-world following the Docker doc.

If you are behind an HTTP Proxy server of corporate, this may solve your problem.

Docker doc also displays other situation about HTTP proxy setting.

Make file echo displaying "$PATH" string

The make uses the $ for its own variable expansions. E.g. single character variable $A or variable with a long name - ${VAR} and $(VAR).

To put the $ into a command, use the $$, for example:

all:
  @echo "Please execute next commands:"
  @echo 'setenv PATH /usr/local/greenhills/mips5/linux86:$$PATH'

Also note that to make the "" and '' (double and single quoting) do not play any role and they are passed verbatim to the shell. (Remove the @ sign to see what make sends to shell.) To prevent the shell from expanding $PATH, second line uses the ''.

How to insert a line break before an element using CSS

It's possible using the \A escape sequence in the psuedo-element generated content. Read more in the CSS2 spec.

#restart:before { content: '\A'; }

You may also need to add white-space:pre; to #restart.

note: \A denotes the end of a line.

p.s. Another treatment to be

:before { content: ' '; display: block; }

How to get cookie's expire time

Putting an encoded json inside the cookie is my favorite method, to get properly formated data out of a cookie. Try that:

$expiry = time() + 12345;
$data = (object) array( "value1" => "just for fun", "value2" => "i'll save whatever I want here" );
$cookieData = (object) array( "data" => $data, "expiry" => $expiry );
setcookie( "cookiename", json_encode( $cookieData ), $expiry );

then when you get your cookie next time:

$cookie = json_decode( $_COOKIE[ "cookiename" ] );

you can simply extract the expiry time, which was inserted as data inside the cookie itself..

$expiry = $cookie->expiry;

and additionally the data which will come out as a usable object :)

$data = $cookie->data;
$value1 = $cookie->data->value1;

etc. I find that to be a much neater way to use cookies, because you can nest as many small objects within other objects as you wish!

Exclude Blank and NA in R

Don't know exactly what kind of dataset you have, so I provide general answer.

x <- c(1,2,NA,3,4,5)
y <- c(1,2,3,NA,6,8)
my.data <- data.frame(x, y)
> my.data
   x  y
1  1  1
2  2  2
3 NA  3
4  3 NA
5  4  6
6  5  8
# Exclude rows with NA values
my.data[complete.cases(my.data),]
  x y
1 1 1
2 2 2
5 4 6
6 5 8

jQuery, get ID of each element in a class using .each?

patrick dw's answer is right on.

For kicks and giggles I thought I would post a simple way to return an array of all the IDs.

var arrayOfIds = $.map($(".myClassName"), function(n, i){
  return n.id;
});
alert(arrayOfIds);

How to disable button in React.js

this.input is undefined until the ref callback is called. Try setting this.input to some initial value in your constructor.

From the React docs on refs, emphasis mine:

the callback will be executed immediately after the component is mounted or unmounted

Format Date output in JSF

With EL 2 (Expression Language 2) you can use this type of construct for your question:

    #{formatBean.format(myBean.birthdate)}

Or you can add an alternate getter in your bean resulting in

    #{myBean.birthdateString}

where getBirthdateString returns the proper text representation. Remember to annotate the get method as @Transient if it is an Entity.

XAMPP: Couldn't start Apache (Windows 10)

  • Go to the start menu, and type Turn Windows features on or off
  • Uncheck Internet Information Services
  • Press OK

Switch statement multiple cases in JavaScript

One of the possible solutions is:

const names = {
afshin: 'afshin',
saeed: 'saeed',
larry: 'larry'
};

switch (varName) {
   case names[varName]: {
       alert('Hey');
       break;
   }

   default: {
       alert('Default case');
       break;
   }
}

null terminating a string

'\0' is the way to go. It's a character, which is what's wanted in a string and has the null value.

When we say null terminated string in C/C++, it really means 'zero terminated string'. The NULL macro isn't intended for use in terminating strings.

How to open some ports on Ubuntu?

If you want to open it for a range and for a protocol

ufw allow 11200:11299/tcp
ufw allow 11200:11299/udp

D3 Appending Text to a SVG Rectangle

A rect can't contain a text element. Instead transform a g element with the location of text and rectangle, then append both the rectangle and the text to it:

var bar = chart.selectAll("g")
    .data(data)
  .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

bar.append("rect")
    .attr("width", x)
    .attr("height", barHeight - 1);

bar.append("text")
    .attr("x", function(d) { return x(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d; });

http://bl.ocks.org/mbostock/7341714

Multi-line labels are also a little tricky, you might want to check out this wrap function.

How do I get the object if it exists, or None if it does not exist?

From django 1.7 onwards you can do like:

class MyQuerySet(models.QuerySet):

    def get_or_none(self, **kwargs):
        try:
            return self.get(**kwargs)
        except self.model.DoesNotExist:
            return None


class MyBaseModel(models.Model):

    objects = MyQuerySet.as_manager()


class MyModel(MyBaseModel):
    ...

class AnotherMyModel(MyBaseModel):
    ...

The advantage of "MyQuerySet.as_manager()" is that both of the following will work:

MyModel.objects.filter(...).get_or_none()
MyModel.objects.get_or_none()

SQL: How to perform string does not equal

select * from table
where tester NOT LIKE '%username%';

What does the "at" (@) symbol do in Python?

It indicates that you are using a decorator. Here is Bruce Eckel's example from 2008.

How to convert NSData to byte array in iPhone?

Already answered, but to generalize to help other readers:

    //Here:   NSData * fileData;
    uint8_t * bytePtr = (uint8_t  * )[fileData bytes];

    // Here, For getting individual bytes from fileData, uint8_t is used.
    // You may choose any other data type per your need, eg. uint16, int32, char, uchar, ... .
    // Make sure, fileData has atleast number of bytes that a single byte chunk would need. eg. for int32, fileData length must be > 4 bytes. Makes sense ?

    // Now, if you want to access whole data (fileData) as an array of uint8_t
    NSInteger totalData = [fileData length] / sizeof(uint8_t);

    for (int i = 0 ; i < totalData; i ++)
    {
        NSLog(@"data byte chunk : %x", bytePtr[i]);
    }

Could not resolve this reference. Could not locate the assembly

I had faced similar linker issues while adding a NuGet package into the iOS project (in Xamarin forms project). We had earlier provided the additional mtouch argument in the build configurations like this -dlsym:false -cxx -v -v -v -v -gcc_flags

After removing -dlsym:false from the configuration, the issues got resolved for me.

How to compare two tags with git?

If source code is on Github, you can use their comparing tool: https://help.github.com/articles/comparing-commits-across-time/

How can I render Partial views in asp.net mvc 3?

Create your partial view something like:

@model YourModelType
<div>
  <!-- HTML to render your object -->
</div>

Then in your view use:

@Html.Partial("YourPartialViewName", Model)

If you do not want a strongly typed partial view remove the @model YourModelType from the top of the partial view and it will default to a dynamic type.

Update

The default view engine will search for partial views in the same folder as the view calling the partial and then in the ~/Views/Shared folder. If your partial is located in a different folder then you need to use the full path. Note the use of ~/ in the path below.

@Html.Partial("~/Views/Partials/SeachResult.cshtml", Model)

How do I catch a PHP fatal (`E_ERROR`) error?

Not really. Fatal errors are called that, because they are fatal. You can't recover from them.

Alter Table Add Column Syntax

Just remove COLUMN from ADD COLUMN

ALTER TABLE Employees
  ADD EmployeeID numeric NOT NULL IDENTITY (1, 1)

ALTER TABLE Employees ADD CONSTRAINT
        PK_Employees PRIMARY KEY CLUSTERED 
        (
          EmployeeID
        ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
        ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

Sorting JSON by values

Solution working with different types and with upper and lower cases.
For example, without the toLowerCase statement, "Goodyear" will come before "doe" with an ascending sort. Run the code snippet at the bottom of my answer to view the different behaviors.

JSON DATA:

var people = [
{
    "f_name" : "john",
    "l_name" : "doe", // lower case
    "sequence": 0 // int
},
{
    "f_name" : "michael",
    "l_name" : "Goodyear", // upper case
    "sequence" : 1 // int
}];

JSON Sort Function:

function sortJson(element, prop, propType, asc) {
  switch (propType) {
    case "int":
      element = element.sort(function (a, b) {
        if (asc) {
          return (parseInt(a[prop]) > parseInt(b[prop])) ? 1 : ((parseInt(a[prop]) < parseInt(b[prop])) ? -1 : 0);
        } else {
          return (parseInt(b[prop]) > parseInt(a[prop])) ? 1 : ((parseInt(b[prop]) < parseInt(a[prop])) ? -1 : 0);
        }
      });
      break;
    default:
      element = element.sort(function (a, b) {
        if (asc) {
          return (a[prop].toLowerCase() > b[prop].toLowerCase()) ? 1 : ((a[prop].toLowerCase() < b[prop].toLowerCase()) ? -1 : 0);
        } else {
          return (b[prop].toLowerCase() > a[prop].toLowerCase()) ? 1 : ((b[prop].toLowerCase() < a[prop].toLowerCase()) ? -1 : 0);
        }
      });
  }
}

Usage:

sortJson(people , "l_name", "string", true);
sortJson(people , "sequence", "int", true);

_x000D_
_x000D_
var people = [{_x000D_
  "f_name": "john",_x000D_
  "l_name": "doe",_x000D_
  "sequence": 0_x000D_
}, {_x000D_
  "f_name": "michael",_x000D_
  "l_name": "Goodyear",_x000D_
  "sequence": 1_x000D_
}, {_x000D_
  "f_name": "bill",_x000D_
  "l_name": "Johnson",_x000D_
  "sequence": 4_x000D_
}, {_x000D_
  "f_name": "will",_x000D_
  "l_name": "malone",_x000D_
  "sequence": 2_x000D_
}, {_x000D_
  "f_name": "tim",_x000D_
  "l_name": "Allen",_x000D_
  "sequence": 3_x000D_
}];_x000D_
_x000D_
function sortJsonLcase(element, prop, asc) {_x000D_
  element = element.sort(function(a, b) {_x000D_
    if (asc) {_x000D_
      return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);_x000D_
    } else {_x000D_
      return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);_x000D_
    }_x000D_
  });_x000D_
}_x000D_
_x000D_
function sortJson(element, prop, propType, asc) {_x000D_
  switch (propType) {_x000D_
    case "int":_x000D_
      element = element.sort(function(a, b) {_x000D_
        if (asc) {_x000D_
          return (parseInt(a[prop]) > parseInt(b[prop])) ? 1 : ((parseInt(a[prop]) < parseInt(b[prop])) ? -1 : 0);_x000D_
        } else {_x000D_
          return (parseInt(b[prop]) > parseInt(a[prop])) ? 1 : ((parseInt(b[prop]) < parseInt(a[prop])) ? -1 : 0);_x000D_
        }_x000D_
      });_x000D_
      break;_x000D_
    default:_x000D_
      element = element.sort(function(a, b) {_x000D_
        if (asc) {_x000D_
          return (a[prop].toLowerCase() > b[prop].toLowerCase()) ? 1 : ((a[prop].toLowerCase() < b[prop].toLowerCase()) ? -1 : 0);_x000D_
        } else {_x000D_
          return (b[prop].toLowerCase() > a[prop].toLowerCase()) ? 1 : ((b[prop].toLowerCase() < a[prop].toLowerCase()) ? -1 : 0);_x000D_
        }_x000D_
      });_x000D_
  }_x000D_
}_x000D_
_x000D_
function sortJsonString() {_x000D_
  sortJson(people, 'l_name', 'string', $("#chkAscString").prop("checked"));_x000D_
  display();_x000D_
}_x000D_
_x000D_
function sortJsonInt() {_x000D_
  sortJson(people, 'sequence', 'int', $("#chkAscInt").prop("checked"));_x000D_
  display();_x000D_
}_x000D_
_x000D_
function sortJsonUL() {_x000D_
  sortJsonLcase(people, 'l_name', $('#chkAsc').prop('checked'));_x000D_
  display();_x000D_
}_x000D_
_x000D_
function display() {_x000D_
  $("#data").empty();_x000D_
  $(people).each(function() {_x000D_
    $("#data").append("<div class='people'>" + this.l_name + "</div><div class='people'>" + this.f_name + "</div><div class='people'>" + this.sequence + "</div><br />");_x000D_
  });_x000D_
}
_x000D_
body {_x000D_
  font-family: Arial;_x000D_
}_x000D_
.people {_x000D_
  display: inline-block;_x000D_
  width: 100px;_x000D_
  border: 1px dotted black;_x000D_
  padding: 5px;_x000D_
  margin: 5px;_x000D_
}_x000D_
.buttons {_x000D_
  border: 1px solid black;_x000D_
  padding: 5px;_x000D_
  margin: 5px;_x000D_
  float: left;_x000D_
  width: 20%;_x000D_
}_x000D_
ul {_x000D_
  margin: 5px 0px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="buttons" style="background-color: rgba(240, 255, 189, 1);">_x000D_
  Sort the JSON array <strong style="color: red;">with</strong> toLowerCase:_x000D_
  <ul>_x000D_
    <li>Type: string</li>_x000D_
    <li>Property: lastname</li>_x000D_
  </ul>_x000D_
  <button onclick="sortJsonString(); return false;">Sort JSON</button>_x000D_
  Asc Sort_x000D_
  <input id="chkAscString" type="checkbox" checked="checked" />_x000D_
</div>_x000D_
<div class="buttons" style="background-color: rgba(255, 214, 215, 1);">_x000D_
  Sort the JSON array <strong style="color: red;">without</strong> toLowerCase:_x000D_
  <ul>_x000D_
    <li>Type: string</li>_x000D_
    <li>Property: lastname</li>_x000D_
  </ul>_x000D_
  <button onclick="sortJsonUL(); return false;">Sort JSON</button>_x000D_
  Asc Sort_x000D_
  <input id="chkAsc" type="checkbox" checked="checked" />_x000D_
</div>_x000D_
<div class="buttons" style="background-color: rgba(240, 255, 189, 1);">_x000D_
  Sort the JSON array:_x000D_
  <ul>_x000D_
    <li>Type: int</li>_x000D_
    <li>Property: sequence</li>_x000D_
  </ul>_x000D_
  <button onclick="sortJsonInt(); return false;">Sort JSON</button>_x000D_
  Asc Sort_x000D_
  <input id="chkAscInt" type="checkbox" checked="checked" />_x000D_
</div>_x000D_
<br />_x000D_
<br />_x000D_
<div id="data" style="float: left; border: 1px solid black; width: 60%; margin: 5px;">Data</div>
_x000D_
_x000D_
_x000D_

How to call a REST web service API from JavaScript?

Before we try to put anything on the front end of the website, let's open a connection the API. We'll do so using XMLHttpRequest objects, which is a way to open files and make an HTTP request.

We'll create a request variable and assign a new XMLHttpRequest object to it. Then we'll open a new connection with the open() method - in the arguments we'll specify the type of request as GET as well as the URL of the API endpoint. The request completes and we can access the data inside the onload function. When we're done, we'll send the request.
// Create a request variable and assign a new XMLHttpRequest object to it. var request = new XMLHttpRequest()

// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)

request.onload = function () {
  // Begin accessing JSON data here
  }
}

// Send request
request.send()

Gson: How to exclude specific fields from Serialization without annotations

Nishant provided a good solution, but there's an easier way. Simply mark the desired fields with the @Expose annotation, such as:

@Expose private Long id;

Leave out any fields that you do not want to serialize. Then just create your Gson object this way:

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

This is the job for style property:

document.getElementById("remember").style.visibility = "visible";

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

Normally when an optimization algorithm does not converge, it is usually because the problem is not well-conditioned, perhaps due to a poor scaling of the decision variables. There are a few things you can try.

  1. Normalize your training data so that the problem hopefully becomes more well conditioned, which in turn can speed up convergence. One possibility is to scale your data to 0 mean, unit standard deviation using Scikit-Learn's StandardScaler for an example. Note that you have to apply the StandardScaler fitted on the training data to the test data.
  2. Related to 1), make sure the other arguments such as regularization weight, C, is set appropriately.
  3. Set max_iter to a larger value. The default is 1000.
  4. Set dual = True if number of features > number of examples and vice versa. This solves the SVM optimization problem using the dual formulation. Thanks @Nino van Hooff for pointing this out, and @JamesKo for spotting my mistake.
  5. Use a different solver, for e.g., the L-BFGS solver if you are using Logistic Regression. See @5ervant's answer.

Note: One should not ignore this warning.

This warning came about because

  1. Solving the linear SVM is just solving a quadratic optimization problem. The solver is typically an iterative algorithm that keeps a running estimate of the solution (i.e., the weight and bias for the SVM). It stops running when the solution corresponds to an objective value that is optimal for this convex optimization problem, or when it hits the maximum number of iterations set.

  2. If the algorithm does not converge, then the current estimate of the SVM's parameters are not guaranteed to be any good, hence the predictions can also be complete garbage.

Edit

In addition, consider the comment by @Nino van Hooff and @5ervant to use the dual formulation of the SVM. This is especially important if the number of features you have, D, is more than the number of training examples N. This is what the dual formulation of the SVM is particular designed for and helps with the conditioning of the optimization problem. Credit to @5ervant for noticing and pointing this out.

Furthermore, @5ervant also pointed out the possibility of changing the solver, in particular the use of the L-BFGS solver. Credit to him (i.e., upvote his answer, not mine).

I would like to provide a quick rough explanation for those who are interested (I am :)) why this matters in this case. Second-order methods, and in particular approximate second-order method like the L-BFGS solver, will help with ill-conditioned problems because it is approximating the Hessian at each iteration and using it to scale the gradient direction. This allows it to get better convergence rate but possibly at a higher compute cost per iteration. That is, it takes fewer iterations to finish but each iteration will be slower than a typical first-order method like gradient-descent or its variants.

For e.g., a typical first-order method might update the solution at each iteration like

x(k + 1) = x(k) - alpha(k) * gradient(f(x(k)))

where alpha(k), the step size at iteration k, depends on the particular choice of algorithm or learning rate schedule.

A second order method, for e.g., Newton, will have an update equation

x(k + 1) = x(k) - alpha(k) * Hessian(x(k))^(-1) * gradient(f(x(k)))

That is, it uses the information of the local curvature encoded in the Hessian to scale the gradient accordingly. If the problem is ill-conditioned, the gradient will be pointing in less than ideal directions and the inverse Hessian scaling will help correct this.

In particular, L-BFGS mentioned in @5ervant's answer is a way to approximate the inverse of the Hessian as computing it can be an expensive operation.

However, second-order methods might converge much faster (i.e., requires fewer iterations) than first-order methods like the usual gradient-descent based solvers, which as you guys know by now sometimes fail to even converge. This can compensate for the time spent at each iteration.

In summary, if you have a well-conditioned problem, or if you can make it well-conditioned through other means such as using regularization and/or feature scaling and/or making sure you have more examples than features, you probably don't have to use a second-order method. But these days with many models optimizing non-convex problems (e.g., those in DL models), second order methods such as L-BFGS methods plays a different role there and there are evidence to suggest they can sometimes find better solutions compared to first-order methods. But that is another story.

how to make a countdown timer in java

You can create a countdown timer using applet, below is the code,

   import java.applet.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.Timer; // not java.util.Timer
   import java.text.NumberFormat;
   import java.net.*;



/**
    * An applet that counts down from a specified time. When it reaches 00:00,
    * it optionally plays a sound and optionally moves the browser to a new page.
    * Place the mouse over the applet to pause the count; move it off to resume.
    * This class demonstrates most applet methods and features.
    **/

public class Countdown extends JApplet implements ActionListener, MouseListener
{
long remaining; // How many milliseconds remain in the countdown.
long lastUpdate; // When count was last updated
JLabel label; // Displays the count
Timer timer; // Updates the count every second
NumberFormat format; // Format minutes:seconds with leading zeros
Image image; // Image to display along with the time
AudioClip sound; // Sound to play when we reach 00:00

// Called when the applet is first loaded
public void init() {
    // Figure out how long to count for by reading the "minutes" parameter
    // defined in a <param> tag inside the <applet> tag. Convert to ms.
    String minutes = getParameter("minutes");
    if (minutes != null) remaining = Integer.parseInt(minutes) * 60000;
    else remaining = 600000; // 10 minutes by default

    // Create a JLabel to display remaining time, and set some properties.
    label = new JLabel();
    label.setHorizontalAlignment(SwingConstants.CENTER );
    label.setOpaque(true); // So label draws the background color

    // Read some parameters for this JLabel object
    String font = getParameter("font");
    String foreground = getParameter("foreground");
    String background = getParameter("background");
    String imageURL = getParameter("image");

    // Set label properties based on those parameters
    if (font != null) label.setFont(Font.decode(font));
    if (foreground != null) label.setForeground(Color.decode(foreground));
    if (background != null) label.setBackground(Color.decode(background));
    if (imageURL != null) {
        // Load the image, and save it so we can release it later
        image = getImage(getDocumentBase(), imageURL);
        // Now display the image in the JLabel.
        label.setIcon(new ImageIcon(image));
    }

    // Now add the label to the applet. Like JFrame and JDialog, JApplet
    // has a content pane that you add children to
    getContentPane().add(label, BorderLayout.CENTER);

    // Get an optional AudioClip to play when the count expires
    String soundURL = getParameter("sound");
    if (soundURL != null) sound=getAudioClip(getDocumentBase(), soundURL);

    // Obtain a NumberFormat object to convert number of minutes and
    // seconds to strings. Set it up to produce a leading 0 if necessary
    format = NumberFormat.getNumberInstance();
    format.setMinimumIntegerDigits(2); // pad with 0 if necessary

    // Specify a MouseListener to handle mouse events in the applet.
    // Note that the applet implements this interface itself
    addMouseListener(this);

    // Create a timer to call the actionPerformed() method immediately,
    // and then every 1000 milliseconds. Note we don't start the timer yet.
    timer = new Timer(1000, this);
    timer.setInitialDelay(0); // First timer is immediate.
}

// Free up any resources we hold; called when the applet is done
public void destroy() { if (image != null) image.flush(); }

// The browser calls this to start the applet running
// The resume() method is defined below.
public void start() { resume(); } // Start displaying updates

// The browser calls this to stop the applet. It may be restarted later.
// The pause() method is defined below
public void stop() { pause(); } // Stop displaying updates

// Return information about the applet
public String getAppletInfo() {
    return "Countdown applet Copyright (c) 2003 by David Flanagan";
}

// Return information about the applet parameters
public String[][] getParameterInfo() { return parameterInfo; }

// This is the parameter information. One array of strings for each
// parameter. The elements are parameter name, type, and description.
static String[][] parameterInfo = {
    {"minutes", "number", "time, in minutes, to countdown from"},
    {"font", "font", "optional font for the time display"},
    {"foreground", "color", "optional foreground color for the time"},
    {"background", "color", "optional background color"},
    {"image", "image URL", "optional image to display next to countdown"},
    {"sound", "sound URL", "optional sound to play when we reach 00:00"},
    {"newpage", "document URL", "URL to load when timer expires"},
};

// Start or resume the countdown
void resume() {
    // Restore the time we're counting down from and restart the timer.
    lastUpdate = System.currentTimeMillis();
    timer.start(); // Start the timer
}

// Pause the countdown
void pause() {
    // Subtract elapsed time from the remaining time and stop timing
    long now = System.currentTimeMillis();
    remaining -= (now - lastUpdate);
    timer.stop(); // Stop the timer
}

// Update the displayed time. This method is called from actionPerformed()
// which is itself invoked by the timer.
void updateDisplay() {
    long now = System.currentTimeMillis(); // current time in ms
    long elapsed = now - lastUpdate; // ms elapsed since last update
    remaining -= elapsed; // adjust remaining time
    lastUpdate = now; // remember this update time

    // Convert remaining milliseconds to mm:ss format and display
    if (remaining < 0) remaining = 0;
    int minutes = (int)(remaining/60000);
    int seconds = (int)((remaining)/1000);
    label.setText(format.format(minutes) + ":" + format.format(seconds));

    // If we've completed the countdown beep and display new page
    if (remaining == 0) {
        // Stop updating now.
        timer.stop();
        // If we have an alarm sound clip, play it now.
        if (sound != null) sound.play();
        // If there is a newpage URL specified, make the browser
        // load that page now.
        String newpage = getParameter("newpage");
        if (newpage != null) {
            try {
                URL url = new URL(getDocumentBase(), newpage);
                getAppletContext().showDocument(url);
            }
            catch(MalformedURLException ex) {      showStatus(ex.toString()); }
        }
    }
}

// This method implements the ActionListener interface.
// It is invoked once a second by the Timer object
// and updates the JLabel to display minutes and seconds remaining.
public void actionPerformed(ActionEvent e) { updateDisplay(); }

// The methods below implement the MouseListener interface. We use
// two of them to pause the countdown when the mouse hovers over the timer.
// Note that we also display a message in the statusline
public void mouseEntered(MouseEvent e) {
    pause(); // pause countdown
    showStatus("Paused"); // display statusline message
}
public void mouseExited(MouseEvent e) {
    resume(); // resume countdown
    showStatus(""); // clear statusline
}
// These MouseListener methods are unused.
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
} 

Curl setting Content-Type incorrectly

I think you want to specify

-H "Content-Type:text/xml"

with a colon, not an equals.

View/edit ID3 data for MP3 files

Thirding TagLib Sharp.

TagLib.File f = TagLib.File.Create(path);
f.Tag.Album = "New Album Title";
f.Save();

disabling spring security in spring boot app

For me only excluding the following classes worked:

import org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class}) {
  // ... 
}

Is there a way to make text unselectable on an HTML page?

If it looks bad you can use CSS to change the appearance of selected sections.

How do I remove a single file from the staging area (undo git add)?

git reset filename.txt

If you have a modification in filename.txt , you added it to stage by mistake and you want to remove the file from staging but you don't want to lose the changes.

Java: Difference between the setPreferredSize() and setSize() methods in components

IIRC ...

setSize sets the size of the component.

setPreferredSize sets the preferred size. The Layoutmanager will try to arrange that much space for your component.

It depends on whether you're using a layout manager or not ...

How to create a horizontal loading progress bar?

Worked for me , can try with the same

<ProgressBar
    android:id="@+id/determinateBar"
    android:indeterminateOnly="true"
    android:indeterminateDrawable="@android:drawable/progress_indeterminate_horizontal"
    android:indeterminateDuration="10"
    android:indeterminateBehavior="repeat"
    android:progressBackgroundTint="#208afa"
    android:progressBackgroundTintMode="multiply"
    android:minHeight="24dip"
    android:maxHeight="24dip"
    android:layout_width="match_parent"
    android:layout_height="10dp"
    android:visibility="visible"/>

How to handle invalid SSL certificates with Apache HttpClient?

https://mms.nw.ru likely uses a certificate not issued by a certification authority. Consequently, you need to add the certificate to your trusted Java key store as explained in unable to find valid certification path to requested target:

When working on a client that works with an SSL enabled server running in https protocol, you could get error 'unable to find valid certification path to requested target' if the server certificate is not issued by certification authority, but a self signed or issued by a private CMS.

Don't panic. All you need to do is to add the server certificate to your trusted Java key store if your client is written in Java. You might be wondering how as if you can not access the machine where the server is installed. There is a simple program can help you. Please download the Java program and run

% java InstallCert _web_site_hostname_

This program opened a connection to the specified host and started an SSL handshake. It printed the exception stack trace of the error that occured and shows you the certificates used by the server. Now it prompts you add the certificate to your trusted KeyStore.

If you've changed your mind, enter 'q'. If you really want to add the certificate, enter '1', or other numbers to add other certificates, even a CA certificate, but you usually don't want to do that. Once you have made your choice, the program will display the complete certificate and then added it to a Java KeyStore named 'jssecacerts' in the current directory.

To use it in your program, either configure JSSE to use it as its trust store or copy it into your $JAVA_HOME/jre/lib/security directory. If you want all Java applications to recognize the certificate as trusted and not just JSSE, you could also overwrite the cacerts file in that directory.

After all that, JSSE will be able to complete a handshake with the host, which you can verify by running the program again.

To get more details, you can check out Leeland's blog No more 'unable to find valid certification path to requested target'

Check if registry key exists using VBScript

See the Scripting Guy! Blog:

How Can I Tell Whether a Value Exists in the Registry?

They discuss doing the check on a remote computer and show that if you read a string value from the key, and if the value is Null (as opposed to Empty), the key does not exist.

With respect to using the RegRead method, if the term "key" refers to the path (or folder) where registry values are kept, and if the leaf items in that key are called "values", using WshShell.RegRead(strKey) to detect key existence (as opposed to value existance) consider the following (as observed on Windows XP):

If strKey name is not the name of an existing registry path, Err.Description reads "Invalid root in registry key"... with an Err.Number of 0x80070002.

If strKey names a registry path that exists but does not include a trailing "\" the RegRead method appears to interpret strKey as a path\value reference rather than as a simple path reference, and returns the same Err.Number but with an Err.Description of "Unable to open registry key". The term "key" in the error message appears to mean "value". This is the same result obtained when strKey references a path\value where the path exists, but the value does not exist.

Pause Console in C++ program

There might be a best way (like using the portable cin.get()), but a good way doesn't exist. A program that has done its job should quit and give its resources back to the computer.

And yes, any usage of system() leads to unportable code, as the parameter is passed to the shell that owns your process.

Having pausing-code in your source code sooner or later causes hassles:

  • someone forgets to delete the pausing code before checking in
    • now all working mates have to wonder why the app does not close anymore
    • version history is tainted
  • #define is hell
  • it's annoying to anyone who runs your code from the console
  • it's very, very, very annoying when trying to start and end your program from within a script; quadly annoying if your program is part of a pipeline in the shell, because if the program does not end, the shell script or pipeline won't, too

Instead, explore your IDE. It probably has an option not to close the console window after running. If not, it's a great justification to you as a developer worth her/his money to always have a console window open nearby.

Alternatively, you can make this a program option, but I personally have never seen a program with an option --keep-alive-when-dead.

Moral of the story: This is the user's problem, and not the program's problem. Don't taint your code.

ADB Shell Input Events

One other difference:

  • "adb shell input" is calling the input.jar to process and send the keycode from the Java layer of the android framework.
  • "adb sendevent" is actually c code (part of toolbox utility ) that sends the input code directly into the /dev/input.... of Linux input subsystem.

More detail code trace into inside AOSP Framework can be found here:

http://www.srcmap.org/sd_share/4/aba57bc6/AOSP_adb_shell_input_Code_Trace.html#RefId=7c8f5285

WPF What is the correct way of using SVG files as icons in WPF

Use the SvgImage or the SvgImageConverter extensions, the SvgImageConverter supports binding. See the following link for samples demonstrating both extensions.

https://github.com/ElinamLLC/SharpVectors/tree/master/TutorialSamples/ControlSamplesWpf

C++ initial value of reference to non-const must be an lvalue

The &nKByte creates a temporary value, which cannot be bound to a reference to non-const.

You could change void test(float *&x) to void test(float * const &x) or you could just drop the pointer altogether and use void test(float &x); /*...*/ test(nKByte);.

How to write and save html file in python?

shorter version of Nurul Akter Towhid's answer (the fp.close is automated):

with open("my.html","w") as fp:
   fp.write(html)

How to get the date and time values in a C program?

I'm getting the following error when compiling Adam Rosenfield's code on Windows. It turns out few things are missing from the code.

Error (Before)

C:\C\Codes>gcc time.c -o time
time.c:3:12: error: initializer element is not constant
 time_t t = time(NULL);
            ^
time.c:4:16: error: initializer element is not constant
 struct tm tm = *localtime(&t);
                ^
time.c:6:8: error: expected declaration specifiers or '...' before string constant
 printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
        ^
time.c:6:36: error: expected declaration specifiers or '...' before 'tm'
 printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
                                    ^
time.c:6:55: error: expected declaration specifiers or '...' before 'tm'
 printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
                                                       ^
time.c:6:70: error: expected declaration specifiers or '...' before 'tm'
 printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
                                                                      ^
time.c:6:82: error: expected declaration specifiers or '...' before 'tm'
 printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
                                                                                  ^
time.c:6:94: error: expected declaration specifiers or '...' before 'tm'
 printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
                                                                                              ^
time.c:6:105: error: expected declaration specifiers or '...' before 'tm'
 printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
                                                                                                         ^
C:\C\Codes>

Solution

C:\C\Codes>more time.c
#include <stdio.h>
#include <time.h>

int main()
{
        time_t t = time(NULL);
        struct tm tm = *localtime(&t);

        printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
}

C:\C\Codes>

Compiling

C:\C\Codes>gcc time.c -o time

C:\C\Codes>    

Final Output

C:\C\Codes>time
now: 2018-3-11 15:46:36

C:\C\Codes>

I hope this will helps others too

Redirecting to URL in Flask

You have to return a redirect:

import os
from flask import Flask,redirect

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect("http://www.example.com", code=302)

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

See the documentation on flask docs. The default value for code is 302 so code=302 can be omitted or replaced by other redirect code (one in 301, 302, 303, 305, and 307).

Minimal web server using netcat

Actually, the best way to close gracefully the connection is to send the Content-Length header like following. Client (like curl will close the connection after receiving the data.

DATA="Date: $(date)"; 
LENGTH=$(echo $DATA | wc -c);
echo -e "HTTP/1.1 200 OK\nContent-Length: ${LENGTH}\n\n${DATA}" | nc -l -p 8000;

How to get a Docker container's IP address from the host

Check this script: https://github.com/jakubthedeveloper/DockerIps

It returns container names with their IP's in the following format:

abc_nginx 172.21.0.4
abc_php 172.21.0.5
abc_phpmyadmin 172.21.0.3
abc_mysql 172.21.0.2

Angular2 @Input to a property with get/set

You could set the @Input on the setter directly, as described below:

_allowDay: boolean;
get allowDay(): boolean {
    return this._allowDay;
}
@Input() set allowDay(value: boolean) {
    this._allowDay = value;
    this.updatePeriodTypes();
}

See this Plunkr: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview.

How can I make an image transparent on Android?

The method setAlpha(int) from the type ImageView is deprecated.

Instead of

image.setImageAlpha(127);
//value: [0-255]. Where 0 is fully transparent and 255 is fully opaque.

Only variables should be passed by reference

Since it raise a flag for over 10 years, but works just fine and return the expected value, a little stfu operator is the goodiest bad practice you are all looking for:

$file_extension = @end(explode('.', $file_name));

But warning, don't use in loops due to a performance hit. Newest version of php 7.3+ offer the method array_key_last() and array_key_first().

https://www.php.net/manual/en/function.array-key-last.php

Read XML file using javascript

You can use below script for reading child of the above xml. It will work with IE and Mozila Firefox both.

<script type="text/javascript">

function readXml(xmlFile){

var xmlDoc;

if(typeof window.DOMParser != "undefined") {
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET",xmlFile,false);
    if (xmlhttp.overrideMimeType){
        xmlhttp.overrideMimeType('text/xml');
    }
    xmlhttp.send();
    xmlDoc=xmlhttp.responseXML;
}
else{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async="false";
    xmlDoc.load(xmlFile);
}
var tagObj=xmlDoc.getElementsByTagName("marker");
var typeValue = tagObj[0].getElementsByTagName("type")[0].childNodes[0].nodeValue;
var titleValue = tagObj[0].getElementsByTagName("title")[0].childNodes[0].nodeValue;
}
</script>

Handling errors in Promise.all

Have you considered Promise.prototype.finally()?

It seems to be designed to do exactly what you want - execute a function once all the promises have settled (resolved/rejected), regardless of some of the promises being rejected.

From the MDN documentation:

The finally() method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome.

The finally() method is very similar to calling .then(onFinally, onFinally) however there are couple of differences:

When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it.

A finally callback will not receive any argument, since there's no reliable means of determining if the promise was fulfilled or rejected. This use case is for precisely when you do not care about the rejection reason, or the fulfillment value, and so there's no need to provide it.

Unlike Promise.resolve(2).then(() => {}, () => {}) (which will be resolved with undefined), Promise.resolve(2).finally(() => {}) will be resolved with 2. Similarly, unlike Promise.reject(3).then(() => {}, () => {}) (which will be fulfilled with undefined), Promise.reject(3).finally(() => {}) will be rejected with 3.

== Fallback ==

If your version of JavaScript doesn't support Promise.prototype.finally() you can use this workaround from Jake Archibald: Promise.all(promises.map(p => p.catch(() => undefined)));

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

You probably do not need to be making lists and appending them to make your array. You can likely just do it all at once, which is faster since you can use numpy to do your loops instead of doing them yourself in pure python.

To answer your question, as others have said, you cannot access a nested list with two indices like you did. You can if you convert mean_data to an array before not after you try to slice it:

R = np.array(mean_data)[:,0]

instead of

R = np.array(mean_data[:,0])

But, assuming mean_data has a shape nx3, instead of

R = np.array(mean_data)[:,0]
P = np.array(mean_data)[:,1]
Z = np.array(mean_data)[:,2]

You can simply do

A = np.array(mean_data).mean(axis=0)

which averages over the 0th axis and returns a length-n array

But to my original point, I will make up some data to try to illustrate how you can do this without building any lists one item at a time:

Can scripts be inserted with innerHTML?

Krasimir Tsonev has a great solution that overcome all problems. His method doesn't need using eval, so no performance nor security problems exist. It allows you to set innerHTML string contains html with js and translate it immediately to an DOM element while also executes the js parts exist along the code. short ,simple, and works exactly as you want.

Enjoy his solution:

http://krasimirtsonev.com/blog/article/Convert-HTML-string-to-DOM-element

Important notes:

  1. You need to wrap the target element with div tag
  2. You need to wrap the src string with div tag.
  3. If you write the src string directly and it includes js parts, please take attention to write the closing script tags correctly (with \ before /) as this is a string.

Simple way to repeat a string

here is the latest Stringutils.java StringUtils.java

    public static String repeat(String str, int repeat) {
    // Performance tuned for 2.0 (JDK1.4)

    if (str == null) {
        return null;
    }
    if (repeat <= 0) {
        return EMPTY;
    }
    int inputLength = str.length();
    if (repeat == 1 || inputLength == 0) {
        return str;
    }
    if (inputLength == 1 && repeat <= PAD_LIMIT) {
        return repeat(str.charAt(0), repeat);
    }

    int outputLength = inputLength * repeat;
    switch (inputLength) {
        case 1 :
            return repeat(str.charAt(0), repeat);
        case 2 :
            char ch0 = str.charAt(0);
            char ch1 = str.charAt(1);
            char[] output2 = new char[outputLength];
            for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
                output2[i] = ch0;
                output2[i + 1] = ch1;
            }
            return new String(output2);
        default :
            StringBuilder buf = new StringBuilder(outputLength);
            for (int i = 0; i < repeat; i++) {
                buf.append(str);
            }
            return buf.toString();
    }
    }

it doesn't even need to be this big, can be made into this, and can be copied and pasted into a utility class in your project.

    public static String repeat(String str, int num) {
    int len = num * str.length();
    StringBuilder sb = new StringBuilder(len);
    for (int i = 0; i < times; i++) {
        sb.append(str);
    }
    return sb.toString();
    }

So e5, I think the best way to do this would be to simply use the above mentioned code,or any of the answers here. but commons lang is just too big if it's a small project

Android Service needs to run always (Never pause or stop)

I had overcome this issue, and my sample code is as follows.

Add the below line in your Main Activity, here BackGroundClass is the service class.You can create this class in New -> JavaClass (In this class, add the process (tasks) in which you needs to occur at background). For Convenience, first denote them with notification ringtone as background process.

 startService(new Intent(this, BackGroundClass .class));

In the BackGroundClass, just include my codings and you may see the result.

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.widget.Toast;

public class BackgroundService  extends Service {
    private MediaPlayer player;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
     player = MediaPlayer.create(this,Settings.System.DEFAULT_RINGTONE_URI);
        player.setLooping(true);
         player.start();
        return START_STICKY;
    }
 @Override
    public void onDestroy() {
        super.onDestroy();
         player.stop();
    }
}

And in AndroidManifest.xml, try to add this.

<service android:name=".BackgroundService"/>

Run the program, just open the application, you may find the notification alert at the background. Even, you may exit the application but still you might have hear the ringtone alert unless and until if you switched off the application or Uninstall the application. This denotes that the notification alert is at the background process. Like this you may add some process for background.

Kind Attention: Please, Don't verify with TOAST as it will run only once even though it was at background process.

Hope it will helps...!!

Laravel Advanced Wheres how to pass variable into function?

@kajetons' answer is fully functional.

You can also pass multiple variables by passing them like: use($var1, $var2)

DB::table('users')->where(function ($query) use ($activated,$var2) {
    $query->where('activated', '=', $activated);
    $query->where('var2', '>', $var2);
})->get();

Check if passed argument is file or directory in Bash

At least write the code without the bushy tree:

#!/bin/bash

PASSED=$1

if   [ -d "${PASSED}" ]
then echo "${PASSED} is a directory";
elif [ -f "${PASSED}" ]
then echo "${PASSED} is a file";
else echo "${PASSED} is not valid";
     exit 1
fi

When I put that into a file "xx.sh" and create a file "xx sh", and run it, I get:

$ cp /dev/null "xx sh"
$ for file in . xx*; do sh "$file"; done
. is a directory
xx sh is a file
xx.sh is a file
$

Given that you are having problems, you should debug the script by adding:

ls -l "${PASSED}"

This will show you what ls thinks about the names you pass the script.