Programs & Examples On #Gui builder

Graphical User Interface Builder for various IDEs.

How to add row of data to Jtable from values received from jtextfield and comboboxes

you can use this code as template please customize it as per your requirement.

DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

Oracle "(+)" Operator

In Oracle, (+) denotes the "optional" table in the JOIN. So in your query,

SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id=b.id(+)

it's a LEFT OUTER JOIN of table 'b' to table 'a'. It will return all data of table 'a' without losing its data when the other side (optional table 'b') has no data.

Diagram of Left Outer Join

The modern standard syntax for the same query would be

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a
LEFT JOIN b ON a.id=b.id

or with a shorthand for a.id=b.id (not supported by all databases):

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a
LEFT JOIN b USING(id)

If you remove (+) then it will be normal inner join query

Older syntax, in both Oracle and other databases:

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id=b.id

More modern syntax:

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a
INNER JOIN b ON a.id=b.id

Or simply:

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a
JOIN b ON a.id=b.id

Diagram of Inner Join

It will only return all data where both 'a' & 'b' tables 'id' value is same, means common part.

If you want to make your query a Right Join

This is just the same as a LEFT JOIN, but switches which table is optional.

Diagram of Right Outer Join

Old Oracle syntax:

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id(+)=b.id

Modern standard syntax:

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a
RIGHT JOIN b ON a.id=b.id

Ref & help:

https://asktom.oracle.com/pls/asktom/f?p=100:11:::::P11_QUESTION_ID:6585774577187

Left Outer Join using + sign in Oracle 11g

https://www.w3schools.com/sql/sql_join_left.asp

How to check if input is numeric in C++

Why not just using scanf("%i") and check its return?

PHP Session Destroy on Log Out Button

// logout

if(isset($_GET['logout'])) {
    session_destroy();
    unset($_SESSION['username']);
    header('location:login.php');
}

?>

How to set the JDK Netbeans runs on?

Thanks to KasunBG's tip, I found the solution in the "suggested" link, update the following file (replace 7.x with your Netbeans version) :

C:\Program Files\NetBeans 7.x\etc\netbeans.conf

Change the following line to point it where your java installation is :

netbeans_jdkhome="C:\Program Files\Java\jdk1.7xxxxx"

You may need Administrator privileges to edit netbeans.conf

VBA Excel sort range by specific column

If the starting cell of the range and of the key is static, the solution can be very simple:

Range("A3").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Sort key1:=Range("B3", Range("B3").End(xlDown)), _
order1:=xlAscending, Header:=xlNo

Is it possible to print a variable's type in standard C++?

Howard Hinnant used magic numbers to extract type name. ??? suggested string prefix and suffix. But prefix/suffix keep changing. With “probe_type” type_name automatically calculates prefix and suffix sizes for “probe_type” to extract type name:

#include <string_view>
using namespace std;

namespace typeName {
 template <typename T>
  constexpr string_view wrapped_type_name () {
#ifdef __clang__
    return __PRETTY_FUNCTION__;
#elif defined(__GNUC__)
    return  __PRETTY_FUNCTION__;
#elif defined(_MSC_VER)
    return  __FUNCSIG__;
#endif
  }

  class probe_type;
  constexpr string_view probe_type_name ("typeName::probe_type");
  constexpr string_view probe_type_name_elaborated ("class typeName::probe_type");
  constexpr string_view probe_type_name_used (wrapped_type_name<probe_type> ().find (probe_type_name_elaborated) != -1 ? probe_type_name_elaborated : probe_type_name);

  constexpr size_t prefix_size () {
    return wrapped_type_name<probe_type> ().find (probe_type_name_used);
  }

  constexpr size_t suffix_size () {
    return wrapped_type_name<probe_type> ().length () - prefix_size () - probe_type_name_used.length ();
  }

  template <typename T>
  string_view type_name () {
    constexpr auto type_name = wrapped_type_name<T> ();

    return type_name.substr (prefix_size (), type_name.length () - prefix_size () - suffix_size ());
  }
}

#include <iostream>

using typeName::type_name;
using typeName::probe_type;

class test;

int main () {
  cout << type_name<class test> () << endl;

  cout << type_name<const int*&> () << endl;
  cout << type_name<unsigned int> () << endl;

  const int ic = 42;
  const int* pic = &ic;
  const int*& rpic = pic;
  cout << type_name<decltype(ic)> () << endl;
  cout << type_name<decltype(pic)> () << endl;
  cout << type_name<decltype(rpic)> () << endl;

  cout << type_name<probe_type> () << endl;
}

Output

gcc 10.2:

test
const int *&
unsigned int
const int
const int *
const int *&
typeName::probe_type

clang 11.0.0:

test
const int *&
unsigned int
const int
const int *
const int *&
typeName::probe_type

VS 2019 version 16.7.6:

class test
const int*&
unsigned int
const int
const int*
const int*&
class typeName::probe_type

Eclipse: How to install a plugin manually?

You can try this

click Help>Install New Software on the menu bar

enter image description here

enter image description here

enter image description here

enter image description here

Move an item inside a list?

l = list(...)
if item in l:
    l.remove(item) #  checks if the item to be moved is present in the list 
l.insert(new_index,item)

Cannot call getSupportFragmentManager() from activity

Instead of

extends Fragment

use

extends android.support.v4.app.Fragment 

This works for me. for *API14 and above

How to make an HTTP request + basic auth in Swift

I am calling the json on login button click

@IBAction func loginClicked(sender : AnyObject){

var request = NSMutableURLRequest(URL: NSURL(string: kLoginURL)) // Here, kLogin contains the Login API.


var session = NSURLSession.sharedSession()

request.HTTPMethod = "POST"

var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(self.criteriaDic(), options: nil, error: &err) // This Line fills the web service with required parameters.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
 //   println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")       
var err1: NSError?
var json2 = NSJSONSerialization.JSONObjectWithData(strData.dataUsingEncoding(NSUTF8StringEncoding), options: .MutableLeaves, error:&err1 ) as NSDictionary

println("json2 :\(json2)")

if(err) {
    println(err!.localizedDescription)
}
else {
    var success = json2["success"] as? Int
    println("Succes: \(success)")
}
})

task.resume()

}

Here, I have made a seperate dictionary for the parameters.

var params = ["format":"json", "MobileType":"IOS","MIN":"f8d16d98ad12acdbbe1de647414495ec","UserName":emailTxtField.text,"PWD":passwordTxtField.text,"SigninVia":"SH"]as NSDictionary
     return params
}

Install .ipa to iPad with or without iTunes

How about iPhone Configuration Utility?

http://support.apple.com/kb/DL1465?viewlocale=en_US&locale=en_US

iPhone Configuration Utility lets you easily create, maintain, encrypt, and install configuration profiles, track and install provisioning profiles and authorized applications, and capture device information including console logs.

Install ipa files using Iphone configuration utility

Update:

Apple Configurator replaces iPhone Configuration Utility. With the the release of iOS 8, iPhone Configuration Utility is no longer supported or available for download. https://itunes.apple.com/gb/app/apple-configurator/id434433123

Apply style to cells of first row

This should do the work:

.category_table tr:first-child td {
    vertical-align: top;
}

LINQ Inner-Join vs Left-Join

You need to get the joined objects into a set and then apply DefaultIfEmpty as JPunyon said:

Person magnus = new Person { Name = "Hedlund, Magnus" };
Person terry = new Person { Name = "Adams, Terry" };
Person charlotte = new Person { Name = "Weiss, Charlotte" };

Pet barley = new Pet { Name = "Barley", Owner = terry };
List<Person> people = new List<Person> { magnus, terry, charlotte };
List<Pet> pets = new List<Pet>{barley};

var results =
    from person in people
    join pet in pets on person.Name equals pet.Owner.Name into ownedPets
    from ownedPet in ownedPets.DefaultIfEmpty(new Pet())
    orderby person.Name
    select new { OwnerName = person.Name, ownedPet.Name };


foreach (var item in results)
{
    Console.WriteLine(
        String.Format("{0,-25} has {1}", item.OwnerName, item.Name ) );
}

Outputs:

Adams, Terry              has Barley
Hedlund, Magnus           has
Weiss, Charlotte          has

Generating random numbers with normal distribution in Excel

IF you have excel 2007, you can use

=NORMSINV(RAND())*SD+MEAN

Because there was a big change in 2010 about excel's function

How do I send email with JavaScript without opening the mail client?

You need to do it directly on a server. But a better way is using PHP. I have heard that PHP has a special code that can send e-mail directly without opening the mail client.

How do I use a Boolean in Python?

Unlike Java where you would declare boolean flag = True, in Python you can just declare myFlag = True

Python would interpret this as a boolean variable

How do I adb pull ALL files of a folder present in SD Card

Single File/Folder using pull:

adb pull "/sdcard/Folder1"

Output:

adb pull "/sdcard/Folder1"
pull: building file list...
pull: /sdcard/Folder1/image1.jpg -> ./image1.jpg
pull: /sdcard/Folder1/image2.jpg -> ./image2.jpg
pull: /sdcard/Folder1/image3.jpg -> ./image3.jpg
3 files pulled. 0 files skipped.

Specific Files/Folders using find from BusyBox:

adb shell find "/sdcard/Folder1" -iname "*.jpg" | tr -d '\015' | while read line; do adb pull "$line"; done;

Here is an explanation:

adb shell find "/sdcard/Folder1" - use the find command, use the top folder
-iname "*.jpg"                   - filter the output to only *.jpg files
|                                - passes data(output) from one command to another
tr -d '\015'                     - explained here: http://stackoverflow.com/questions/9664086/bash-is-removing-commands-in-while
while read line;                 - while loop to read input of previous commands
do adb pull "$line"; done;         - pull the files into the current running directory, finish. The quotation marks around $line are required to work with filenames containing spaces.

The scripts will start in the top folder and recursively go down and find all the "*.jpg" files and pull them from your phone to the current directory.

How do I fix the Visual Studio compile error, "mismatch between processor architecture"?

A good rule of thumb is "open DLLs, closed EXEs", that is:

  • EXE targets the OS, by specifying x86 or x64.
  • DLLs are left open (i.e., AnyCPU) so they can be instantiated within a 32-bit or a 64-bit process.

When you build an EXE as AnyCPU, all you're doing is deferring the decision on what process bitness to use to the OS, which will JIT the EXE to its liking. That is, an x64 OS will create a 64-bit process, an x86 OS will create an 32-bit process.

Building DLLs as AnyCPU makes them compatible to either process.

For more on the subtleties of assembly loading, see here. The executive summary reads something like:

  • AnyCPU – loads as x64 or x86 assembly, depending on the invoking process
  • x86 – loads as x86 assembly; will not load from an x64 process
  • x64 – loads as x64 assembly; will not load from an x86 process

Why is the <center> tag deprecated in HTML?

HTML is intended for structuring data, not controlling layout. CSS is intended to control layout. You'll also find that many designers frown on using <table> for layouts for this very same reason.

Why is processing a sorted array faster than processing an unsorted array?

Besides the fact that the branch prediction may slow you down, a sorted array has another advantage:

You can have a stop condition instead of just checking the value, this way you only loop over the relevant data, and ignore the rest.
The branch prediction will miss only once.

 // sort backwards (higher values first), may be in some other part of the code
 std::sort(data, data + arraySize, std::greater<int>());

 for (unsigned c = 0; c < arraySize; ++c) {
       if (data[c] < 128) {
              break;
       }
       sum += data[c];               
 }

What is aria-label and how should I use it?

It's an attribute designed to help assistive technology (e.g. screen readers) attach a label to an otherwise anonymous HTML element.

So there's the <label> element:

<label for="fmUserName">Your name</label>
<input id="fmUserName">

The <label> explicitly tells the user to type their name into the input box where id="fmUserName".

aria-label does much the same thing, but it's for those cases where it isn't practical or desirable to have a label on screen. Take the MDN example:

<button aria-label="Close" onclick="myDialog.close()">X</button>`

Most people would be able to infer visually that this button will close the dialog. A blind person using assistive technology might just hear "X" read aloud, which doesn't mean much without the visual clues. aria-label explicitly tells them what the button will do.

How to select true/false based on column value?

If the way you determine whether or not an entity has a profile is a deterministic function, and doesn't require any access to another table, you could write a stored function and define a computed, persisted field which would store that value for you and not have to re-compute it over and over again.

If you need to query a separate table (to e.g. check the existance of a row), you could still make this "HasProfile" a column in your entity table and just compute that field on a regular basis, e.g. every night or so. If you have the value stored as an atomic value, you don't need the computation every time. This works as long as that fact - has a profile or not - doesn't change too frequently.

To add a column to check whether or not EntityProfile is empty, do something like this:

CREATE FUNCTION CheckHasProfile(@Field VARCHAR(MAX))
RETURNS BIT
WITH SCHEMABINDING
AS BEGIN
    DECLARE @Result BIT

    IF @Field IS NULL OR LEN(@Field) <= 0
        SET @Result = 0
    ELSE
        SET @Result = 1

    RETURN @Result
END

and then add a new computed column to your table Entity:

ALTER TABLE dbo.Entity
   ADD HasProfile AS dbo.CheckHasProfile(EntityProfile) PERSISTED

Now you have a BIT column and it's persisted, e.g. doesn't get computed every time to access the row, and should perform just fine!

Best HTTP Authorization header type for JWT

Short answer

The Bearer authentication scheme is what you are looking for.

Long answer

Is it related to bears?

Errr... No :)

According to the Oxford Dictionaries, here's the definition of bearer:

bearer /'b??r?/
noun

  1. A person or thing that carries or holds something.

  2. A person who presents a cheque or other order to pay money.

The first definition includes the following synonyms: messenger, agent, conveyor, emissary, carrier, provider.

And here's the definition of bearer token according to the RFC 6750:

1.2. Terminology

Bearer Token

A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

The Bearer authentication scheme is registered in IANA and originally defined in the RFC 6750 for the OAuth 2.0 authorization framework, but nothing stops you from using the Bearer scheme for access tokens in applications that don't use OAuth 2.0.

Stick to the standards as much as you can and don't create your own authentication schemes.


An access token must be sent in the Authorization request header using the Bearer authentication scheme:

2.1. Authorization Request Header Field

When sending the access token in the Authorization request header field defined by HTTP/1.1, the client uses the Bearer authentication scheme to transmit the access token.

For example:

GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer mF_9.B5f-4.1JqM

[...]

Clients SHOULD make authenticated requests with a bearer token using the Authorization request header field with the Bearer HTTP authorization scheme. [...]

In case of invalid or missing token, the Bearer scheme should be included in the WWW-Authenticate response header:

3. The WWW-Authenticate Response Header Field

If the protected resource request does not include authentication credentials or does not contain an access token that enables access to the protected resource, the resource server MUST include the HTTP WWW-Authenticate response header field [...].

All challenges defined by this specification MUST use the auth-scheme value Bearer. This scheme MUST be followed by one or more auth-param values. [...].

For example, in response to a protected resource request without authentication:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example"

And in response to a protected resource request with an authentication attempt using an expired access token:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example",
                         error="invalid_token",
                         error_description="The access token expired"

Parallel foreach with asynchronous lambda

The following is set to work with IAsyncEnumerable but can be modified to use IEnumerable by just changing the type and removing the "await" on the foreach. It's far more appropriate for large sets of data than creating countless parallel tasks and then awaiting them all.

    public static async Task ForEachAsyncConcurrent<T>(this IAsyncEnumerable<T> enumerable, Func<T, Task> action, int maxDegreeOfParallelism, int? boundedCapacity = null)
    {
        ActionBlock<T> block = new ActionBlock<T>(
           action, 
           new ExecutionDataflowBlockOptions 
           { 
             MaxDegreeOfParallelism = maxDegreeOfParallelism, 
             BoundedCapacity = boundedCapacity ?? maxDegreeOfParallelism * 3 
           });

        await foreach (T item in enumerable)
        {
           await block.SendAsync(item).ConfigureAwait(false);
        }

        block.Complete();
        await block.Completion;
    }

how to convert string into dictionary in python 3.*?

  1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval
    
    python_dict = literal_eval("{'a': 1}")
    
  2. json.loads but it would require your string to use double quotes:

    import json
    
    python_dict = json.loads('{"a": 1}')
    

How do I programmatically force an onchange event on an input?

For some reason ele.onchange() is throwing a "method not found" expception for me in IE on my page, so I ended up using this function from the link Kolten provided and calling fireEvent(ele, 'change'), which worked:

function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

I did however, create a test page that confirmed calling should onchange() work:

<input id="test1" name="test1" value="Hello" onchange="alert(this.value);"/>
<input type="button" onclick="document.getElementById('test1').onchange();" value="Say Hello"/>

Edit: The reason ele.onchange() didn't work was because I hadn't actually declared anything for the onchange event. But the fireEvent still works.

Remove non-ASCII characters from CSV

# -i (inplace)

sed -i 's/[\d128-\d255]//g' FILENAME

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

To plot multiple graphs on the same figure you will have to do:

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

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

plt.plot(t, a, 'r') # plotting t, a separately 
plt.plot(t, b, 'b') # plotting t, b separately 
plt.plot(t, c, 'g') # plotting t, c separately 
plt.show()

enter image description here

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

I was doing what doug suggests ("Reset Content and Settings") which works but takes a lot of time and it is really annoying... until I recently found completely accidental another solution that is much quicker and seems to also work so far! Just hit cmd+L on your simulator or go to the simulator menu "Hardware -> Lock", which locks the screen, when you unlock the screen the app works like nothing ever happened :)

Using two CSS classes on one element

You can try this:

HTML

<div class="social">
    <div class="socialIcon"><img src="images/facebook.png" alt="Facebook" /></div>
    <div class="socialText">Find me on Facebook</div>
</div>

CSS CODE

.social {
  width:330px;
  height:75px;
  float:right;
  text-align:left;
  padding:10px 0;
  border-bottom:dotted 1px #6d6d6d;
}
.social .socialIcon{
  padding-top:0;
}
.social .socialText{
  border:0;
}

To add multiple class in the same element you can use the following format:

<div class="class1 class2 class3"></div>

DEMO

How do I use InputFilter to limit characters in an EditText in Android?

For some reason the android.text.LoginFilter class's constructor is package-scoped, so you can't directly extend it (even though it would be identical to this code). But you can extend LoginFilter.UsernameFilterGeneric! Then you just have this:

class ABCFilter extends LoginFilter.UsernameFilterGeneric {
    public UsernameFilter() {
        super(false); // false prevents not-allowed characters from being appended
    }

    @Override
    public boolean isAllowed(char c) {
        if ('A' <= c && c <= 'C')
            return true;
        if ('a' <= c && c <= 'c')
            return true;

        return false;
    }
}

This isn't really documented, but it's part of the core lib, and the source is straightforward. I've been using it for a while now, so far no problems, though I admit I haven't tried doing anything complex involving spannables.

Run jar file with command line arguments

For the question

How can i run a jar file in command prompt but with arguments

.

To pass arguments to the jar file at the time of execution

java -jar myjar.jar arg1 arg2

In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:

String arg1 = args[0];
String arg2 = args[1];

Java Inheritance - calling superclass method

Whenever you create child class object then that object has all the features of parent class. Here Super() is the facilty for accession parent.

If you write super() at that time parents's default constructor is called. same if you write super.

this keyword refers the current object same as super key word facilty for accessing parents.

Adding Python Path on Windows 7

You need to make changes in your system variable
-- Right click on "My computer"
-- Click "Properties"
-- Click "Advanced system settings" in the side panel
-- Click on Environment Variable -- You will two sections of user variable and system variable
-- Under system variable section search for the variable 'Path' click on edit and add
"C:\Python27;" (without quotes) save it
-- Now open command line type 'path' hit enter you will see path variable has been modified
-- Now type python --version you will see the python version

And it is done

How to set JFrame to appear centered, regardless of monitor resolution?

As simple as this...

setSize(220, 400);
setLocationRelativeTo(null);  

or if you are using a frame then set the frame to

frame.setSize(220, 400);
frame.setLocationRelativeTo(null);  

For clarification, from the docs:

If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen.

Including one C source file in another?

is it ok? yes, it will compile

is it recommended? no - .c files compile to .obj files, which are linked together after compilation (by the linker) into the executable (or library), so there is no need to include one .c file in another. What you probably want to do instead is to make a .h file that lists the functions/variables available in the other .c file, and include the .h file

Which sort algorithm works best on mostly sorted data?

Splaysort is an obscure sorting method based on splay trees, a type of adaptive binary tree. Splaysort is good not only for partially sorted data, but also partially reverse-sorted data, or indeed any data that has any kind of pre-existing order. It is O(nlogn) in the general case, and O(n) in the case where the data is sorted in some way (forward, reverse, organ-pipe, etc.).

Its great advantage over insertion sort is that it doesn't revert to O(n^2) behaviour when the data isn't sorted at all, so you don't need to be absolutely sure that the data is partially sorted before using it.

Its disadvantage is the extra space overhead of the splay tree structure it needs, as well as the time required to build and destroy the splay tree. But depending on the size of data and amount of pre-sortedness that you expect, the overhead may be worth it for the increase in speed.

A paper on splaysort was published in Software--Practice & Experience.

C++ queue - simple example

Simply declare it as below if you want to us the STL queue container.

std::queue<myclass*> my_queue;

Handling identity columns in an "Insert Into TABLE Values()" statement?

Since it isn't practical to put code in a comment, in response to your comment in Eric's answer that it's not working for you...

I just ran the following on a SQL 2005 box (sorry, no 2000 handy) with default settings and it worked without error:

CREATE TABLE dbo.Test_Identity_Insert
(
    id  INT IDENTITY NOT NULL,
    my_string   VARCHAR(20) NOT NULL,
    CONSTRAINT PK_Test_Identity_Insert PRIMARY KEY CLUSTERED (id)
)
GO

INSERT INTO dbo.Test_Identity_Insert VALUES ('test')
GO

SELECT * FROM dbo.Test_Identity_Insert
GO

Are you perhaps sending the ID value over in your values list? I don't think that you can make it ignore the column if you actually pass a value for it. For example, if your table has 6 columns and you want to ignore the IDENTITY column you can only pass 5 values.

jQuery change URL of form submit

Send the data from the form:

$("#change_section_type").live "change", ->
url = $(this).attr("data-url")
postData = $(this).parents("#contract_setting_form").serializeArray()
$.ajax
  type: "PUT"
  url: url
  dataType: "script"
  data: postData

Loop X number of times

This may be what you are looking for:

for ($i=1; $i -le $ActiveCampaigns; $i++)
{
  $PQCampaign     = Get-Variable -Name "PQCampaign$i"     -ValueOnly
  $PQCampaignPath = Get-Variable -Name "PQCampaignPath$i" -ValueOnly

  # Do stuff with $PQCampaign and $PQCampaignPath
}

Detect IF hovering over element with jQuery

Expanding on @Mohamed's answer. You could use a little encapsulation

Like this:

jQuery.fn.mouseIsOver = function () {
    if($(this[0]).is(":hover"))
    {
        return true;
    }
    return false;
}; 

Use it like:

$("#elem").mouseIsOver();//returns true or false

Forked the fiddle: http://jsfiddle.net/cgWdF/1/

How do you add CSS with Javascript?

if you know at least one <style> tag exist in page , use this function :

CSS=function(i){document.getElementsByTagName('style')[0].innerHTML+=i};

usage :

CSS("div{background:#00F}");

Converting a column within pandas dataframe from int to string

Change data type of DataFrame column:

To int:

df.column_name = df.column_name.astype(np.int64)

To str:

df.column_name = df.column_name.astype(str)

Hashing a string with Sha256

I also had this problem with another style of implementation but I forgot where I got it since it was 2 years ago.

static string sha256(string randomString)
{
    var crypt = new SHA256Managed();
    string hash = String.Empty;
    byte[] crypto = crypt.ComputeHash(Encoding.ASCII.GetBytes(randomString));
    foreach (byte theByte in crypto)
    {
        hash += theByte.ToString("x2");
    }
    return hash;
}

When I input something like abcdefghi2013 for some reason it gives different results and results in errors in my login module. Then I tried modifying the code the same way as suggested by Quuxplusone and changed the encoding from ASCII to UTF8 then it finally worked!

static string sha256(string randomString)
{
    var crypt = new System.Security.Cryptography.SHA256Managed();
    var hash = new System.Text.StringBuilder();
    byte[] crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(randomString));
    foreach (byte theByte in crypto)
    {
        hash.Append(theByte.ToString("x2"));
    }
    return hash.ToString();
}

Thanks again Quuxplusone for the wonderful and detailed answer! :)

JQuery Event for user pressing enter in a textbox?

If your input is search, you also can use on 'search' event. Example

<input type="search" placeholder="Search" id="searchTextBox">

.

$("#searchPostTextBox").on('search', function () {
    alert("search value: "+$(this).val());
});

Bash mkdir and subfolders

You can:

mkdir -p folder/subfolder

The -p flag causes any parent directories to be created if necessary.

When should an IllegalArgumentException be thrown?

Throwing runtime exceptions "sparingly" isn't really a good policy -- Effective Java recommends that you use checked exceptions when the caller can reasonably be expected to recover. (Programmer error is a specific example: if a particular case indicates programmer error, then you should throw an unchecked exception; you want the programmer to have a stack trace of where the logic problem occurred, not to try to handle it yourself.)

If there's no hope of recovery, then feel free to use unchecked exceptions; there's no point in catching them, so that's perfectly fine.

It's not 100% clear from your example which case this example is in your code, though.

Palindrome check in Javascript

It works to me

function palindrome(str) {
  /* remove special characters, spaces and make lowercase*/
  var removeChar = str.replace(/[^A-Z0-9]/ig, "").toLowerCase();

  /* reverse removeChar for comparison*/
  var checkPalindrome = removeChar.split('').reverse().join('');

  /* Check to see if str is a Palindrome*/
   return (removeChar === checkPalindrome);
}

How to Set a Custom Font in the ActionBar Title?

    ActionBar actionBar = getSupportActionBar();
    TextView tv = new TextView(getApplicationContext());
    Typeface typeface = ResourcesCompat.getFont(this, R.font.monotype_corsiva);
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, // Width of TextView
            RelativeLayout.LayoutParams.WRAP_CONTENT); // Height of TextView
    tv.setLayoutParams(lp);
    tv.setText("Your Text"); // ActionBar title text
    tv.setTextSize(25);
    tv.setTextColor(Color.WHITE);
    tv.setTypeface(typeface, typeface.ITALIC);
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    actionBar.setCustomView(tv);

Output grep results to text file, need cleaner output

Redirection of program output is performed by the shell.

grep ... > output.txt

grep has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1) man page for details, specifically the -C and --color options.

Enabling error display in PHP via htaccess only

.htaccess:

php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag  log_errors on
php_value error_log  /home/path/public_html/domain/PHP_errors.log

Convert object of any type to JObject with Json.NET

JObject implements IDictionary, so you can use it that way. For ex,

var cycleJson  = JObject.Parse(@"{""name"":""john""}");

//add surname
cycleJson["surname"] = "doe";

//add a complex object
cycleJson["complexObj"] = JObject.FromObject(new { id = 1, name = "test" });

So the final json will be

{
  "name": "john",
  "surname": "doe",
  "complexObj": {
    "id": 1,
    "name": "test"
  }
}

You can also use dynamic keyword

dynamic cycleJson  = JObject.Parse(@"{""name"":""john""}");
cycleJson.surname = "doe";
cycleJson.complexObj = JObject.FromObject(new { id = 1, name = "test" });

This view is not constrained

Right Click in then designing part on that component in which you got error and follow these steps:

  • [for ex. if error occur in Plain Text]

[1]

Plain Text Constraint Layout > Infer Constraints:

finally error has gone

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

I have answered on this.

In my case, the problem was because of Video Downloader professional and AdBlock

In short, this problem occurs due to some google chrome plugins

how I can show the sum of in a datagridview column?

Add the total row to your data collection that will be bound to the grid.

Print a file's last modified date in Bash

You can use:

ls -lrt filename |awk '{print "%02d",$7}'

This will display the date in 2 digits.

If between 1 to 9 it adds "0" prefix to it and converts to 01 - 09.

Hope this meets the expectation.

google maps v3 marker info window on mouseover

Thanks to duncan answer, I end up with this:

marker.addListener('mouseover', () => infoWindow.open(map, marker))
marker.addListener('mouseout', () => infoWindow.close())

yum error "Cannot retrieve metalink for repository: epel. Please verify its path and try again" updating ContextBroker

Another possible cause is that your architecture is not supported. I ran into this because I was provided with a CentOS VM, wanted to install EPEL and couldn't for the life of me get it done.

Turns out the VM was CentOS 7 i386, which is an architecture that is apparently no longer supported by EPEL. I guess the only remedy in this case is to reinstall.

How to get the name of the current Windows user in JavaScript

There is no fully compatible alternative in JavaScript as it posses an unsafe security issue to allow client-side code to become aware of the logged in user.

That said, the following code would allow you to get the logged in username, but it will only work on Windows, and only within Internet Explorer, as it makes use of ActiveX. Also Internet Explorer will most likely display a popup alerting you to the potential security problems associated with using this code, which won't exactly help usability.

<!doctype html>
<html>
<head>
    <title>Windows Username</title>
</head>
<body>
<script type="text/javascript">
    var WinNetwork = new ActiveXObject("WScript.Network");
    alert(WinNetwork.UserName); 
</script>
</body>
</html>

As Surreal Dreams suggested you could use AJAX to call a server-side method that serves back the username, or render the HTML with a hidden input with a value of the logged in user, for e.g.

(ASP.NET MVC 3 syntax)

<input id="username" type="hidden" value="@User.Identity.Name" />

Emulate a 403 error page

Use ModRewrite:

RewriteRule ^403.html$ - [F]

Just make sure you create a blank document called "403.html" in your www root or you'll get a 404 error instead of 403.

jQuery-UI datepicker default date

Try passing in a Date object instead. I can't see why it doesn't work in the format you have entered:

<script type="text/javascript">
$(function() {               
    $("#birthdate" ).datepicker({
        changeMonth: true,
        changeYear: true,
        yearRange: '1920:2010',
        dateFormat : 'dd-mm-yy',
        defaultDate: new Date(1985, 00, 01)
    });
});
</script>

http://api.jqueryui.com/datepicker/#option-defaultDate

Specify either an actual date via a Date object or as a string in the current dateFormat, or a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null for today.

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

tl;dr:

concat and append currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True to silence it. In the future the default will change to not sort, so it's best to specify either sort=True or False now, or better yet ensure that your non-concatenation indices match.


The warning is new in pandas 0.23.0:

In a future version of pandas pandas.concat() and DataFrame.append() will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned, link.

More information from linked very old github issue, comment by smcinerney :

When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.

This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.

After some time the parameter sort was implemented in pandas.concat and DataFrame.append:

sort : boolean, default None

Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.

Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.

This has no effect when join='inner', which already preserves the order of the non-concatenation axis.

So if both DataFrames have the same columns in the same order, there is no warning and no sorting:

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])

print (pd.concat([df1, df2]))
   a  b
0  1  0
1  2  8
0  4  7
1  5  3

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])

print (pd.concat([df1, df2]))
   b  a
0  0  1
1  8  2
0  7  4
1  3  5

But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort is explicitly set (sort=None is the default value):

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])

print (pd.concat([df1, df2]))

FutureWarning: Sorting because non-concatenation axis is not aligned.

   a  b
0  1  0
1  2  8
0  4  7
1  5  3

print (pd.concat([df1, df2], sort=True))
   a  b
0  1  0
1  2  8
0  4  7
1  5  3

print (pd.concat([df1, df2], sort=False))
   b  a
0  0  1
1  8  2
0  7  4
1  3  5

If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a and b from df1 with a and b from df2 in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.

Lastly, if you pass sort=True, columns are sorted alphanumerically. If sort=False and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]}, 
                    columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]}, 
                    columns=['c','b','a','d'])

print (pd.concat([df1, df2]))

FutureWarning: Sorting because non-concatenation axis is not aligned.

   a  b    c    d    e
0  1  0  NaN  NaN  5.0
1  2  8  NaN  NaN  0.0
0  4  7  2.0  7.0  NaN
1  5  3  8.0  0.0  NaN

print (pd.concat([df1, df2], sort=True))
   a  b    c    d    e
0  1  0  NaN  NaN  5.0
1  2  8  NaN  NaN  0.0
0  4  7  2.0  7.0  NaN
1  5  3  8.0  0.0  NaN

print (pd.concat([df1, df2], sort=False))

   b  a    e    c    d
0  0  1  5.0  NaN  NaN
1  8  2  0.0  NaN  NaN
0  7  4  NaN  2.0  7.0
1  3  5  NaN  8.0  0.0

In your code:

placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
                                                       .append(placement_by_video_summary_new, sort=True)
                                                       .sort_index()

Command /usr/bin/codesign failed with exit code 1

Spent hours figuring out the issue, it's due very generic error by xcode. One of my frameworks was failing with codesign on one of the laptop with below error :

XYZ.framework : unknown error -1=ffffffffffffffff

Command /usr/bin/codesign failed with exit code 1

However, there is no Codesign set for this framework and still it fails with codesign error.

Below is the answer:

I have generated new development certificate (with new private key) and installed on my new mac.

this error is not relevant to XYZ.frameowrk. Basically codesign failed while archiving coz we newly created certificate asks "codesign wants to sign using key "my account Name" in your keychain" and the buttons Always Allow, Deny and Allow.

Issue was I never accepted it. Once I clicked on Allow. It started working.

Hope this helps.

Perl: function to trim string leading and trailing whitespace

This is available in String::Util with the trim method:

Editor's note: String::Util is not a core module, but you can install it from CPAN with [sudo] cpan String::Util.

use String::Util 'trim';
my $str = "  hello  ";
$str = trim($str);
print "string is now: '$str'\n";

prints:

string is now 'hello'

However it is easy enough to do yourself:

$str =~ s/^\s+//;
$str =~ s/\s+$//;

ComboBox: Adding Text and Value to an Item (no Binding Source)

If anyone is still interested in this, here is a simple and flexible class for a combobox item with a text and a value of any type (very similar to Adam Markowitz's example):

public class ComboBoxItem<T>
{
    public string Name;
    public T value = default(T);

    public ComboBoxItem(string Name, T value)
    {
        this.Name = Name;
        this.value = value;
    }

    public override string ToString()
    {
        return Name;
    }
}

Using the <T> is better than declaring the value as an object, because with object you'd then have to keep track of the type you used for each item, and cast it in your code to use it properly.

I've been using it on my projects for quite a while now. It is really handy.

Can I use Class.newInstance() with constructor arguments?

You can use the getDeclaredConstructor method of Class. It expects an array of classes. Here is a tested and working example:

public static JFrame createJFrame(Class c, String name, Component parentComponent)
{
    try
    {
        JFrame frame = (JFrame)c.getDeclaredConstructor(new Class[] {String.class}).newInstance("name");
        if (parentComponent != null)
        {
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
        else
        {
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        }
        frame.setLocationRelativeTo(parentComponent);
        frame.pack();
        frame.setVisible(true);
    }
    catch (InstantiationException instantiationException)
    {
        ExceptionHandler.handleException(instantiationException, parentComponent, Language.messages.get(Language.InstantiationExceptionKey), c.getName());
    }
    catch(NoSuchMethodException noSuchMethodException)
    {
        //ExceptionHandler.handleException(noSuchMethodException, parentComponent, Language.NoSuchMethodExceptionKey, "NamedConstructor");
        ExceptionHandler.handleException(noSuchMethodException, parentComponent, Language.messages.get(Language.NoSuchMethodExceptionKey), "(Constructor or a JFrame method)");
    }
    catch (IllegalAccessException illegalAccessException)
    {
        ExceptionHandler.handleException(illegalAccessException, parentComponent, Language.messages.get(Language.IllegalAccessExceptionKey));
    }
    catch (InvocationTargetException invocationTargetException)
    {
        ExceptionHandler.handleException(invocationTargetException, parentComponent, Language.messages.get(Language.InvocationTargetExceptionKey));
    }
    finally
    {
        return null;
    }
}

How to customize an end time for a YouTube video?

I tried the method of @mystic11 ( https://stackoverflow.com/a/11422551/506073 ) and got redirected around. Here is a working example URL:

http://youtube.googleapis.com/v/WA8sLsM3McU?start=15&end=20&version=3

If the version=3 parameter is omitted, the video starts at the correct place but runs all the way to the end. From the documentation for the end parameter I am guessing version=3 asks for the AS3 player to be used. See:

end (supported players: AS3, HTML5)

Additional Experiments

Autoplay

Autoplay of the clipped video portion works:

http://youtube.googleapis.com/v/WA8sLsM3McU?start=15&end=20&version=3&autoplay=1

Looping

Adding looping as per the documentation unfortunately starts the second and subsequent iterations at the beginning of the video: http://youtube.googleapis.com/v/WA8sLsM3McU?start=15&end=20&version=3&loop=1&playlist=WA8sLsM3McU

To do this properly, you probably need to set enablejsapi=1 and use the javascript API.

FYI, the above video looped: http://www.infinitelooper.com/?v=WA8sLsM3McU&p=n#/15;19

Remove Branding and Related Videos

To get rid of the Youtube logo and the list of videos to click on to at the end of playing the video you want to watch, add these (&modestBranding=1&rel=0) parameters:

http://youtube.googleapis.com/v/WA8sLsM3McU?start=15&end=20&version=3&autoplay=1&modestBranding=1&rel=0

Remove the uploader info with showinfo=0:

http://youtube.googleapis.com/v/WA8sLsM3McU?start=15&end=20&version=3&autoplay=1&modestBranding=1&rel=0&showinfo=0

This eliminates the thin strip with video title, up and down thumbs, and info icon at the top of the video. The final version produced is fairly clean and doesn't have the downside of giving your viewers an exit into unproductive clicking around Youtube at the end of watching the video portion that you wanted them to see.

Stack array using pop() and push()

Better solution for your Stack implementation

import java.util.List;
import java.util.ArrayList;
public class IntegerStack 

{

    private List<Integer> stack;

    public IntegerStack(int SIZE) 
    {
        stack = new ArrayList<Integer>(SIZE);
    }

    public void push(int i) 
    {

       stack.add(0,i);
     }

     public int pop() 
     { 
        if(!stack.isEmpty()){
           int i= stack.get(0);
           stack.remove(0);
           return i;
        } else{
           return -1;// Or any invalid value
        }
     }

     public int peek()
     {
        if(!stack.isEmpty()){
           return stack.get(0);
        } else{
           return -1;// Or any invalid value
        }
     }


     public boolean isEmpty() 
     {
       stack.isEmpty();
     }

 }

If you have to use Array... Here are problems in your code and possible solutions

import java.util.Arrays;
public class IntegerStack 
{

    private int stack [];
    private int top; 

    public IntegerStack(int SIZE) 
   {
    stack = new int [SIZE];
    top = -1; // top should be 0. If you keep it as -1, problems will arise when SIZE is passed as 0. 
    // In your push method -1==0 will be false and your code will try to add the invalid element to Stack .. 
     /**Solution top=0; */
    }

public void push(int i) 
{
    if (top == stack.length)
    {
        extendStack();
    }

       stack[top]= i;
        top++;

}

public int pop() 
{
    top --; // here you are reducing the top before giving the Object back 
   /*Solution 
      if(!isEmpty()){
      int value = stack[top];
       top --;
     return value; 
    } else{
      return -1;// OR invalid value
    }
   */
    return stack[top];
}

public int peek()
{
    return stack[top]; // Problem when stack is empty or size is 0
    /*Solution 
       if(!isEmpty()){
         return stack[top];
       }else{
         return -1;// Or any invalid value
       }
    */


}


public boolean isEmpty() 
{
    if ( top == -1); // problem... we changed top to 0 above so here it need to check if its 0 and there should be no semicolon after the if statement
   /* Solution if(top==0) */
    {
        return true;
    }
}

private void extendStack()
{

    int [] copy = Arrays.copyOf(stack, stack.length); // The second parameter in Arrays.copyOf has no changes, so there will be no change in array length.
  /*Solution  
    stack=Arrays.copyOf(stack, stack.length+1); 
   */
     }

     }

What is the difference between logical data model and conceptual data model?

First of all, a data model is an abstraction tool and a database model (or scheme/diagramm) is a modeling result.

Conceptual data model is DBMS-independent and covers functional/domain design area. The most known conceptual data model is "Entity-Relationship". Normally, you can reuse the conceptual scheme to produce different logical schemes not only relational.

Logical data model is intended to be implemented by some DBMS and corresponds mostly to the conceptual level of ANSI/SPARC architecture (proposed in 1975); this point gives some collisions of terminology. Zachman Framework tried to resolve this kind of collision ten years later introducing conceptual, logical and physical models.

There are many logical data models, and the most known is relational one.

So main differences of conceptual data model are the focusing on the domain and DBMS-independence whereas logical data model is the most abstract level of concrete DBMS you plan to use. Note that contemporary DBMS support several logical models at the same time.

You can also have a look to my book and to the article for more details.

In Visual Studio Code How do I merge between two local branches?

Update June 2017 (from VSCode 1.14)

The ability to merge local branches has been added through PR 25731 and commit 89cd05f: accessible through the "Git: merge branch" command.
And PR 27405 added handling the diff3-style merge correctly.

Vahid's answer mention 1.17, but that September release actually added nothing regarding merge.
Only the 1.18 October one added Git conflict markers

https://code.visualstudio.com/assets/updates/1_18/merge.png

From 1.18, with the combination of merge command (1.14) and merge markers (1.18), you truly can do local merges between branches.


Original answer 2016:

The Version Control doc does not mention merge commands, only merge status and conflict support.

Even the latest 1.3 June release does not bring anything new to the VCS front.

This is supported by issue 5770 which confirms you cannot use VS Code as a git mergetool, because:

Is this feature being included in the next iteration, by any chance?

Probably not, this is a big endeavour, since a merge UI needs to be implemented.

That leaves the actual merge to be initiated from command line only.

Error: Segmentation fault (core dumped)

In my case: I forgot to activate virtualenv

I installed "pip install example" in the wrong virtualenv

What exactly is std::atomic?

std::atomic exists because many ISAs have direct hardware support for it

What the C++ standard says about std::atomic has been analyzed in other answers.

So now let's see what std::atomic compiles to to get a different kind of insight.

The main takeaway from this experiment is that modern CPUs have direct support for atomic integer operations, for example the LOCK prefix in x86, and std::atomic basically exists as a portable interface to those intructions: What does the "lock" instruction mean in x86 assembly? In aarch64, LDADD would be used.

This support allows for faster alternatives to more general methods such as std::mutex, which can make more complex multi-instruction sections atomic, at the cost of being slower than std::atomic because std::mutex it makes futex system calls in Linux, which is way slower than the userland instructions emitted by std::atomic, see also: Does std::mutex create a fence?

Let's consider the following multi-threaded program which increments a global variable across multiple threads, with different synchronization mechanisms depending on which preprocessor define is used.

main.cpp

#include <atomic>
#include <iostream>
#include <thread>
#include <vector>

size_t niters;

#if STD_ATOMIC
std::atomic_ulong global(0);
#else
uint64_t global = 0;
#endif

void threadMain() {
    for (size_t i = 0; i < niters; ++i) {
#if LOCK
        __asm__ __volatile__ (
            "lock incq %0;"
            : "+m" (global),
              "+g" (i) // to prevent loop unrolling
            :
            :
        );
#else
        __asm__ __volatile__ (
            ""
            : "+g" (i) // to prevent he loop from being optimized to a single add
            : "g" (global)
            :
        );
        global++;
#endif
    }
}

int main(int argc, char **argv) {
    size_t nthreads;
    if (argc > 1) {
        nthreads = std::stoull(argv[1], NULL, 0);
    } else {
        nthreads = 2;
    }
    if (argc > 2) {
        niters = std::stoull(argv[2], NULL, 0);
    } else {
        niters = 10;
    }
    std::vector<std::thread> threads(nthreads);
    for (size_t i = 0; i < nthreads; ++i)
        threads[i] = std::thread(threadMain);
    for (size_t i = 0; i < nthreads; ++i)
        threads[i].join();
    uint64_t expect = nthreads * niters;
    std::cout << "expect " << expect << std::endl;
    std::cout << "global " << global << std::endl;
}

GitHub upstream.

Compile, run and disassemble:

comon="-ggdb3 -O3 -std=c++11 -Wall -Wextra -pedantic main.cpp -pthread"
g++ -o main_fail.out                    $common
g++ -o main_std_atomic.out -DSTD_ATOMIC $common
g++ -o main_lock.out       -DLOCK       $common

./main_fail.out       4 100000
./main_std_atomic.out 4 100000
./main_lock.out       4 100000

gdb -batch -ex "disassemble threadMain" main_fail.out
gdb -batch -ex "disassemble threadMain" main_std_atomic.out
gdb -batch -ex "disassemble threadMain" main_lock.out

Extremely likely "wrong" race condition output for main_fail.out:

expect 400000
global 100000

and deterministic "right" output of the others:

expect 400000
global 400000

Disassembly of main_fail.out:

   0x0000000000002780 <+0>:     endbr64 
   0x0000000000002784 <+4>:     mov    0x29b5(%rip),%rcx        # 0x5140 <niters>
   0x000000000000278b <+11>:    test   %rcx,%rcx
   0x000000000000278e <+14>:    je     0x27b4 <threadMain()+52>
   0x0000000000002790 <+16>:    mov    0x29a1(%rip),%rdx        # 0x5138 <global>
   0x0000000000002797 <+23>:    xor    %eax,%eax
   0x0000000000002799 <+25>:    nopl   0x0(%rax)
   0x00000000000027a0 <+32>:    add    $0x1,%rax
   0x00000000000027a4 <+36>:    add    $0x1,%rdx
   0x00000000000027a8 <+40>:    cmp    %rcx,%rax
   0x00000000000027ab <+43>:    jb     0x27a0 <threadMain()+32>
   0x00000000000027ad <+45>:    mov    %rdx,0x2984(%rip)        # 0x5138 <global>
   0x00000000000027b4 <+52>:    retq

Disassembly of main_std_atomic.out:

   0x0000000000002780 <+0>:     endbr64 
   0x0000000000002784 <+4>:     cmpq   $0x0,0x29b4(%rip)        # 0x5140 <niters>
   0x000000000000278c <+12>:    je     0x27a6 <threadMain()+38>
   0x000000000000278e <+14>:    xor    %eax,%eax
   0x0000000000002790 <+16>:    lock addq $0x1,0x299f(%rip)        # 0x5138 <global>
   0x0000000000002799 <+25>:    add    $0x1,%rax
   0x000000000000279d <+29>:    cmp    %rax,0x299c(%rip)        # 0x5140 <niters>
   0x00000000000027a4 <+36>:    ja     0x2790 <threadMain()+16>
   0x00000000000027a6 <+38>:    retq   

Disassembly of main_lock.out:

Dump of assembler code for function threadMain():
   0x0000000000002780 <+0>:     endbr64 
   0x0000000000002784 <+4>:     cmpq   $0x0,0x29b4(%rip)        # 0x5140 <niters>
   0x000000000000278c <+12>:    je     0x27a5 <threadMain()+37>
   0x000000000000278e <+14>:    xor    %eax,%eax
   0x0000000000002790 <+16>:    lock incq 0x29a0(%rip)        # 0x5138 <global>
   0x0000000000002798 <+24>:    add    $0x1,%rax
   0x000000000000279c <+28>:    cmp    %rax,0x299d(%rip)        # 0x5140 <niters>
   0x00000000000027a3 <+35>:    ja     0x2790 <threadMain()+16>
   0x00000000000027a5 <+37>:    retq

Conclusions:

  • the non-atomic version saves the global to a register, and increments the register.

    Therefore, at the end, very likely four writes happen back to global with the same "wrong" value of 100000.

  • std::atomic compiles to lock addq. The LOCK prefix makes the following inc fetch, modify and update memory atomically.

  • our explicit inline assembly LOCK prefix compiles to almost the same thing as std::atomic, except that our inc is used instead of add. Not sure why GCC chose add, considering that our INC generated a decoding 1 byte smaller.

ARMv8 could use either LDAXR + STLXR or LDADD in newer CPUs: How do I start threads in plain C?

Tested in Ubuntu 19.10 AMD64, GCC 9.2.1, Lenovo ThinkPad P51.

How to enter ssh password using bash?

Double check if you are not able to use keys.

Otherwise use expect:

#!/usr/bin/expect -f
spawn ssh [email protected]
expect "assword:"
send "mypassword\r"
interact

SQL Error: ORA-00913: too many values

If you are having 112 columns in one single table and you would like to insert data from source table, you could do as

create table employees as select * from source_employees where employee_id=100;

Or from sqlplus do as

copy from source_schema/password insert employees using select * from 
source_employees where employee_id=100;

Inserting NOW() into Database with CodeIgniter's Active Record

aspirinemaga, just replace:

$this->db->set('time', 'NOW()', FALSE);
$this->db->insert('mytable', $data);

for it:

$this->db->set('time', 'NOW() + INTERVAL 1 DAY', FALSE);
$this->db->insert('mytable', $data);

How to show full object in Chrome console?

Use console.dir() to output a browse-able object you can click through instead of the .toString() version, like this:

console.dir(functor);

Prints a JavaScript representation of the specified object. If the object being logged is an HTML element, then the properties of its DOM representation are printed [1]


[1] https://developers.google.com/web/tools/chrome-devtools/debug/console/console-reference#dir

Is it possible to run CUDA on AMD GPUs?

As of 2019_10_10 I have NOT tested it, but there is the "GPU Ocelot" project

http://gpuocelot.gatech.edu/

that according to its advertisement tries to compile CUDA code for a variety of targets, including AMD GPUs.

Is there an easy way to check the .NET Framework version?

public class DA {
  public static class VersionNetFramework {
    public static string Get45or451FromRegistry()
    {//https://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx
        using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\"))
        {
            int releaseKey = Convert.ToInt32(ndpKey.GetValue("Release"));
            if (true)
            {
                return (@"Version: " + CheckFor45DotVersion(releaseKey));
            }
        }
    }
    // Checking the version using >= will enable forward compatibility, 
    // however you should always compile your code on newer versions of
    // the framework to ensure your app works the same.
    private static string CheckFor45DotVersion(int releaseKey)
    {//https://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx
        if (releaseKey >= 394271)
            return "4.6.1 installed on all other Windows OS versions or later";
        if (releaseKey >= 394254)
            return "4.6.1 installed on Windows 10 or later";
        if (releaseKey >= 393297)
            return "4.6 installed on all other Windows OS versions or later";
        if (releaseKey >= 393295)
            return "4.6 installed with Windows 10 or later";
        if (releaseKey >= 379893)
            return "4.5.2 or later";
        if (releaseKey >= 378758)
            return "4.5.1 installed on Windows 8, Windows 7 SP1, or Windows Vista SP2 or later";
        if (releaseKey >= 378675)
            return "4.5.1 installed with Windows 8.1 or later";
        if (releaseKey >= 378389)
            return "4.5 or later";

        return "No 4.5 or later version detected";
    }
    public static string GetVersionFromRegistry()
    {//https://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx
        string res = @"";
        // Opens the registry key for the .NET Framework entry.
        using (RegistryKey ndpKey =
            RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "").
            OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\"))
        {
            // As an alternative, if you know the computers you will query are running .NET Framework 4.5 
            // or later, you can use:
            // using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, 
            // RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\"))
            foreach (string versionKeyName in ndpKey.GetSubKeyNames())
            {
                if (versionKeyName.StartsWith("v"))
                {

                    RegistryKey versionKey = ndpKey.OpenSubKey(versionKeyName);
                    string name = (string)versionKey.GetValue("Version", "");
                    string sp = versionKey.GetValue("SP", "").ToString();
                    string install = versionKey.GetValue("Install", "").ToString();
                    if (install == "") //no install info, must be later.
                        res += (versionKeyName + "  " + name) + Environment.NewLine;
                    else
                    {
                        if (sp != "" && install == "1")
                        {
                            res += (versionKeyName + "  " + name + "  SP" + sp) + Environment.NewLine;
                        }

                    }
                    if (name != "")
                    {
                        continue;
                    }
                    foreach (string subKeyName in versionKey.GetSubKeyNames())
                    {
                        RegistryKey subKey = versionKey.OpenSubKey(subKeyName);
                        name = (string)subKey.GetValue("Version", "");
                        if (name != "")
                            sp = subKey.GetValue("SP", "").ToString();
                        install = subKey.GetValue("Install", "").ToString();
                        if (install == "") //no install info, must be later.
                            res += (versionKeyName + "  " + name) + Environment.NewLine;
                        else
                        {
                            if (sp != "" && install == "1")
                            {
                                res += ("  " + subKeyName + "  " + name + "  SP" + sp) + Environment.NewLine;
                            }
                            else if (install == "1")
                            {
                                res += ("  " + subKeyName + "  " + name) + Environment.NewLine;
                            }
                        }
                    }
                }
            }
        }
        return res;
    }
    public static string GetUpdateHistory()
    {//https://msdn.microsoft.com/en-us/library/hh925567(v=vs.110).aspx
        string res=@"";
        using (RegistryKey baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\Updates"))
        {
            foreach (string baseKeyName in baseKey.GetSubKeyNames())
            {
                if (baseKeyName.Contains(".NET Framework") || baseKeyName.StartsWith("KB") || baseKeyName.Contains(".NETFramework"))
                {

                    using (RegistryKey updateKey = baseKey.OpenSubKey(baseKeyName))
                    {
                        string name = (string)updateKey.GetValue("PackageName", "");
                        res += baseKeyName + "  " + name + Environment.NewLine;
                        foreach (string kbKeyName in updateKey.GetSubKeyNames())
                        {
                            using (RegistryKey kbKey = updateKey.OpenSubKey(kbKeyName))
                            {
                                name = (string)kbKey.GetValue("PackageName", "");
                                res += ("  " + kbKeyName + "  " + name) + Environment.NewLine;

                                if (kbKey.SubKeyCount > 0)
                                {
                                    foreach (string sbKeyName in kbKey.GetSubKeyNames())
                                    {
                                        using (RegistryKey sbSubKey = kbKey.OpenSubKey(sbKeyName))
                                        {
                                            name = (string)sbSubKey.GetValue("PackageName", "");
                                            if (name == "")
                                                name = (string)sbSubKey.GetValue("Description", "");
                                            res += ("    " + sbKeyName + "  " + name) + Environment.NewLine;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return res;
    }
}

using class DA.VersionNetFramework

private void Form1_Shown(object sender, EventArgs e)
{
    //
    // Current OS Information
    //
    richTextBox1.Text = @"Current OS Information:";
    richTextBox1.AppendText(Environment.NewLine +
                            "Machine Name: " + Environment.MachineName);
    richTextBox1.AppendText(Environment.NewLine +
                            "Platform: " + Environment.OSVersion.Platform.ToString());
    richTextBox1.AppendText(Environment.NewLine +
                            Environment.OSVersion);
    //
    // .NET Framework Environment Information
    //
    richTextBox1.AppendText(Environment.NewLine + Environment.NewLine +
                                       ".NET Framework Environment Information:");
    richTextBox1.AppendText(Environment.NewLine +
                            "Environment.Version " + Environment.Version);
    richTextBox1.AppendText(Environment.NewLine + 
                            DA.VersionNetFramework.GetVersionDicription());
    //
    // .NET Framework Information From Registry
    //
    richTextBox1.AppendText(Environment.NewLine + Environment.NewLine +
                                       ".NET Framework Information From Registry:");
    richTextBox1.AppendText(Environment.NewLine +
                            DA.VersionNetFramework.GetVersionFromRegistry());
    //
    // .NET Framework 4.5 or later Information From Registry
    //
    richTextBox1.AppendText(Environment.NewLine + 
                                       ".NET Framework 4.5 or later Information From Registry:");
    richTextBox1.AppendText(Environment.NewLine +
                            DA.VersionNetFramework.Get45or451FromRegistry());
    //
    // Update History
    //
    richTextBox1.AppendText(Environment.NewLine + Environment.NewLine +
                            "Update History");
    richTextBox1.AppendText(Environment.NewLine + 
                            DA.VersionNetFramework.GetUpdateHistory());
    //
    // Setting Cursor to first character of textbox
    //
    if (!richTextBox1.Text.Equals(""))
    {
        richTextBox1.SelectionStart = 1;
    }
}

Result:

Current OS Information: Machine Name: D1 Platform: Win32NT Microsoft Windows NT 6.2.9200.0

.NET Framework Environment Information: Environment.Version 4.0.30319.42000 .NET 4.6 on Windows 8.1 64 - bit or later

.NET Framework Information From Registry: v2.0.50727 2.0.50727.4927 SP2 v3.0 3.0.30729.4926 SP2 v3.5 3.5.30729.4926 SP1

v4
Client 4.6.00079 Full 4.6.00079 v4.0
Client 4.0.0.0

.NET Framework 4.5 or later Information From Registry: Version: 4.6 installed with Windows 10 or later

Update History Microsoft .NET Framework 4 Client Profile
KB2468871
KB2468871v2
KB2478063
KB2533523
KB2544514
KB2600211
KB2600217
Microsoft .NET Framework 4 Extended
KB2468871
KB2468871v2
KB2478063
KB2533523
KB2544514
KB2600211
KB2600217
Microsoft .NET Framework 4 Multi-Targeting Pack
KB2504637 Update for (KB2504637)

Bash script to calculate time elapsed

Try the following code:

start=$(date +'%s') && sleep 5 && echo "It took $(($(date +'%s') - $start)) seconds"

How to shift a column in Pandas DataFrame

This is how I do it:

df_ext = pd.DataFrame(index=pd.date_range(df.index[-1], periods=8, closed='right'))
df2 = pd.concat([df, df_ext], axis=0, sort=True)
df2["forecast"] = df2["some column"].shift(7)

Basically I am generating an empty dataframe with the desired index and then just concatenate them together. But I would really like to see this as a standard feature in pandas so I have proposed an enhancement to pandas.

How to pipe list of files returned by find command to cat to view all the files

Here's my way to find file names that contain some content that I'm interested in, just a single bash line that nicely handles spaces in filenames too:

find . -name \*.xml | while read i; do grep '<?xml' "$i" >/dev/null; [ $? == 0 ] && echo $i; done

What is the function of the push / pop instructions used on registers in x86 assembly?

Where is it pushed on?

esp - 4. More precisely:

  • esp gets subtracted by 4
  • the value is pushed to esp

pop reverses this.

The System V ABI tells Linux to make rsp point to a sensible stack location when the program starts running: What is default register state when program launches (asm, linux)? which is what you should usually use.

How can you push a register?

Minimal GNU GAS example:

.data
    /* .long takes 4 bytes each. */
    val1:
        /* Store bytes 0x 01 00 00 00 here. */
        .long 1
    val2:
        /* 0x 02 00 00 00 */
        .long 2
.text
    /* Make esp point to the address of val2.
     * Unusual, but totally possible. */
    mov $val2, %esp

    /* eax = 3 */
    mov $3, %ea 

    push %eax
    /*
    Outcome:
    - esp == val1
    - val1 == 3
    esp was changed to point to val1,
    and then val1 was modified.
    */

    pop %ebx
    /*
    Outcome:
    - esp == &val2
    - ebx == 3
    Inverses push: ebx gets the value of val1 (first)
    and then esp is increased back to point to val2.
    */

The above on GitHub with runnable assertions.

Why is this needed?

It is true that those instructions could be easily implemented via mov, add and sub.

They reason they exist, is that those combinations of instructions are so frequent, that Intel decided to provide them for us.

The reason why those combinations are so frequent, is that they make it easy to save and restore the values of registers to memory temporarily so they don't get overwritten.

To understand the problem, try compiling some C code by hand.

A major difficulty, is to decide where each variable will be stored.

Ideally, all variables would fit into registers, which is the fastest memory to access (currently about 100x faster than RAM).

But of course, we can easily have more variables than registers, specially for the arguments of nested functions, so the only solution is to write to memory.

We could write to any memory address, but since the local variables and arguments of function calls and returns fit into a nice stack pattern, which prevents memory fragmentation, that is the best way to deal with it. Compare that with the insanity of writing a heap allocator.

Then we let compilers optimize the register allocation for us, since that is NP complete, and one of the hardest parts of writing a compiler. This problem is called register allocation, and it is isomorphic to graph coloring.

When the compiler's allocator is forced to store things in memory instead of just registers, that is known as a spill.

Does this boil down to a single processor instruction or is it more complex?

All we know for sure is that Intel documents a push and a pop instruction, so they are one instruction in that sense.

Internally, it could be expanded to multiple microcodes, one to modify esp and one to do the memory IO, and take multiple cycles.

But it is also possible that a single push is faster than an equivalent combination of other instructions, since it is more specific.

This is mostly un(der)documented:

How to copy in bash all directory and files recursive?

code for a simple copy.

cp -r ./SourceFolder ./DestFolder

code for a copy with success result

cp -rv ./SourceFolder ./DestFolder

code for Forcefully if source contains any readonly file it will also copy

cp -rf ./SourceFolder ./DestFolder

for details help

cp --help

Getting the exception value in Python

Even though I realise this is an old question, I'd like to suggest using the traceback module to handle output of the exceptions.

Use traceback.print_exc() to print the current exception to standard error, just like it would be printed if it remained uncaught, or traceback.format_exc() to get the same output as a string. You can pass various arguments to either of those functions if you want to limit the output, or redirect the printing to a file-like object.

Groovy - Convert object to JSON string

I couldn't get the other answers to work within the evaluate console in Intellij so...

groovy.json.JsonOutput.toJson(myObject)

This works quite well, but unfortunately

groovy.json.JsonOutput.prettyString(myObject)

didn't work for me.

To get it pretty printed I had to do this...

groovy.json.JsonOutput.prettyPrint(groovy.json.JsonOutput.toJson(myObject))

how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery

You might want to use helper library like http://momentjs.com/ which wraps the native javascript date object for easier manipulations

Then you can do things like:

var day = moment("12-25-1995", "MM-DD-YYYY");

or

var day = moment("25/12/1995", "DD/MM/YYYY");

then operate on the date

day.add('days', 7)

and to get the native javascript date

day.toDate();

Hide Signs that Meteor.js was Used

The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.

That being said, I suggest looking at buildwith.com

You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.

Is there StartsWith or Contains in t sql with variables?

I would use

like 'Express Edition%'

Example:

DECLARE @edition varchar(50); 
set @edition = cast((select SERVERPROPERTY ('edition')) as varchar)

DECLARE @isExpress bit
if @edition like 'Express Edition%'
    set @isExpress = 1;
else
    set @isExpress = 0;

print @isExpress

event Action<> vs event EventHandler<>

Based on some of the previous answers, I'm going to break my answer down into three areas.

First, physical limitations of using Action<T1, T2, T2... > vs using a derived class of EventArgs. There are three: First, if you change the number or types of parameters, every method that subscribes to will have to be changed to conform to the new pattern. If this is a public facing event that 3rd party assemblies will be using, and there is any possiblity that the event args would change, this would be a reason to use a custom class derived from event args for consistencies sake (remember, you COULD still use an Action<MyCustomClass>) Second, using Action<T1, T2, T2... > will prevent you from passing feedback BACK to the calling method unless you have a some kind of object (with a Handled property for instance) that is passed along with the Action. Third, you don't get named parameters, so if you're passing 3 bool's an int, two string's, and a DateTime, you have no idea what the meaning of those values are. As a side note, you can still have a "Fire this event safely method while still using Action<T1, T2, T2... >".

Secondly, consistency implications. If you have a large system you're already working with, it's nearly always better to follow the way the rest of the system is designed unless you have an very good reason not too. If you have publicly facing events that need to be maintained, the ability to substitute derived classes can be important. Keep that in mind.

Thirdly, real life practice, I personally find that I tend to create a lot of one off events for things like property changes that I need to interact with (Particularly when doing MVVM with view models that interact with each other) or where the event has a single parameter. Most of the time these events take on the form of public event Action<[classtype], bool> [PropertyName]Changed; or public event Action SomethingHappened;. In these cases, there are two benefits. First, I get a type for the issuing class. If MyClass declares and is the only class firing the event, I get an explicit instance of MyClass to work with in the event handler. Secondly, for simple events such as property change events, the meaning of the parameters is obvious and stated in the name of the event handler and I don't have to create a myriad of classes for these kinds of events.

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

Get the full URL in PHP

This works for both HTTP and HTTPS.

echo 'http' . (($_SERVER['HTTPS'] == 'on') ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

Output something like this.

https://example.com/user.php?token=3f0d9sickc0flmg8hnsngk5u07&access_level=application

How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list?

wget is an invaluable resource and something I use myself. However sometimes there are characters in the address that wget identifies as syntax errors. I'm sure there is a fix for that, but as this question did not ask specifically about wget I thought I would offer an alternative for those people who will undoubtedly stumble upon this page looking for a quick fix with no learning curve required.

There are a few browser extensions that can do this, but most require installing download managers, which aren't always free, tend to be an eyesore, and use a lot of resources. Heres one that has none of these drawbacks:

"Download Master" is an extension for Google Chrome that works great for downloading from directories. You can choose to filter which file-types to download, or download the entire directory.

https://chrome.google.com/webstore/detail/download-master/dljdacfojgikogldjffnkdcielnklkce

For an up-to-date feature list and other information, visit the project page on the developer's blog:

http://monadownloadmaster.blogspot.com/

"Find next" in Vim

You may be looking for the n key.

Trim a string in C

/* Function to remove white spaces on both sides of a string i.e trim */

void trim (char *s)
{
    int i;

    while (isspace (*s)) s++;   // skip left side white spaces
    for (i = strlen (s) - 1; (isspace (s[i])); i--) ;   // skip right side white spaces
    s[i + 1] = '\0';
    printf ("%s\n", s);
}

What is __stdcall?

I never had to use this before until today. Its because in my code I am using multi-threadding and the multi-threading API I am using is the windows one (_beginthreadex).

To start the thread:

_beginthreadex(NULL, 0, ExecuteCommand, currCommand, 0, 0);

The ExecuteCommand function MUST use the __stdcall keyword in the method signature in order for beginthreadex to call it:

unsigned int __stdcall Scene::ExecuteCommand(void* command)
{
    return system(static_cast<char*>(command));
}

PG COPY error: invalid input syntax for integer

Just came across this while looking for a solution and wanted to add I was able to solve the issue by adding the "null" parameter to the copy_from call:

cur.copy_from(f, tablename, sep=',', null='')

What is the difference between "SMS Push" and "WAP Push"?

SMS Push uses SMS as a carrier, WAP uses download via WAP.

Left align and right align within div in Bootstrap

<div class="row">
  <div class="col-xs-6 col-sm-4">Total cost</div>
  <div class="col-xs-6 col-sm-4"></div>
  <div class="clearfix visible-xs-block"></div>
  <div class="col-xs-6 col-sm-4">$42</div>
</div>

That should do the job just ok

Java and HTTPS url connection without downloading certificate

But why don't I have to install a certificate locally for the site?

Well the code that you are using is explicitly designed to accept the certificate without doing any checks whatsoever. This is not good practice ... but if that is what you want to do, then (obviously) there is no need to install a certificate that your code is explicitly ignoring.

Shouldn't I have to install a certificate locally and load it for this program or is it downloaded behind the covers?

No, and no. See above.

Is the traffic between the client to the remote site still encrypted in transmission?

Yes it is. However, the problem is that since you have told it to trust the server's certificate without doing any checks, you don't know if you are talking to the real server, or to some other site that is pretending to be the real server. Whether this is a problem depends on the circumstances.


If we used the browser as an example, typically a browser doesn't ask the user to explicitly install a certificate for each ssl site visited.

The browser has a set of trusted root certificates pre-installed. Most times, when you visit an "https" site, the browser can verify that the site's certificate is (ultimately, via the certificate chain) secured by one of those trusted certs. If the browser doesn't recognize the cert at the start of the chain as being a trusted cert (or if the certificates are out of date or otherwise invalid / inappropriate), then it will display a warning.

Java works the same way. The JVM's keystore has a set of trusted certificates, and the same process is used to check the certificate is secured by a trusted certificate.

Does the java https client api support some type of mechanism to download certificate information automatically?

No. Allowing applications to download certificates from random places, and install them (as trusted) in the system keystore would be a security hole.

DataAnnotations validation (Regular Expression) in asp.net mvc 4 - razor view

UPDATE 9 July 2012 - Looks like this is fixed in RTM.

  1. We already imply ^ and $ so you don't need to add them. (It doesn't appear to be a problem to include them, but you don't need them)
  2. This appears to be a bug in ASP.NET MVC 4/Preview/Beta. I've opened a bug

View source shows the following:

data-val-regex-pattern="([a-zA-Z0-9 .&amp;&#39;-]+)"                  <-- MVC 3
data-val-regex-pattern="([a-zA-Z0-9&#32;.&amp;amp;&amp;#39;-]+)"      <-- MVC 4/Beta

It looks like we're double encoding.

How to call a shell script from python code?

In case you want to pass some parameters to your shell script, you can use the method shlex.split():

import subprocess
import shlex
subprocess.call(shlex.split('./test.sh param1 param2'))

with test.sh in the same folder:

#!/bin/sh
echo $1
echo $2
exit 0

Outputs:

$ python test.py 
param1
param2

Python Socket Multiple Clients

Here is the example from the SocketServer documentation which would make an excellent starting point

import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print "{} wrote:".format(self.client_address[0])
        print self.data
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

Try it from a terminal like this

$ telnet localhost 9999
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello
HELLOConnection closed by foreign host.
$ telnet localhost 9999
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Sausage
SAUSAGEConnection closed by foreign host.

You'll probably need to use A Forking or Threading Mixin too

How can I make a JPA OneToOne relation lazy

If the relation must not be bidirectional then an @ElementCollection might be easier than using a lazy One2Many collection.

Can I set a breakpoint on 'memory access' in GDB?

What you're looking for is called a watchpoint.

Usage

(gdb) watch foo: watch the value of variable foo

(gdb) watch *(int*)0x12345678: watch the value pointed by an address, casted to whatever type you want

(gdb) watch a*b + c/d: watch an arbitrarily complex expression, valid in the program's native language

Watchpoints are of three kinds:

  • watch: gdb will break when a write occurs
  • rwatch: gdb will break wnen a read occurs
  • awatch: gdb will break in both cases

You may choose the more appropriate for your needs.

For more information, check this out.

How to get a list of installed Jenkins plugins with name and version pair

From the Jenkins home page:

  1. Click Manage Jenkins.
  2. Click Manage Plugins.
  3. Click on the Installed tab.

Or

  1. Go to the Jenkins URL directly: {Your Jenkins base URL}/pluginManager/installed

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Yes, it's possible, the syntax is curl [protocol://]<host>[:port], for example:

curl example.com:1234

If you're using Bash, you can also use pseudo-device /dev files to open a TCP connection, e.g.:

exec 5<>/dev/tcp/127.0.0.1/1234
echo "send some stuff" >&5
cat <&5 # Receive some stuff.

See also: More on Using Bash's Built-in /dev/tcp File (TCP/IP).

Creating a segue programmatically

A couple of problems, actually:

First, in that project you uploaded for us, the segue does not bear the "segue1" identifier:

no identifier

You should fill in that identifier if you haven't already.

Second, as you're pushing from table view to table view, you're calling initWithNibName to create a view controller. You really want to use instantiateViewControllerWithIdentifier.

Creating a BAT file for python script

Here's how you can put both batch code and the python one in single file:

0<0# : ^
''' 
@echo off
echo batch code
python "%~f0" %*
exit /b 0
'''

print("python code")

the ''' respectively starts and ends python multi line comments.

0<0# : ^ is more interesting - due to redirection priority in batch it will be interpreted like :0<0# ^ by the batch script which is a label which execution will be not displayed on the screen. The caret at the end will escape the new line and second line will be attached to the first line.For python it will be 0<0 statement and a start of inline comment.

The credit goes to siberia-man

Max size of URL parameters in _GET

See What is the maximum length of a URL in different browsers?

The length of the url can't be changed in PHP. The linked question is about the URL size limit, you will find what you want.

jQuery: serialize() form and other parameters

Alternatively you could use form.serialize() with $.param(object) if you store your params in some object variable. The usage would be:

var data = form.serialize() + '&' + $.param(object)

See http://api.jquery.com/jQuery.param for further reference.

write() versus writelines() and concatenated strings

Actually, I think the problem is that your variable "lines" is bad. You defined lines as a tuple, but I believe that write() requires a string. All you have to change is your commas into pluses (+).

nl = "\n"
lines = line1+nl+line2+nl+line3+nl
textdoc.writelines(lines)

should work.

How to fix Cannot find module 'typescript' in Angular 4?

If you don't have particular needs, I suggest to install Typescript locally.

NPM Installation Method

npm install --global typescript # Global installation
npm install --save-dev typescript # Local installation

Yarn Installation Method

yarn global add typescript # Global installation
yarn add --dev typescript # Local installation

How to extract code of .apk file which is not working?

Any .apk file from market or unsigned

  1. If you apk is downloaded from market and hence signed Install Astro File Manager from market. Open Astro > Tools > Application Manager/Backup and select the application to backup on to the SD card . Mount phone as USB drive and access 'backupsapps' folder to find the apk of target app (lets call it app.apk) . Copy it to your local drive same is the case of unsigned .apk.

  2. Download Dex2Jar zip from this link: SourceForge

  3. Unzip the downloaded zip file.

  4. Open command prompt & write the following command on reaching to directory where dex2jar exe is there and also copy the apk in same directory.

    dex2jar targetapp.apk file(./dex2jar app.apk on terminal)

  5. http://jd.benow.ca/ download decompiler from this link.

  6. Open ‘targetapp.apk.dex2jar.jar’ with jd-gui File > Save All Sources to sava the class files in jar to java files.

Converting between datetime, Timestamp and datetime64

I've come back to this answer more times than I can count, so I decided to throw together a quick little class, which converts a Numpy datetime64 value to Python datetime value. I hope it helps others out there.

from datetime import datetime
import pandas as pd

class NumpyConverter(object):
    @classmethod
    def to_datetime(cls, dt64, tzinfo=None):
        """
        Converts a Numpy datetime64 to a Python datetime.
        :param dt64: A Numpy datetime64 variable
        :type dt64: numpy.datetime64
        :param tzinfo: The timezone the date / time value is in
        :type tzinfo: pytz.timezone
        :return: A Python datetime variable
        :rtype: datetime
        """
        ts = pd.to_datetime(dt64)
        if tzinfo is not None:
            return datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second, tzinfo=tzinfo)
        return datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)

I'm gonna keep this in my tool bag, something tells me I'll need it again.

What does the percentage sign mean in Python

What does the percentage sign mean?

It's an operator in Python that can mean several things depending on the context. A lot of what follows was already mentioned (or hinted at) in the other answers but I thought it could be helpful to provide a more extensive summary.

% for Numbers: Modulo operation / Remainder / Rest

The percentage sign is an operator in Python. It's described as:

x % y       remainder of x / y

So it gives you the remainder/rest that remains if you "floor divide" x by y. Generally (at least in Python) given a number x and a divisor y:

x == y * (x // y) + (x % y)

For example if you divide 5 by 2:

>>> 5 // 2
2
>>> 5 % 2
1

>>> 2 * (5 // 2) + (5 % 2)
5

In general you use the modulo operation to test if a number divides evenly by another number, that's because multiples of a number modulo that number returns 0:

>>> 15 % 5  # 15 is 3 * 5
0

>>> 81 % 9  # 81 is 9 * 9
0

That's how it's used in your example, it cannot be a prime if it's a multiple of another number (except for itself and one), that's what this does:

if n % x == 0:
    break

If you feel that n % x == 0 isn't very descriptive you could put it in another function with a more descriptive name:

def is_multiple(number, divisor):
    return number % divisor == 0

...

if is_multiple(n, x):
    break

Instead of is_multiple it could also be named evenly_divides or something similar. That's what is tested here.

Similar to that it's often used to determine if a number is "odd" or "even":

def is_odd(number):
    return number % 2 == 1

def is_even(number):
    return number % 2 == 0

And in some cases it's also used for array/list indexing when wrap-around (cycling) behavior is wanted, then you just modulo the "index" by the "length of the array" to achieve that:

>>> l = [0, 1, 2]
>>> length = len(l)
>>> for index in range(10):
...     print(l[index % length])
0
1
2
0
1
2
0
1
2
0

Note that there is also a function for this operator in the standard library operator.mod (and the alias operator.__mod__):

>>> import operator
>>> operator.mod(5, 2)  # equivalent to 5 % 2
1

But there is also the augmented assignment %= which assigns the result back to the variable:

>>> a = 5
>>> a %= 2  # identical to: a = a % 2
>>> a
1

% for strings: printf-style String Formatting

For strings the meaning is completely different, there it's one way (in my opinion the most limited and ugly) for doing string formatting:

>>> "%s is %s." % ("this", "good") 
'this is good'

Here the % in the string represents a placeholder followed by a formatting specification. In this case I used %s which means that it expects a string. Then the string is followed by a % which indicates that the string on the left hand side will be formatted by the right hand side. In this case the first %s is replaced by the first argument this and the second %s is replaced by the second argument (good).

Note that there are much better (probably opinion-based) ways to format strings:

>>> "{} is {}.".format("this", "good")
'this is good.'

% in Jupyter/IPython: magic commands

To quote the docs:

To Jupyter users: Magics are specific to and provided by the IPython kernel. Whether magics are available on a kernel is a decision that is made by the kernel developer on a per-kernel basis. To work properly, Magics must use a syntax element which is not valid in the underlying language. For example, the IPython kernel uses the % syntax element for magics as % is not a valid unary operator in Python. While, the syntax element has meaning in other languages.

This is regularly used in Jupyter notebooks and similar:

In [1]:  a = 10
         b = 20
         %timeit a + b   # one % -> line-magic

54.6 ns ± 2.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [2]:  %%timeit  # two %% -> cell magic 
         a ** b

362 ns ± 8.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

The % operator on arrays (in the NumPy / Pandas ecosystem)

The % operator is still the modulo operator when applied to these arrays, but it returns an array containing the remainder of each element in the array:

>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> a % 2
array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1])

Customizing the % operator for your own classes

Of course you can customize how your own classes work when the % operator is applied to them. Generally you should only use it to implement modulo operations! But that's a guideline, not a hard rule.

Just to provide a simple example that shows how it works:

class MyNumber(object):
    def __init__(self, value):
        self.value = value

    def __mod__(self, other):
        print("__mod__ called on '{!r}'".format(self))
        return self.value % other

    def __repr__(self):
        return "{self.__class__.__name__}({self.value!r})".format(self=self)

This example isn't really useful, it just prints and then delegates the operator to the stored value, but it shows that __mod__ is called when % is applied to an instance:

>>> a = MyNumber(10)
>>> a % 2
__mod__ called on 'MyNumber(10)'
0

Note that it also works for %= without explicitly needing to implement __imod__:

>>> a = MyNumber(10)
>>> a %= 2
__mod__ called on 'MyNumber(10)'

>>> a
0

However you could also implement __imod__ explicitly to overwrite the augmented assignment:

class MyNumber(object):
    def __init__(self, value):
        self.value = value

    def __mod__(self, other):
        print("__mod__ called on '{!r}'".format(self))
        return self.value % other

    def __imod__(self, other):
        print("__imod__ called on '{!r}'".format(self))
        self.value %= other
        return self

    def __repr__(self):
        return "{self.__class__.__name__}({self.value!r})".format(self=self)

Now %= is explicitly overwritten to work in-place:

>>> a = MyNumber(10)
>>> a %= 2
__imod__ called on 'MyNumber(10)'

>>> a
MyNumber(0)

How to add chmod permissions to file in Git?

Antwane's answer is correct, and this should be a comment but comments don't have enough space and do not allow formatting. :-) I just want to add that in Git, file permissions are recorded only1 as either 644 or 755 (spelled (100644 and 100755; the 100 part means "regular file"):

diff --git a/path b/path
new file mode 100644

The former—644—means that the file should not be executable, and the latter means that it should be executable. How that turns into actual file modes within your file system is somewhat OS-dependent. On Unix-like systems, the bits are passed through your umask setting, which would normally be 022 to remove write permission from "group" and "other", or 002 to remove write permission only from "other". It might also be 077 if you are especially concerned about privacy and wish to remove read, write, and execute permission from both "group" and "other".


1Extremely-early versions of Git saved group permissions, so that some repositories have tree entries with mode 664 in them. Modern Git does not, but since no part of any object can ever be changed, those old permissions bits still persist in old tree objects.

The change to store only 0644 or 0755 was in commit e44794706eeb57f2, which is before Git v0.99 and dated 16 April 2005.

What is PHPSESSID?

PHP uses one of two methods to keep track of sessions. If cookies are enabled, like in your case, it uses them.

If cookies are disabled, it uses the URL. Although this can be done securely, it's harder and it often, well, isn't. See, e.g., session fixation.

Search for it, you will get lots of SEO advice. The conventional wisdom is that you should use the cookies, but php will keep track of the session either way.

Show a message box from a class in c#?

using System.Windows.Forms;

public class message
{
    static void Main()
    {  
        MessageBox.Show("Hello World!"); 
    }
}

How do I build JSON dynamically in javascript?

As myJSON is an object you can just set its properties, for example:

myJSON.list1 = ["1","2"];

If you dont know the name of the properties, you have to use the array access syntax:

myJSON['list'+listnum] = ["1","2"];

If you want to add an element to one of the properties, you can do;

myJSON.list1.push("3");

How to compile multiple java source files in command line

Here is another example, for compiling a java file in a nested directory.

I was trying to build this from the command line. This is an example from 'gradle', which has dependency 'commons-collection.jar'. For more info, please see 'gradle: java quickstart' example. -- of course, you would use the 'gradle' tools to build it. But i thought to extend this example, for a nested java project, with a dependent jar.

Note: You need the 'gradle binary or source' distribution for this, example code is in: 'samples/java/quickstart'

% mkdir -p temp/classes
% curl --get \
    http://central.maven.org/maven2/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar \
        --output commons-collections-3.2.2.jar

% javac -g -classpath commons-collections-3.2.2.jar \
     -sourcepath src/main/java -d temp/classes \
      src/main/java/org/gradle/Person.java 

% jar cf my_example.jar -C temp/classes org/gradle/Person.class
% jar tvf my_example.jar
   0 Wed Jun 07 14:11:56 CEST 2017 META-INF/
  69 Wed Jun 07 14:11:56 CEST 2017 META-INF/MANIFEST.MF
 519 Wed Jun 07 13:58:06 CEST 2017 org/gradle/Person.class

How to increase size of DOSBox window?

Looking again at your question, I think I see what's wrong with your conf file. You set:

fullresolution=1366x768 windowresolution=1366x768

That's why you're getting the letterboxing (black on either side). You've essentially told Dosbox that your screen is the same size as your window, but your screen is actually bigger, 1600x900 (or higher) per the Googled specs for that computer. So the 'difference' shows up in black. So you either should change fullresolution to your actual screen resolution, or revert to fullresolution=original default, and only specify the window resolution.

So now I wonder if you really want fullscreen, though your question asks about only a window. For you are getting a window, but you sized it short of your screen, hence the two black stripes (letterboxing). If you really want fullscreen, then you need to specify the actual resolution of your screen. 1366x768 is not big enough.

The next issue is, what's the resolution of the program itself? It won't go past its own resolution. So if the program/game is (natively) say 1280x720 (HD), then your window resolution setting shouldn't be bigger than that (remember, it's fixed not dynamic when you use AxB as windowresolution).

Example: DOS Lotus 123 will only extend eight columns and 20 rows. The bigger the Dosbox, the bigger the text, but not more columns and rows. So setting a higher windowresolution for that, only results in bigger text, not more columns and rows. After that you'll have letterboxing.

Hope this helps you better.

How to get the size of the current screen in WPF?

I understand the demands. The thing is, there are WPF Methods for getting those values - but yes, one of the contributors is right, not directly. The Solution is not to get all those workarounds, but to change the initial approach according to clean Design and Development.

A) Set the initial Main Window to Screen

B) Get the Values for the ActualWindow including a ton of useful WPF Methods

C) You can add as many Windows as you like for the behaviour you want to have, like resizeable, minimized whatever… but now you always can access the Loaded and Rendered Screen

Please be careful with the following example, there is some Code around that makes it necessary to use that kind of approach, however it should work (It would give you the Points for each of the Corners of your Screen): Working Example on Single, Dual Monitor and different Resolutions (Within the Primal Main Window Class):

InitializeComponent();
[…]
ActualWindow.AddHandler(Window.LoadedEvent, new RoutedEventHandler(StartUpScreenLoaded));

Routed Event:

private void StartUpScreenLoaded(object sender, RoutedEventArgs e)
    {
        Window StartUpScreen = sender as Window;

        // Dispatcher Format B:
        Dispatcher.Invoke(new Action(() =>
        {
            // Get Actual Window on Loaded
            StartUpScreen.InvalidateVisual();
            System.Windows.Point CoordinatesTopRight = StartUpScreen.TranslatePoint(new System.Windows.Point((StartUpScreen.ActualWidth), (0d)), ActualWindow);
            System.Windows.Point CoordinatesBottomRight = StartUpScreen.TranslatePoint(new System.Windows.Point((StartUpScreen.ActualWidth), (StartUpScreen.ActualHeight)), ActualWindow);
            System.Windows.Point CoordinatesBottomLeft = StartUpScreen.TranslatePoint(new System.Windows.Point((0d), (StartUpScreen.ActualHeight)), ActualWindow);

            // Set the Canvas Top Right, Bottom Right, Bottom Left Coordinates
            System.Windows.Application.Current.Resources["StartUpScreenPointTopRight"] = CoordinatesTopRight;
            System.Windows.Application.Current.Resources["StartUpScreenPointBottomRight"] = CoordinatesBottomRight;
            System.Windows.Application.Current.Resources["StartUpScreenPointBottomLeft"] = CoordinatesBottomLeft;
        }), DispatcherPriority.Loaded);
    }

How do I get hour and minutes from NSDate?

Use an NSDateFormatter to convert string1 into an NSDate, then get the required NSDateComponents:

Obj-C:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"<your date format goes here"];
NSDate *date = [dateFormatter dateFromString:string1];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];

Swift 1 and 2:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "Your date Format"
let date = dateFormatter.dateFromString(string1)
let calendar = NSCalendar.currentCalendar()
let comp = calendar.components([.Hour, .Minute], fromDate: date)
let hour = comp.hour
let minute = comp.minute

Swift 3:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "Your date Format"
let date = dateFormatter.date(from: string1)
let calendar = Calendar.current
let comp = calendar.dateComponents([.hour, .minute], from: date)
let hour = comp.hour
let minute = comp.minute

More about the dateformat is on the official unicode site

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

The problem arose because you added the following code as request header in your front-end :

headers.append('Access-Control-Allow-Origin', 'http://localhost:3000');
headers.append('Access-Control-Allow-Credentials', 'true');

Those headers belong to response, not request. So remove them, including the line :

headers.append('GET', 'POST', 'OPTIONS');

Your request had 'Content-Type: application/json', hence triggered what is called CORS preflight. This caused the browser sent the request with OPTIONS method. See CORS preflight for detailed information.

Therefore in your back-end, you have to handle this preflighted request by returning the response headers which include :

Access-Control-Allow-Origin : http://localhost:3000
Access-Control-Allow-Credentials : true
Access-Control-Allow-Methods : GET, POST, OPTIONS
Access-Control-Allow-Headers : Origin, Content-Type, Accept

Of course, the actual syntax depends on the programming language you use for your back-end.

In your front-end, it should be like so :

function performSignIn() {
    let headers = new Headers();

    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');
    headers.append('Authorization', 'Basic ' + base64.encode(username + ":" +  password));
    headers.append('Origin','http://localhost:3000');

    fetch(sign_in, {
        mode: 'cors',
        credentials: 'include',
        method: 'POST',
        headers: headers
    })
    .then(response => response.json())
    .then(json => console.log(json))
    .catch(error => console.log('Authorization failed : ' + error.message));
}

How to change date format using jQuery?

var d = new Date();

var curr_date = d.getDate();

var curr_month = d.getMonth();

var curr_year = d.getFullYear();

curr_year = curr_year.toString().substr(2,2);

document.write(curr_date+"-"+curr_month+"-"+curr_year);

You can change this as your need..

Vuex - Computed property "name" was assigned to but it has no setter

If you're going to v-model a computed, it needs a setter. Whatever you want it to do with the updated value (probably write it to the $store, considering that's what your getter pulls it from) you do in the setter.

If writing it back to the store happens via form submission, you don't want to v-model, you just want to set :value.

If you want to have an intermediate state, where it's saved somewhere but doesn't overwrite the source in the $store until form submission, you'll need to create such a data item.

Python:Efficient way to check if dictionary is empty or not

I just wanted to know if the dictionary i was going to try to pull data from had data in it in the first place, this seems to be simplest way.

d = {}

bool(d)

#should return
False

d = {'hello':'world'}

bool(d)

#should return
True

What are named pipes?

Named pipes in a unix/linux context can be used to make two different shells to communicate since a shell just can't share anything with another.

Furthermore, one script instantiated twice in the same shell can't share anything through the two instances. I found a use for named pipes when coding a daemon that contains the start() and stop() function, and I wanted to use the same script to perform the two actions.

Without named pipes (or any kind of semaphore) starting the script in the background is not a problem. The thing is when it finishes you just can't access the instance in background.

So when you want to send him the stop command you just can't: running the same script without named pipes and calling the stop() function won't do anything since you are actually running another instance.

The solution was to implement two pipes, one READ and the other WRITE when you start the daemon. Then make him, among its other tasks, listen to the READ pipe. Then the Stop() function contains a command that will write a message in the pipe, that will be handled by the background running script that will perform an exit 0. This way our second instance of the same script has only on task to do: tell the first instance to stop.

This way one and only one script can start and stop itself.

Of course you have different ways to do it by triggering the stop via a touch for example. But this one is nice and interesting to code.

Insert multiple rows with one query MySQL

Here are a few ways to do it

INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip) 
select '$realname','$email','$address','$phone','0','$dateTime','$ip' 
from SOMETABLEWITHTONSOFROWS LIMIT 3;

or

INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip) 
select '$realname','$email','$address','$phone','0','$dateTime','$ip'
union all select '$realname','$email','$address','$phone','0','$dateTime','$ip'
union all select '$realname','$email','$address','$phone','0','$dateTime','$ip'

or

INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip) 
values ('$realname','$email','$address','$phone','0','$dateTime','$ip')
,('$realname','$email','$address','$phone','0','$dateTime','$ip')
,('$realname','$email','$address','$phone','0','$dateTime','$ip')

How to get active user's UserDetails

Spring Security is intended to work with other non-Spring frameworks, hence it is not tightly integrated with Spring MVC. Spring Security returns the Authentication object from the HttpServletRequest.getUserPrincipal() method by default so that's what you get as the principal. You can obtain your UserDetails object directly from this by using

UserDetails ud = ((Authentication)principal).getPrincipal()

Note also that the object types may vary depending on the authentication mechanism used (you may not get a UsernamePasswordAuthenticationToken, for example) and the Authentication doesn't strictly have to contain a UserDetails. It can be a string or any other type.

If you don't want to call SecurityContextHolder directly, the most elegant approach (which I would follow) is to inject your own custom security context accessor interface which is customized to match your needs and user object types. Create an interface, with the relevant methods, for example:

interface MySecurityAccessor {

    MyUserDetails getCurrentUser();

    // Other methods
}

You can then implement this by accessing the SecurityContextHolder in your standard implementation, thus decoupling your code from Spring Security entirely. Then inject this into the controllers which need access to security information or information on the current user.

The other main benefit is that it is easy to make simple implementations with fixed data for testing, without having to worry about populating thread-locals and so on.

How do you initialise a dynamic array in C++?

No internal means, AFAIK. Use this: memset(c, 0, length);

Reorder / reset auto increment primary key

SELECT * from `user` ORDER BY `user_id`; 

SET @count = 0;

UPDATE `user`  SET `user_id` = @count:= @count + 1;

ALTER TABLE `user_id` AUTO_INCREMENT = 1;

if you want to order by

How to make a window always stay on top in .Net?

What is the other application you are trying to suppress the visibility of? Have you investigated other ways of achieving your desired effect? Please do so before subjecting your users to such rogue behaviour as you are describing: what you are trying to do sound rather like what certain naughty sites do with browser windows...

At least try to adhere to the rule of Least Surprise. Users expect to be able to determine the z-order of most applications themselves. You don't know what is most important to them, so if you change anything, you should focus on pushing the other application behind everything rather than promoting your own.

This is of course trickier, since Windows doesn't have a particularly sophisticated window manager. Two approaches suggest themselves:

  1. enumerating top-level windows and checking which process they belong to, dropping their z-order if so. (I'm not sure if there are framework methods for these WinAPI functions.)
  2. Fiddling with child process permissions to prevent it from accessing the desktop... but I wouldn't try this until the othe approach failed, as the child process might end up in a zombie state while requiring user interaction.

Algorithm to find Largest prime factor of a number

JavaScript code:

'option strict';

function largestPrimeFactor(val, divisor = 2) { 
    let square = (val) => Math.pow(val, 2);

    while ((val % divisor) != 0 && square(divisor) <= val) {
        divisor++;
    }

    return square(divisor) <= val
        ? largestPrimeFactor(val / divisor, divisor)
        : val;
}

Usage Example:

let result = largestPrimeFactor(600851475143);

Here is an example of the code:

Replace HTML Table with Divs

This ought to do the trick.

<style>
div.block{
  overflow:hidden;
}
div.block label{
  width:160px;
  display:block;
  float:left;
  text-align:left;
}
div.block .input{
  margin-left:4px;
  float:left;
}
</style>

<div class="block">
  <label>First field</label>
  <input class="input" type="text" id="txtFirstName"/>
</div>
<div class="block">
  <label>Second field</label>
  <input class="input" type="text" id="txtLastName"/>
</div>

I hope you get the concept.

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

I get this error whenever I use np.concatenate the wrong way:

>>> a = np.eye(2)
>>> np.concatenate(a, a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<__array_function__ internals>", line 6, in concatenate
TypeError: only integer scalar arrays can be converted to a scalar index

The correct way is to input the two arrays as a tuple:

>>> np.concatenate((a, a))
array([[1., 0.],
       [0., 1.],
       [1., 0.],
       [0., 1.]])

What is the use of DesiredCapabilities in Selenium WebDriver?

DesiredCapabilities are options that you can use to customize and configure a browser session.

You can read more about them here!

Show Image View from file path?

All the answers are outdated. It is best to use picasso for such purposes. It has a lot of features including background image processing.

Did I mention it is super easy to use:

Picasso.with(context).load(new File(...)).into(imageView);

In a javascript array, how do I get the last 5 elements, excluding the first element?

Try this:

var array = [1, 55, 77, 88, 76, 59];
var array_last_five;
array_last_five = array.slice(-5);
if (array.length < 6) {
     array_last_five.shift();
}

Running Node.js in apache?

Although there are a lot of good tips here I'd like to answer the question you asked:

So in other words can they work hand in hand just like Apache/Perl or Apache/PHP etc..

YES, you can run Node.js on Apache along side Perl and PHP IF you run it as a CGI module. As of yet, I am unable to find a mod-node for Apache but check out: CGI-Node for Apache here http://www.cgi-node.org/ .

The interesting part about cgi-node is that it uses JavaScript exactly like you would use PHP to generate dynamic content, service up static pages, access SQL database etc. You can even share core JavaScript libraries between the server and the client/browser.

I think the shift to a single language between client and server is happening and JavaScript seems to be a good candidate.

A quick example from cgi-node.org site:

<? include('myJavaScriptFile.js'); ?>
<html>
   <body>
      <? var helloWorld = 'Hello World!'; ?>
      <b><?= helloWorld ?><br/>
      <? for( var index = 0; index < 10; index++) write(index + ' '); ?>
   </body>
</html>

This outputs:

Hello World!
0 1 2 3 4 5 6 7 8 9

You also have full access to the HTTP request. That includes forms, uploaded files, headers etc.

I am currently running Node.js through the cgi-node module on Godaddy.

CGI-Node.org site has all the documentation to get started.

I know I'm raving about this but it is finally a relief to use something other than PHP. Also, to be able to code JavaScript on both client and server.

Hope this helps.

Allow Google Chrome to use XMLHttpRequest to load a URL from a local file

Using --disable-web-security switch is quite dangerous! Why disable security at all while you can just allow XMLHttpRequest to access files from other files using --allow-file-access-from-files switch?

Before using these commands be sure to end all running instances of Chrome.

On Windows:

chrome.exe --allow-file-access-from-files

On Mac:

open /Applications/Google\ Chrome.app/ --args --allow-file-access-from-files

Discussions of this "feature" of Chrome:

How to iterate through range of Dates in Java?

JodaTime is nice, however, for the sake of completeness and/or if you prefer API-provided facilities, here are the standard API approaches.

When starting off with java.util.Date instances like below:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = formatter.parse("2010-12-20");
Date endDate = formatter.parse("2010-12-26");

Here's the legacy java.util.Calendar approach in case you aren't on Java8 yet:

Calendar start = Calendar.getInstance();
start.setTime(startDate);
Calendar end = Calendar.getInstance();
end.setTime(endDate);

for (Date date = start.getTime(); start.before(end); start.add(Calendar.DATE, 1), date = start.getTime()) {
    // Do your job here with `date`.
    System.out.println(date);
}

And here's Java8's java.time.LocalDate approach, basically exactly the JodaTime approach:

LocalDate start = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate end = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

for (LocalDate date = start; date.isBefore(end); date = date.plusDays(1)) {
    // Do your job here with `date`.
    System.out.println(date);
}

If you'd like to iterate inclusive the end date, then use !start.after(end) and !date.isAfter(end) respectively.

Parsing JSON Array within JSON Object

This could be an answer to your question:

JSONArray msg1 = (JSONArray) json.get("source");
for(int i = 0; i < msg1.length(); i++){
  String name = msg1.getString("name");
  int age     = msg1.getInt("age");
}

Representing EOF in C code?

I have been researching a lot about the EOF signal. In the book on Programming in C by Dennis Ritchie it is first encountered while introducing putchar() and getchar() commands. It basically marks the end of the character string input.

For eg. Let us write a program that seeks two numerical inputs and prints their sum. You'll notice after each numerical input you press Enter to mark the signal that you have completed the iput action. But while working with character strings Enter is read as just another character ['\n': newline character]. To mark the termination of input you enter ^Z(Ctrl + Z on keyboard) in a completely new line and then enter. That signals the next lines of command to get executed.

#include <stdio.h>

int main()
{
char c;
int i = 0;
printf("INPUT:\t");
c = getchar();

while (c != EOF)
{
   ++i;
   c = getchar();
   
};

printf("NUMBER OF CHARACTERS %d.", i);

return 0;}

The above is the code to count number of characters including '\n'(newline) and '\t'( space) characters. If you don't wanna count the newline characters do this :

#include <stdio.h>

int main()
{
char c;
int i = 0;
printf("INPUT:\t");
c = getchar();

while (c != EOF)
{
    if (c != '\n')
    {
        ++i;
    }

    c = getchar();
    };

printf("NUMBER OF CHARACTERS %d.", i);

return 0;}. 

NOW THE MAIN THINK HOOW TO GIVE INPUT. IT'S SIMPLE: Write all the story you want then go in a new line and enter ^Z and then enter again.

When to use LinkedList over ArrayList in Java?

It depends upon what operations you will be doing more on the List.

ArrayList is faster to access an indexed value. It is much worse when inserting or deleting objects.

To find out more, read any article that talks about the difference between arrays and linked lists.

node.js http 'get' request with query string parameters

If you don't want use external package , Just add the following function in your utilities :

var params=function(req){
  let q=req.url.split('?'),result={};
  if(q.length>=2){
      q[1].split('&').forEach((item)=>{
           try {
             result[item.split('=')[0]]=item.split('=')[1];
           } catch (e) {
             result[item.split('=')[0]]='';
           }
      })
  }
  return result;
}

Then , in createServer call back , add attribute params to request object :

 http.createServer(function(req,res){
     req.params=params(req); // call the function above ;
      /**
       * http://mysite/add?name=Ahmed
       */
     console.log(req.params.name) ; // display : "Ahmed"

})

Import error No module named skimage

OSX python3

Just run this code in your terminal:

sudo pip3 install scikit-image

If you faced any other issues please check this link for more.

Set up DNS based URL forwarding in Amazon Route53

If you're still having issues with the simple approach, creating an empty bucket then Redirect all requests to another host name under Static web hosting in properties via the console. Ensure that you have set 2 A records in route53, one for final-destination.com and one for redirect-to.final-destination.com. The settings for each of these will be identical, but the name will be different so it matches the names that you set for your buckets / URLs.

get the value of DisplayName attribute

Following Rich Tebb's and Matt Baker's answer, I wanted to use the ReflectionExtensions methods in a LINQ query, but it didn't work, so I've made this method for it to work.

If DisplayNameAttribute is set the method will return it, otherwise it will return the MemberInfo name.

Test method:

static void Main(string[] args)
{
    var lst = new List<Test>();
    lst.Add(new Test("coucou1", "kiki1"));
    lst.Add(new Test("coucou2", "kiki2"));
    lst.Add(new Test("coucou3", "kiki3"));
    lst.Add(new Test("coucou4", "kiki4"));
    lst.ForEach(i => 
        Console.WriteLine(i.GetAttributeName<Test>(t => t.Name) + ";" + i.GetAttributeName<Test>(t=>t.t2)));
}

Test method output:

Test method output

The class with DisplayName1 Attribute:

public class Test
{
    public Test() { }
    public Test(string name, string T2)
    {
        Name = name;
        t2 = T2;
    }
    [DisplayName("toto")]
    public string Name { get; set; }
    public string t2 { get; set; }
}

And the extension method:

public static string GetAttributeName<T>(this T itm, Expression<Func<T, object>> propertyExpression)
{
    var memberInfo = GetPropertyInformation(propertyExpression.Body);
    if (memberInfo == null)
    {
        throw new ArgumentException(
            "No property reference expression was found.",
            "propertyExpression");
    }

    var pi = typeof(T).GetProperty(memberInfo.Name);
    var ret = pi.GetCustomAttributes(typeof(DisplayNameAttribute), true).Cast<DisplayNameAttribute>().SingleOrDefault();
    return ret != null ? ret.DisplayName : pi.Name;

}

How to import a new font into a project - Angular 5

You need to put the font files in assets folder (may be a fonts sub-folder within assets) and refer to it in the styles:

@font-face {
  font-family: lato;
  src: url(assets/font/Lato.otf) format("opentype");
}

Once done, you can apply this font any where like:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: 'lato', 'arial', sans-serif;
}

You can put the @font-face definition in your global styles.css or styles.scss and you would be able to refer to the font anywhere - even in your component specific CSS/SCSS. styles.css or styles.scss is already defined in angular-cli.json. Or, if you want you can create a separate CSS/SCSS file and declare it in angular-cli.json along with the styles.css or styles.scss like:

"styles": [
  "styles.css",
  "fonts.css"
],

How to serve .html files with Spring

I faced the same issue and tried various solutions to load the html page from Spring MVC, following solution worked for me

Step-1 in server's web.xml comment these two lines

<!--     <mime-mapping>
        <extension>htm</extension>
        <mime-type>text/html</mime-type>
    </mime-mapping>--> 
<!--     <mime-mapping>
        <extension>html</extension>
        <mime-type>text/html</mime-type>
    </mime-mapping>
 -->

Step-2 enter following code in application's web xml

  <servlet-mapping>
    <servlet-name>jsp</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>

Step-3 create a static controller class

@Controller 
public class FrontController {
     @RequestMapping("/landingPage") 
    public String getIndexPage() { 
    return "CompanyInfo"; 

    }

}

Step-4 in the Spring configuration file change the suffix to .htm .htm

Step-5 Rename page as .htm file and store it in WEB-INF and build/start the server

localhost:8080/.../landingPage

TypeError: 'str' object cannot be interpreted as an integer

A simplest fix would be:

x = input("Give starting number: ")
y = input("Give ending number: ")

x = int(x)  # parse string into an integer
y = int(y)  # parse string into an integer

for i in range(x,y):
    print(i)

input returns you a string (raw_input in Python 2). int tries to parse it into an integer. This code will throw an exception if the string doesn't contain a valid integer string, so you'd probably want to refine it a bit using try/except statements.

Remove all whitespace in a string

"Whitespace" includes space, tabs, and CRLF. So an elegant and one-liner string function we can use is str.translate:

Python 3

' hello  apple '.translate(str.maketrans('', '', ' \n\t\r'))

OR if you want to be thorough:

import string
' hello  apple'.translate(str.maketrans('', '', string.whitespace))

Python 2

' hello  apple'.translate(None, ' \n\t\r')

OR if you want to be thorough:

import string
' hello  apple'.translate(None, string.whitespace)

How can I combine two commits into one commit?

Lazy simple version for forgetfuls like me:

git rebase -i HEAD~3 or however many commits instead of 3.

Turn this

pick YourCommitMessageWhatever
pick YouGetThePoint
pick IdkManItsACommitMessage

into this

pick YourCommitMessageWhatever
s YouGetThePoint
s IdkManItsACommitMessage

and do some action where you hit esc then enter to save the changes. [1]

When the next screen comes up, get rid of those garbage # lines [2] and create a new commit message or something, and do the same escape enter action. [1]

Wowee, you have fewer commits. Or you just broke everything.


[1] - or whatever works with your git configuration. This is just a sequence that's efficient given my setup.

[2] - you'll see some stuff like # this is your n'th commit a few times, with your original commits right below these message. You want to remove these lines, and create a commit message to reflect the intentions of the n commits that you're combining into 1.

WAMP won't turn green. And the VCRUNTIME140.dll error

I had the same problem, and I solved it by installing :

NB : 64 bit installation was enough, I had to uninstall / reinstall Wamp after that

What is an optional value in Swift?

When i started to learn Swift it was very difficult to realize why optional.

Lets think in this way. Let consider a class Person which has two property name and company.

class Person: NSObject {
    
    var name : String //Person must have a value so its no marked as optional
    var companyName : String? ///Company is optional as a person can be unemployed that is nil value is possible
    
    init(name:String,company:String?) {
        
        self.name = name
        self.companyName = company
        
    }
}

Now lets create few objects of Person

var tom:Person = Person.init(name: "Tom", company: "Apple")//posible
var bob:Person = Person.init(name: "Bob", company:nil) // also Possible because company is marked as optional so we can give Nil

But we can not pass Nil to name

var personWithNoName:Person = Person.init(name: nil, company: nil)

Now Lets talk about why we use optional?. Lets consider a situation where we want to add Inc after company name like apple will be apple Inc. We need to append Inc after company name and print.

print(tom.companyName+" Inc") ///Error saying optional is not unwrapped.
print(tom.companyName!+" Inc") ///Error Gone..we have forcefully unwrap it which is wrong approach..Will look in Next line
print(bob.companyName!+" Inc") ///Crash!!!because bob has no company and nil can be unwrapped.

Now lets study why optional takes into place.

if let companyString:String = bob.companyName{///Compiler safely unwrap company if not nil.If nil,no unwrap.
    
    print(companyString+" Inc") //Will never executed and no crash!!!
}

Lets replace bob with tom

if let companyString:String = tom.companyName{///Compiler safely unwrap company if not nil.If nil,no unwrap.
    
    print(companyString+" Inc") //Will executed and no crash!!!
}

And Congratulation! we have properly deal with optional?

So the realization points are

  1. We will mark a variable as optional if its possible to be nil
  2. If we want to use this variable somewhere in code compiler will remind you that we need to check if we have proper deal with that variable if it contain nil.

Thank you...Happy Coding

Check if a Windows service exists and delete in PowerShell

You can use WMI or other tools for this since there is no Remove-Service cmdlet until Powershell 6.0 (See Remove-Service doc)

For example:

$service = Get-WmiObject -Class Win32_Service -Filter "Name='servicename'"
$service.delete()

Or with the sc.exe tool:

sc.exe delete ServiceName

Finally, if you do have access to PowerShell 6.0:

Remove-Service -Name ServiceName

How can I get the request URL from a Java Filter?

Building on another answer on this page,

public static String getCurrentUrlFromRequest(ServletRequest request)
{
   if (! (request instanceof HttpServletRequest))
       return null;

   return getCurrentUrlFromRequest((HttpServletRequest)request);
}

public static String getCurrentUrlFromRequest(HttpServletRequest request)
{
    StringBuffer requestURL = request.getRequestURL();
    String queryString = request.getQueryString();

    if (queryString == null)
        return requestURL.toString();

    return requestURL.append('?').append(queryString).toString();
}

How to sort multidimensional array by column?

You can use the sorted method with a key.

sorted(a, key=lambda x : x[1])

CSS to keep element at "fixed" position on screen

HTML

<div id="fixedbtn"><button type="button" value="Delete"></button></div>

CSS

#fixedbtn{
 position: fixed;
 margin: 0px 10px 0px 10px;
 width: 10%;
}

Get original URL referer with PHP?

As Johnathan Suggested, you would either want to save it in a cookie or a session.

The easier way would be to use a Session variable.

session_start();
if(!isset($_SESSION['org_referer']))
{
    $_SESSION['org_referer'] = $_SERVER['HTTP_REFERER'];
}

Put that at the top of the page, and you will always be able to access the first referer that the site visitor was directed by.

Default Values to Stored Procedure in Oracle

Default-Values are only considered for parameters NOT given to the function.

So given a function

procedure foo( bar1 IN number DEFAULT 3,
     bar2 IN number DEFAULT 5,
     bar3 IN number DEFAULT 8 );

if you call this procedure with no arguments then it will behave as if called with

foo( bar1 => 3,
     bar2 => 5,
     bar3 => 8 );

but 'NULL' is still a parameter.

foo( 4,
     bar3 => NULL );

This will then act like

foo( bar1 => 4,
     bar2 => 5,
     bar3 => Null );

( oracle allows you to either give the parameter in order they are specified in the procedure, specified by name, or first in order and then by name )

one way to treat NULL the same as a default value would be to default the value to NULL

procedure foo( bar1 IN number DEFAULT NULL,
     bar2 IN number DEFAULT NULL,
     bar3 IN number DEFAULT NULL );

and using a variable with the desired value then

procedure foo( bar1 IN number DEFAULT NULL,
     bar2 IN number DEFAULT NULL,
     bar3 IN number DEFAULT NULL )
AS
     v_bar1    number := NVL( bar1, 3);
     v_bar2    number := NVL( bar2, 5);
     v_bar3    number := NVL( bar3, 8);

Hiding table data using <div style="display:none">

You are not allowed to have div tags between tr tags. You have to look for some other strategies like creating a CSS class with display: none and adding it to concerning rows or adding inline style display: none to concerning rows.

.hidden
{
  display:none;
}

<table>
  <tr><td>I am visible</td><tr>
  <tr class="hidden"><td>I am hidden using CSS class</td><tr>
  <tr class="hidden"><td>I am hidden using CSS class</td><tr>
  <tr class="hidden"><td>I am hidden using CSS class</td><tr>
  <tr class="hidden"><td>I am hidden using CSS class</td><tr>
</table>

or

<table>
  <tr><td>I am visible</td><tr>
  <tr style="display:none"><td>I am hidden using inline style</td><tr>
  <tr style="display:none"><td>I am hidden using inline style</td><tr>
  <tr style="display:none"><td>I am hidden using inline style</td><tr>
</table>

Where are logs located?

  • Ensure debug mode is on - either add APP_DEBUG=true to .env file or set an environment variable

  • Log files are in storage/logs folder. laravel.log is the default filename. If there is a permission issue with the log folder, Laravel just halts. So if your endpoint generally works - permissions are not an issue.

  • In case your calls don't even reach Laravel or aren't caused by code issues - check web server's log files (check your Apache/nginx config files to see the paths).

  • If you use PHP-FPM, check its log files as well (you can see the path to log file in PHP-FPM pool config).

How do I change the font size and color in an Excel Drop Down List?

I work on 60-70% zoom vue and my dropdown are unreadable so I made this simple code to overcome the issue

Note that I selected first all my dropdown lsts (CTRL+mouse click), went on formula tab, clicked "define name" and called them "ProduktSelection"

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim KeyCells As Range
Set KeyCells = Range("ProduktSelection")
    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then

ActiveWindow.Zoom = 100

End If

End Sub

I then have another sub

Private Sub Worksheet_Change(ByVal Target As Range) 

where I come back to 65% when value is changed.

Adding an image to a project in Visual Studio

You need to turn on Show All Files option on solution pane toolbar and include this file manually.

Using JQuery to open a popup window and print

Are you sure you can't alter the HTML in the popup window?

If you can, add a <script> tag at the end of the popup's HTML, and call window.print() inside it. Then it won't be called until the HTML has loaded.

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

Not sure if anyone is having the same responsive issue, but it was just a simple css solution for me.

same example

...  ng-init="isCollapsed = true" ng-click="isCollapsed = !isCollapsed"> ...
...  div collapse="isCollapsed"> ...

with

@media screen and (min-width: 768px) {
    .collapse{
        display: block !important;
    }
}

Python base64 data decode

Python 3 (and 2)

import base64
a = 'eW91ciB0ZXh0'
base64.b64decode(a)

Python 2

A quick way to decode it without importing anything:

'eW91ciB0ZXh0'.decode('base64')

or more descriptive

>>> a = 'eW91ciB0ZXh0'
>>> a.decode('base64')
'your text'

How can I convert a string with dot and comma into a float in Python

What about this?

 my_string = "123,456.908"
 commas_removed = my_string.replace(',', '') # remove comma separation
 my_float = float(commas_removed) # turn from string to float.

In short:

my_float = float(my_string.replace(',', ''))

Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig

It seems easy for me that use plt.savefig() function after plot() function:

import matplotlib.pyplot as plt
dtf = pd.DataFrame.from_records(d,columns=h)
dtf.plot()
plt.savefig('~/Documents/output.png')

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

The requested jar is probably not jackson-annotations-x.y.z.jar but jackson-core-x.y.z.jar which could be found here: http://www.java2s.com/Code/Jar/j/Downloadjacksoncore220rc1jar.htm

how to implement Pagination in reactJs

I have implemented pagination + search in ReactJs, see the output: Pagination in React

View complete code on GitHub: https://github.com/navanathjadhav/generic-pagination

Also visit this article for step by step implementation of pagination: https://everblogs.com/react/3-simple-steps-to-add-pagination-in-react/

IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

[For IntelliJ IDEA 2016.2]

I would like to expand upon part of Peter Gromov's answer with an up-to-date screenshot. Specifically this particular part:

You might also want to take a look at Settings | Compiler | Java Compiler | Per-module bytecode version.

I believe that (at least in 2016.2): checking out different commits in git resets these to 1.5.

Per-module bytecode version

php & mysql query not echoing in html with tags?

Change <?php echo $proxy ?> to ' . $proxy . '.

You use <?php when you're outputting HTML by leaving PHP mode with ?>. When you using echo, you have to use concatenation, or wrap your string in double quotes and use interpolation.

SQL Inner Join On Null Values

I'm pretty sure that the join doesn't even do what you want. If there are 100 records in table a with a null qid and 100 records in table b with a null qid, then the join as written should make a cross join and give 10,000 results for those records. If you look at the following code and run the examples, I think that the last one is probably more the result set you intended:

create table #test1 (id int identity, qid int)
create table #test2 (id int identity, qid int)

Insert #test1 (qid)
select null
union all
select null
union all
select 1
union all
select 2
union all
select null

Insert #test2 (qid)
select null
union all
select null
union all
select 1
union all
select 3
union all
select null


select * from #test2 t2
join #test1 t1 on t2.qid = t1.qid

select * from #test2 t2
join #test1 t1 on isnull(t2.qid, 0) = isnull(t1.qid, 0)


select * from #test2 t2
join #test1 t1 on 
 t1.qid = t2.qid OR ( t1.qid IS NULL AND t2.qid IS NULL )


select t2.id, t2.qid, t1.id, t1.qid from #test2 t2
join #test1 t1 on t2.qid = t1.qid
union all
select null, null,id, qid from #test1 where qid is null
union all
select id, qid, null, null from #test2  where qid is null

How to fix/convert space indentation in Sublime Text?

Recently I faced a similar problem. I was using the sublime editor. it's not an issue with the code but with the editor.

Below change in the preference settings worked for me.

Sublime Text menu -> Preferences -> Settings: Syntax-Specific:

{
    "tab_size": 4,
    "translate_tabs_to_spaces": true
}

Setting Remote Webdriver to run tests in a remote computer using Java

This is how I got rid of the error:

WebDriverException: Error forwarding the new session cannot find : {platform=WINDOWS, ensureCleanSession=true, browserName=internet explorer, version=11}

In your nodeconfig.json, the version must be a String, not an integer.

So instead of using "version": 11 use "version": "11" (note the double quotes).

A full example of a working nodecondig.json file for a RemoteWebDriver:

{
  "capabilities":
  [
    {
      "platform": "WIN8_1",
      "browserName": "internet explorer",
      "maxInstances": 1,
      "seleniumProtocol": "WebDriver"
      "version": "11"
    }
    ,{
      "platform": "WIN7",
      "browserName": "chrome",
      "maxInstances": 4,
      "seleniumProtocol": "WebDriver"
      "version": "40"
    }
    ,{
      "platform": "LINUX",
      "browserName": "firefox",
      "maxInstances": 4,
      "seleniumProtocol": "WebDriver"
      "version": "33"
    }
  ],
  "configuration":
  {
    "proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
    "maxSession": 3,
    "port": 5555,
    "host": ip,
    "register": true,
    "registerCycle": 5000,
    "hubPort": 4444,
    "hubHost": {your-ip-address}
  }
}

Different color for each bar in a bar chart; ChartJS

As of August 2019, Chart.js now has this functionality built in.

Successful bar chart with different colored bars

You simply need to provide an array to backgroundColor.

Example taken from https://www.chartjs.org/docs/latest/getting-started/

Before:

  data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
            label: 'My First dataset',
            backgroundColor: 'rgb(255, 99, 132)',
            borderColor: 'rgb(255, 99, 132)',
            data: [0, 10, 5, 2, 20, 30, 45]
        }]
    },

After:

  data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
            label: 'My First dataset',
            backgroundColor: ['rgb(255, 99, 132)','rgb(0, 255, 0)','rgb(255, 99, 132)','rgb(128, 255, 0)','rgb(0, 255, 255)','rgb(255, 255, 0)','rgb(255, 255, 128)'],
            borderColor: 'rgb(255, 99, 132)',
            data: [0, 10, 5, 2, 20, 30, 45]
        }]
    },

I just tested this method and it works. Each bar has a different color.

How to get htaccess to work on MAMP

The problem I was having with the rewrite is that some .htaccess files for Codeigniter, etc come with

RewriteBase /

Which doesn't seem to work in MAMP...at least for me.

How to upgrade docker container after its image changed

Here's what it looks like using docker-compose when building a custom Dockerfile.

  1. Build your custom Dockerfile first, appending a next version number to differentiate. Ex: docker build -t imagename:version . This will store your new version locally.
  2. Run docker-compose down
  3. Edit your docker-compose.yml file to reflect the new image name you set at step 1.
  4. Run docker-compose up -d. It will look locally for the image and use your upgraded one.

-EDIT-

My steps above are more verbose than they need to be. I've optimized my workflow by including the build: . parameter to my docker-compose file. The steps looks this now:

  1. Verify that my Dockerfile is what I want it to look like.
  2. Set the version number of my image name in my docker-compose file.
  3. If my image isn't built yet: run docker-compose build
  4. Run docker-compose up -d

I didn't realize at the time, but docker-compose is smart enough to simply update my container to the new image with the one command, instead of having to bring it down first.

Vagrant ssh authentication failure

If you are using default SSH setup in your VagrantFile and started seeing SSH authentication errors after re-associating your VM box due to crash, try replacing public key in your vagrant machine.

Vagrant replaces public key associated with insecure private key pair at each log out due to security reasons. If you didn't properly shut down your machine, public/private key pair can go out of sync, causing SSH authentication error.

To resolve this issue, simply load up the current insecure private key and then copy the public key pair into your VM's authorized_keys file.

What's the best way to calculate the size of a directory in .NET?

An alternative to Trikaldarshi's one line solution. (It avoids having to construct FileInfo objects)

long sizeInBytes = Directory.EnumerateFiles("{path}","*", SearchOption.AllDirectories).Sum(fileInfo => new FileInfo(fileInfo).Length);

How to put a symbol above another in LaTeX?

If you're using # as an operator, consider defining a new operator for it:

\newcommand{\pound}{\operatornamewithlimits{\#}}

You can then write things like \pound_{n = 1}^N and get:

alt text

How to do Base64 encoding in node.js?

I have created a ultimate small js npm library for the base64 encode/decode conversion in Node.js.

Installation

npm install nodejs-base64-converter --save

Usage

var nodeBase64 = require('nodejs-base64-converter');

console.log(nodeBase64.encode("test text")); //dGVzdCB0ZXh0
console.log(nodeBase64.decode("dGVzdCB0ZXh0")); //test text

Git diff --name-only and copy that list

It works perfectly.

git diff 1526043 82a4f7d --name-only | xargs zip update.zip

git diff 1526043 82a4f7d --name-only |xargs -n 10 zip update.zip

How to use a class from one C# project with another C# project

If you have two projects in one solution folder.Just add the Reference of the Project into another.using the Namespace you can get the classes. While Creating the object for that the requried class. Call the Method which you want.

FirstProject:

class FirstClass()
{
   public string Name()
   {
      return "James";
   }
}

Here add reference to the Second Project

SecondProject:

class SeccondClass
{
    FirstProject.FirstClass obj=new FirstProject.FirstClass();
    obj.Name();
}

Countdown timer using Moment js

I thought I'd throw this out there too (no plugins). It counts down for 10 seconds into the future.

_x000D_
_x000D_
    var countDownDate = moment().add(10, 'seconds');_x000D_
_x000D_
      var x = setInterval(function() {_x000D_
        diff = countDownDate.diff(moment());_x000D_
    _x000D_
        if (diff <= 0) {_x000D_
          clearInterval(x);_x000D_
           // If the count down is finished, write some text _x000D_
          $('.countdown').text("EXPIRED");_x000D_
        } else_x000D_
          $('.countdown').text(moment.utc(diff).format("HH:mm:ss"));_x000D_
_x000D_
      }, 1000);
_x000D_
<script src="https://momentjs.com/downloads/moment.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div class="countdown"></div>
_x000D_
_x000D_
_x000D_

How to install SQL Server Management Studio 2012 (SSMS) Express?

You can download the 32bit or 64bit version of "Express With Tools" or "SQL Server Management Studio Express" (SSMSE tools only) from:

https://web.archive.org/web/20170507040411/https://www.microsoft.com/betaexperience/pd/SQLEXPNOCTAV2/enus/default.aspx

This link is for SQL Server 2012 Express Service Pack 1 released 11/09/2012 (11.0.3000.00) The original RTM release was 11.0.2100.60 from March or May of 2012.

enter image description here

Converting int to string in C

Use snprintf - it is standard an available in every compilator. Query it for the size needed by calling it with NULL, 0 parameters. Allocate one character more for null at the end.

int length = snprintf( NULL, 0, "%d", x );
char* str = malloc( length + 1 );
snprintf( str, length + 1, "%d", x );
...
free(str);

ResourceDictionary in a separate assembly

Check out the pack URI syntax. You want something like this:

<ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Subfolder/YourResourceFile.xaml"/>

How can you customize the numbers in an ordered list?

You can also specify your own numbers in the HTML - e.g. if the numbers are being provided by a database:

_x000D_
_x000D_
ol {_x000D_
  list-style: none;_x000D_
}_x000D_
_x000D_
ol>li:before {_x000D_
  content: attr(seq) ". ";_x000D_
}
_x000D_
<ol>_x000D_
  <li seq="1">Item one</li>_x000D_
  <li seq="20">Item twenty</li>_x000D_
  <li seq="300">Item three hundred</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

The seq attribute is made visible using a method similar to that given in other answers. But instead of using content: counter(foo), we use content: attr(seq).

Demo in CodePen with more styling

How to test if a file is a directory in a batch script?

One issue with using %%~si\NUL method is that there is the chance that it guesses wrong. Its possible to have a filename shorten to the wrong file. I don't think %%~si resolves the 8.3 filename, but guesses it, but using string manipulation to shorten the filepath. I believe if you have similar file paths it may not work.

An alternative method:

dir /AD %F% 2>&1 | findstr /C:"Not Found">NUL:&&(goto IsFile)||(goto IsDir)

:IsFile
  echo %F% is a file
  goto done

:IsDir
  echo %F% is a directory
  goto done

:done

You can replace (goto IsFile)||(goto IsDir) with other batch commands:
(echo Is a File)||(echo is a Directory)

Error 1053 the service did not respond to the start or control request in a timely fashion

In my case, the issue was about caching configuration which is set in the App.config file. Once I removed below lines from the App.config file, the issue was resolved.

<cachingConfiguration defaultCacheManager="MyCacheManager">
<cacheManagers>
  <add name="MyCacheManager" type="Microsoft.Practices.EnterpriseLibrary.Caching.CacheManager, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
       expirationPollFrequencyInSeconds="60"
       maximumElementsInCacheBeforeScavenging="50000"
       numberToRemoveWhenScavenging="1000"
       backingStoreName="NullBackingStore" />
</cacheManagers>
<backingStores>
  <add type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.NullBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
       name="NullBackingStore" />
</backingStores>

ssh script returns 255 error

If there's a problem with authentication or connection, such as not being able to read a password from the terminal, ssh will exit with 255 without being able to run your actual script. Verify to make sure you can run 'true' instead, to see if the ssh connection is established successfully.

What is an AssertionError? In which case should I throw it from my own code?

The meaning of an AssertionError is that something happened that the developer thought was impossible to happen.

So if an AssertionError is ever thrown, it is a clear sign of a programming error.