Programs & Examples On #Wysiwyg

WYSIWYG (What You See Is What You Get) describes editors for graphical design which commonly do not require knowledge of the code underlying the product. The editor translates the user's edits back into a markup language such as HTML. Examples include Microsoft Visual Studio, Adobe Dreamweaver's design view and many CMS editors.

GUI-based or Web-based JSON editor that works like property explorer

Generally when I want to create a JSON or YAML string, I start out by building the Perl data structure, and then running a simple conversion on it. You could put a UI in front of the Perl data structure generation, e.g. a web form.

Converting a structure to JSON is very straightforward:

use strict;
use warnings;
use JSON::Any;

my $data = { arbitrary structure in here };
my $json_handler = JSON::Any->new(utf8=>1);
my $json_string = $json_handler->objToJson($data);

How do I get the number of elements in a list?

While this may not be useful due to the fact that it'd make a lot more sense as being "out of the box" functionality, a fairly simple hack would be to build a class with a length property:

class slist(list):
    @property
    def length(self):
        return len(self)

You can use it like so:

>>> l = slist(range(10))
>>> l.length
10
>>> print l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Essentially, it's exactly identical to a list object, with the added benefit of having an OOP-friendly length property.

As always, your mileage may vary.

Passing references to pointers in C++

I have just made use of a reference to a pointer to make all the pointers in a deleted binary tree except the root safe. To make the pointer safe we just have to set it to 0. I could not make the function that deletes the tree (keeping only the root) to accept a ref to a pointer since I am using the root (this pointer) as the first input to traverse left and right.

void BinTree::safe_tree(BinTree * &vertex ) {
    if ( vertex!=0 ) {  // base case
        safe_tree(vertex->left);    // left subtree.
            safe_tree(vertex->right);   //  right subtree.
          // delete vertex;  // using this delete causes an error, since they were deleted on the fly using inorder_LVR. If inorder_LVR does not perform delete to the nodes, then, use delete vertex;
        vertex=0;  // making a safe pointer
    }
} // end in

Bottom line, a reference to a pointer is invalid when the formal parameter is the (this) pointer.

What are the differences between a HashMap and a Hashtable in Java?

Old and classic topic, just want to add this helpful blog that explains this:

http://blog.manishchhabra.com/2012/08/the-5-main-differences-betwen-hashmap-and-hashtable/

Blog by Manish Chhabra

The 5 main differences betwen HashMap and Hashtable

HashMap and Hashtable both implement java.util.Map interface but there are some differences that Java developers must understand to write more efficient code. As of the Java 2 platform v1.2, Hashtable class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework.

  1. One of the major differences between HashMap and Hashtable is that HashMap is non-synchronized whereas Hashtable is synchronized, which means Hashtable is thread-safe and can be shared between multiple threads but HashMap cannot be shared between multiple threads without proper synchronization. Java 5 introduced ConcurrentHashMap which is an alternative of Hashtable and provides better scalability than Hashtable in Java.Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.

  2. The HashMap class is roughly equivalent to Hashtable, except that it permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).

  3. The third significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator’s own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort. This is also an important difference between Enumeration and Iterator in Java.

  4. One more notable difference between Hashtable and HashMap is that because of thread-safety and synchronization Hashtable is much slower than HashMap if used in Single threaded environment. So if you don’t need synchronization and HashMap is only used by one thread, it out perform Hashtable in Java.

  5. HashMap does not guarantee that the order of the map will remain constant over time.

Note that HashMap can be synchronized by

Map m = Collections.synchronizedMap(hashMap);

In Summary there are significant differences between Hashtable and HashMap in Java e.g. thread-safety and speed and based upon that only use Hashtable if you absolutely need thread-safety, if you are running Java 5 consider using ConcurrentHashMap in Java.

What is the difference between sscanf or atoi to convert a string to an integer?

When there is no concern about invalid string input or range issues, use the simplest: atoi()

Otherwise, the method with best error/range detection is neither atoi(), nor sscanf(). This good answer all ready details the lack of error checking with atoi() and some error checking with sscanf().

strtol() is the most stringent function in converting a string to int. Yet it is only a start. Below are detailed examples to show proper usage and so the reason for this answer after the accepted one.

// Over-simplified use
int strtoi(const char *nptr) {
  int i = (int) strtol(nptr, (char **)NULL, 10);
  return i; 
}

This is the like atoi() and neglects to use the error detection features of strtol().

To fully use strtol(), there are various features to consider:

  1. Detection of no conversion: Examples: "xyz", or "" or "--0"? In these cases, endptr will match nptr.

    char *endptr;
    int i = (int)strtol(nptr, &endptr, 10);
    if (nptr == endptr) return FAIL_NO_CONVERT;
    
  2. Should the whole string convert or just the leading portion: Is "123xyz" OK?

    char *endptr;
    int i = (int)strtol(nptr, &endptr, 10);
    if (*endptr != '\0') return FAIL_EXTRA_JUNK;
    
  3. Detect if value was so big, the the result is not representable as a long like "999999999999999999999999999999".

    errno = 0;
    long L = strtol(nptr, &endptr, 10);
    if (errno == ERANGE) return FAIL_OVERFLOW;
    
  4. Detect if the value was outside the range of than int, but not long. If int and long have the same range, this test is not needed.

    long L = strtol(nptr, &endptr, 10);
    if (L < INT_MIN || L > INT_MAX) return FAIL_INT_OVERFLOW;
    
  5. Some implementations go beyond the C standard and set errno for additional reasons such as errno to EINVAL in case no conversion was performed or EINVAL The value of the Base parameter is not valid.. The best time to test for these errno values is implementation dependent.

Putting this all together: (Adjust to your needs)

#include <errno.h>
#include <stdlib.h>

int strtoi(const char *nptr, int *error_code) {
  char *endptr;
  errno = 0;
  long i = strtol(nptr, &endptr, 10);

  #if LONG_MIN < INT_MIN || LONG_MAX > INT_MAX
  if (errno == ERANGE || i > INT_MAX || i < INT_MIN) {
    errno = ERANGE;
    i = i > 0 : INT_MAX : INT_MIN;
    *error_code = FAIL_INT_OVERFLOW;
  }
  #else
  if (errno == ERANGE) {
    *error_code = FAIL_OVERFLOW;
  }
  #endif

  else if (endptr == nptr) {
    *error_code = FAIL_NO_CONVERT;
  } else if (*endptr != '\0') {
    *error_code = FAIL_EXTRA_JUNK;
  } else if (errno) {
    *error_code = FAIL_IMPLEMENTATION_REASON;
  }
  return (int) i;
}

Note: All functions mentioned allow leading spaces, an optional leading sign character and are affected by locale change. Additional code is required for a more restrictive conversion.


Note: Non-OP title change skewed emphasis. This answer applies better to original title "convert string to integer sscanf or atoi"

Determine path of the executing script

Steamer25's approach works, but only if there is no whitespace in the path. On macOS at least the cmdArgs[match] returns something like /base/some~+~dir~+~with~+~whitespace/ for /base/some\ dir\ with\ whitespace/.

I worked around this by replacing the "~+~" with a simple whitespace before returning it.

thisFile <- function() {
  cmdArgs <- commandArgs(trailingOnly = FALSE)
  needle <- "--file="
  match <- grep(needle, cmdArgs)
  if (length(match) > 0) {
    # Rscript
    path <- cmdArgs[match]
    path <- gsub("\\~\\+\\~", " ", path)
    return(normalizePath(sub(needle, "", path)))
  } else {
    # 'source'd via R console
    return(normalizePath(sys.frames()[[1]]$ofile))
  }
}

Obviously you can still extend the else block like aprstar did.

R solve:system is exactly singular

Lapack is a Linear Algebra package which is used by R (actually it's used everywhere) underneath solve(), dgesv spits this kind of error when the matrix you passed as a parameter is singular.

As an addendum: dgesv performs LU decomposition, which, when using your matrix, forces a division by 0, since this is ill-defined, it throws this error. This only happens when matrix is singular or when it's singular on your machine (due to approximation you can have a really small number be considered 0)

I'd suggest you check its determinant if the matrix you're using contains mostly integers and is not big. If it's big, then take a look at this link.

How to send Request payload to REST API in java?

I tried with a rest client.

Headers :

  • POST /r/gerrit/rpc/ChangeDetailService HTTP/1.1
  • Host: git.eclipse.org
  • User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0
  • Accept: application/json
  • Accept-Language: null
  • Accept-Encoding: gzip,deflate,sdch
  • accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
  • Content-Type: application/json; charset=UTF-8
  • Content-Length: 73
  • Connection: keep-alive

it works fine. I retrieve 200 OK with a good body.

Why do you set a status code in your request? and multiple declaration "Accept" with Accept:application/json,application/json,application/jsonrequest. just a statement is enough.

Creating an instance using the class name and calling constructor

You can use reflections

return Class.forName(className).getConstructor(String.class).newInstance(arg);

How do you hide the Address bar in Google Chrome for Chrome Apps?

MAC: CMD+Control+F goes fullscreen, and CMD+Shift+F hides the navbar

WINDOWS: F11 (possibly Alt+Enter too, as with many games like Dota)


Mac used to be CMD+Shift+F

How to change the button color when it is active using bootstrap?

CSS has different pseudo selector by which you can achieve such effect. In your case you can use

:active : if you want background color only when the button is clicked and don't want to persist.

:focus: if you want background color untill the focus is on the button.

button:active{
    background:olive;
}

and

button:focus{
    background:olive;
}

JsFiddle Example

P.S.: Please don't give the number in Id attribute of html elements.

NSUserDefaults - How to tell if a key exists

Extend UserDefaults once to don't copy-paste this solution:

extension UserDefaults {

    func hasValue(forKey key: String) -> Bool {
        return nil != object(forKey: key)
    }
}

// Example
UserDefaults.standard.hasValue(forKey: "username")

jQuery checkbox event handling

Using the new 'on' method in jQuery (1.7): http://api.jquery.com/on/

    $('#myform').on('change', 'input[type=checkbox]', function(e) {
        console.log(this.name+' '+this.value+' '+this.checked);

    });
  • the event handler will live on
  • will capture if the checkbox was changed by keyboard, not just click

Where can I find the TypeScript version installed in Visual Studio?

You can do npm list | grep typescript if it's installed through npm.

Want to move a particular div to right

For me, I used margin-left: auto; which is more responsive with horizontal resizing.

Java HashMap: How to get a key and value by index?

A solution is already selected. However, I post this solution for those who want to use an alternative approach:

// use LinkedHashMap if you want to read values from the hashmap in the same order as you put them into it
private ArrayList<String> getMapValueAt(LinkedHashMap<String, ArrayList<String>> hashMap, int index)
{
    Map.Entry<String, ArrayList<String>> entry = (Map.Entry<String, ArrayList<String>>) hashMap.entrySet().toArray()[index];
    return entry.getValue();
}

How to Maximize window in chrome using webDriver (python)

Nothing worked for me except:

driver.set_window_size(1024, 600)
driver.maximize_window()

I found this by inspecting selenium/webdriver/remote/webdriver.py. I've never found any useful documentation, but reading the code has been marginally effective.

Save image from url with curl PHP

try this:

function grab_image($url,$saveto){
    $ch = curl_init ($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    $raw=curl_exec($ch);
    curl_close ($ch);
    if(file_exists($saveto)){
        unlink($saveto);
    }
    $fp = fopen($saveto,'x');
    fwrite($fp, $raw);
    fclose($fp);
}

and ensure that in php.ini allow_url_fopen is enable

How to import a SQL Server .bak file into MySQL?

SQL Server databases are very Microsoft proprietary. Two options I can think of are:

  1. Dump the database in CSV, XML or similar format that you'd then load into MySQL.

  2. Setup ODBC connection to MySQL and then using DTS transport the data. As Charles Graham has suggested, you may need to build the tables before doing this. But that's as easy as a cut and paste from SQL Enterprise Manager windows to the corresponding MySQL window.

Can I add a custom attribute to an HTML tag?

well! you can actually create a bunch of custom HTML attributes by disguising the data attributes in what you actually want.

eg.

[attribute='value']{
color:red;
}
<span attribute="value" >hello world</span>

It apparently works but that would invalidate your document, there is no need of using JScript for you to have custom attributes or even elements unless you have to, you just need to treat your new formulated(custom) attributes just the same way you treat your "data" attribute

Remember "invalid" does not mean anything. The document will load fine at all the time. and some browsers would actually validate your document only by the presence of DOCTYPE....., you actually know what I mean.

How do I explicitly specify a Model's table-name mapping in Rails?

class Countries < ActiveRecord::Base
    self.table_name = "cc"
end

In Rails 3.x this is the way to specify the table name.

Using Jquery AJAX function with datatype HTML

var datos = $("#id_formulario").serialize();
$.ajax({         
    url: "url.php",      
    type: "POST",                   
    dataType: "html",                 
    data: datos,                 
    success: function (prueba) { 
        alert("funciona!");
    }//FIN SUCCES

});//FIN  AJAX

How does true/false work in PHP?

think of operator as unary function: is_false(type value) which returns true or false, depending on the exact implementation for specific type and value. Consider if statement to invoke such function implicitly, via syntactic sugar.

other possibility is that type has cast operator, which turns type into another type implicitly, in this case string to Boolean.

PHP does not expose such details, but C++ allows operator overloading which exposes fine details of operator implementation.

open link in iframe

Well, there's an alternate way! You can use a button instead of hyperlink. Hence, when the button is clicked the web page specified in "name_of_webpage" is opened in the target frame named "name_of_iframe". It works for me!

<form method="post" action="name_of_webpage" target="name_of_iframe">
<input type="submit" value="any_name_you_want" />
</form>
<iframe name="name_of_iframe"></iframe>

Is there a function in python to split a word into a list?

The easiest way is probably just to use list(), but there is at least one other option as well:

s = "Word to Split"
wordlist = list(s)               # option 1, 
wordlist = [ch for ch in s]      # option 2, list comprehension.

They should both give you what you need:

['W','o','r','d',' ','t','o',' ','S','p','l','i','t']

As stated, the first is likely the most preferable for your example but there are use cases that may make the latter quite handy for more complex stuff, such as if you want to apply some arbitrary function to the items, such as with:

[doSomethingWith(ch) for ch in s]

pdftk compression option

After trying gpdf as nullglob suggested, I found that I got the same compression results (a ~900mb file down to ~30mb) by just using the cups-pdf printer. This might be easier/preferred if you are already viewing a document and only need to compress one or two documents.

In Ubuntu 12.04, you can install this by

sudo apt-get install cups-pdf

After installation, be sure to check in System Tools > Administration > Printing > right-click 'PDF' and set it to 'enable'

By default, the output is saved into a folder named PDF in your home directory.

Pandas DataFrame to List of Lists

I don't know if it will fit your needs, but you can also do:

>>> lol = df.values
>>> lol
array([[1, 2, 3],
       [3, 4, 5]])

This is just a numpy array from the ndarray module, which lets you do all the usual numpy array things.

Understanding Fragment's setRetainInstance(boolean)

setRetainInstance() - Deprecated

As Fragments Version 1.3.0-alpha01

The setRetainInstance() method on Fragments has been deprecated. With the introduction of ViewModels, developers have a specific API for retaining state that can be associated with Activities, Fragments, and Navigation graphs. This allows developers to use a normal, not retained Fragment and keep the specific state they want retained separate, avoiding a common source of leaks while maintaining the useful properties of a single creation and destruction of the retained state (namely, the constructor of the ViewModel and the onCleared() callback it receives).

Where is the php.ini file on a Linux/CentOS PC?

#php -i | grep php.ini also will work too!

How to get only filenames within a directory using c#?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GetNameOfFiles
{
    public class Program
    {
        static void Main(string[] args)
        {
           string[] fileArray = Directory.GetFiles(@"YOUR PATH");
           for (int i = 0; i < fileArray.Length; i++)
           {

               Console.WriteLine(fileArray[i]);
           }
            Console.ReadLine();
        }
    }
}

How to convert string to long

IF your input is String then I recommend you to store the String into a double and then convert the double to the long.

String str = "123.45";
Double  a = Double.parseDouble(str);

long b = Math.round(a);

IF...THEN...ELSE using XML

<IF id="if-1">
   <TIME from="5pm" to="9pm" />
<ELSE>
   <something else />
</ELSE>
</IF>

I don't know if this makes any sense to anyone else or it is actually usable in your program, but I would do it like this.

My point of view: You need to have everything related to your "IF" inside your IF-tag, otherwise you won't know what ELSE belongs to what IF. Secondly, I'd skip the THEN tag because it always follows an IF.

Press any key to continue

Here is what I use.

Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

Ruby: How to turn a hash into HTTP parameters?

{:a=>"a", :b=>"b", :c=>"c"}.map{ |x,v| "#{x}=#{v}" }.reduce{|x,v| "#{x}&#{v}" }

"a=a&b=b&c=c"

Here's another way. For simple queries.

SQL alias for SELECT statement

Yes, but you can select only one column in your subselect

SELECT (SELECT id FROM bla) AS my_select FROM bla2

A valid provisioning profile for this executable was not found... (again)

I'm still not sure what the issue was but deleting all certificates and starting over (albeit twice) eventually solved it.

My best guess is that I've missed some small but important detail of the procedure. Unfortunately I can't be any more specific than that.

How do operator.itemgetter() and sort() work?

a = []
a.append(["Nick", 30, "Doctor"])
a.append(["John",  8, "Student"])
a.append(["Paul",  8,"Car Dealer"])
a.append(["Mark", 66, "Retired"])
print a

[['Nick', 30, 'Doctor'], ['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Mark', 66, 'Retired']]

def _cmp(a,b):     

    if a[1]<b[1]:
        return -1
    elif a[1]>b[1]:
        return 1
    else:
        return 0

sorted(a,cmp=_cmp)

[['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Nick', 30, 'Doctor'], ['Mark', 66, 'Retired']]

def _key(list_ele):

    return list_ele[1]

sorted(a,key=_key)

[['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Nick', 30, 'Doctor'], ['Mark', 66, 'Retired']]
>>> 

How to load npm modules in AWS Lambda?

npm module has to be bundeled inside your nodejs package and upload to AWS Lambda Layers as zip, then you would need to refer to your module/js as below and use available methods from it. const mymodule = require('/opt/nodejs/MyLogger');

How to create SPF record for multiple IPs?

Yes the second syntax is fine.

Have you tried using the SPF wizard? https://www.spfwizard.net/

It can quickly generate basic and complex SPF records.

You can't specify target table for update in FROM clause

It's quite simple. For example, instead of writing:

INSERT INTO x (id, parent_id, code) VALUES (
    NULL,
    (SELECT id FROM x WHERE code='AAA'),
    'BBB'
);

you should write

INSERT INTO x (id, parent_id, code)
VALUES (
    NULL,
    (SELECT t.id FROM (SELECT id, code FROM x) t WHERE t.code='AAA'),
    'BBB'
);

or similar.

Jaxb, Class has two properties of the same name

just declare the member variables to private in the class you want to convert to XML. Happy coding

Removing "http://" from a string

Try this out:

$url = 'http://techcrunch.com/startups/'; $url = str_replace(array('http://', 'https://'), '', $url); 

EDIT:

Or, a simple way to always remove the protocol:

$url = 'https://www.google.com/'; $url = preg_replace('@^.+?\:\/\/@', '', $url); 

Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

Declare an output cursor variable to the inner sp :

@c CURSOR VARYING OUTPUT

Then declare a cursor c to the select you want to return. Then open the cursor. Then set the reference:

DECLARE c CURSOR LOCAL FAST_FORWARD READ_ONLY FOR 
SELECT ...
OPEN c
SET @c = c 

DO NOT close or reallocate.

Now call the inner sp from the outer one supplying a cursor parameter like:

exec sp_abc a,b,c,, @cOUT OUTPUT

Once the inner sp executes, your @cOUT is ready to fetch. Loop and then close and deallocate.

How to redirect 404 errors to a page in ExpressJS?

There are some cases where 404 page cannot be written to be executed as the last route, especially if you have an asynchronous routing function that brings in a /route late to the party. The pattern below might be adopted in those cases.

var express = require("express.io"),
    app = express(),
    router = express.Router();

router.get("/hello", function (req, res) {
    res.send("Hello World");
});

// Router is up here.
app.use(router);

app.use(function(req, res) {
    res.send("Crime Scene 404. Do not repeat");
});

router.get("/late", function (req, res) {
    res.send("Its OK to come late");
});

app.listen(8080, function (){
    console.log("Ready");
});

@Html.DisplayFor - DateFormat ("mm/dd/yyyy")

Maybe try simply

@(Model.AuditDate.HasValue ? Model.AuditDate.ToString("mm/dd/yyyy") : String.Empty)

also you can use many type of string format like .ToString("dd MMM, yyyy") .ToString("d") etc

An efficient compression algorithm for short text strings

You might want to take a look at Standard Compression Scheme for Unicode.

SQL Server 2008 R2 use it internally and can achieve up to 50% compression.

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

Alternatively, you can use Inner Queries to do so.

SQL> INSERT INTO <NEW_TABLE> SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM <OLD_TABLE>);

Hope this helps!

Difference between string and StringBuilder in C#

A String is an immutable type. This means that whenever you start concatenating strings with each other you're creating new strings each time. If you do so many times you end up with a lot of heap overhead and the risk of running out of memory.

A StringBuilder instance is used to be able to append strings to the same instance, creating a string when you call the ToString method on it.

Due to the overhead of instantiating a StringBuilder object it's said by Microsoft that it's useful to use when you have more than 5-10 string concatenations.

For sample code I suggest you take a look here:

Create Map in Java

I use such kind of a Map population thanks to Java 9. In my honest opinion, this approach provides more readability to the code.

  public static void main(String[] args) {
    Map<Integer, Point2D.Double> map = Map.of(
        1, new Point2D.Double(1, 1),
        2, new Point2D.Double(2, 2),
        3, new Point2D.Double(3, 3),
        4, new Point2D.Double(4, 4));
    map.entrySet().forEach(System.out::println);
  }

Disable a Button

The button can be Disabled in Swift 4 by the code

@IBAction func yourButtonMethodname(sender: UIButon) {
 yourButton.isEnabled = false 
}

The remote server returned an error: (407) Proxy Authentication Required

I had a similar proxy related problem. In my case it was enough to add:

webRequest.Proxy.Credentials = new NetworkCredential("user", "password", "domain");

How to change workspace and build record Root Directory on Jenkins?

The variables you need are explained here in the jenkins wiki: https://wiki.jenkins.io/display/JENKINS/Features+controlled+by+system+properties

The default variable ITEM_ROOTDIR points to a directory inside the jenkins installation. As you already found out you need:

  • Workspace Root Directory: E:/myJenkinsRootFolderOnE/${ITEM_FULL_NAME}/workspace
  • Build Record Root Directory: E:/myJenkinsRootFolderOnE/${ITEM_FULL_NAME}/builds

You need to achieve this through config.xml nowerdays. Citing from the wiki page linked above:

This used to be a UI setting, but was removed in 2.119 as it did not support migration of existing build records and could lead to build-related errors until restart.

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

How to navigate to a directory in C:\ with Cygwin?

As you'll probably want to do this often, add aliases into your .bashrc file, like:

alias cdc='cd /cygdrive/c'
alias cdp='cd /cygdrive/p'

Then you can just type on the command line:

cdc

Copy and Paste a set range in the next empty row

Be careful with the "Range(...)" without first qualifying a Worksheet because it will use the currently Active worksheet to make the copy from. It's best to fully qualify both sheets. Please give this a shot (please change "Sheet1" with the copy worksheet):

EDIT: edited for pasting values only based on comments below.

Private Sub CommandButton1_Click()
  Application.ScreenUpdating = False
  Dim copySheet As Worksheet
  Dim pasteSheet As Worksheet

  Set copySheet = Worksheets("Sheet1")
  Set pasteSheet = Worksheets("Sheet2")

  copySheet.Range("A3:E3").Copy
  pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
  Application.CutCopyMode = False
  Application.ScreenUpdating = True
End Sub

Why does printf not flush after the call unless a newline is in the format string?

The stdout stream is line buffered by default, so will only display what's in the buffer after it reaches a newline (or when it's told to). You have a few options to print immediately:

Print to stderrinstead using fprintf (stderr is unbuffered by default):

fprintf(stderr, "I will be printed immediately");

Flush stdout whenever you need it to using fflush:

printf("Buffered, will be flushed");
fflush(stdout); // Will now print everything in the stdout buffer

Edit: From Andy Ross's comment below, you can also disable buffering on stdout by using setbuf:

setbuf(stdout, NULL);

or its secure version setvbuf as explained here

setvbuf(stdout, NULL, _IONBF, 0); 

Setting a minimum/maximum character count for any character using a regular expression

Like this: .

The . means any character except newline (which sometimes is but often isn't included, check your regex flavour).

You can rewrite your expression as ^.{1,35}$, which should match any line of length 1-35.

Swift: Testing optionals for nil

Also you can use Nil-Coalescing Operator

The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

let value = optionalValue ?? defaultValue

If optionalValue is nil, it automatically assigns value to defaultValue

When correctly use Task.Run and when just async-await

One issue with your ContentLoader is that internally it operates sequentially. A better pattern is to parallelize the work and then sychronize at the end, so we get

public class PageViewModel : IHandle<SomeMessage>
{
   ...

   public async void Handle(SomeMessage message)
   {
      ShowLoadingAnimation();

      // makes UI very laggy, but still not dead
      await this.contentLoader.LoadContentAsync(); 

      HideLoadingAnimation();   
   }
}

public class ContentLoader 
{
    public async Task LoadContentAsync()
    {
        var tasks = new List<Task>();
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoIoBoundWorkAsync());
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoSomeOtherWorkAsync());

        await Task.WhenAll(tasks).ConfigureAwait(false);
    }
}

Obviously, this doesn't work if any of the tasks require data from other earlier tasks, but should give you better overall throughput for most scenarios.

Import txt file and having each line as a list

Do not create separate lists; create a list of lists:

results = []
with open('inputfile.txt') as inputfile:
    for line in inputfile:
        results.append(line.strip().split(','))

or better still, use the csv module:

import csv

results = []
with open('inputfile.txt', newline='') as inputfile:
    for row in csv.reader(inputfile):
        results.append(row)

Lists or dictionaries are far superiour structures to keep track of an arbitrary number of things read from a file.

Note that either loop also lets you address the rows of data individually without having to read all the contents of the file into memory either; instead of using results.append() just process that line right there.

Just for completeness sake, here's the one-liner compact version to read in a CSV file into a list in one go:

import csv

with open('inputfile.txt', newline='') as inputfile:
    results = list(csv.reader(inputfile))

Finding a branch point with Git?

You can examine the reflog of branch A to find from which commit it was created, as well as the full history of which commits that branch pointed to. Reflogs are in .git/logs.

How to trigger ngClick programmatically

Just in case everybody see's it, I added additional duplicating answer with an important line which will not break event propagation

$scope.clickOnUpload = function ($event) {    
    $event.stopPropagation(); // <-- this is important

    $timeout(function() {
        angular.element(domElement).trigger('click');
    }, 0);
};

Eclipse java debugging: source not found

Eclipse debugging works with the class actually loaded by the program.

The symptoms you describe sounds like the class in question was not found in the project, but in a distribution jar without debug info found before the project you are working with.

This can happen for several reasons but have a look at the location where the classes showing this behaviour is found (look in the navigation pane to identify it). You will most likely need to change the build path of the project to avoid using this jar and have the JVM use the project instead.

EDIT: Note that as of 2018 it is common to use a build framework like Maven, where the build path is managed by the m2e plugin so this problem should be very less frequent than when the question was asked. If you use Maven and m2e, make sure to enable Preferences / Maven / "Download Artifact Sources" or right-click the project, Maven / "Download Sources".

Finding even or odd ID values

For finding the even number we should use

select num from table where ( num % 2 ) = 0

How to insert a new line in strings in Android

Try:

String str = "my string \n my other string";

When printed you will get:

my string
my other string

JPA eager fetch does not join

The fetchType attribute controls whether the annotated field is fetched immediately when the primary entity is fetched. It does not necessarily dictate how the fetch statement is constructed, the actual sql implementation depends on the provider you are using toplink/hibernate etc.

If you set fetchType=EAGER This means that the annotated field is populated with its values at the same time as the other fields in the entity. So if you open an entitymanager retrieve your person objects and then close the entitymanager, subsequently doing a person.address will not result in a lazy load exception being thrown.

If you set fetchType=LAZY the field is only populated when it is accessed. If you have closed the entitymanager by then a lazy load exception will be thrown if you do a person.address. To load the field you need to put the entity back into an entitymangers context with em.merge(), then do the field access and then close the entitymanager.

You might want lazy loading when constructing a customer class with a collection for customer orders. If you retrieved every order for a customer when you wanted to get a customer list this may be a expensive database operation when you only looking for customer name and contact details. Best to leave the db access till later.

For the second part of the question - how to get hibernate to generate optimised SQL?

Hibernate should allow you to provide hints as to how to construct the most efficient query but I suspect there is something wrong with your table construction. Is the relationship established in the tables? Hibernate may have decided that a simple query will be quicker than a join especially if indexes etc are missing.

How can I display the users profile pic using the facebook graph api?

You can also resize the profile picture by providing parameters as shown below.

https://graph.facebook.com/[UID]/picture?width=140&height=140

would work too.

This declaration has no storage class or type specifier in C++

Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables. In C++, code can only appear inside function bodies or in variable initializes.

Run Stored Procedure in SQL Developer?

Though this question is quite old, I keep stumbling into same result without finding an easy way to run from sql developer. After couple of tries, I found an easy way to execute the stored procedure from sql developer itself.

  • Under packages, select your desired package and right click on the package name (not on the stored procedure name).

  • You will find option to run. Select that and supply the required arguments. Click OK and you can see the output in output variables section below

I'm using SQL developer version 4.1.3.20

How to extract filename.tar.gz file

A tar.gz is a tar file inside a gzip file, so 1st you must unzip the gzip file with gunzip -d filename.tar.gz , and then use tar to untar it. However, since gunzip says it isn't in gzip format, you can see what format it is in with file filename.tar.gz, and use the appropriate program to open it.

How do I create an executable in Visual Studio 2013 w/ C++?

Do ctrl+F5 to compile and run your project without debugging. Look at the output pane (defaults to "Show output from Build"). If it compiled successfully, the path to the .exe file should be there after {projectname}.vcxproj ->

Wpf control size to content?

For most controls, you set its height and width to Auto in the XAML, and it will size to fit its content.

In code, you set the width/height to double.NaN. For details, see FrameworkElement.Width, particularly the "remarks" section.

PHP - Get key name of array value

if you need to return an array elements with same value, use array_keys() function

$array = array('red' => 1, 'blue' => 1, 'green' => 2);
print_r(array_keys($array, 1));

Format datetime in asp.net mvc 4

Thanks Darin, For me, to be able to post to the create method, It only worked after I modified the BindModel code to :

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
    var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

    if (!string.IsNullOrEmpty(displayFormat) && value != null)
    {
        DateTime date;
        displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
        // use the format specified in the DisplayFormat attribute to parse the date
         if (DateTime.TryParse(value.AttemptedValue, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out date))
        {
            return date;
        }
        else
        {
            bindingContext.ModelState.AddModelError(
                bindingContext.ModelName,
                string.Format("{0} is an invalid date format", value.AttemptedValue)
            );
        }
    }

    return base.BindModel(controllerContext, bindingContext);
}

Hope this could help someone else...

How do I POST XML data with curl

You can try the following solution:

curl -v -X POST -d @payload.xml https://<API Path> -k -H "Content-Type: application/xml;charset=utf-8"

How to add title to seaborn boxplot

.set_title('') can be used to add title to Seaborn Plot

import seaborn as sb
sb.boxplot().set_title('Title')

Session 'app' error while installing APK

I was using CyanogenMod 12.1 and was building with libgdx when I met with the same error. Rebuilding didn't work for me. My phone was connected as UMS or USB mass storage to my PC when I ran the app. Just changed the USB configuration from mass storage to MTP and it fixed my problem.

mysql extract year from date format

This should work:

SELECT YEAR(STR_TO_DATE(subdateshow, '%m/%d/%Y')) FROM table;

eg:

SELECT YEAR(STR_TO_DATE('01/17/2009', '%m/%d/%Y'));  /* shows "2009" */

List View Filter Android

Add an EditText on top of your listview in its .xml layout file. And in your activity/fragment..

lv = (ListView) findViewById(R.id.list_view);
    inputSearch = (EditText) findViewById(R.id.inputSearch);

// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name,    products);
lv.setAdapter(adapter);       
inputSearch.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        // When user changed the Text
        MainActivity.this.adapter.getFilter().filter(cs);
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }

    @Override
    public void afterTextChanged(Editable arg0) {}
});

The basic here is to add an OnTextChangeListener to your edit text and inside its callback method apply filter to your listview's adapter.

EDIT

To get filter to your custom BaseAdapter you"ll need to implement Filterable interface.

class CustomAdapter extends BaseAdapter implements Filterable {

    public View getView(){
    ...
    }
    public Integer getCount()
    {
    ...
    }

    @Override
    public Filter getFilter() {

        Filter filter = new Filter() {

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {

                arrayListNames = (List<String>) results.values;
                notifyDataSetChanged();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                FilterResults results = new FilterResults();
                ArrayList<String> FilteredArrayNames = new ArrayList<String>();

                // perform your search here using the searchConstraint String.

                constraint = constraint.toString().toLowerCase();
                for (int i = 0; i < mDatabaseOfNames.size(); i++) {
                    String dataNames = mDatabaseOfNames.get(i);
                    if (dataNames.toLowerCase().startsWith(constraint.toString()))  {
                        FilteredArrayNames.add(dataNames);
                    }
                }

                results.count = FilteredArrayNames.size();
                results.values = FilteredArrayNames;
                Log.e("VALUES", results.values.toString());

                return results;
            }
        };

        return filter;
    }
}

Inside performFiltering() you need to do actual comparison of the search query to values in your database. It will pass its result to publishResults() method.

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

For chat applications or any other application that is in constant conversation with the server, WebSockets are the best option. However, you can only use WebSockets with a server that supports them, so that may limit your ability to use them if you cannot install the required libraries. In which case, you would need to use Long Polling to obtain similar functionality.

Is it possible to get the index you're sorting over in Underscore.js?

When available, I believe that most lodash array functions will show the iteration. But sorting isn't really an iteration in the same way: when you're on the number 66, you aren't processing the fourth item in the array until it's finished. A custom sort function will loop through an array a number of times, nudging adjacent numbers forward or backward, until the everything is in its proper place.

What is the best way to search the Long datatype within an Oracle database?

Example:

create table longtable(id number,text long);

insert into longtable values(1,'hello world');
insert into longtable values(2,'say hello!');

commit;

create or replace function search_long(r rowid) return varchar2 is
temporary_varchar varchar2(4000);
begin
select text into temporary_varchar from longtable where rowid=r;
return temporary_varchar;
end;
/


SQL> select text from longtable where search_long(rowid) like '%hello%';                                                                              

TEXT
--------------------------------------------------------------------------------
hello world
say hello!

But be careful. A PL/SQL function will only search the first 32K of LONG.

Copying formula to the next row when inserting a new row

You need to insert the new row and then copy from the source row to the newly inserted row. Excel allows you to paste special just formulas. So in Excel:

  • Insert the new row
  • Copy the source row
  • Select the newly created target row, right click and paste special
  • Paste as formulas

VBA if required with Rows("1:1") being source and Rows("2:2") being target:

Rows("2:2").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Rows("2:2").Clear

Rows("1:1").Copy
Rows("2:2").PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone

detect key press in python?

Use this code for find the which key pressed

from pynput import keyboard

def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.esc:
        # Stop listener
        return False

# Collect events until released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

Display number always with 2 decimal places in <input>

Simply use the number pipe like so :

{{ numberValue | number : '.2-2'}}

The pipe above works as follows :

  • Show at-least 1 integer digit before decimal point, set by default
  • Show not less 2 integer digits after the decimal point
  • Show not more than 2 integer digits after the decimal point

How to call Android contacts list?

Looking around for an API Level 5 solution using ContactsContract API you could slightly modify the code above with the following:

  Intent intent = new Intent(Intent.ACTION_PICK);
  intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
  startActivityForResult(intent, PICK_CONTACT);

And then in onActivityResult use the column name:

  ContactsContract.Contacts.DISPLAY_NAME

Using OpenGl with C#?

SharpGL is a project that lets you use OpenGL in your Windows Forms or WPF applications.

Create whole path automatically when writing to a new file

Use FileUtils to handle all these headaches.

Edit: For example, use below code to write to a file, this method will 'checking and creating the parent directory if it does not exist'.

openOutputStream(File file [, boolean append]) 

How do you change the value inside of a textfield flutter?

First Thing

  TextEditingController MyController= new TextEditingController();

Then add it to init State or in any SetState

    MyController.value = TextEditingValue(text: "ANY TEXT");

How to schedule a function to run every hour on Flask?

I'm a little bit new with the concept of application schedulers, but what I found here for APScheduler v3.3.1 , it's something a little bit different. I believe that for the newest versions, the package structure, class names, etc., have changed, so I'm putting here a fresh solution which I made recently, integrated with a basic Flask application:

#!/usr/bin/python3
""" Demonstrating Flask, using APScheduler. """

from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask

def sensor():
    """ Function for test purposes. """
    print("Scheduler is alive!")

sched = BackgroundScheduler(daemon=True)
sched.add_job(sensor,'interval',minutes=60)
sched.start()

app = Flask(__name__)

@app.route("/home")
def home():
    """ Function for test purposes. """
    return "Welcome Home :) !"

if __name__ == "__main__":
    app.run()

I'm also leaving this Gist here, if anyone have interest on updates for this example.

Here are some references, for future readings:

MySQL JOIN the most recent row only?

It's a good idea that logging actual data into "customer_data" table. With this data you can select all data from "customer_data" table as you wish.

Column calculated from another column?

MySQL 5.7 supports computed columns. They call it "Generated Columns" and the syntax is a little weird, but it supports the same options I see in other databases.

https://dev.mysql.com/doc/refman/5.7/en/create-table.html#create-table-generated-columns

Where does Anaconda Python install on Windows?

You can search for "Anaconda prompt" in installed programs and run it.
When it opens, it shows the directory anaconda is working from.
enter image description here

As you can see c:\programdata\anaconda2 is my installed directory.
*side note: programdata folder is hidden in windows so you'll have to enter its path in the folder explorer to access it.

Foreach with JSONArray and JSONObject

Seems like you can't iterate through JSONArray with a for each. You can loop through your JSONArray like this:

for (int i=0; i < arr.length(); i++) {
    arr.getJSONObject(i);
}

Source

How to go back (ctrl+z) in vi/vim

On a mac you can also use command Z and that will go undo. I'm not sure why, but sometimes it stops, and if your like me and vimtutor is on the bottom of that long list of things you need to learn, than u can just close the window and reopen it and should work fine.

Getting a "This application is modifying the autolayout engine from a background thread" error?

Had the same problem because I was using performSelectorInBackground.

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

The solution is running this command:

set OPENSSL_CONF=C:\OpenSSL-Win32\bin\openssl.cfg   

or

set OPENSSL_CONF=[path-to-OpenSSL-install-dir]\bin\openssl.cfg

in the command prompt before using openssl command.

Let openssl know for sure where to find its .cfg file.

Alternatively you could set the same variable OPENSSL_CONF in the Windows environment variables.

NOTE: This can happen when using the OpenSSL binary distribution from Shining Light Productions (a compiled + installer version of the official OpenSSL that is free to download & use). This distribution is "semi-officially" linked from OpenSSL's site as a "service primarily for operating systems where there are no pre-compiled OpenSSL packages".

generate random double numbers in c++

something like this:

#include <iostream>
#include <time.h>

using namespace std;

int main()
{
    const long max_rand = 1000000L;
    double x1 = 12.33, x2 = 34.123, x;

    srandom(time(NULL));

    x = x1 + ( x2 - x1) * (random() % max_rand) / max_rand;

    cout << x1 << " <= " << x << " <= " << x2 << endl;

    return 0;
}

How can I measure the actual memory usage of an application or process?

Note: this works 100% well only when memory consumption increases

If you want to monitor memory usage by given process (or group of processed sharing common name, e.g. google-chrome, you can use my bash-script:

while true; do ps aux | awk ‚{print $5, $11}’ | grep chrome | sort -n > /tmp/a.txt; sleep 1; diff /tmp/{b,a}.txt; mv /tmp/{a,b}.txt; done;

this will continuously look for changes and print them.

Enter image description here

Remove from the beginning of std::vector

Given

std::vector<Rule>& topPriorityRules;

The correct way to remove the first element of the referenced vector is

topPriorityRules.erase(topPriorityRules.begin());

which is exactly what you suggested.

Looks like i need to do iterator overloading.

There is no need to overload an iterator in order to erase first element of std::vector.


P.S. Vector (dynamic array) is probably a wrong choice of data structure if you intend to erase from the front.

Why does configure say no C compiler found when GCC is installed?

Install GCC in Ubuntu Debian Base

sudo apt-get install build-essential

Linq to SQL .Sum() without group ... into

I know this is an old question but why can't you do it like:

db.OrderLineItems.Where(o => o.OrderId == currentOrder.OrderId).Sum(o => o.WishListItem.Price);

I am not sure how to do this using query expressions.

How to get the insert ID in JDBC?

With Hibernate's NativeQuery, you need to return a ResultList instead of a SingleResult, because Hibernate modifies a native query

INSERT INTO bla (a,b) VALUES (2,3) RETURNING id

like

INSERT INTO bla (a,b) VALUES (2,3) RETURNING id LIMIT 1

if you try to get a single result, which causes most databases (at least PostgreSQL) to throw a syntax error. Afterwards, you may fetch the resulting id from the list (which usually contains exactly one item).

How to validate Google reCAPTCHA v3 on server side?

this is solution

index.html

<html>
  <head>
    <title>Google recapcha demo - Codeforgeek</title>
    <script src='https://www.google.com/recaptcha/api.js'></script>
  </head>
  <body>
    <h1>Google reCAPTHA Demo</h1>
    <form id="comment_form" action="form.php" method="post">
      <input type="email" placeholder="Type your email" size="40"><br><br>
      <textarea name="comment" rows="8" cols="39"></textarea><br><br>
      <input type="submit" name="submit" value="Post comment"><br><br>
      <div class="g-recaptcha" data-sitekey="=== Your site key ==="></div>
    </form>
  </body>
</html>

verify.php

<?php
    $email; $comment; $captcha;

    if(isset($_POST['email']))
        $email=$_POST['email'];
    if(isset($_POST['comment']))
        $comment=$_POST['comment'];
    if(isset($_POST['g-recaptcha-response']))
        $captcha=$_POST['g-recaptcha-response'];

    if(!$captcha){
        echo '<h2>Please check the the captcha form.</h2>';
        exit;
    }

    $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRET KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
    if($response['success'] == false)
    {
        echo '<h2>You are spammer ! Get the @$%K out</h2>';
    }
    else
    {
        echo '<h2>Thanks for posting comment.</h2>';
    }
?>

http://codeforgeek.com/2014/12/google-recaptcha-tutorial/

Cannot import scipy.misc.imread

If you have Pillow installed with scipy and it is still giving you error then check your scipy version because it has been removed from scipy since 1.3.0rc1.

rather install scipy 1.1.0 by :

pip install scipy==1.1.0

check https://github.com/scipy/scipy/issues/6212


The method imread in scipy.misc requires the forked package of PIL named Pillow. If you are having problem installing the right version of PIL try using imread in other packages:

from matplotlib.pyplot import imread
im = imread(image.png)

To read jpg images without PIL use:

import cv2 as cv
im = cv.imread(image.jpg)

You can try from scipy.misc.pilutil import imread instead of from scipy.misc import imread

Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.

How to print multiple variable lines in Java

Or try this one:

System.out.println("First Name: " + firstname + " Last Name: "+ lastname +".");

Good luck!

How do I hide javascript code in a webpage?

I'm not sure there's a way to hide that information. No matter what you do to obfuscate or hide whatever you're doing in JavaScript, it still comes down to the fact that your browser needs to load it in order to use it. Modern browsers have web debugging/analysis tools out of the box that make extracting and viewing scripts trivial (just hit F12 in Chrome, for example).

If you're worried about exposing some kind of trade secret or algorithm, then your only recourse is to encapsulate that logic in a web service call and have your page invoke that functionality via AJAX.

Text border using css (border around text)

Use multiple text shadows:

text-shadow: 2px 0 0 #fff, -2px 0 0 #fff, 0 2px 0 #fff, 0 -2px 0 #fff, 1px 1px #fff, -1px -1px 0 #fff, 1px -1px 0 #fff, -1px 1px 0 #fff;

enter image description here

_x000D_
_x000D_
body {_x000D_
  font-family: sans-serif;_x000D_
  background: #222;_x000D_
  color: darkred;_x000D_
  }_x000D_
h1 {_x000D_
  text-shadow: 2px 0 0 #fff, -2px 0 0 #fff, 0 2px 0 #fff, 0 -2px 0 #fff, 1px 1px #fff, -1px -1px 0 #fff, 1px -1px 0 #fff, -1px 1px 0 #fff;_x000D_
}
_x000D_
<h1>test</h1>
_x000D_
_x000D_
_x000D_

Alternatively, you could use text stroke, which only works in webkit:

-webkit-text-stroke-width: 2px;
-webkit-text-stroke-color: #fff;

enter image description here

_x000D_
_x000D_
body {_x000D_
  font-family: sans-serif;_x000D_
  background: #222;_x000D_
  color: darkred;_x000D_
  }_x000D_
h1 {_x000D_
  -webkit-text-stroke-width: 2px;_x000D_
-webkit-text-stroke-color: #fff;_x000D_
}
_x000D_
<h1>test</h1>
_x000D_
_x000D_
_x000D_

Also read more as CSS-Tricks.

PHP CSV string to array

Do this:

$csvData = file_get_contents($fileName);
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
    $array[] = str_getcsv($line);
}
print_r($array);

It will give you an output like this:

Array
(
    [0] => Array
        (
            [0] => 12345
            [1] => Computers
            [2] => Acer
            [3] => 4
            [4] => Varta
            [5] => 5.93
            [6] => 1
            [7] => 0.04
            [8] => 27-05-2013
        )

    [1] => Array
        (
            [0] => 12346
            [1] => Computers
            [2] => Acer
            [3] => 5
            [4] => Decra
            [5] => 5.94
            [6] => 1
            [7] => 0.04
            [8] => 27-05-2013
        )

)

I hope this can be of some help.

How to customize the background/border colors of a grouped table view cell?

I have been having problems with this and tried lots of combinations of things as I noticed that for some cells it worked fine but not for others.

Strangely I found out that it is possible to set the cell.backgroundColor to lightGrayColor and all works perfectly - but blueColor caused me problems of not updating the outside edges.

Unless it is really important to use green - perhaps you might want to try this. It might be that this is a feature to get people to use only grey colours when indicating a cell is selected.

Adding an onclicklistener to listview (android)

You are doing

Object o = prestListView.getItemAtPosition(position);
String str=(String)o;//As you are using Default String Adapter

The o that you get back is not a String, but a prestationEco so you get a CCE when doing the (String)o

How to SELECT WHERE NOT EXIST using LINQ?

How about..

var result = (from s in context.Shift join es in employeeshift on s.shiftid equals es.shiftid where es.empid == 57 select s)

Edit: This will give you shifts where there is an associated employeeshift (because of the join). For the "not exists" I'd do what @ArsenMkrt or @hyp suggest

How do I use this JavaScript variable in HTML?

The HTML tags that you want to edit is called the DOM (Document object manipulate), you can edit the DOM with many functions in the document global object.

The best example that would work on almost any browser is the document.getElementById, it's search for html tag with that id set as an attribute.

There is another option which is easier but works only on modern browsers (IE8+), the querySelector function, it's will find the first element with the matched selector (CSS selectors).

Examples for both options:

_x000D_
_x000D_
<script>_x000D_
var name = prompt("What's your name?");_x000D_
var lengthOfName = name.length_x000D_
</script>_x000D_
<body>_x000D_
  <p id="a"></p>_x000D_
  <p id="b"></p>_x000D_
  <script>_x000D_
    document.getElementById('a').innerHTML = name;_x000D_
document.querySelector('#b').innerHTML = name.length;</script>_x000D_
</body>
_x000D_
_x000D_
_x000D_

InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately

If you are not able to upgrade your Python version to 2.7.9, and want to suppress warnings,

you can downgrade your 'requests' version to 2.5.3:

pip install requests==2.5.3

Bugfix disclosure / Warning introduced in 2.6.0

customize Android Facebook Login button

<FrameLayout
    android:id="@+id/FrameLayout1"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:layout_marginStart="132dp"
    android:layout_marginTop="12dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/logbu">


    <ImageView
        android:id="@+id/fb"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/fb"
        android:onClick="onClickFacebookButton"
        android:textAllCaps="false"
        android:textColor="#ffffff"
        android:textSize="22sp" />

    <com.facebook.login.widget.LoginButton

        android:alpha="0"  <!--***SOLUTION***-->
        android:id="@+id/buttonFacebookLogin"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="45sp"
        android:visibility="visible"
        app:com_facebook_login_text="Log in with Facebook" />

</FrameLayout>

The easiest way to customize the integrated facebook button for both java and kotlin

How to add form validation pattern in Angular 2?

Now, you don't need to use FormBuilder and all this complicated valiation angular stuff. I put more details from this (Angular 2.0.8 - 3march2016): https://github.com/angular/angular/commit/38cb526

Example from repo :

<input [ngControl]="fullName" pattern="[a-zA-Z ]*">

I test it and it works :) - here is my code:

<form (ngSubmit)="onSubmit(room)" #roomForm='ngForm'  >
...
<input 
  id='room-capacity' 
  type="text" 
  class="form-control" 
  [(ngModel)]='room.capacity' 
  ngControl="capacity" 
  required
  pattern="[0-9]+" 
  #capacity='ngForm'>

Alternative approach (UPDATE June 2017)

Validation is ONLY on server side. If something is wrong then server return error code e.g HTTP 400 and following json object in response body (as example):

this.err = { 
    "capacity" : "too_small"
    "filed_name" : "error_name", 
    "field2_name" : "other_error_name",
    ... 
}

In html template I use separate tag (div/span/small etc.)

<input [(ngModel)]='room.capacity' ...>
<small *ngIf="err.capacity" ...>{{ translate(err.capacity) }}</small>

If in 'capacity' is error then tag with msg translation will be visible. This approach have following advantages:

  • it is very simple
  • avoid backend validation code duplication on frontend (for regexp validation this can either prevent or complicate ReDoS attacks)
  • control on way the error is shown (e.g. <small> tag)
  • backend return error_name which is easy to translate to proper language in frontend

Of course sometimes I make exception if validation is needed on frontend side (e.g. retypePassword field on registration is never send to server).

How to determine the content size of a UIWebView?

Xcode8 swift3.1:

  1. Set webView height to 0 first.
  2. In webViewDidFinishLoad Delegate:

let height = webView.scrollView.contentSize.height

Without step1, if webview.height > actual contentHeight, step 2 will return webview.height but not contentsize.height.

CSS3 animate border color

You can use a CSS3 transition for this. Have a look at this example:

http://jsfiddle.net/ujDkf/1/

Here is the main code:

#box {
  position : relative;
  width : 100px;
  height : 100px;
  background-color : gray;
  border : 5px solid black;
  -webkit-transition : border 500ms ease-out;
  -moz-transition : border 500ms ease-out;
  -o-transition : border 500ms ease-out;
  transition : border 500ms ease-out;
}

#box:hover {
   border : 10px solid red;   
}

Inserting a text where cursor is using Javascript/jquery

Use this, from here:

_x000D_
_x000D_
function insertAtCaret(areaId, text) {_x000D_
  var txtarea = document.getElementById(areaId);_x000D_
  if (!txtarea) {_x000D_
    return;_x000D_
  }_x000D_
_x000D_
  var scrollPos = txtarea.scrollTop;_x000D_
  var strPos = 0;_x000D_
  var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?_x000D_
    "ff" : (document.selection ? "ie" : false));_x000D_
  if (br == "ie") {_x000D_
    txtarea.focus();_x000D_
    var range = document.selection.createRange();_x000D_
    range.moveStart('character', -txtarea.value.length);_x000D_
    strPos = range.text.length;_x000D_
  } else if (br == "ff") {_x000D_
    strPos = txtarea.selectionStart;_x000D_
  }_x000D_
_x000D_
  var front = (txtarea.value).substring(0, strPos);_x000D_
  var back = (txtarea.value).substring(strPos, txtarea.value.length);_x000D_
  txtarea.value = front + text + back;_x000D_
  strPos = strPos + text.length;_x000D_
  if (br == "ie") {_x000D_
    txtarea.focus();_x000D_
    var ieRange = document.selection.createRange();_x000D_
    ieRange.moveStart('character', -txtarea.value.length);_x000D_
    ieRange.moveStart('character', strPos);_x000D_
    ieRange.moveEnd('character', 0);_x000D_
    ieRange.select();_x000D_
  } else if (br == "ff") {_x000D_
    txtarea.selectionStart = strPos;_x000D_
    txtarea.selectionEnd = strPos;_x000D_
    txtarea.focus();_x000D_
  }_x000D_
_x000D_
  txtarea.scrollTop = scrollPos;_x000D_
}
_x000D_
<textarea id="textareaid"></textarea>_x000D_
<a href="#" onclick="insertAtCaret('textareaid', 'text to insert');return false;">Click Here to Insert</a>
_x000D_
_x000D_
_x000D_

Detecting input change in jQuery?

// .blur is triggered when element loses focus

$('#target').blur(function() {
  alert($(this).val());
});

// To trigger manually use:

$('#target').blur();

Instantly detect client disconnection from server socket

"That's just the way TCP works and you have to live with it."

Yup, you're right. It's a fact of life I've come to realize. You will see the same behavior exhibited even in professional applications utilizing this protocol (and even others). I've even seen it occur in online games; you're buddy says "goodbye", and he appears to be online for another 1-2 minutes until the server "cleans house".

You can use the suggested methods here, or implement a "heartbeat", as also suggested. I choose the former. But if I did choose the latter, I'd simply have the server "ping" each client every so often with a single byte, and see if we have a timeout or no response. You could even use a background thread to achieve this with precise timing. Maybe even a combination could be implemented in some sort of options list (enum flags or something) if you're really worried about it. But it's no so big a deal to have a little delay in updating the server, as long as you DO update. It's the internet, and no one expects it to be magic! :)

What do the terms "CPU bound" and "I/O bound" mean?

IO bound processes: spend more time doing IO than computations, have many short CPU bursts. CPU bound processes: spend more time doing computations, few very long CPU bursts

Python SQLite: database is locked

Turned out the problem happened because the path to the db file was actually a samba mounted dir. I moved it and that started working.

How To Show And Hide Input Fields Based On Radio Button Selection

Use display:none/block, instead of visibility, and add a margin-top/bottom for the space you want to see ONLY when the inputs are shown

 function yesnoCheck() {
        if (document.getElementById('yesCheck').checked) {
           document.getElementById('ifYes').style.display = 'block';
        } else {
           document.getElementById('ifYes').style.display = 'none';
        }
    }

and your HTML line for the ifYes tag

<div id="ifYes" style="display:none;margin-top:3%;">If yes, explain:

Javascript loading CSV file into an array

The original code works fine for reading and separating the csv file data but you need to change the data type from csv to text.

Checking host availability by using ping in bash scripts

FYI, I just did some test using the method above and if we use multi ping (10 requests)

ping -c10 8.8.8.8 &> /dev/null ; echo $?

the result of multi ping command will be "0" if at least one of ping result reachable, and "1" in case where all ping requests are unreachable.

How to stop a JavaScript for loop?

The logic is incorrect. It would always return the result of last element in the array.

remIndex = -1;

for (i = 0; i < remSize.length; i++) {      
    if (remSize[i].size == remData.size) {
        remIndex = i
        break;
    }
}

SQL Query - Using Order By in UNION

(SELECT table1.field1 FROM table1 
UNION
SELECT table2.field1 FROM table2) ORDER BY field1 

Work? Remember think sets. Get the set you want using a union and then perform your operations on it.

Counting words in string

I'm not sure if this has been said previously, or if it's what is needed here, but couldn't you make the string an array and then find the length?

let randomString = "Random String";

let stringWords = randomString.split(' ');
console.log(stringWords.length);

Can't specify the 'async' modifier on the 'Main' method of a console app

In my case I had a list of jobs that I wanted to run in async from my main method, have been using this in production for quite sometime and works fine.

static void Main(string[] args)
{
    Task.Run(async () => { await Task.WhenAll(jobslist.Select(nl => RunMulti(nl))); }).GetAwaiter().GetResult();
}
private static async Task RunMulti(List<string> joblist)
{
    await ...
}

Logcat not displaying my log calls

Using the SDK 4.0.3 you have to explicitly select it on debug configurations > project > target or else it will never show using Eclipse Indigo (3.7). Of course an eclipse restart ensues.

When and why to 'return false' in JavaScript?

Also, this short and interesting link to read through https://www.w3schools.com/jsref/event_preventdefault.asp

Definition and Usage

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.

For example, this can be useful when:

Clicking on a "Submit" button, prevent it from submitting a form
Clicking on a link, prevent the link from following the URL

Note: Not all events are cancelable. Use the cancelable property to find out if an event is cancelable.

Note: The preventDefault() method does not prevent further propagation of an event through the DOM. Use the stopPropagation() method to handle this.

Get class labels from Keras functional model

UPDATE: This is no longer valid for newer Keras versions. Please use argmax() as in the answer from Emilia Apostolova.

The functional API models have just the predict() function which for classification would return the class probabilities. You can then select the most probable classes using the probas_to_classes() utility function. Example:

y_proba = model.predict(x)
y_classes = keras.np_utils.probas_to_classes(y_proba)

This is equivalent to model.predict_classes(x) on the Sequential model.

The reason for this is that the functional API support more general class of tasks where predict_classes() would not make sense.

More info: https://github.com/fchollet/keras/issues/2524

How to get correlation of two vectors in python

The docs indicate that numpy.correlate is not what you are looking for:

numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
  Cross-correlation of two 1-dimensional sequences.
  This function computes the correlation as generally defined in signal processing texts:
     z[k] = sum_n a[n] * conj(v[n+k])
  with a and v sequences being zero-padded where necessary and conj being the conjugate.

Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

from scipy.stats.stats import pearsonr   
a = [1,4,6]
b = [1,2,3]   
print pearsonr(a,b)

This gives

(0.99339926779878274, 0.073186395040328034)

You can also use numpy.corrcoef:

import numpy
print numpy.corrcoef(a,b)

This gives:

[[ 1.          0.99339927]
 [ 0.99339927  1.        ]]

How to store Query Result in variable using mysql

Select count(*) from table_name into @var1; 
Select @var1;

On Selenium WebDriver how to get Text from Span Tag

PHP way of getting text from span tag:

$spanText = $this->webDriver->findElement(WebDriverBy::xpath("//*[@id='specInformation']/tbody/tr[2]/td[1]/span[1]"))->getText();

c# datagridview doubleclick on row with FullRowSelect

For your purpose, there is a default event when the row header is double-clicked. Check the following code,

 private void dgvCustom_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
 {
      //Your code goes here
 }

How to implement swipe gestures for mobile devices?

Have you tried Hammerjs? It supports swipe gestures by using the velocity of the touch. http://eightmedia.github.com/hammer.js/

How to pass integer from one Activity to another?

Their are two methods you can use to pass an integer. One is as shown below.

A.class

Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);

B.class

Intent intent = getIntent();
int intValue = intent.getIntExtra("intVariableName", 0);

The other method converts the integer to a string and uses the following code.

A.class

Intent intent = new Intent(A.this, B.class);
Bundle extras = new Bundle();
extras.putString("StringVariableName", intValue + "");
intent.putExtras(extras);
startActivity(intent);

The code above will pass your integer value as a string to class B. On class B, get the string value and convert again as an integer as shown below.

B.class

   Bundle extras = getIntent().getExtras();
   String stringVariableName = extras.getString("StringVariableName");
   int intVariableName = Integer.parseInt(stringVariableName);

What are public, private and protected in object oriented programming?

A public item is one that is accessible from any other class. You just have to know what object it is and you can use a dot operator to access it. Protected means that a class and its subclasses have access to the variable, but not any other classes, they need to use a getter/setter to do anything with the variable. A private means that only that class has direct access to the variable, everything else needs a method/function to access or change that data. Hope this helps.

jQuery: Wait/Delay 1 second without executing code

ES6 setTimeout

setTimeout(() => {
  console.log("we waited 204586560000 ms to run this code, oh boy wowwoowee!");
}, 204586560000);

Edit: 204586560000 ms is the approximate time between the original question and this answer... assuming I calculated correctly.

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

It's safer to always percent-encode all characters except those defined as "unreserved" in RFC-3986.

unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"

So, percent-encode the plus character and other special characters.

The problem that you are having with pluses is because, according to RFC-1866 (HTML 2.0 specification), paragraph 8.2.1. subparagraph 1., "The form field names and values are escaped: space characters are replaced by `+', and then reserved characters are escaped"). This way of encoding form data is also given in later HTML specifications, look for relevant paragraphs about application/x-www-form-urlencoded.

How do we use runOnUiThread in Android?

runOnUiThread(new Runnable() {
                public void run() {
                //Do something on UiThread
            }
        });

Jquery Chosen plugin - dynamically populate list by Ajax

The chosen answer is outdated, same goes to meltingice /ajax-chosen plugin.

With Select2 plugin got many bugs which is i can't resolve it.

Here my answer for this question.

I integrated my solution with function trigger after user type. Thanks to this answer : https://stackoverflow.com/a/5926782/4319179.

//setup before functions
  var typingTimer;                //timer identifier
  var doneTypingInterval = 2000;  //time in ms (2 seconds)
  var selectID = 'YourSelectId';    //Hold select id
  var selectData = [];           // data for unique id array

  //on keyup, start the countdown
  $('#' + selectID + '_chosen .chosen-choices input').keyup(function(){

      // Change No Result Match text to Searching.
      $('#' + selectID + '_chosen .no-results').html('Searching = "'+ $('#' + selectID + '_chosen .chosen-choices input').val() + '"');


      clearTimeout(typingTimer);  //Refresh Timer on keyup 
      if ($('#' + selectID + '_chosen .chosen-choices input').val()) {

           typingTimer = setTimeout(doneTyping, doneTypingInterval);  //Set timer back if got value on input

      }

  });

  //user is "finished typing," do something
  function doneTyping () {

      var inputData = $('#' + selectID + '_chosen .chosen-choices input').val();  //get input data

      $.ajax({
        url: "YourUrl",
         data: {data: inputData},
        type:'POST',
        dataType: "json",
        beforeSend: function(){
          // Change No Result Match to Getting Data beforesend
          $('#' + selectID + '_chosen .no-results').html('Getting Data = "'+$('#' + selectID + '_chosen .chosen-choices input').val()+'"');
    },
        success: function( data ) { 

          // iterate data before append
          $.map( data, function( item ) {

            // matching data eg: by id or something unique; if data match: <option> not append - else: append <option>
            // This will prevent from select the same thing twice.
            if($.inArray(item.attr_hash,selectData) == -1){

              // if not match then append in select
              $('#' + selectID ).append('<option id="'+item.id+'" data-id = "'+item.id+'">' + item.data + '</option>');

            }            

          });

          // Update chosen again after append <option>
          $('#' + selectID ).trigger("chosen:updated");

        }
      });

  }

  // Chosen event listen on input change eg: after select data / deselect this function will be trigger
  $('#' + selectID ).on('change', function() {

    // get select jquery object
    var domArray = $('#' + selectID ).find('option:selected');

    // empty array data
    selectData = [];

    for (var i = 0, length = domArray.length; i < length; i++ ){

      // Push unique data to array (for matching purpose)
      selectData.push( $(domArray[i]).data('id') );

    }

    // Replace select <option> to only selected option
    $('#' + selectID ).html(domArray);

    // Update chosen again after replace selected <option>
    $('#' + selectID ).trigger("chosen:updated");

  });

Remove duplicate rows in MySQL

As of version 8.0 (2018), MySQL finally supports window functions.

Window functions are both handy and efficient. Here is a solution that demonstrates how to use them to solve this assignment.

In a subquery, we can use ROW_NUMBER() to assign a position to each record in the table within column1/column2 groups, ordered by id. If there is no duplicates, the record will get row number 1. If duplicate exists, they will be numbered by ascending id (starting at 1).

Once records are properly numbered in the subquery, the outer query just deletes all records whose row number is not 1.

Query :

DELETE FROM tablename
WHERE id IN (
    SELECT id
    FROM (
        SELECT 
            id, 
            ROW_NUMBER() OVER(PARTITION BY column1, column2 ORDER BY id) rn
        FROM output
    ) t
    WHERE rn > 1
)

How to add a hook to the application context initialization event?

Create your annotation

  @Retention(RetentionPolicy.RUNTIME)
    public @interface AfterSpringLoadComplete {
    }

Create class

    public class PostProxyInvokerContextListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    ConfigurableListableBeanFactory factory;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext context = event.getApplicationContext();
        String[] names = context.getBeanDefinitionNames();
        for (String name : names) {
            try {
                BeanDefinition definition = factory.getBeanDefinition(name);
                String originalClassName = definition.getBeanClassName();
                Class<?> originalClass = Class.forName(originalClassName);
                Method[] methods = originalClass.getMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(AfterSpringLoadComplete.class)){
                        Object bean = context.getBean(name);
                        Method currentMethod = bean.getClass().getMethod(method.getName(), method.getParameterTypes());
                        currentMethod.invoke(bean);
                    }
                }
            } catch (Exception ignored) {
            }
        }
    }
}

Register this class by @Component annotation or in xml

<bean class="ua.adeptius.PostProxyInvokerContextListener"/>

and use annotation where you wan on any method that you want to run after context initialized, like:

   @AfterSpringLoadComplete
    public void init() {}

If Else If In a Sql Server Function

If yes_ans > no_ans and yes_ans > na_ans  

You're using column names in a statement (outside of a query). If you want variables, you must declare and assign them.

Simple way to transpose columns and rows in SQL?

This way Convert all Data From Filelds(Columns) In Table To Record (Row).

Declare @TableName  [nvarchar](128)
Declare @ExecStr    nvarchar(max)
Declare @Where      nvarchar(max)
Set @TableName = 'myTableName'
--Enter Filtering If Exists
Set @Where = ''

--Set @ExecStr = N'Select * From '+quotename(@TableName)+@Where
--Exec(@ExecStr)

Drop Table If Exists #tmp_Col2Row

Create Table #tmp_Col2Row
(Field_Name nvarchar(128) Not Null
,Field_Value nvarchar(max) Null
)

Set @ExecStr = N' Insert Into #tmp_Col2Row (Field_Name , Field_Value) '
Select @ExecStr += (Select N'Select '''+C.name+''' ,Convert(nvarchar(max),'+quotename(C.name) + ') From ' + quotename(@TableName)+@Where+Char(10)+' Union All '
         from sys.columns as C
         where (C.object_id = object_id(@TableName)) 
         for xml path(''))
Select @ExecStr = Left(@ExecStr,Len(@ExecStr)-Len(' Union All '))
--Print @ExecStr
Exec (@ExecStr)

Select * From #tmp_Col2Row
Go

how to get the attribute value of an xml node using java

Since your question is more generic so try to implement it with XML Parsers available in Java .If you need it in specific to parsers, update your code here what you have tried yet

<?xml version="1.0" encoding="UTF-8"?>
<ep>
    <source type="xml">TEST</source>
    <source type="text"></source>
</ep>
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("uri to xmlfile");
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//ep/source[@type]");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

for (int i = 0; i < nl.getLength(); i++)
{
    Node currentItem = nl.item(i);
    String key = currentItem.getAttributes().getNamedItem("type").getNodeValue();
    System.out.println(key);
}

Javascript wait() function

You shouldn't edit it, you should completely scrap it.

Any attempt to make execution stop for a certain amount of time will lock up the browser and switch it to a Not Responding state. The only thing you can do is use setTimeout correctly.

Calling a phone number in swift

For swift 3.0

if let url = URL(string: "tel://\(number)"), UIApplication.shared.canOpenURL(url) {
    if #available(iOS 10, *) {
        UIApplication.shared.open(url)
    } else {
        UIApplication.shared.openURL(url)
    }
}
else {
    print("Your device doesn't support this feature.")
}

SQL Sum Multiple rows into one

Thank you for your responses. Turns out my problem was a database issue with duplicate entries, not with my logic. A quick table sync fixed that and the SUM feature worked as expected. This is all still useful knowledge for the SUM feature and is worth reading if you are having trouble using it.

How to encrypt a large file in openssl using public key

You can't directly encrypt a large file using rsautl. instead, do something like the following:

  1. Generate a key using openssl rand, eg. openssl rand 32 -out keyfile
  2. Encrypt the key file using openssl rsautl
  3. Encrypt the data using openssl enc, using the generated key from step 1.
  4. Package the encrypted key file with the encrypted data. the recipient will need to decrypt the key with their private key, then decrypt the data with the resulting key.

How to run composer from anywhere?

For MAC and LINUX use the following procedure:

Add the directory where composer.phar is located to you PATH:

export PATH=$PATH:/yourdirectory

and then rename composer.phar to composer:

mv composer.phar composer

Execute an action when an item on the combobox is selected

Not an answer to the original question, but an example to the how-to-make-reusable and working custom renderers without breaking MVC :-)

// WRONG
public class DataWrapper {
   final Data data;
   final String description;
   public DataWrapper(Object data, String description) {
       this.data = data;
       this.description = description;
   }
   ....
   @Override
   public String toString() {
       return description;
   } 
}
// usage
myModel.add(new DataWrapper(data1, data1.getName());

It is wrong in a MVC environment, because it is mixing data and view: now the model doesn't contain the data but a wrapper which is introduced for view reasons. That's breaking separation of concerns and encapsulation (every class interacting with the model needs to be aware of the wrapped data).

The driving forces for breaking of rules were:

  • keep functionality of the default KeySelectionManager (which is broken by a custom renderer)
  • reuse of the wrapper class (can be applied to any data type)

As in Swing a custom renderer is the small coin designed to accomodate for custom visual representation, a default manager which can't cope is ... broken. Tweaking design just to accommodate for such a crappy default is the wrong way round, kind of upside-down. The correct is, to implement a coping manager.

While re-use is fine, doing so at the price of breaking the basic architecture is not a good bargin.

We have a problem in the presentation realm, let's solve it in the presentation realm with the elements designed to solve exactly that problem. As you might have guessed, SwingX already has such a solution :-)

In SwingX, the provider of a string representation is called StringValue, and all default renderers take such a StringValue to configure themselves:

StringValue sv = new StringValue() {
     @Override
     public String getString(Object value) {
        if (value instanceof Data) {
            return ((Data) value).getSomeProperty();
        }
        return TO_STRING.getString(value);
     }
};
DefaultListRenderer renderer = new DefaultListRenderer(sv);

As the defaultRenderer is-a StringValue (implemented to delegate to the given), a well-behaved implementation of KeySelectionManager now can delegate to the renderer to find the appropriate item:

public BetterKeySelectionManager implements KeySelectionManager {

     @Override
     public int selectionForKey(char ch, ComboBoxModel model) {

         ....
         if (getCellRenderer() instance of StringValue) {
              String text = ((StringValue) getCellRenderer()).getString(model.getElementAt(row));
              ....
         } 
     }

}

Outlined the approach because it is easily implementable even without using SwingX, simply define implement something similar and use it:

  • some provider of a string representation
  • a custom renderer which is configurable by that provider and guarantees to use it in configuring itself
  • a well-behaved keySelectionManager with queries the renderer for its string represention

All except the string provider is reusable as-is (that is exactly one implemenation of the custom renderer and the keySelectionManager). There can be general implementations of the string provider, f.i. those formatting value or using bean properties via reflection. And all without breaking basic rules :-)

Change drive in git bash for windows

In order to navigate to a different drive/directory you can do it in convenient way (instead of typing cd /e/Study/Codes), just type in cd[Space], and drag-and-drop your directory Codes with your mouse to git bash, hit [Enter].

Evaluating a mathematical expression in a string

This is a massively late reply, but I think useful for future reference. Rather than write your own math parser (although the pyparsing example above is great) you could use SymPy. I don't have a lot of experience with it, but it contains a much more powerful math engine than anyone is likely to write for a specific application and the basic expression evaluation is very easy:

>>> import sympy
>>> x, y, z = sympy.symbols('x y z')
>>> sympy.sympify("x**3 + sin(y)").evalf(subs={x:1, y:-3})
0.858879991940133

Very cool indeed! A from sympy import * brings in a lot more function support, such as trig functions, special functions, etc., but I've avoided that here to show what's coming from where.

Creating a new user and password with Ansible

I know that I'm late to the party, but there is another solution that I'm using. It might be handy for distros that don't have --stdin in passwd binary.

- hosts: localhost
  become: True
  tasks:
    - name: Change user password
      shell: "yes '{{ item.pass }}' | passwd {{ item.user }}"
      loop:
       - { pass: 123123, user: foo }
       - { pass: asdf, user: bar }
      loop_control:
        label: "{{ item.user }}"

Label in loop_control is responsible for printing only username. The whole playbook or just user variables (you can use vars_files:) should be encrypted with ansible-vault.

Can (domain name) subdomains have an underscore "_" in it?

Not if you want it to resolve on the Internet.

You cannot have: http://my_subdomain.example.com is invalid.

You can have: http://my-subdomain.example.com with a hyphen.

IIS: Where can I find the IIS logs?

Enabling Tracing may be a better alternative to the Windows Event Log. This gave me the information I needed to fix my own WebService.

Using relative URL in CSS file, what location is it relative to?

Try using:

body {
  background-attachment: fixed;
  background-image: url(./Images/bg4.jpg);
}

Images being folder holding the picture that you want to post.

What is the best way to implement nested dictionaries?

For easy iterating over your nested dictionary, why not just write a simple generator?

def each_job(my_dict):
    for state, a in my_dict.items():
        for county, b in a.items():
            for job, value in b.items():
                yield {
                    'state'  : state,
                    'county' : county,
                    'job'    : job,
                    'value'  : value
                }

So then, if you have your compilicated nested dictionary, iterating over it becomes simple:

for r in each_job(my_dict):
    print "There are %d %s in %s, %s" % (r['value'], r['job'], r['county'], r['state'])

Obviously your generator can yield whatever format of data is useful to you.

Why are you using try catch blocks to read the tree? It's easy enough (and probably safer) to query whether a key exists in a dict before trying to retrieve it. A function using guard clauses might look like this:

if not my_dict.has_key('new jersey'):
    return False

nj_dict = my_dict['new jersey']
...

Or, a perhaps somewhat verbose method, is to use the get method:

value = my_dict.get('new jersey', {}).get('middlesex county', {}).get('salesmen', 0)

But for a somewhat more succinct way, you might want to look at using a collections.defaultdict, which is part of the standard library since python 2.5.

import collections

def state_struct(): return collections.defaultdict(county_struct)
def county_struct(): return collections.defaultdict(job_struct)
def job_struct(): return 0

my_dict = collections.defaultdict(state_struct)

print my_dict['new jersey']['middlesex county']['salesmen']

I'm making assumptions about the meaning of your data structure here, but it should be easy to adjust for what you actually want to do.

Python Graph Library

There are two excellent choices:

NetworkX

and

igraph

I like NetworkX, but I read good things about igraph as well. I routinely use NetworkX with graphs with 1 million nodes with no problem (it's about double the overhead of a dict of size V + E)

If you want a feature comparison, see this from the Networkx-discuss list

Feature comparison thread

ld cannot find -l<library>

you can add the Path to coinhsl lib to LD_LIBRARY_PATH variable. May be that will help.

export LD_LIBRARY_PATH=/xx/yy/zz:$LD_LIBRARY_PATH

where /xx/yy/zz represent the path to coinhsl lib.

How to add a footer to the UITableView?

Initially I was just trying the method:

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section

but after using this along with:

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section

problem was solved. Sample Program-

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 30.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *sampleView = [[UIView alloc] init];
    sampleView.frame = CGRectMake(SCREEN_WIDTH/2, 5, 60, 4);
    sampleView.backgroundColor = [UIColor blackColor];
    return sampleView;
}

and include UITableViewDelegate protocol.

@interface TestViewController : UIViewController <UITableViewDelegate>

How do I create a new line in Javascript?

If you are using a JavaScript file (.js) then use document.write("\n");. If you are in a html file (.html or . htm) then use document.write("<br/>");.

Undefined Reference to

I was getting this error because my cpp files was not added in the CMakeLists.txt file

How to dynamically add and remove form fields in Angular 2

That is the HTML code. Anyone can use this:

<div class="card-header">Contact Information</div>
          <div class="card-body" formArrayName="funds">
            <div class="row">
              <div class="col-6" *ngFor="let contact of contactFormGroup.controls; let i = index;">
                <div [formGroupName]="i" class="row">
                  <div class="form-group col-6">
                    <label>Type of Contact</label>
                    <select class="form-control" formControlName="fundName" type="text">
                      <option value="01">Balance Fund</option>
                      <option value="02">Equity Fund</option>
                    </select> 
                  </div>
                  <div class="form-group col-12">
                    <label>Allocation</label>
                    <input class="form-control" formControlName="allocation" type="number">
                    <span class="text-danger" *ngIf="getContactsFormGroup(i).controls['allocation'].touched && 
                    getContactsFormGroup(i).controls['allocation'].hasError('required')">
                        Allocation % is required! </span>
                  </div>
                  <div class="form-group col-12 text-right">
                    <button class="btn btn-danger" type="button" (click)="removeContact(i)"> Remove </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <button class="btn btn-primary m-1" type="button" (click)="addContact()"> Add Contact </button>

Non-conformable arrays error in code

The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

In particular, you'll have to replace this line:

omega   = rgamma(1,a0,1) / L0

with:

omega   = as.vector(rgamma(1,a0,1) / L0)

everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

Here's the modified code that should work:

gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                     a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
    m0      = c(m01, m02) 
    C0      = matrix(nrow = 2, ncol = 2) 
    C0[1,1] = 1 / k01 
    C0[1,2] = 0 
    C0[2,1] = 0 
    C0[2,2] = 1 / k02 
    beta    = mvrnorm(1,m0,C0) 
    omega   = as.vector(rgamma(1,a0,1) / L0)
    draws   = matrix(ncol = 3,nrow = ndraw) 
    it      = -nburn 

    while (it < ndraw) {
        it    = it + 1 
        C1    = solve(solve(C0) + omega * t(X) %*% X) 
        m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
        beta  = mvrnorm(1, m1, C1) 
        a1    = a0 + n / 2 
        L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
        omega = as.vector(rgamma(1, a1, 1) / L1)
        if (it > 0) { 
            draws[it,1] = beta[1]
            draws[it,2] = beta[2]
            draws[it,3] = omega
        }
    }
    return(draws)
}

Hide vertical scrollbar in <select> element

This is where we appreciate all the power of CSS3:

_x000D_
_x000D_
.bloc {_x000D_
  display: inline-block;_x000D_
  vertical-align: top;_x000D_
  overflow: hidden;_x000D_
  border: solid grey 1px;_x000D_
}_x000D_
_x000D_
.bloc select {_x000D_
  padding: 10px;_x000D_
  margin: -5px -20px -5px -5px;_x000D_
}
_x000D_
<div class="bloc">_x000D_
  <select name="year" size="5">_x000D_
    <option value="2010">2010</option>_x000D_
    <option value="2011">2011</option>_x000D_
    <option value="2012" SELECTED>2012</option>_x000D_
    <option value="2013">2013</option>_x000D_
    <option value="2014">2014</option>_x000D_
  </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle

How to listen to the window scroll event in a VueJS component?

Here's what works directly with Vue custom components.

 <MyCustomComponent nativeOnScroll={this.handleScroll}>

or

<my-component v-on:scroll.native="handleScroll">

and define a method for handleScroll. Simple!

Get number of digits with JavaScript

The length property returns the length of a string (number of characters).

The length of an empty string is 0.

var str = "Hello World!";
var n = str.length;

The result of n will be: 12

    var str = "";
    var n = str.length;

The result of n will be: 0


Array length Property:


The length property sets or returns the number of elements in an array.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length;

The result will be: 4

Syntax:

Return the length of an array:

array.length

Set the length of an array:

array.length=number

How to Make Laravel Eloquent "IN" Query?

Syntax:

$data = Model::whereIn('field_name', [1, 2, 3])->get();

Use for Users Model

$usersList = Users::whereIn('id', [1, 2, 3])->get();

How should I resolve java.lang.IllegalArgumentException: protocol = https host = null Exception?

URLs use forward slashes (/), not backward ones (as windows). Try:

serverURLS = "https://abc.my.domain.com:55555/update";

The reason why you get the error is that the URL class can't parse the host part of the string and therefore, host is null.

Accuracy Score ValueError: Can't Handle mix of binary and continuous target

The sklearn.metrics.accuracy_score(y_true, y_pred) method defines y_pred as:

y_pred : 1d array-like, or label indicator array / sparse matrix. Predicted labels, as returned by a classifier.

Which means y_pred has to be an array of 1's or 0's (predicated labels). They should not be probabilities.

The predicated labels (1's and 0's) and/or predicted probabilites can be generated using the LinearRegression() model's methods predict() and predict_proba() respectively.

1. Generate predicted labels:

LR = linear_model.LinearRegression()
y_preds=LR.predict(X_test)
print(y_preds)

output:

[1 1 0 1]

y_preds can now be used for the accuracy_score() method: accuracy_score(y_true, y_pred)

2. Generate probabilities for labels:

Some metrics such as 'precision_recall_curve(y_true, probas_pred)' require probabilities, which can be generated as follows:

LR = linear_model.LinearRegression()
y_preds=LR.predict_proba(X_test)
print(y_preds)

output:

[0.87812372 0.77490434 0.30319547 0.84999743]

Need a query that returns every field that contains a specified letter

where somefield like '%a%' or somefield like '%b%'

How to dynamically update labels captions in VBA form?

Use Controls object

For i = 1 To X
    Controls("Label" & i).Caption =  MySheet.Cells(i + 1, i).Value
Next

Run java jar file on a server as background process

Systemd which now runs in the majority of distros

Step 1:

Find your user defined services mine was at /usr/lib/systemd/system/

Step 2:

Create a text file with your favorite text editor name it whatever_you_want.service

Step 3:

Put following Template to the file whatever_you_want.service

[Unit]
Description=webserver Daemon

[Service]
ExecStart=/usr/bin/java -jar /web/server.jar
User=user

[Install]
WantedBy=multi-user.target

Step 4:

Run your service
as super user

$ systemctl start whatever_you_want.service # starts the service
$ systemctl enable whatever_you_want.service # auto starts the service
$ systemctl disable whatever_you_want.service # stops autostart
$ systemctl stop whatever_you_want.service # stops the service
$ systemctl restart whatever_you_want.service # restarts the service

Split string with string as delimiter

I've found two older scripts that use an indefinite or even a specific string to split. As an approach, these are always helpful.

https://www.administrator.de/contentid/226533#comment-1059704 https://www.administrator.de/contentid/267522#comment-1000886

@echo off
:noOption
if "%~1" neq "" goto :nohelp
echo Gibt eine Ausgabe bis zur angebenen Zeichenfolge&echo(
echo %~n0 ist mit Eingabeumleitung zu nutzen
echo %~n0 "Zeichenfolge" ^<Quelldatei [^>Zieldatei]&echo(
echo    Zeichenfolge    die zu suchende Zeichenfolge wird mit FIND bestimmt
echo            ohne AusgabeUmleitung Ausgabe im CMD Fenster
exit /b
:nohelp
setlocal disabledelayedexpansion
set "intemp=%temp%%time::=%"
set "string=%~1"
set "stringlength=0"
:Laenge string bestimmen
for /f eol^=^

^ delims^= %%i in (' cmd /u /von /c "echo(!string!"^|find /v "" ') do set /a Stringlength += 1

:Eingabe temporär speichern
>"%intemp%" find /n /v ""

:suchen der Zeichenfolge und Zeile bestimmen und speichen
set "NRout="
for /f "tokens=*delims=" %%a in (' find "%string%"^<"%intemp%" ') do if not defined NRout (set "LineStr=%%a"
  for /f "delims=[]" %%b in ("%%a") do set "NRout=%%b"
)
if not defined NRout >&2 echo Zeichenfolge nicht gefunden.& set /a xcode=1 &goto :end
if %NRout% gtr 1 call :Line
call :LineStr

:end
del "%intemp%"
exit /b %xcode%

:LineStr Suche nur jeden ersten Buchstaben des Strings in der Treffer-Zeile dann Ausgabe bis dahin
for /f eol^=^

^ delims^= %%a in ('cmd /u /von /c "echo(!String!"^|findstr .') do (
  for /f "delims=[]" %%i in (' cmd /u /von /c "echo(!LineStr!"^|find /n "%%a" ') do (
    setlocal enabledelayedexpansion
    for /f %%n in ('set /a %%i-1') do if !LineStr:^~%%n^,%stringlength%! equ !string! (
      set "Lineout=!LineStr:~0,%%n!!string!"
      echo(!Lineout:*]=!
      exit /b
    )
) )
exit /b 

:Line vorige Zeilen ausgeben
for /f "usebackq tokens=* delims=" %%i in ("%intemp%") do (
  for /f "tokens=1*delims=[]" %%n in ("%%i") do if %%n EQU %NRout%  exit /b
  set "Line=%%i"
  setlocal enabledelayedexpansion 
  echo(!Line:*]=!
  endlocal
)
exit /b

@echo off
:: CUTwithWildcards.cmd
:noOption
if "%~1" neq "" goto :nohelp
echo Gibt eine Ausgabe ohne die angebene Zeichenfolge.
echo Der Rest wird abgeschnitten.&echo(
echo %~n0 "Zeichenfolge" B n E [/i] &echo(
echo    Zeichenfolge    String zum Durchsuchen
echo    B   Zeichen Wonach am Anfang gesucht wird
echo    n   Auszulassende Zeichenanzahl
echo    E   Zeichen was das Ende der Zeichen Bestimmt
echo    /i  Case intensive
exit /b
:nohelp
setlocal disabledelayedexpansion
set  "Original=%~1"
set     "Begin=%~2"
set /a    Excl=%~3 ||echo Syntaxfehler.>&2 &&exit /b 1
set       "End=%~4"
if not defined end echo Syntaxfehler.>&2 &exit /b 1
set   "CaseInt=%~5"
:: end Setting Input Param
set       "out="
set      "more="
call :read Original
if errorlevel 1 echo Zeichenfolge nicht gefunden.>&2
exit /b
:read VarName B # E [/i]
for /f "delims=[]" %%a in (' cmd /u /von /c "echo  !%~1!"^|find /n %CaseInt% "%Begin%" ') do (
  if defined out exit /b 0
  for /f "delims=[]" %%b in (' cmd /u /von /c "echo !%1!"^|more +%Excl%^|find /n %CaseInt% "%End%"^|find "[%%a]" ') do (
    set "out=1"
    setlocal enabledelayedexpansion
    set "In=  !Original!"
    set "In=!In:~,%%a!"
    echo !In:^~2!
    endlocal
) )
if not defined out exit /b 1 
exit /b

::oneliner for CMDLine
set "Dq=""
for %i in ("*S??E*") do @set "out=1" &for /f "delims=[]" %a in ('cmd/u/c "echo  %i"^|find /n "S"') do @if defined out for /f "delims=[]" %b in ('cmd/u/c "echo %i"^|more +2^|find /n "E"^|find "[%a]"') do @if %a equ %b set "out=" & set in= "%i" &cmd /v/c echo ren "%i" !in:^~0^,%a!!Dq!)

How do I sort a two-dimensional (rectangular) array in C#?

I like the DataTable approach proposed by MusiGenesis above. The nice thing about it is that you can sort by any valid SQL 'order by' string that uses column names, e.g. "x, y desc, z" for 'order by x, y desc, z'. (FWIW, I could not get it to work using column ordinals, e.g. "3,2,1 " for 'order by 3,2,1') I used only integers, but clearly you could add mixed type data into the DataTable and sort it any which way.

In the example below, I first loaded some unsorted integer data into a tblToBeSorted in Sandbox (not shown). With the table and its data already existing, I load it (unsorted) into a 2D integer array, then to a DataTable. The array of DataRows is the sorted version of DataTable. The example is a little odd in that I load my array from the DB and could have sorted it then, but I just wanted to get an unsorted array into C# to use with the DataTable object.

static void Main(string[] args)
{
    SqlConnection cnnX = new SqlConnection("Data Source=r90jroughgarden\\;Initial Catalog=Sandbox;Integrated Security=True");
    SqlCommand cmdX = new SqlCommand("select * from tblToBeSorted", cnnX);
    cmdX.CommandType = CommandType.Text;
    SqlDataReader rdrX = null;
    if (cnnX.State == ConnectionState.Closed) cnnX.Open();

    int[,] aintSortingArray = new int[100, 4];     //i, elementid, planid, timeid

    try
    {
        //Load unsorted table data from DB to array
        rdrX = cmdX.ExecuteReader();
        if (!rdrX.HasRows) return;

        int i = -1;
        while (rdrX.Read() && i < 100)
        {
            i++;
            aintSortingArray[i, 0] = rdrX.GetInt32(0);
            aintSortingArray[i, 1] = rdrX.GetInt32(1);
            aintSortingArray[i, 2] = rdrX.GetInt32(2);
            aintSortingArray[i, 3] = rdrX.GetInt32(3);
        }
        rdrX.Close();

        DataTable dtblX = new DataTable();
        dtblX.Columns.Add("ChangeID");
        dtblX.Columns.Add("ElementID");
        dtblX.Columns.Add("PlanID");
        dtblX.Columns.Add("TimeID");
        for (int j = 0; j < i; j++)
        {
            DataRow drowX = dtblX.NewRow();
            for (int k = 0; k < 4; k++)
            {
                drowX[k] = aintSortingArray[j, k];
            }
            dtblX.Rows.Add(drowX);
        }

        DataRow[] adrowX = dtblX.Select("", "ElementID, PlanID, TimeID");
        adrowX = dtblX.Select("", "ElementID desc, PlanID asc, TimeID desc");

    }
    catch (Exception ex)
    {
        string strErrMsg = ex.Message;
    }
    finally
    {
        if (cnnX.State == ConnectionState.Open) cnnX.Close();
    }
}

How to generate random number in Bash?

What about:

perl -e 'print int rand 10, "\n"; '

How do you run a .bat file from PHP?

<?php
 pclose(popen("start /B test.bat", "r")); die();
?> 

Override default Spring-Boot application.properties settings in Junit Test

TLDR:

So what I did was to have the standard src/main/resources/application.properties and also a src/test/resources/application-default.properties where i override some settings for ALL my tests.

Whole Story

I ran into the same problem and was not using profiles either so far. It seemed to be bothersome to have to do it now and remember declaring the profile -- which can be easily forgotten.

The trick is, to leverage that a profile specific application-<profile>.properties overrides settings in the general profile. See https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties.

how to merge 200 csv files in Python

Quite easy to combine all files in a directory and merge them

import glob
import csv


# Open result file
with open('output.txt','wb') as fout:
    wout = csv.writer(fout,delimiter=',') 
    interesting_files = glob.glob("*.csv") 
    h = True
    for filename in interesting_files: 
        print 'Processing',filename 
        # Open and process file
        with open(filename,'rb') as fin:
            if h:
                h = False
            else:
                fin.next()#skip header
            for line in csv.reader(fin,delimiter=','):
                wout.writerow(line)

Connect to SQL Server Database from PowerShell

I did remove integrated security ... my goal is to log onto a sql server using a connection string WITH active directory username / password. When I do that it always fails. Does not matter the format ... sam company\user ... upn [email protected] ... basic username.

Keep only first n characters in a string?

You can use .substring, which returns a potion of a string:

"abcdefghijklmnopq".substring(0, 8) === "abcdefgh"; // portion from index 0 to 8

Firebase FCM force onTokenRefresh() to be called

Try to implement FirebaseInstanceIdService to get refresh token.

Access the registration token:

You can access the token's value by extending FirebaseInstanceIdService. Make sure you have added the service to your manifest, then call getToken in the context of onTokenRefresh, and log the value as shown:

     @Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);

    // TODO: Implement this method to send any registration to your app's servers.
    sendRegistrationToServer(refreshedToken);
}

Full Code:

   import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;


public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";

    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. Note that this is called when the InstanceID token
     * is initially generated so this is where you would retrieve the token.
     */
    // [START refresh_token]
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // TODO: Implement this method to send any registration to your app's servers.
        sendRegistrationToServer(refreshedToken);
    }
    // [END refresh_token]

    /**
     * Persist token to third-party servers.
     *
     * Modify this method to associate the user's FCM InstanceID token with any server-side account
     * maintained by your application.
     *
     * @param token The new token.
     */
    private void sendRegistrationToServer(String token) {
        // Add custom implementation, as needed.
    }
}

See my answer here.

EDITS:

You shouldn't be starting a FirebaseInstanceIdService yourself.

It will Called when the system determines that the tokens need to be refreshed. The application should call getToken() and send the tokens to all application servers.

This will not be called very frequently, it is needed for key rotation and to handle Instance ID changes due to:

  • App deletes Instance ID
  • App is restored on a new device User
  • uninstalls/reinstall the app
  • User clears app data

The system will throttle the refresh event across all devices to avoid overloading application servers with token updates.

Try below way:

you'd call FirebaseInstanceID.getToken() anywhere off your main thread (whether it is a service, AsyncTask, etc), store the returned token locally and send it to your server. Then whenever onTokenRefresh() is called, you'd call FirebaseInstanceID.getToken() again, get a new token, and send that up to the server (probably including the old token as well so your server can remove it, replacing it with the new one).

ng serve not detecting file changes automatically

I don't recommend changing SO parameters. I've experienced some (lag) issues after changing fs.inotify.max_user_watches parameter since you will have other services running...

The "ng serve --poll=2000" is a good solution but you will probably forget this parameter...

Investigating: https://github.com/angular/angular-cli/wiki/angular-cli I'd done the following solution.

Changed de angular.json with poll parameter

"serve": {
   "builder....
   "options": {
        "browserTarget": "xkcd:build",
        "poll": 2000
   }
   ...

Works on My Machine :D

Error in model.frame.default: variable lengths differ

Another thing that can cause this error is creating a model with the centering/scaling standardize function from the arm package -- m <- standardize(lm(y ~ x, data = train))

If you then try predict(m), you get the same error as in this question.

Get key from a HashMap using the value

If you are not bound to use Hashmap, I would advise to use pair< T,T >. The individual elements can be accessed by first and second calls.

Have a look at this http://www.cplusplus.com/reference/utility/pair/

I used it here : http://codeforces.com/contest/507/submission/9531943

Prevent double curly brace notation from displaying momentarily before angular.js compiles/interpolates document

I think that you are looking for the ngCloak directive: https://docs.angularjs.org/api/ng/directive/ngCloak

From the documentation:

The ngCloak directive is used to prevent the Angular html template from being briefly displayed by the browser in its raw (uncompiled) form while your application is loading. Use this directive to avoid the undesirable flicker effect caused by the html template display.

The directive can be applied to the <body> element, but the preferred usage is to apply multiple ngCloak directives to small portions of the page to permit progressive rendering of the browser view

find without recursion

I believe you are looking for -maxdepth 1.

Java - get index of key in HashMap?

Use LinkedHashMap instead of HashMap It will always return keys in same order (as insertion) when calling keySet()

For more detail, see Class LinkedHashMap

XPath - Difference between node() and text()

For me it was a big difference when I faced this scenario (here my story:)

<?xml version="1.0" encoding="UTF-8"?>
<sentence id="S1.6">When U937 cells were infected with HIV-1, 
        
    <xcope id="X1.6.3">
        <cue ref="X1.6.3" type="negation">no</cue> 
                        
                        induction of NF-KB factor was detected
        
    </xcope>
                    
, whereas high level of progeny virions was produced, 
        
    <xcope id="X1.6.2">
        <cue ref="X1.6.2" type="speculation">suggesting</cue> that this factor was 
        <xcope id="X1.6.1">
            <cue ref="X1.6.1" type="negation">not</cue> required for viral replication
        </xcope>
    </xcope>.

</sentence>

I needed to extract text between tags and aggregate (by concat) the text including in innner tags.

/node() did the job, while /text() made half job

/text() only returned text not included in inner tags, because inner tags are not "text nodes". You may think, "just extract text included in the inner tags in an additional xpath", however, it becomes challenging to sort the text in this original order because you dont know where to place the aggregated text from the inner tags!because you dont know where to place the aggregated text from the inner nodes.

  1. When U937 cells were infected with HIV-1,
  2. no induction of NF-KB factor was detected
  3. , whereas high level of progeny virions was produced,
  4. suggesting that this factor was not required for viral replication
  5. .

Finally, /node() did exactly what I wanted, because it gets the text from inner tags too.

What does it mean by select 1 from table?

This means that You want a value "1" as output or Most of the time used as Inner Queries because for some reason you want to calculate the outer queries based on the result of inner queries.. not all the time you use 1 but you have some specific values...

This will statically gives you output as value 1.

PHP shorthand for isset()?

PHP 7.4+; with the null coalescing assignment operator

$var ??= '';

PHP 7.0+; with the null coalescing operator

$var = $var ?? '';

PHP 5.3+; with the ternary operator shorthand

isset($var) ?: $var = '';

Or for all/older versions with isset:

$var = isset($var) ? $var : '';

or

!isset($var) && $var = '';

Objective-C implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int' warning

Contrary to Martin's answer, casting to int (or ignoring the warning) isn't always safe even if you know your array doesn't have more than 2^31-1 elements. Not when compiling for 64-bit.

For example:

NSArray *array = @[@"a", @"b", @"c"];

int i = (int) [array indexOfObject:@"d"];
// indexOfObject returned NSNotFound, which is NSIntegerMax, which is LONG_MAX in 64 bit.
// We cast this to int and got -1.
// But -1 != NSNotFound. Trouble ahead!

if (i == NSNotFound) {
    // thought we'd get here, but we don't
    NSLog(@"it's not here");
}
else {
    // this is what actually happens
    NSLog(@"it's here: %d", i);

    // **** crash horribly ****
    NSLog(@"the object is %@", array[i]);
}