Programs & Examples On #Multibox

Plugin org.apache.maven.plugins:maven-compiler-plugin or one of its dependencies could not be resolved

You only need to delete one folder it is throwing error for. Just go to your M2 repo and org/apache/maven/plugins/maven-compiler-plugins and delete the folder 2.3.2

Converting a pointer into an integer

I think the "meaning" of void* in this case is a generic handle. It is not a pointer to a value, it is the value itself. (This just happens to be how void* is used by C and C++ programmers.)

If it is holding an integer value, it had better be within integer range!

Here is easy rendering to integer:

int x = (char*)p - (char*)0;

It should only give a warning.

Modifying local variable from inside lambda

I had a slightly different problem. Instead of incrementing a local variable in the forEach, I needed to assign an object to the local variable.

I solved this by defining a private inner domain class that wraps both the list I want to iterate over (countryList) and the output I hope to get from that list (foundCountry). Then using Java 8 "forEach", I iterate over the list field, and when the object I want is found, I assign that object to the output field. So this assigns a value to a field of the local variable, not changing the local variable itself. I believe that since the local variable itself is not changed, the compiler doesn't complain. I can then use the value that I captured in the output field, outside of the list.

Domain Object:

public class Country {

    private int id;
    private String countryName;

    public Country(int id, String countryName){
        this.id = id;
        this.countryName = countryName;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
}

Wrapper object:

private class CountryFound{
    private final List<Country> countryList;
    private Country foundCountry;
    public CountryFound(List<Country> countryList, Country foundCountry){
        this.countryList = countryList;
        this.foundCountry = foundCountry;
    }
    public List<Country> getCountryList() {
        return countryList;
    }
    public void setCountryList(List<Country> countryList) {
        this.countryList = countryList;
    }
    public Country getFoundCountry() {
        return foundCountry;
    }
    public void setFoundCountry(Country foundCountry) {
        this.foundCountry = foundCountry;
    }
}

Iterate operation:

int id = 5;
CountryFound countryFound = new CountryFound(countryList, null);
countryFound.getCountryList().forEach(c -> {
    if(c.getId() == id){
        countryFound.setFoundCountry(c);
    }
});
System.out.println("Country found: " + countryFound.getFoundCountry().getCountryName());

You could remove the wrapper class method "setCountryList()" and make the field "countryList" final, but I did not get compilation errors leaving these details as-is.

Efficiently sorting a numpy array in descending order?

temp[::-1].sort() sorts the array in place, whereas np.sort(temp)[::-1] creates a new array.

In [25]: temp = np.random.randint(1,10, 10)

In [26]: temp
Out[26]: array([5, 2, 7, 4, 4, 2, 8, 6, 4, 4])

In [27]: id(temp)
Out[27]: 139962713524944

In [28]: temp[::-1].sort()

In [29]: temp
Out[29]: array([8, 7, 6, 5, 4, 4, 4, 4, 2, 2])

In [30]: id(temp)
Out[30]: 139962713524944

link_to method and click event in Rails

another solution is catching onClick event and for aggregate data to js function you can

.hmtl.erb

<%= link_to "Action", 'javascript:;', class: 'my-class', data: { 'array' => %w(foo bar) } %>

.js

// handle my-class click
$('a.my-class').on('click', function () {
  var link = $(this);
  var array = link.data('array');
});

Xcode is not currently available from the Software Update server

Had the same issue and was getting the same error. When i ran xcode-select -p, it gave output as /Library/Developer/CommandLineTools. So that means xcode was already installed in my system. Then i ran steps as given on this answer. After which any command which required xcode ran successfully.

How to copy a file along with directory structure/path using python?

take a look at shutil. shutil.copyfile(src, dst) will copy a file to another file.

Note that shutil.copyfile will not create directories that do not already exist. for that, use os.makedirs

Swift - How to convert String to Double

As of Swift 1.1, you can directly pass String to const char * parameter.

import Foundation

let str = "123.4567"
let num = atof(str) // -> 123.4567

atof("123.4567fubar") // -> 123.4567

If you don't like deprecated atof:

strtod("765.4321", nil) // -> 765.4321

One caveat: the behavior of conversion is different from NSString.doubleValue.

atof and strtod accept 0x prefixed hex string:

atof("0xffp-2") // -> 63.75
atof("12.3456e+2") // -> 1,234.56
atof("nan") // -> (not a number)
atof("inf") // -> (+infinity)

If you prefer .doubleValue behavior, we can still use CFString bridging:

let str = "0xff"
atof(str)                      // -> 255.0
strtod(str, nil)               // -> 255.0
CFStringGetDoubleValue(str)    // -> 0.0
(str as NSString).doubleValue  // -> 0.0

Limitations of SQL Server Express

There are a number of limitations, notably:

  • Constrained to a single CPU (in 2012, this limitation has been changed to "The lesser of one socket or four cores", so multi-threading is possible)
  • 1GB RAM (Same in 2008/2012)
  • 4GB database size (raised to 10GB in SQL 2008 R2 and SQL 2012) per database

http://www.dotnetspider.com/tutorials/SqlServer-Tutorial-158.aspx http://www.microsoft.com/sqlserver/2008/en/us/editions.aspx

With regards to the number of databases, this MSDN article says there's no limit:

The 4 GB database size limit applies only to data files and not to log files. However, there are no limits to the number of databases that can be attached to the server.

However, as mentioned in the comments and above, the database size limit was raised to 10GB in 2008 R2 and 2012. Also, this 10GB limit only applies to relational data, and Filestream data does not count towards this limit (http://msdn.microsoft.com/en-us/library/bb895334.aspx).

Move to another EditText when Soft Keyboard Next is clicked on Android

If you have the element in scroll view then you can also solve this issue as :

<com.google.android.material.textfield.TextInputEditText
                android:id="@+id/ed_password"
                android:inputType="textPassword"
                android:focusable="true"
                android:imeOptions="actionNext"
                android:nextFocusDown="@id/ed_confirmPassword" />

and in your activity:

edPassword.setOnEditorActionListener(new EditText.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_NEXT) {
                focusOnView(scroll,edConfirmPassword);
                return true;
            }
            return false;
        }
    });

public void focusOnView(ScrollView scrollView, EditText viewToScrollTo){
    scrollView.post(new Runnable() {
        @Override
        public void run() {
            scrollView.smoothScrollTo(0, viewToScrollTo.getBottom());
            viewToScrollTo.requestFocus();
        }
    });
}

How can I get log4j to delete old rotating log files?

There is no default value to control deleting old log files created by DailyRollingFileAppender. But you can write your own custom Appender that deletes old log files in much the same way as setting maxBackupIndex does for RollingFileAppender.

Simple instructions found here

From 1:

If you are trying to use the Apache Log4J DailyRollingFileAppender for a daily log file, you may need to want to specify the maximum number of files which should be kept. Just like rolling RollingFileAppender supports maxBackupIndex. But the current version of Log4j (Apache log4j 1.2.16) does not provide any mechanism to delete old log files if you are using DailyRollingFileAppender. I tried to make small modifications in the original version of DailyRollingFileAppender to add maxBackupIndex property. So, it would be possible to clean up old log files which may not be required for future usage.

How to turn off Wifi via ADB?

Using "svc" through ADB (rooted required):

Enable:

adb shell su -c 'svc wifi enable'

Disable:

adb shell su -c 'svc wifi disable'

Using Key Events through ADB:

adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings
adb shell input keyevent 20 & adb shell input keyevent 23

The first line launch "wifi.WifiSettings" activity which open the WiFi Settings page. The second line simulate key presses.

I tested those two lines on a Droid X. But Key Events above probably need to edit in other devices because of different Settings layout.

More info about "keyevents" here.

How to convert a Base64 string into a Bitmap image to show it in a ImageView?

To check online you can use

http://codebeautify.org/base64-to-image-converter

You can convert string to image like this way

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView image =(ImageView)findViewById(R.id.image);

        //encode image to base64 string
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);

        //decode base64 string to image
        imageBytes = Base64.decode(imageString, Base64.DEFAULT);
        Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
        image.setImageBitmap(decodedImage);
    }
}

http://www.thecrazyprogrammer.com/2016/10/android-convert-image-base64-string-base64-string-image.html

Remove all non-"word characters" from a String in Java, leaving accented characters?

Use [^\p{L}\p{Nd}]+ - this matches all (Unicode) characters that are neither letters nor (decimal) digits.

In Java:

String resultString = subjectString.replaceAll("[^\\p{L}\\p{Nd}]+", "");

Edit:

I changed \p{N} to \p{Nd} because the former also matches some number symbols like ¼; the latter doesn't. See it on regex101.com.

Sending HTML Code Through JSON

In PHP:

$data = "<html>....";
exit(json_encode($data));

Then you should use AJAX to retrieve the data and do what you want with it. I suggest using JQuery: http://api.jquery.com/jQuery.getJSON/

Using floats with sprintf() in embedded C

Don't do this; integers in C/C++ are always rounded down so there is no need to use the floor function.

char str[100]; 
int d1 = value;

Better to use

int d1 = (int)(floor(value));

Then you won't get rounding up of the integer part (68.9999999999999999 becomes 69.00..). 68.09999847 instead of 68.1 is difficult to avoid - any floating point format has limited precision.

Whitespaces in java

boolean containsWhitespace = false;
for (int i = 0; i < text.length() && !containsWhitespace; i++) {
    if (Character.isWhitespace(text.charAt(i)) {
        containsWhitespace = true;
    }
}
return containsWhitespace;

or, using Guava,

boolean containsWhitespace = CharMatcher.WHITESPACE.matchesAnyOf(text);

VBA Excel 2-Dimensional Arrays

For this example you will need to create your own type, that would be an array. Then you create a bigger array which elements are of type you have just created.

To run my example you will need to fill columns A and B in Sheet1 with some values. Then run test(). It will read first two rows and add the values to the BigArr. Then it will check how many rows of data you have and read them all, from the place it has stopped reading, i.e., 3rd row.

Tested in Excel 2007.

Option Explicit
Private Type SmallArr
  Elt() As Variant
End Type

Sub test()
    Dim x As Long, max_row As Long, y As Long
    '' Define big array as an array of small arrays
    Dim BigArr() As SmallArr
    y = 2
    ReDim Preserve BigArr(0 To y)
    For x = 0 To y
        ReDim Preserve BigArr(x).Elt(0 To 1)
        '' Take some test values
        BigArr(x).Elt(0) = Cells(x + 1, 1).Value
        BigArr(x).Elt(1) = Cells(x + 1, 2).Value
    Next x
    '' Write what has been read
    Debug.Print "BigArr size = " & UBound(BigArr) + 1
    For x = 0 To UBound(BigArr)
        Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
    Next x
    '' Get the number of the last not empty row
    max_row = Range("A" & Rows.Count).End(xlUp).Row

    '' Change the size of the big array
    ReDim Preserve BigArr(0 To max_row)

    Debug.Print "new size of BigArr with old data = " & UBound(BigArr)
    '' Check haven't we lost any data
    For x = 0 To y
        Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
    Next x

    For x = y To max_row
        '' We have to change the size of each Elt,
        '' because there are some new for,
        '' which the size has not been set, yet.
        ReDim Preserve BigArr(x).Elt(0 To 1)
        '' Take some test values
        BigArr(x).Elt(0) = Cells(x + 1, 1).Value
        BigArr(x).Elt(1) = Cells(x + 1, 2).Value
    Next x

    '' Check what we have read
    Debug.Print "BigArr size = " & UBound(BigArr) + 1
    For x = 0 To UBound(BigArr)
        Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
    Next x

End Sub

How can I view the contents of an ElasticSearch index?

You can even add the size of the terms (indexed terms). Have a look at Elastic Search: how to see the indexed data

GoogleMaps API KEY for testing

There seems no way to have google maps api key free without credit card. To test the functionality of google map you can use it while leaving the api key field "EMPTY". It will show a message saying "For Development Purpose Only". And that way you can test google map functionality without putting billing information for google map api key.

<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap" async defer></script>

hibernate - get id after save object

The session.save(object) returns the id of the object, or you could alternatively call the id getter method after performing a save.

Save() return value:

Serializable save(Object object) throws HibernateException

Returns:

the generated identifier

Getter method example:

UserDetails entity:

@Entity
public class UserDetails {
    @Id
    @GeneratedValue
    private int id;
    private String name;

    // Constructor, Setters & Getters
}

Logic to test the id's :

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.getTransaction().begin();
UserDetails user1 = new UserDetails("user1");
UserDetails user2 = new UserDetails("user2");

//int userId = (Integer) session.save(user1); // if you want to save the id to some variable

System.out.println("before save : user id's = "+user1.getId() + " , " + user2.getId());

session.save(user1);
session.save(user2);

System.out.println("after save : user id's = "+user1.getId() + " , " + user2.getId());

session.getTransaction().commit();

Output of this code:

before save : user id's = 0 , 0

after save : user id's = 1 , 2

As per this output, you can see that the id's were not set before we save the UserDetails entity, once you save the entities then Hibernate set's the id's for your objects - user1 and user2

Is it possible to add an HTML link in the body of a MAILTO link

Add the full link, with:

 "http://"

to the beginning of a line, and most decent email clients will auto-link it either before sending, or at the other end when receiving.

For really long urls that will likely wrap due to all the parameters, wrap the link in a less than/greater than symbol. This tells the email client not to wrap the url.

e.g.

  <http://www.example.com/foo.php?this=a&really=long&url=with&lots=and&lots=and&lots=of&prameters=on_it>

How do I write a custom init for a UIView subclass in Swift?

Here is how I do it on iOS 9 in Swift -

import UIKit

class CustomView : UIView {

    init() {
        super.init(frame: UIScreen.mainScreen().bounds);

        //for debug validation
        self.backgroundColor = UIColor.blueColor();
        print("My Custom Init");

        return;
    }

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); }
}

Here is a full project with example:

Angular 2 Dropdown Options Default Value

Add a binding to the selected property, like this:

<option *ngFor="#workout of workouts" 
    [selected]="workout.name == 'back'">{{workout.name}}</option>

CSS full screen div with text in the middle

The standard approach is to give the centered element fixed dimensions, and place it absolutely:

<div class='fullscreenDiv'>
    <div class="center">Hello World</div>
</div>?

.center {
    position: absolute;
    width: 100px;
    height: 50px;
    top: 50%;
    left: 50%;
    margin-left: -50px; /* margin is -0.5 * dimension */
    margin-top: -25px; 
}?

Asp.net - <customErrors mode="Off"/> error when trying to access working webpage

Sometime in the future Comment out the following code in web.config

 <!--<system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>-->

update the to the following code.

<system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <customErrors mode="Off"/>
    <trust level="Full"/>
  </system.web>

Does an HTTP Status code of 0 have any meaning?

status 0 appear when an ajax call was cancelled before getting the response by refreshing the page or requesting a URL that is unreachable.

this status is not documented but exist over ajax and makeRequest call's from gadget.io.

Modelling an elevator using Object-Oriented Analysis and Design

See:

Lu Luo, A UML Documentation for a Elevator System
Distributed Embedded Systems, Fall 2000
Ph.D. Project Report
Carneghie Mellon University

link

How to reset (clear) form through JavaScript?

You can clear the whole form using onclick function.Here is the code for it.

 <button type="reset" value="reset" type="reset" class="btnreset" onclick="window.location.reload()">Reset</button>

window.location.reload() function will refresh your page and all data will clear.

How do I vertically align text in a div?

You can do this by setting the display to 'table-cell' and applying a vertical-align: middle;:

    {
        display: table-cell;
        vertical-align: middle;
    }

This is however not supported by all versions of Internet Explorer according to this excerpt I copied from http://www.w3schools.com/cssref/pr_class_display.asp without permission.

Note: The values "inline-table", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-row", "table-row-group", and "inherit" are not supported by Internet Explorer 7 and earlier. Internet Explorer 8 requires a !DOCTYPE. Internet Explorer 9 supports the values.

The following table shows the allowed display values also from http://www.w3schools.com/cssref/pr_class_display.asp.

Enter image description here

How to detect lowercase letters in Python?

If you don't want to use the libraries and want simple answer then the code is given below:

  def swap_alpha(test_string):
      new_string = ""
      for i in test_string:
          if i.upper() in test_string:
              new_string += i.lower()

          elif i.lower():
                new_string += i.upper()

          else:
              return "invalid "

      return new_string


user_string = input("enter the string:")
updated = swap_alpha(user_string)
print(updated)

SQL update fields of one table from fields of another one

The question is old but I felt the best answer hadn't been given, yet.

Is there an UPDATE syntax ... without specifying the column names?

General solution with dynamic SQL

You don't need to know any column names except for some unique column(s) to join on (id in the example). Works reliably for any possible corner case I can think of.

This is specific to PostgreSQL. I am building dynamic code based on the the information_schema, in particular the table information_schema.columns, which is defined in the SQL standard and most major RDBMS (except Oracle) have it. But a DO statement with PL/pgSQL code executing dynamic SQL is totally non-standard PostgreSQL syntax.

DO
$do$
BEGIN

EXECUTE (
SELECT
  'UPDATE b
   SET   (' || string_agg(        quote_ident(column_name), ',') || ')
       = (' || string_agg('a.' || quote_ident(column_name), ',') || ')
   FROM   a
   WHERE  b.id = 123
   AND    a.id = b.id'
FROM   information_schema.columns
WHERE  table_name   = 'a'       -- table name, case sensitive
AND    table_schema = 'public'  -- schema name, case sensitive
AND    column_name <> 'id'      -- all columns except id
);

END
$do$;

Assuming a matching column in b for every column in a, but not the other way round. b can have additional columns.

WHERE b.id = 123 is optional, to update a selected row.

SQL Fiddle.

Related answers with more explanation:

Partial solutions with plain SQL

With list of shared columns

You still need to know the list of column names that both tables share. With a syntax shortcut for updating multiple columns - shorter than what other answers suggested so far in any case.

UPDATE b
SET   (  column1,   column2,   column3)
    = (a.column1, a.column2, a.column3)
FROM   a
WHERE  b.id = 123    -- optional, to update only selected row
AND    a.id = b.id;

SQL Fiddle.

This syntax was introduced with Postgres 8.2 in 2006, long before the question was asked. Details in the manual.

Related:

With list of columns in B

If all columns of A are defined NOT NULL (but not necessarily B),
and you know the column names of B (but not necessarily A).

UPDATE b
SET   (column1, column2, column3, column4)
    = (COALESCE(ab.column1, b.column1)
     , COALESCE(ab.column2, b.column2)
     , COALESCE(ab.column3, b.column3)
     , COALESCE(ab.column4, b.column4)
      )
FROM (
   SELECT *
   FROM   a
   NATURAL LEFT JOIN  b -- append missing columns
   WHERE  b.id IS NULL  -- only if anything actually changes
   AND    a.id = 123    -- optional, to update only selected row
   ) ab
WHERE b.id = ab.id;

The NATURAL LEFT JOIN joins a row from b where all columns of the same name hold same values. We don't need an update in this case (nothing changes) and can eliminate those rows early in the process (WHERE b.id IS NULL).
We still need to find a matching row, so b.id = ab.id in the outer query.

db<>fiddle here
Old sqlfiddle.

This is standard SQL except for the FROM clause.
It works no matter which of the columns are actually present in A, but the query cannot distinguish between actual NULL values and missing columns in A, so it is only reliable if all columns in A are defined NOT NULL.

There are multiple possible variations, depending on what you know about both tables.

python JSON only get keys in first level

Just do a simple .keys()

>>> dct = {
...     "1": "a", 
...     "3": "b", 
...     "8": {
...         "12": "c", 
...         "25": "d"
...     }
... }
>>> 
>>> dct.keys()
['1', '8', '3']
>>> for key in dct.keys(): print key
...
1
8
3
>>>

If you need a sorted list:

keylist = dct.keys()
keylist.sort()

What does ellipsize mean in android?

You can find documentation here.

Based on your requirement you can try according option.

to ellipsize, a neologism, means to shorten text using an ellipsis, i.e. three dots ... or more commonly ligature , to stand in for the omitted bits.

Say original value pf text view is aaabbbccc and its fitting inside the view

start's output will be : ...bccc

end's output will be : aaab...

middle's output will be : aa...cc

marquee's output will be : aaabbbccc auto sliding from right to left

Editable text to string

If I understand correctly, you want to get the String of an Editable object, right? If yes, try using toString().

Convert `List<string>` to comma-separated string

That's the way I'd prefer to see if I was maintaining your code. If you manage to find a faster solution, it's going to be very esoteric, and you should really bury it inside of a method that describes what it does.

(does it still work without the ToArray)?

Procedure or function !!! has too many arguments specified

You invoke the function with 2 parameters (@GenId and @Description):

EXEC etl.etl_M_Update_Promo @GenID, @Description

However you have declared the function to take 1 argument:

ALTER PROCEDURE [etl].[etl_M_Update_Promo]
    @GenId bigint = 0

SQL Server is telling you that [etl_M_Update_Promo] only takes 1 parameter (@GenId)

You can alter the procedure to take two parameters by specifying @Description.

ALTER PROCEDURE [etl].[etl_M_Update_Promo]
    @GenId bigint = 0,
    @Description NVARCHAR(50)
AS 

.... Rest of your code.

Playing MP4 files in Firefox using HTML5 video

This is caused by the limited support for the MP4 format within the video tag in Firefox. Support was not added until Firefox 21, and it is still limited to Windows 7 and above. The main reason for the limited support revolves around the royalty fee attached to the mp4 format.

Check out Supported media formats and Media formats supported by the audio and video elements directly from the Mozilla crew or the following blog post for more information:

http://pauljacobson.org/2010/01/22/2010122firefox-and-its-limited-html-5-video-support-html/

Open File in Another Directory (Python)

If you know the full path to the file you can just do something similar to this. However if you question directly relates to relative paths, that I am unfamiliar with and would have to research and test.

path = 'C:\\Users\\Username\\Path\\To\\File'

with open(path, 'w') as f:
    f.write(data)

Edit:

Here is a way to do it relatively instead of absolute. Not sure if this works on windows, you will have to test it.

import os

cur_path = os.path.dirname(__file__)

new_path = os.path.relpath('..\\subfldr1\\testfile.txt', cur_path)
with open(new_path, 'w') as f:
    f.write(data)

Edit 2: One quick note about __file__, this will not work in the interactive interpreter due it being ran interactively and not from an actual file.

Can't install any packages in Node.js using "npm install"

npm set registry http://85.10.209.91/

(this proxy fetches the original data from registry.npmjs.org and manipulates the tarball urls to fix the tarball file structure issue).

The other solutions seem to have outdated versions.

Rendering partial view on button click in ASP.NET MVC

Change the button to

<button id="search">Search</button>

and add the following script

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('#search').click(function() {
  var keyWord = $('#Keyword').val();
  $('#searchResults').load(url, { searchText: keyWord });
})

and modify the controller method to accept the search text

public ActionResult DisplaySearchResults(string searchText)
{
  var model = // build list based on parameter searchText
   return PartialView("SearchResults", model);
}

The jQuery .load method calls your controller method, passing the value of the search text and updates the contents of the <div> with the partial view.

Side note: The use of a <form> tag and @Html.ValidationSummary() and @Html.ValidationMessageFor() are probably not necessary here. Your never returning the Index view so ValidationSummary makes no sense and I assume you want a null search text to return all results, and in any case you do not have any validation attributes for property Keyword so there is nothing to validate.

Edit

Based on OP's comments that SearchCriterionModel will contain multiple properties with validation attributes, then the approach would be to include a submit button and handle the forms .submit() event

<input type="submit" value="Search" />

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('form').submit(function() {
  if (!$(this).valid()) { 
    return false; // prevent the ajax call if validation errors
  }
  var form = $(this).serialize();
  $('#searchResults').load(url, form);
  return false; // prevent the default submit action
})

and the controller method would be

public ActionResult DisplaySearchResults(SearchCriterionModel criteria)
{
  var model = // build list based on the properties of criteria
  return PartialView("SearchResults", model);
}

Install mysql-python (Windows)

Just Download mysqlclient from here https://www.lfd.uci.edu/~gohlke/pythonlibs/ be careful while downloading the right version depending on your your python version installed. Then proceed with the import. It worked for me because in my case the error was telling to install Visual Studio C++ 14.0 something which wasted my time and occupied around 10GB of space in my C drive. So recommending installing mysqlclient using pip install mysqlclient

Select unique or distinct values from a list in UNIX shell script

For larger data sets where sorting may not be desirable, you can also use the following perl script:

./yourscript.ksh | perl -ne 'if (!defined $x{$_}) { print $_; $x{$_} = 1; }'

This basically just remembers every line output so that it doesn't output it again.

It has the advantage over the "sort | uniq" solution in that there's no sorting required up front.

Java system properties and environment variables

I think the difference between the two boils down to access. Environment variables are accessible by any process and Java system properties are only accessible by the process they are added to.

Also as Bohemian stated, env variables are set in the OS (however they 'can' be set through Java) and system properties are passed as command line options or set via setProperty().

ReactJS - Add custom event listener to component

I recommend using React.createRef() and ref=this.elementRef to get the DOM element reference instead of ReactDOM.findDOMNode(this). This way you can get the reference to the DOM element as an instance variable.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class MenuItem extends Component {

  constructor(props) {
    super(props);

    this.elementRef = React.createRef();
  }

  handleNVFocus = event => {
      console.log('Focused: ' + this.props.menuItem.caption.toUpperCase());
  }
    
  componentDidMount() {
    this.elementRef.addEventListener('nv-focus', this.handleNVFocus);
  }

  componentWillUnmount() {
    this.elementRef.removeEventListener('nv-focus', this.handleNVFocus);
  }

  render() {
    return (
      <element ref={this.elementRef} />
    )
  }

}

export default MenuItem;

Can dplyr package be used for conditional mutating?

The derivedFactor function from mosaic package seems to be designed to handle this. Using this example, it would look like:

library(dplyr)
library(mosaic)
df <- mutate(df, g = derivedFactor(
     "2" = (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)),
     "3" = (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
     .method = "first",
     .default = NA
     ))

(If you want the result to be numeric instead of a factor, you can wrap derivedFactor in an as.numeric call.)

derivedFactor can be used for an arbitrary number of conditionals, too.

java.sql.SQLException: Fail to convert to internal representation

Check with your bean class. Column data type and bean datatype must be same.

How to obtain the start time and end time of a day?

I know it's a bit late, but in case of Java 8, if you are using OffsetDateTime (which offers a lot of advantages, such as TimeZone, Nanoseconds, etc.), you can use the following code:

OffsetDateTime reallyEndOfDay = someDay.withHour(23).withMinute(59).withSecond(59).withNano(999999999);
// output: 2019-01-10T23:59:59.999999999Z

How to lock specific cells but allow filtering and sorting

Here is an article that explains the problem and solution with alot more detail:

Sorting Locked Cells in Protected Worksheets

The thing to understand is that the purpose of locking cells is to prevent them from being changed, and sorting permanently changes cell values. You can write a macro, but a much better solution is to use the "Allow Users to Edit Ranges" feature. This makes the cells editable so sorting can work, but because the cells are still technically locked you can prevent users from selecting them.

Calculate RSA key fingerprint

The fastest way if your keys are in an SSH agent:

$ ssh-add -L | ssh-keygen -E md5 -lf /dev/stdin

Each key in the agent will be printed as:

4096 MD5:8f:c9:dc:40:ec:9e:dc:65:74:f7:20:c1:29:d1:e8:5a /Users/cmcginty/.ssh/id_rsa (RSA)

Not class selector in jQuery

You need the :not() selector:

$('div[class^="first-"]:not(.first-bar)')

or, alternatively, the .not() method:

$('div[class^="first-"]').not('.first-bar');

CSS media query to target iPad and iPad only?

/*working only in ipad portrait device*/
@media only screen and (width: 768px) and (height: 1024px) and (orientation:portrait) {
  body{
    background: red !important;
  }  
}
/*working only in ipad landscape device*/
@media all and (width: 1024px) and (height: 768px) and (orientation:landscape){
  body{
    background: green !important;
  }   
}

In the media query of specific devices, please use '!important' keyword to override the default CSS. Otherwise that does not change your webpage view on that particular devices.

printf not printing on console

  1. In your project folder, create a “.gdbinit” text file. It will contain your gdb debugger configuration
  2. Edit “.gdbinit”, and add the line (without the quotes) : “set new-console on”
  3. After building the project right click on the project Debug > “Debug Configurations”, as shown below Debug configuration

  4. In the “debugger” tab, ensure the “GDB command file” now points to your “.gdbinit” file. Else, input the path to your “.gdbinit” configuration file : Gdb configuration

  5. Click “Apply” and “Debug”. A native DOS command line should be launched as shown below Console

How can I display an RTSP video stream in a web page?

Roughly you can have 3 choices to display RTSP video stream in a web page:

  1. Realplayer
  2. Quicktime player
  3. VLC player

You can find the code to embed the activeX via google search.

As far as I know, there are some limitations for each player.

  1. Realplayer does not support H.264 video natively, you must install a quicktime plugin for Realplayer to achieve H.264 decoding.
  2. Quicktime player does not support RTP/AVP/TCP transport, and it's RTP/AVP (UDP) transport does not include NAT hole punching. Thus the only feasible transport is HTTP tunneling in WAN deployment.
  3. VLC neither supports NAT hole punching for RTP/AVP transport, but RTP/AVP/TCP transport is available.

Encode html entities in javascript

one of the Easy Way for Encode Or Decode HTML-entities
just Call a Function with one argument...

Decode HTML-entities

function decodeHTMLEntities(text) {
  var textArea = document.createElement('textarea');
  textArea.innerHTML = text;
  return textArea.value;
}

Decode HTML-entities (JQuery)

function decodeHTMLEntities(text) {
  return $("<textarea/>").html(text).text();
}

Encode HTML-entities

function encodeHTMLEntities(text) {
  var textArea = document.createElement('textarea');
  textArea.innerText = text;
  return textArea.innerHTML;
}

Encode HTML-entities (JQuery)

function encodeHTMLEntities(text) {
  return $("<textarea/>").text(text).html();
}

Unpivot with column name

You may also try standard sql un-pivoting method by using a sequence of logic with the following code.. The following code has 3 steps:

  1. create multiple copies for each row using cross join (also creating subject column in this case)
  2. create column "marks" and fill in relevant values using case expression ( ex: if subject is science then pick value from science column)
  3. remove any null combinations ( if exists, table expression can be fully avoided if there are strictly no null values in base table)

     select *
     from 
     (
        select name, subject,
        case subject
        when 'Maths' then maths
        when 'Science' then science
        when 'English' then english
        end as Marks
    from studentmarks
    Cross Join (values('Maths'),('Science'),('English')) AS Subjct(Subject)
    )as D
    where marks is not null;
    

calculating number of days between 2 columns of dates in data frame

In Ronald's example, if the date formats are different (as displayed below) then modify the format parameter

survey <- data.frame(date=c("2012-07-26","2012-07-25"),tx_start=c("2012-01-01","2012-01-01"))

survey$date_diff <- as.Date(as.character(survey$date), format="%Y-%m-%d")-
              as.Date(as.character(survey$tx_start), format="%Y-%m-%d")

survey:

   date      tx_start     date_diff
1 2012-07-26     2012-01-01    207 days
2 2012-07-25     2012-01-01    206 days

Convert date to UTC using moment.js

here, I'm passing the date object and converting it into UTC time.

$.fn.convertTimeToUTC = function (convertTime) {
   if($(this).isObject(convertTime)) {
        return moment.tz(convertTime.format("Y-MM-DD HH:mm:ss"), moment.tz.guess()).utc().format("Y-MM-DD HH:mm:ss");
    }
};
// Returns if a value is an object
$.fn.isObject =  function(value) {
    return value && typeof value === 'object';
};


//you can call it as below
$(this).convertTimeToUTC(date);

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

Netbeans needs to be able to index the maven repository. Allow it to do that and try again. It was giving me the same error and after it indexed the repository it ran like a charm

Match exact string

Use the start and end delimiters: ^abc$

How to update /etc/hosts file in Docker image during "docker build"

With a more recent version of docker, this could be done with docker-compose and its extra_hosts directive

Add hostname mappings.
Use the same values as the docker run client --add-host parameter (which should already be available for docker 1.8).

extra_hosts:
 - "somehost:162.242.195.82"
 - "otherhost:50.31.209.229"

In short: modify /etc/hosts of your container when running it, instead of when building it.


With Docker 17.x+, you have a docker build --add-host mentioned below, but, as commented in issue 34078 and in this answer:

The --add-host feature during build is designed to allow overriding a host during build, but not to persist that configuration in the image.

The solutions mentioned do refer the docker-compose I was suggesting above:

  • Run an internal DNS; you can set the default DNS server to use in the daemon; that way every container started will automatically use the configured DNS by default
  • Use docker compose and provide a docker-compose.yml to your developers.
    The docker compose file allows you to specify all the options that should be used when starting a container, so developers could just docker compose up to start the container with all the options they need to set.

JavaScript chop/slice/trim off last character in string

For a number like your example, I would recommend doing this over substring:

_x000D_
_x000D_
console.log(parseFloat('12345.00').toFixed(1));
_x000D_
_x000D_
_x000D_

Do note that this will actually round the number, though, which I would imagine is desired but maybe not:

_x000D_
_x000D_
console.log(parseFloat('12345.46').toFixed(1));
_x000D_
_x000D_
_x000D_

Nginx serves .php files as downloads, instead of executing them

check your nginx config file extension is *.conf.
for example: /etc/nginx/conf.d/myfoo.conf

I got the same situation. After I rename the my config file from myfoo to myfoo.conf, it fixed. Do not forget to restart nginx after rename it.

Removing a non empty directory programmatically in C or C++

//======================================================
// Recursely Delete files using:
//   Gnome-Glib & C++11
//======================================================

#include <iostream>
#include <string>
#include <glib.h>
#include <glib/gstdio.h>

using namespace std;

int DirDelete(const string& path)
{
   const gchar*    p;
   GError*   gerr;
   GDir*     d;
   int       r;
   string    ps;
   string    path_i;
   cout << "open:" << path << "\n";
   d        = g_dir_open(path.c_str(), 0, &gerr);
   r        = -1;

   if (d) {
      r = 0;

      while (!r && (p=g_dir_read_name(d))) {
          ps = string{p};
          if (ps == "." || ps == "..") {
            continue;
          }

          path_i = path + string{"/"} + p;


          if (g_file_test(path_i.c_str(), G_FILE_TEST_IS_DIR) != 0) {
            cout << "recurse:" << path_i << "\n";
            r = DirDelete(path_i);
          }
          else {
            cout << "unlink:" << path_i << "\n";
            r = g_unlink(path_i.c_str());
          }
      }

      g_dir_close(d);
   }

   if (r == 0) {
      r = g_rmdir(path.c_str());
     cout << "rmdir:" << path << "\n";

   }

   return r;
}

Android, getting resource ID from string?

A simple way to getting resource ID from string. Here resourceName is the name of resource ImageView in drawable folder which is included in XML file as well.

int resID = getResources().getIdentifier(resourceName, "id", getPackageName());
ImageView im = (ImageView) findViewById(resID);
Context context = im.getContext();
int id = context.getResources().getIdentifier(resourceName, "drawable",
context.getPackageName());
im.setImageResource(id);

Hibernate Error executing DDL via JDBC Statement

Another sneaky issue related to this is naming your columns with - instead of _.

Something like this will trigger an error at the moment your tables are getting created.

@Column(name="verification-token")

Converting Object to JSON and JSON to Object in PHP, (library like Gson for Java)

json_decode($json, true); 
// the second param being true will return associative array. This one is easy.

Creating a script for a Telnet session?

Write the telnet session inside a BAT Dos file and execute.

C++ style cast from unsigned char * to const char *

Hope it help. :)

const unsigned attribName = getname();
const unsigned attribVal = getvalue();
const char *attrName=NULL, *attrVal=NULL;
attrName = (const char*) attribName;
attrVal = (const char*) attribVal;

What is the use of static constructors?

No you can't overload it; a static constructor is useful for initializing any static fields associated with a type (or any other per-type operations) - useful in particular for reading required configuration data into readonly fields, etc.

It is run automatically by the runtime the first time it is needed (the exact rules there are complicated (see "beforefieldinit"), and changed subtly between CLR2 and CLR4). Unless you abuse reflection, it is guaranteed to run at most once (even if two threads arrive at the same time).

For homebrew mysql installs, where's my.cnf?

One way to find out:

sudo /usr/libexec/locate.updatedb
# wait a few minutes for it to finish
locate my.cnf

OS X Framework Library not loaded: 'Image not found'

What solved it for me was changing abstract_target to target for the main target in my Podfile. I had previously set it to abstract_target and this caused the described error. Now it works like a charm

Extracting .jar file with command line

In Ubuntu:

unzip file.jar -d dir_name_where_extracting

Correct way to convert size in bytes to KB, MB, GB in JavaScript

Using bitwise operation would be a better solution. Try this

function formatSizeUnits(bytes)
{
    if ( ( bytes >> 30 ) & 0x3FF )
        bytes = ( bytes >>> 30 ) + '.' + ( bytes & (3*0x3FF )) + 'GB' ;
    else if ( ( bytes >> 20 ) & 0x3FF )
        bytes = ( bytes >>> 20 ) + '.' + ( bytes & (2*0x3FF ) ) + 'MB' ;
    else if ( ( bytes >> 10 ) & 0x3FF )
        bytes = ( bytes >>> 10 ) + '.' + ( bytes & (0x3FF ) ) + 'KB' ;
    else if ( ( bytes >> 1 ) & 0x3FF )
        bytes = ( bytes >>> 1 ) + 'Bytes' ;
    else
        bytes = bytes + 'Byte' ;
    return bytes ;
}

How to change fonts in matplotlib (python)?

I prefer to employ:

from matplotlib import rc
#rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('font',**{'family':'serif','serif':['Times']})
rc('text', usetex=True)

python: SyntaxError: EOL while scanning string literal

You are not putting a " before the end of the line.

Use """ if you want to do this:

""" a very long string ...... 
....that can span multiple lines
"""

How Do I Insert a Byte[] Into an SQL Server VARBINARY Column

My solution would be to use a parameterised query, as the connectivity objects take care of formatting the data correctly (including ensuring the correct data-type, and escaping "dangerous" characters where applicable):

// Assuming "conn" is an open SqlConnection
using(SqlCommand cmd = new SqlCommand("INSERT INTO mssqltable(varbinarycolumn) VALUES (@binaryValue)", conn))
{
    // Replace 8000, below, with the correct size of the field
    cmd.Parameters.Add("@binaryValue", SqlDbType.VarBinary, 8000).Value = arraytoinsert;
    cmd.ExecuteNonQuery();
}

Edit: Added the wrapping "using" statement as suggested by John Saunders to correctly dispose of the SqlCommand after it is finished with

Display an image into windows forms

private void Form1_Load(object sender, EventArgs e)
    {
        PictureBox pb = new PictureBox();
        pb.Location = new Point(0, 0);
        pb.Size = new Size(150, 150);
        pb.Image = Image.FromFile("E:\\Wallpaper (204).jpg");
        pb.Visible = true;
        this.Controls.Add(pb);
    }

How do I move files in node.js?

Just my 2 cents as stated in the answer above : The copy() method shouldn't be used as-is for copying files without a slight adjustment:

function copy(callback) {
    var readStream = fs.createReadStream(oldPath);
    var writeStream = fs.createWriteStream(newPath);

    readStream.on('error', callback);
    writeStream.on('error', callback);

    // Do not callback() upon "close" event on the readStream
    // readStream.on('close', function () {
    // Do instead upon "close" on the writeStream
    writeStream.on('close', function () {
        callback();
    });

    readStream.pipe(writeStream);
}

The copy function wrapped in a Promise:

function copy(oldPath, newPath) {
  return new Promise((resolve, reject) => {
    const readStream = fs.createReadStream(oldPath);
    const writeStream = fs.createWriteStream(newPath);

    readStream.on('error', err => reject(err));
    writeStream.on('error', err => reject(err));

    writeStream.on('close', function() {
      resolve();
    });

    readStream.pipe(writeStream);
  })

However, keep in mind that the filesystem might crash if the target folder doesn't exist.

Set content of iframe

You want to be using the iframe's srcdoc attribute for that (MDN documentation).

var html_string = "<html><body><h1>My epic iframe</p></body></html>";
document.querySelector('iframe').srcdoc = html_string;

The nice thing about using this method over for example Red's method listed on this page, is that iframe contents added with srcdoc are seen as the same-origin. That way can continue to manipulate and access the iframe with JavaScript if you wish.

Getting the first index of an object

I had the same problem yesterday. I solved it like this:

var obj = {
        foo:{},
        bar:{},
        baz:{}
    },
   first = null,
   key = null;
for (var key in obj) {
    first = obj[key];
    if(typeof(first) !== 'function') {
        break;
    }
}
// first is the first enumerated property, and key it's corresponding key.

Not the most elegant solution, and I am pretty sure that it may yield different results in different browsers (i.e. the specs says that enumeration is not required to enumerate the properties in the same order as they were defined). However, I only had a single property in my object so that was a non-issue. I just needed the first key.

Route.get() requires callback functions but got a "object Undefined"

This thing also happened with my code, but somehow I solved my problem. I checked my routes folder (where my all endpoints are their). I would recommend you check your routes folder file and check whether you forgot to add your particular router link.

Swift: declare an empty dictionary

The Swift documentation recommends the following way to initialize an empty Dictionary:

var emptyDict = [String: String]()

I was a little confused when I first came across this question because different answers showed different ways to initialize an empty Dictionary. It turns out that there are actually a lot of ways you can do it, though some are a little redundant or overly verbose given Swift's ability to infer the type.

var emptyDict = [String: String]()
var emptyDict = Dictionary<String, String>()
var emptyDict: [String: String] = [:]
var emptyDict: [String: String] = [String: String]()
var emptyDict: [String: String] = Dictionary<String, String>()
var emptyDict: Dictionary = [String: String]()
var emptyDict: Dictionary = Dictionary<String, String>()
var emptyDict: Dictionary<String, String> = [:]
var emptyDict: Dictionary<String, String> = [String: String]()
var emptyDict: Dictionary<String, String> = Dictionary<String, String>()

After you have an empty Dictionary you can add a key-value pair like this:

emptyDict["some key"] = "some value"

If you want to empty your dictionary again, you can do the following:

emptyDict = [:]

The types are still <String, String> because that is how it was initialized.

How to send email using simple SMTP commands via Gmail?

to send over gmail, you need to use an encrypted connection. this is not possible with telnet alone, but you can use tools like openssl

either connect using the starttls option in openssl to convert the plain connection to encrypted...

openssl s_client -starttls smtp -connect smtp.gmail.com:587 -crlf -ign_eof

or connect to a ssl sockect directly...

openssl s_client -connect smtp.gmail.com:465 -crlf -ign_eof

EHLO localhost

after that, authenticate to the server using the base64 encoded username/password

AUTH PLAIN AG15ZW1haWxAZ21haWwuY29tAG15cGFzc3dvcmQ=

to get this from the commandline:

echo -ne '\[email protected]\00password' | base64
AHVzZXJAZ21haWwuY29tAHBhc3N3b3Jk

then continue with "mail from:" like in your example

example session:

openssl s_client -connect smtp.gmail.com:465 -crlf -ign_eof
[... lots of openssl output ...]
220 mx.google.com ESMTP m46sm11546481eeh.9
EHLO localhost
250-mx.google.com at your service, [1.2.3.4]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH
250 ENHANCEDSTATUSCODES
AUTH PLAIN AG5pY2UudHJ5QGdtYWlsLmNvbQBub2l0c25vdG15cGFzc3dvcmQ=
235 2.7.0 Accepted
MAIL FROM: <[email protected]>
250 2.1.0 OK m46sm11546481eeh.9
rcpt to: <[email protected]>
250 2.1.5 OK m46sm11546481eeh.9
DATA
354  Go ahead m46sm11546481eeh.9
Subject: it works

yay!
.
250 2.0.0 OK 1339757532 m46sm11546481eeh.9
quit
221 2.0.0 closing connection m46sm11546481eeh.9
read:errno=0

How to set Spinner Default by its Value instead of Position?

this is how i did it:

String[] listAges = getResources().getStringArray(R.array.ages);

        // Creating adapter for spinner
        ArrayAdapter<String> dataAdapter =
                new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listAges);

        // Drop down layout style - list view with radio button
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        spinner_age.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.spinner_icon), PorterDuff.Mode.SRC_ATOP);
        spinner_age.setAdapter(dataAdapter);
        spinner_age.setSelection(0);
        spinner_age.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String item = parent.getItemAtPosition(position).toString();

                if(position > 0){
                    // get spinner value
                    Toast.makeText(parent.getContext(), "Age..." + item, Toast.LENGTH_SHORT).show();
                }else{
                    // show toast select gender
                    Toast.makeText(parent.getContext(), "none" + item, Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

Java "?" Operator for checking null - What is it? (Not Ternary!)

One way to workaround the lack of "?" operator using Java 8 without the overhead of try-catch (which could also hide a NullPointerException originated elsewhere, as mentioned) is to create a class to "pipe" methods in a Java-8-Stream style.

public class Pipe<T> {
    private T object;

    private Pipe(T t) {
        object = t;
    }

    public static<T> Pipe<T> of(T t) {
        return new Pipe<>(t);
    }

    public <S> Pipe<S> after(Function<? super T, ? extends S> plumber) {
        return new Pipe<>(object == null ? null : plumber.apply(object));
    }

    public T get() {
        return object;
    }

    public T orElse(T other) {
        return object == null ? other : object;
    }
}

Then, the given example would become:

public String getFirstName(Person person) {
    return Pipe.of(person).after(Person::getName).after(Name::getGivenName).get();
}

[EDIT]

Upon further thought, I figured out that it is actually possible to achieve the same only using standard Java 8 classes:

public String getFirstName(Person person) {
    return Optional.ofNullable(person).map(Person::getName).map(Name::getGivenName).orElse(null);
}

In this case, it is even possible to choose a default value (like "<no first name>") instead of null by passing it as parameter of orElse.

Environment variable substitution in sed

You can use other characters besides "/" in substitution:

sed "s#$1#$2#g" -i FILE

How to pass argument to Makefile from command line?

You probably shouldn't do this; you're breaking the basic pattern of how Make works. But here it is:

action:
        @echo action $(filter-out $@,$(MAKECMDGOALS))

%:      # thanks to chakrit
    @:    # thanks to William Pursell

EDIT:
To explain the first command,

$(MAKECMDGOALS) is the list of "targets" spelled out on the command line, e.g. "action value1 value2".

$@ is an automatic variable for the name of the target of the rule, in this case "action".

filter-out is a function that removes some elements from a list. So $(filter-out bar, foo bar baz) returns foo baz (it can be more subtle, but we don't need subtlety here).

Put these together and $(filter-out $@,$(MAKECMDGOALS)) returns the list of targets specified on the command line other than "action", which might be "value1 value2".

href overrides ng-click in Angular.js

I don't think you need to remove "#" from href. Following works with Angularjs 1.2.10

<a href="#/" ng-click="logout()">Logout</a>

PowerShell: Run command from script's directory

I often used the following code to import a module which sit under the same directory as the running script. It will first get the directory from which powershell is running

$currentPath=Split-Path ((Get-Variable MyInvocation -Scope 0).Value).MyCommand.Path

import-module "$currentPath\sqlps.ps1"

Maven: add a folder or jar file into current classpath

This might have been asked before. See Can I add jars to maven 2 build classpath without installing them?

In a nutshell: include your jar as dependency with system scope. This requires specifying the absolute path to the jar.

See also http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html

How to access a dictionary element in a Django template?

Use Dictionary Items:

{% for key, value in my_dictionay.items %}
  <li>{{ key }} : {{ value }}</li>
{% endfor %}

Hide text using css

Using zero value for font-size and line-height in the element does the trick for me:

<style>
    .text {
        display: block;
        width: 200px;
        height: 200px;

        font-size: 0;
        line-height: 0;
    }
</style>

<span class="text">
    Invisible Text
</span>

How to copy data from another workbook (excel)?

I don't think you need to select anything at all. I opened two blank workbooks Book1 and Book2, put the value "A" in Range("A1") of Sheet1 in Book2, and submitted the following code in the immediate window -

Workbooks(2).Worksheets(1).Range("A1").Copy Workbooks(1).Worksheets(1).Range("A1")

The Range("A1") in Sheet1 of Book1 now contains "A".

Also, given the fact that in your code you are trying to copy from the ActiveWorkbook to "myfile.xls", the order seems to be reversed as the Copy method should be applied to a range in the ActiveWorkbook, and the destination (argument to the Copy function) should be the appropriate range in "myfile.xls".

How to put a Scanner input into an array... for example a couple of numbers

**Simple solution**
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int size;
    System.out.println("Enter the number of size of array");
    size = sc.nextInt();
    int[] a = new int[size];
    System.out.println("Enter the array element");
    //For reading the element
    for(int i=0;i<size;i++) {
        a[i] = sc.nextInt();
    }
    //For print the array element
    for(int i : a) {
        System.out.print(i+" ,");
    }
}

Equals(=) vs. LIKE

For this example we take it for granted that varcharcol doesn't contain '' and have no empty cell against this column

select * from some_table where varcharCol = ''
select * from some_table where varcharCol like ''

The first one results in 0 row output while the second one shows the whole list. = is strictly-match case while like acts like a filter. if filter has no criteria, every data is valid.

like - by the virtue of its purpose works a little slower and is intended for use with varchar and similar data.

NPM: npm-cli.js not found when running npm

Change the environment path variable C:\Program Files\nodejs\node_modules\npm\bin and open the command terminal and npm -v and

Chart.js v2 - hiding grid lines

OK, nevermind.. I found the trick:

    scales: {
      yAxes: [
        {
          gridLines: {
                lineWidth: 0
            }
        }
      ]
    }

Lodash remove duplicates from array

_.unique no longer works for the current version of Lodash as version 4.0.0 has this breaking change. The functionality of _.unique was splitted into _.uniq, _.sortedUniq, _.sortedUniqBy, and _.uniqBy.

You could use _.uniqBy like this:

_.uniqBy(data, function (e) {
  return e.id;
});

...or like this:

_.uniqBy(data, 'id');

Documentation: https://lodash.com/docs#uniqBy


For older versions of Lodash (< 4.0.0 ):

Assuming that the data should be uniqued by each object's id property and your data is stored in data variable, you can use the _.unique() function like this:

_.unique(data, function (e) {
  return e.id;
});

Or simply like this:

_.uniq(data, 'id');

How to get integer values from a string in Python?

An answer taken from ChristopheD here: https://stackoverflow.com/a/2500023/1225603

r = "456results string789"
s = ''.join(x for x in r if x.isdigit())
print int(s)
456789

diff current working copy of a file with another branch's committed copy

The following works for me:

git diff master:foo foo

In the past, it may have been:

git diff foo master:foo

Changing the selected option of an HTML Select element

You can change the value of the select element, which changes the selected option to the one with that value, using JavaScript:

document.getElementById('sel').value = 'bike';??????????

DEMO

css rotate a pseudo :after or :before content:""

.process-list:after{
    content: "\2191";
    position: absolute;
    top:50%;
    right:-8px;
    background-color: #ea1f41;
    width:35px;
    height: 35px;
    border:2px solid #ffffff;
    border-radius: 5px;
    color: #ffffff;
    z-index: 10000;
    -webkit-transform: rotate(50deg) translateY(-50%);
    -moz-transform: rotate(50deg) translateY(-50%);
    -ms-transform: rotate(50deg) translateY(-50%);
    -o-transform: rotate(50deg) translateY(-50%);
    transform: rotate(50deg) translateY(-50%);
}

you can check this code . i hope you will easily understand.

How to upgrade pip3?

In Ubuntu 18.04, below are the steps that I followed.

python3 -m pip install --upgrade pip

For some reason you will be getting an error, and that be fixed by making bash forget the wrongly referenced locations using the following command.

hash -r pip

Unable to run Java code with Intellij IDEA

-First Move Your Code Files in side the "src" Folder

-Make sure your Main method is declared like the following

   public class Main {
         public static void main(String []args){


       }
    }

then:

  • Go to Project configurations
  • select Java application,
  • check allow parallel run
  • and select your main class

and it should work

Access Https Rest Service using Spring RestTemplate

Here is what I ended up with for the similar problem. The idea is the same as in @Avi's answer, but I also wanted to avoid the static "System.setProperty("https.protocols", "TLSv1");", so that any adjustments won't affect the system. Inspired by an answer from here http://www.coderanch.com/t/637177/Security/Disabling-handshake-message-Java

public class MyCustomClientHttpRequestFactory extends SimpleClientHttpRequestFactory {

@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
    try {
        if (!(connection instanceof HttpsURLConnection)) {
            throw new RuntimeException("An instance of HttpsURLConnection is expected");
        }

        HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;

        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    }

                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }

                }
        };
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory()));

        httpsConnection.setHostnameVerifier((hostname, session) -> true);

        super.prepareConnection(httpsConnection, httpMethod);
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

/**
 * We need to invoke sslSocket.setEnabledProtocols(new String[] {"SSLv3"});
 * see http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html (Java 8 section)
 */
private static class MyCustomSSLSocketFactory extends SSLSocketFactory {

    private final SSLSocketFactory delegate;

    public MyCustomSSLSocketFactory(SSLSocketFactory delegate) {
        this.delegate = delegate;
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return delegate.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return delegate.getSupportedCipherSuites();
    }

    @Override
    public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException {
        final Socket underlyingSocket = delegate.createSocket(socket, host, port, autoClose);
        return overrideProtocol(underlyingSocket);
    }

    @Override
    public Socket createSocket(final String host, final int port) throws IOException {
        final Socket underlyingSocket = delegate.createSocket(host, port);
        return overrideProtocol(underlyingSocket);
    }

    @Override
    public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort) throws IOException {
        final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
        return overrideProtocol(underlyingSocket);
    }

    @Override
    public Socket createSocket(final InetAddress host, final int port) throws IOException {
        final Socket underlyingSocket = delegate.createSocket(host, port);
        return overrideProtocol(underlyingSocket);
    }

    @Override
    public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress, final int localPort) throws IOException {
        final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
        return overrideProtocol(underlyingSocket);
    }

    private Socket overrideProtocol(final Socket socket) {
        if (!(socket instanceof SSLSocket)) {
            throw new RuntimeException("An instance of SSLSocket is expected");
        }
        ((SSLSocket) socket).setEnabledProtocols(new String[] {"SSLv3"});
        return socket;
    }
}
}

Is a GUID unique 100% of the time?

While each generated GUID is not guaranteed to be unique, the total number of unique keys (2128 or 3.4×1038) is so large that the probability of the same number being generated twice is very small. For example, consider the observable universe, which contains about 5×1022 stars; every star could then have 6.8×1015 universally unique GUIDs.

From Wikipedia.


These are some good articles on how a GUID is made (for .NET) and how you could get the same guid in the right situation.

https://ericlippert.com/2012/04/24/guid-guide-part-one/

https://ericlippert.com/2012/04/30/guid-guide-part-two/

https://ericlippert.com/2012/05/07/guid-guide-part-three/

??

Jquery Ajax Posting json to webservice

I have query,

$("#login-button").click(function(e){ alert("hiii");

        var username = $("#username-field").val();
        var password = $("#username-field").val();

        alert(username);
        alert("password" + password);



        var markers = { "userName" : "admin","password" : "admin123"};
        $.ajax({
            type: "POST",
            url: url,
            // The key needs to match your method's input parameter (case-sensitive).
            data: JSON.stringify(markers),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data){alert("got the data"+data);},
            failure: function(errMsg) {
                alert(errMsg);
            }
        });

    });

I'm posting the the login details in json and getting a string as "Success",but I'm not getting the response.

onclick open window and specific size

window.open ("http://www.javascript-coder.com",
"mywindow","menubar=1,resizable=1,width=350,height=250");

from

http://www.javascript-coder.com/window-popup/javascript-window-open.phtml

:]

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

Some version working

<div class="hidden-xs">Only Mobile hidden</div>
<div class="visible-xs">Only Mobile visible</div>

How do I get the offset().top value of an element without using jQuery?

Seems you can just use the prop method on the angular element:

var top = $el.prop('offsetTop');

Works for me. Does anyone know any downside to this?

How to get exception message in Python properly

from traceback import format_exc


try:
    fault = 10/0
except ZeroDivision:
    print(format_exc())

Another possibility is to use the format_exc() method from the traceback module.

Renaming a directory in C#

One already exists. If you cannot get over the "Move" syntax of the System.IO namespace. There is a static class FileSystem within the Microsoft.VisualBasic.FileIO namespace that has both a RenameDirectory and RenameFile already within it.

As mentioned by SLaks, this is just a wrapper for Directory.Move and File.Move.

Include PHP file into HTML file

You would have to configure your webserver to utilize PHP as handler for .html files. This is typically done by modifying your with AddHandler to include .html along with .php.

Note that this could have a performance impact as this would cause ALL .html files to be run through PHP handler even if there is no PHP involved. So you might strongly consider using .php extension on these files and adding a redirect as necessary to route requests to specific .html URL's to their .php equivalents.

Vertical Menu in Bootstrap

With Bootstrap 2.0 you can give your tabs the "stackable" class, which makes them stack vertically.

how to loop through rows columns in excel VBA Macro

Try this:

Create A Macro with the following thing inside:

Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(-1, 1).Select
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(0, -1).Select

That particular macro will copy the current cell (place your cursor in the VOL cell you wish to copy) down one row and then copy the CAP cell also.

This is only a single loop so you can automate copying VOL and CAP of where your current active cell (where your cursor is) to down 1 row.

Just put it inside a For loop statement to do it x number of times. like:

For i = 1 to 100 'Do this 100 times
    Selection.Copy
    ActiveCell.Offset(1, 0).Select
    ActiveSheet.Paste
    ActiveCell.Offset(-1, 1).Select
    Selection.Copy
    ActiveCell.Offset(1, 0).Select
    ActiveSheet.Paste
    ActiveCell.Offset(0, -1).Select
Next i

HTML5 event handling(onfocus and onfocusout) using angular 2

The solution is this:

  <input (click)="focusOut()" type="text" matInput [formControl]="inputControl"
  [matAutocomplete]="auto">
   <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn" >
     <mat-option (onSelectionChange)="submitValue($event)" *ngFor="let option of 
      options | async" [value]="option">
      {{option.name | translate}}
     </mat-option>
  </mat-autocomplete>

TS
focusOut() {
this.inputControl.disable();
this.inputControl.enable();
}

How can I resize an image dynamically with CSS as the browser width/height changes?

window.onresize = function(){
    var img = document.getElementById('fullsize');
    img.style.width = "100%";
};

In IE onresize event gets fired on every pixel change (width or height) so there could be performance issue. Delay image resizing for few milliseconds by using javascript's window.setTimeout().

http://mbccs.blogspot.com/2007/11/fixing-window-resize-event-in-ie.html

Open youtube video in Fancybox jquery

If you wanna add autoplay function to it. Simply replace

this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'), 

with

this.href = this.href.replace(new RegExp("watch\\?v=", "i"), 'v/') + '&autoplay=1',

also you can do the same with vimeo

this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1'),

with

this.href = this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1') + '&autoplay=1',

Where are $_SESSION variables stored?

They're generally stored on the server. Where they're stored is up to you as the developer. You can use the session.save_handler configuration variable and the session_set_save_handler to control how sessions get saved on the server. The default save method is to save sessions to files. Where they get saved is controlled by the session.save_path variable.

Rendering HTML elements to <canvas>

Take a look on MDN

It will render html element using creating SVG images.

For Example: There is <em>I</em> like <span style="color:white; text-shadow:0 0 2px blue;">cheese</span> HTML element. And I want to add it into <canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas> Canvas Element.

Here is Javascript Code to add HTML element to canvas.

_x000D_
_x000D_
var canvas = document.getElementById('canvas');_x000D_
var ctx = canvas.getContext('2d');_x000D_
_x000D_
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +_x000D_
  '<foreignObject width="100%" height="100%">' +_x000D_
  '<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +_x000D_
  '<em>I</em> like <span style="color:white; text-shadow:0 0 2px blue;">cheese</span>' +_x000D_
  '</div>' +_x000D_
  '</foreignObject>' +_x000D_
  '</svg>';_x000D_
_x000D_
var DOMURL = window.URL || window.webkitURL || window;_x000D_
_x000D_
var img = new Image();_x000D_
var svg = new Blob([data], {_x000D_
  type: 'image/svg+xml;charset=utf-8'_x000D_
});_x000D_
var url = DOMURL.createObjectURL(svg);_x000D_
_x000D_
img.onload = function() {_x000D_
  ctx.drawImage(img, 0, 0);_x000D_
  DOMURL.revokeObjectURL(url);_x000D_
}_x000D_
_x000D_
img.src = url;
_x000D_
<canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas>
_x000D_
_x000D_
_x000D_

How to know if docker is already logged in to a docker registry server

You can do the following command to see the username you are logged in with and the registry used:

docker system info | grep -E 'Username|Registry'

BigDecimal to string

The BigDecimal can not be a double. you can use Int number. if you want to display exactly own number, you can use the String constructor of BigDecimal .

like this:

BigDecimal bd1 = new BigDecimal("10.0001");

now, you can display bd1 as 10.0001

So simple. GOOD LUCK.

How to return images in flask response?

You use something like

from flask import send_file

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename, mimetype='image/gif')

to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

Difference between git pull and git pull --rebase

In the very most simple case of no collisions

  • with rebase: rebases your local commits ontop of remote HEAD and does not create a merge/merge commit
  • without/normal: merges and creates a merge commit

See also:

man git-pull

More precisely, git pull runs git fetch with the given parameters and calls git merge to merge the retrieved branch heads into the current branch. With --rebase, it runs git rebase instead of git merge.

See also:
When should I use git pull --rebase?
http://git-scm.com/book/en/Git-Branching-Rebasing

UML class diagram enum

Typically you model the enum itself as a class with the enum stereotype

Why .NET String is immutable?

  1. Instances of immutable types are inherently thread-safe, since no thread can modify it, the risk of a thread modifying it in a way that interferes with another is removed (the reference itself is a different matter).
  2. Similarly, the fact that aliasing can't produce changes (if x and y both refer to the same object a change to x entails a change to y) allows for considerable compiler optimisations.
  3. Memory-saving optimisations are also possible. Interning and atomising being the most obvious examples, though we can do other versions of the same principle. I once produced a memory saving of about half a GB by comparing immutable objects and replacing references to duplicates so that they all pointed to the same instance (time-consuming, but a minute's extra start-up to save a massive amount of memory was a performance win in the case in question). With mutable objects that can't be done.
  4. No side-effects can come from passing an immutable type as a method to a parameter unless it is out or ref (since that changes the reference, not the object). A programmer therefore knows that if string x = "abc" at the start of a method, and that doesn't change in the body of the method, then x == "abc" at the end of the method.
  5. Conceptually, the semantics are more like value types; in particular equality is based on state rather than identity. This means that "abc" == "ab" + "c". While this doesn't require immutability, the fact that a reference to such a string will always equal "abc" throughout its lifetime (which does require immutability) makes uses as keys where maintaining equality to previous values is vital, much easier to ensure correctness of (strings are indeed commonly used as keys).
  6. Conceptually, it can make more sense to be immutable. If we add a month onto Christmas, we haven't changed Christmas, we have produced a new date in late January. It makes sense therefore that Christmas.AddMonths(1) produces a new DateTime rather than changing a mutable one. (Another example, if I as a mutable object change my name, what has changed is which name I am using, "Jon" remains immutable and other Jons will be unaffected.
  7. Copying is fast and simple, to create a clone just return this. Since the copy can't be changed anyway, pretending something is its own copy is safe.
  8. [Edit, I'd forgotten this one]. Internal state can be safely shared between objects. For example, if you were implementing list which was backed by an array, a start index and a count, then the most expensive part of creating a sub-range would be copying the objects. However, if it was immutable then the sub-range object could reference the same array, with only the start index and count having to change, with a very considerable change to construction time.

In all, for objects which don't have undergoing change as part of their purpose, there can be many advantages in being immutable. The main disadvantage is in requiring extra constructions, though even here it's often overstated (remember, you have to do several appends before StringBuilder becomes more efficient than the equivalent series of concatenations, with their inherent construction).

It would be a disadvantage if mutability was part of the purpose of an object (who'd want to be modeled by an Employee object whose salary could never ever change) though sometimes even then it can be useful (in a many web and other stateless applications, code doing read operations is separate from that doing updates, and using different objects may be natural - I wouldn't make an object immutable and then force that pattern, but if I already had that pattern I might make my "read" objects immutable for the performance and correctness-guarantee gain).

Copy-on-write is a middle ground. Here the "real" class holds a reference to a "state" class. State classes are shared on copy operations, but if you change the state, a new copy of the state class is created. This is more often used with C++ than C#, which is why it's std:string enjoys some, but not all, of the advantages of immutable types, while remaining mutable.

Get program execution time in the shell

Use the built-in time keyword:

$ help time

time: time [-p] PIPELINE
    Execute PIPELINE and print a summary of the real time, user CPU time,
    and system CPU time spent executing PIPELINE when it terminates.
    The return status is the return status of PIPELINE.  The `-p' option
    prints the timing summary in a slightly different format.  This uses
    the value of the TIMEFORMAT variable as the output format.

Example:

$ time sleep 2
real    0m2.009s
user    0m0.000s
sys     0m0.004s

How do you display a Toast from a background thread on Android?

I made this approach based on mjaggard answer:

public static void toastAnywhere(final String text) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        public void run() {
            Toast.makeText(SuperApplication.getInstance().getApplicationContext(), text, 
                    Toast.LENGTH_LONG).show();
        }
    });
}

Worked well for me.

Copy a file list as text from Windows Explorer

If you paste the listing into your word processor instead of Notepad, (since each file name is in quotation marks with the full path name), you can highlight all the stuff you don't want on the first file, then use Find and Replace to replace every occurrence of that with nothing. Same with the ending quote (").

It makes a nice clean list of file names.

How to Exit a Method without Exiting the Program?

The basic problem here is that you are mistaking System.Environment.Exit for return.

Is there a way to get the git root directory in one command?

As others have noted, the core of the solution is to use git rev-parse --show-cdup. However, there are a few of edge cases to address:

  1. When the cwd already is the root of the working tree, the command yields an empty string.
    Actually it produces an empty line, but command substitution strip off the trailing line break. The final result is an empty string.

    Most answers suggest prepending the output with ./ so that an empty output becomes "./" before it is fed to cd.

  2. When GIT_WORK_TREE is set to a location that is not the parent of the cwd, the output may be an absolute pathname.

    Prepending ./ is wrong in this situation. If a ./ is prepended to an absolute path, it becomes a relative path (and they only refer to the same location if the cwd is the root directory of the system).

  3. The output may contain whitespace.

    This really only applies in the second case, but it has an easy fix: use double quotes around the command substitution (and any subsequent uses of the value).

As other answers have noted, we can do cd "./$(git rev-parse --show-cdup)", but this breaks in the second edge case (and the third edge case if we leave off the double quotes).

Many shells treat cd "" as a no-op, so for those shells we could do cd "$(git rev-parse --show-cdup)" (the double quotes protect the empty string as an argument in the first edge case, and preserve whitespace in the third edge case). POSIX says the result of cd "" is unspecified, so it may be best to avoid making this assumption.

A solution that works in all of the above cases requires a test of some sort. Done explicitly, it might look like this:

cdup="$(git rev-parse --show-cdup)" && test -n "$cdup" && cd "$cdup"

No cd is done for the first edge case.

If it is acceptable to run cd . for the first edge case, then the conditional can be done in the expansion of the parameter:

cdup="$(git rev-parse --show-cdup)" && cd "${cdup:-.}"

Get everything after and before certain character in SQL Server

SELECT SUBSTRING('[email protected]',1,(CHARINDEX('@','[email protected]')-1)) Before, RIGHT('[email protected]',(CHARINDEX('@','[email protected]')+1)) After

Android difference between Two Dates

Short & Sweet:

/**
 * Get a diff between two dates
 *
 * @param oldDate the old date
 * @param newDate the new date
 * @return the diff value, in the days
 */
public static long getDateDiff(SimpleDateFormat format, String oldDate, String newDate) {
    try {
        return TimeUnit.DAYS.convert(format.parse(newDate).getTime() - format.parse(oldDate).getTime(), TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

Usage:

int dateDifference = (int) getDateDiff(new SimpleDateFormat("dd/MM/yyyy"), "29/05/2017", "31/05/2017");
System.out.println("dateDifference: " + dateDifference);

Output:

dateDifference: 2

Kotlin Version:

@ExperimentalTime
fun getDateDiff(format: SimpleDateFormat, oldDate: String, newDate: String): Long {
    return try {
        DurationUnit.DAYS.convert(
            format.parse(newDate).time - format.parse(oldDate).time,
            DurationUnit.MILLISECONDS
        )
    } catch (e: Exception) {
        e.printStackTrace()
        0
    }
}

How can I print out C++ map values?

If your compiler supports (at least part of) C++11 you could do something like:

for (auto& t : myMap)
    std::cout << t.first << " " 
              << t.second.first << " " 
              << t.second.second << "\n";

For C++03 I'd use std::copy with an insertion operator instead:

typedef std::pair<string, std::pair<string, string> > T;

std::ostream &operator<<(std::ostream &os, T const &t) { 
    return os << t.first << " " << t.second.first << " " << t.second.second;
}

// ...
std:copy(myMap.begin(), myMap.end(), std::ostream_iterator<T>(std::cout, "\n"));

How to set the default value of an attribute on a Laravel model

The other answers are not working for me - they may be outdated. This is what I used as my solution for auto setting an attribute:

/**
 * The "booting" method of the model.
 *
 * @return void
 */
protected static function boot()
{
    parent::boot();

    // auto-sets values on creation
    static::creating(function ($query) {
        $query->is_voicemail = $query->is_voicemail ?? true;
    });
}

SQL SELECT WHERE field contains words

Note that if you use LIKE to determine if a string is a substring of another string, you must escape the pattern matching characters in your search string.

If your SQL dialect supports CHARINDEX, it's a lot easier to use it instead:

SELECT * FROM MyTable
WHERE CHARINDEX('word1', Column1) > 0
  AND CHARINDEX('word2', Column1) > 0
  AND CHARINDEX('word3', Column1) > 0

Also, please keep in mind that this and the method in the accepted answer only cover substring matching rather than word matching. So, for example, the string 'word1word2word3' would still match.

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

Yes, this is possible and I would like to provide a slight alternative to Rajeev's answer that does not pass a php-generated datetime formatted string to the query.

The important distinction about how to declare the values to be SET in the UPDATE query is that they must not be quoted as literal strings.

To prevent CodeIgniter from doing this "favor" automatically, use the set() method with a third parameter of false.

$userId = 444;
$this->db->set('Last', 'Current', false);
$this->db->set('Current', 'NOW()', false);
$this->db->where('Id', $userId);
// return $this->db->get_compiled_update('Login');  // uncomment to see the rendered query
$this->db->update('Login');
return $this->db->affected_rows();  // this is expected to return the integer: 1

The generated query (depending on your database adapter) would be like this:

UPDATE `Login` SET Last = Current, Current = NOW() WHERE `Id` = 444

Demonstrated proof that the query works: https://www.db-fiddle.com/f/vcc6PfMcYhDD87wZE5gBtw/0

In this case, Last and Current ARE MySQL Keywords, but they are not Reserved Keywords, so they don't need to be backtick-wrapped.

If your precise query needs to have properly quoted identifiers (table/column names), then there is always protectIdentifiers().

Install specific branch from github using Npm

The Doc of the npm defines that only tag/version can be specified after repo_url.

Here is the Doc: https://docs.npmjs.com/cli/install

How set maximum date in datepicker dialog in android?

Get today's date (& time) and apply them as maximum date.

Calendar c = Calendar.getInstance();
c.set(2017, 0, 1);//Year,Mounth -1,Day
your_date_picker.setMaxDate(c.getTimeInMillis());

ALSO WE MAY DO THIS (check this Stackoverflow answer for System.currentTimeMillis() vs Calendar method)

long now = System.currentTimeMillis() - 1000;
dp_time.setMinDate(now);
dp_time.setMaxDate(now+(1000*60*60*24*7)); //After 7 Days from Now

Mocking HttpClient in unit tests

DO NOT have a wrapper that creates a new instance of HttpClient. If you do that, you will run out of sockets at runtime (even though you are disposing the HttpClient object).

If using MOQ, the correct way to do this is to add using Moq.Protected; to your test and then write code like the following:

var response = new HttpResponseMessage(HttpStatusCode.OK)
{
    Content = new StringContent("It worked!")
};
var mockHttpMessageHandler = new Mock<HttpMessageHandler>();
mockHttpMessageHandler
    .Protected()
    .Setup<Task<HttpResponseMessage>>(
        "SendAsync",
        ItExpr.IsAny<HttpRequestMessage>(),
        ItExpr.IsAny<CancellationToken>())
    .ReturnsAsync(() => response);


var httpClient = new HttpClient(mockHttpMessageHandler.Object);

Best way to store passwords in MYSQL database

best to use crypt for password storing in DB

example code :

$crypted_pass = crypt($password);

//$pass_from_login is the user entered password
//$crypted_pass is the encryption
if(crypt($pass_from_login,$crypted_pass)) == $crypted_pass)
{
   echo("hello user!")
}

documentation :

http://www.php.net/manual/en/function.crypt.php

How to fix libeay32.dll was not found error

Download libeay32.dll and ssleay32.dll binary package for 32Bit and 64Bit from http://indy.fulgan.com/SSL/ then put it into executable or System32 directory.

Checking for NULL pointer in C/C++

I use if (ptr), but this is completely not worth arguing about.

I like my way because it's concise, though others say == NULL makes it easier to read and more explicit. I see where they're coming from, I just disagree the extra stuff makes it any easier. (I hate the macro, so I'm biased.) Up to you.

I disagree with your argument. If you're not getting warnings for assignments in a conditional, you need to turn your warning levels up. Simple as that. (And for the love of all that is good, don't switch them around.)

Note in C++0x, we can do if (ptr == nullptr), which to me does read nicer. (Again, I hate the macro. But nullptr is nice.) I still do if (ptr), though, just because it's what I'm used to.

Access-Control-Allow-Origin wildcard subdomains, ports and protocols

We were having similar issues with Font Awesome on a static "cookie-less" domain when reading fonts from the "cookie domain" (www.domain.tld) and this post was our hero. See here: How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

For the copy/paste-r types (and to give some props) I pieced this together from all the contributions and added it to the top of the .htaccess file of the site root:

<IfModule mod_headers.c>
 <IfModule mod_rewrite.c>
    SetEnvIf Origin "http(s)?://(.+\.)?(othersite\.com|mywebsite\.com)(:\d{1,5})?$" CORS=$0
    Header set Access-Control-Allow-Origin "%{CORS}e" env=CORS
    Header merge  Vary "Origin"
 </IfModule>
</IfModule>

Super Secure, Super Elegant. Love it: You don't have to open up your servers bandwidth to resource thieves / hot-link-er types.

Props to:@Noyo @DaveRandom @pratap-koritala

(I tried to leave this as a comment to the accepted answer, but I can't do that yet)

MongoDB vs Firebase

In my experience, working with Firebase is a huge advantage if you are trying to do user management, database, messaging sort of app since all of these features are already well integrated.

Like others have said, if you're just focused on the database/querying aspect, stick to mongo.

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

You are passing floats to a classifier which expects categorical values as the target vector. If you convert it to int it will be accepted as input (although it will be questionable if that's the right way to do it).

It would be better to convert your training scores by using scikit's labelEncoder function.

The same is true for your DecisionTree and KNeighbors qualifier.

from sklearn import preprocessing
from sklearn import utils

lab_enc = preprocessing.LabelEncoder()
encoded = lab_enc.fit_transform(trainingScores)
>>> array([1, 3, 2, 0], dtype=int64)

print(utils.multiclass.type_of_target(trainingScores))
>>> continuous

print(utils.multiclass.type_of_target(trainingScores.astype('int')))
>>> multiclass

print(utils.multiclass.type_of_target(encoded))
>>> multiclass

JSON encode MySQL results

The above will not work, in my experience, before you name the root-element in the array to something, I have not been able to access anything in the final json before that.

$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $rows['root_name'] = $r;
}
print json_encode($rows);

That should do the trick!

jQuery: get parent, parent id?

 $(this).closest('ul').attr('id');

Where can I find a list of Mac virtual key codes?

Here are the all keycodes.

Here is a table with some keycodes for the three platforms. It is based on a US Extended keyboard layout.

http://web.archive.org/web/20100501161453/http://www.classicteck.com/rbarticles/mackeyboard.php

Or, there is an app in the Mac App Store named "Key Codes". Download it to see the keycodes of the keys you press.

Key Codes:
https://itunes.apple.com/tr/app/key-codes/id414568915?l=tr&mt=12

Why is there no SortedList in Java?

Think of it like this: the List interface has methods like add(int index, E element), set(int index, E element). The contract is that once you added an element at position X you will find it there unless you add or remove elements before it.

If any list implementation would store elements in some order other than based on the index, the above list methods would make no sense.

How to search for file names in Visual Studio?

The best option now is to install Microsoft Visual Studio add on called Productivity Power Tools (VS 2010 version, VS 2013 version).

With this comes "Solution Navigator" (alternative to Solution Explorer, with a lot of benefits).

search solution navigator

BTW, this feature is built-in into Visual Studio 2012.

How to Join to first row

Correlated sub queries are sub queries that depend on the outer query. It’s like a for loop in SQL. The sub-query will run once for each row in the outer query:

select * from users join widgets on widgets.id = (
    select id from widgets
    where widgets.user_id = users.id
    order by created_at desc
    limit 1
)

Check if string contains only letters in javascript

With /^[a-zA-Z]/ you only check the first character:

  • ^: Assert position at the beginning of the string
  • [a-zA-Z]: Match a single character present in the list below:
    • a-z: A character in the range between "a" and "z"
    • A-Z: A character in the range between "A" and "Z"

If you want to check if all characters are letters, use this instead:

/^[a-zA-Z]+$/.test(str);
  • ^: Assert position at the beginning of the string
  • [a-zA-Z]: Match a single character present in the list below:
    • +: Between one and unlimited times, as many as possible, giving back as needed (greedy)
    • a-z: A character in the range between "a" and "z"
    • A-Z: A character in the range between "A" and "Z"
  • $: Assert position at the end of the string (or before the line break at the end of the string, if any)

Or, using the case-insensitive flag i, you could simplify it to

/^[a-z]+$/i.test(str);

Or, since you only want to test, and not match, you could check for the opposite, and negate it:

!/[^a-z]/i.test(str);

Finding the max value of an attribute in an array of objects

if you (or, someone here) are free to use lodash utility library, it has a maxBy function which would be very handy in your case.

hence you can use as such:

_.maxBy(jsonSlice, 'y');

Add to Array jQuery

You are right. This has nothing to do with jQuery though.

var myArray = [];
myArray.push("foo");
// myArray now contains "foo" at index 0.

How can I tell what edition of SQL Server runs on the machine?

You can get just the edition (plus under individual properties) using SERVERPROPERTY

e.g.

SELECT SERVERPROPERTY('Edition')

Quote (for "Edition"):

Installed product edition of the instance of SQL Server. Use the value of this property to determine the features and the limits, such as maximum number of CPUs, that are supported by the installed product.
Returns:
'Desktop Engine' (Not available for SQL Server 2005.)
'Developer Edition'
'Enterprise Edition'
'Enterprise Evaluation Edition'
'Personal Edition'(Not available for SQL Server 2005.)
'Standard Edition'
'Express Edition'
'Express Edition with Advanced Services'
'Workgroup Edition'
'Windows Embedded SQL'
Base data type: nvarchar(128)

javascript regular expression to not match a word

This can be done in 2 ways:

if (str.match(/abc|def/)) {
                       ...
                    }


if (/abc|def/.test(str)) {
                        ....
                    } 

PostgreSQL psql terminal command

psql --pset=format=FORMAT

Great for executing queries from command line, e.g.

psql --pset=format=unaligned -c "select bandanavalue from bandana where bandanakey = 'atlassian.confluence.settings';"

Multiple aggregations of the same column using pandas GroupBy.agg()

Would something like this work:

In [7]: df.groupby('dummy').returns.agg({'func1' : lambda x: x.sum(), 'func2' : lambda x: x.prod()})
Out[7]: 
              func2     func1
dummy                        
1     -4.263768e-16 -0.188565

How to check if two arrays are equal with JavaScript?

Based on Tim James answer and Fox32's comment, the following should check for nulls, with the assumption that two nulls are not equal.

function arrays_equal(a,b) { return !!a && !!b && !(a<b || b<a); }

> arrays_equal([1,2,3], [1,3,4])
false
> arrays_equal([1,2,3], [1,2,3])
true
> arrays_equal([1,3,4], [1,2,3])
false
> arrays_equal(null, [1,2,3])
false
> arrays_equal(null, null)
false

Delegation: EventEmitter or Observable in Angular

Update 2016-06-27: instead of using Observables, use either

  • a BehaviorSubject, as recommended by @Abdulrahman in a comment, or
  • a ReplaySubject, as recommended by @Jason Goemaat in a comment

A Subject is both an Observable (so we can subscribe() to it) and an Observer (so we can call next() on it to emit a new value). We exploit this feature. A Subject allows values to be multicast to many Observers. We don't exploit this feature (we only have one Observer).

BehaviorSubject is a variant of Subject. It has the notion of "the current value". We exploit this: whenever we create an ObservingComponent, it gets the current navigation item value from the BehaviorSubject automatically.

The code below and the plunker use BehaviorSubject.

ReplaySubject is another variant of Subject. If you want to wait until a value is actually produced, use ReplaySubject(1). Whereas a BehaviorSubject requires an initial value (which will be provided immediately), ReplaySubject does not. ReplaySubject will always provide the most recent value, but since it does not have a required initial value, the service can do some async operation before returning it's first value. It will still fire immediately on subsequent calls with the most recent value. If you just want one value, use first() on the subscription. You do not have to unsubscribe if you use first().

import {Injectable}      from '@angular/core'
import {BehaviorSubject} from 'rxjs/BehaviorSubject';

@Injectable()
export class NavService {
  // Observable navItem source
  private _navItemSource = new BehaviorSubject<number>(0);
  // Observable navItem stream
  navItem$ = this._navItemSource.asObservable();
  // service command
  changeNav(number) {
    this._navItemSource.next(number);
  }
}
import {Component}    from '@angular/core';
import {NavService}   from './nav.service';
import {Subscription} from 'rxjs/Subscription';

@Component({
  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
})
export class ObservingComponent {
  item: number;
  subscription:Subscription;
  constructor(private _navService:NavService) {}
  ngOnInit() {
    this.subscription = this._navService.navItem$
       .subscribe(item => this.item = item)
  }
  ngOnDestroy() {
    // prevent memory leak when component is destroyed
    this.subscription.unsubscribe();
  }
}
@Component({
  selector: 'my-nav',
  template:`
    <div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
    <div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>`
})
export class Navigation {
  item = 1;
  constructor(private _navService:NavService) {}
  selectedNavItem(item: number) {
    console.log('selected nav item ' + item);
    this._navService.changeNav(item);
  }
}

Plunker


Original answer that uses an Observable: (it requires more code and logic than using a BehaviorSubject, so I don't recommend it, but it may be instructive)

So, here's an implementation that uses an Observable instead of an EventEmitter. Unlike my EventEmitter implementation, this implementation also stores the currently selected navItem in the service, so that when an observing component is created, it can retrieve the current value via API call navItem(), and then be notified of changes via the navChange$ Observable.

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/share';
import {Observer} from 'rxjs/Observer';

export class NavService {
  private _navItem = 0;
  navChange$: Observable<number>;
  private _observer: Observer;
  constructor() {
    this.navChange$ = new Observable(observer =>
      this._observer = observer).share();
    // share() allows multiple subscribers
  }
  changeNav(number) {
    this._navItem = number;
    this._observer.next(number);
  }
  navItem() {
    return this._navItem;
  }
}

@Component({
  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
})
export class ObservingComponent {
  item: number;
  subscription: any;
  constructor(private _navService:NavService) {}
  ngOnInit() {
    this.item = this._navService.navItem();
    this.subscription = this._navService.navChange$.subscribe(
      item => this.selectedNavItem(item));
  }
  selectedNavItem(item: number) {
    this.item = item;
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

@Component({
  selector: 'my-nav',
  template:`
    <div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
    <div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>
  `,
})
export class Navigation {
  item:number;
  constructor(private _navService:NavService) {}
  selectedNavItem(item: number) {
    console.log('selected nav item ' + item);
    this._navService.changeNav(item);
  }
}

Plunker


See also the Component Interaction Cookbook example, which uses a Subject in addition to observables. Although the example is "parent and children communication," the same technique is applicable for unrelated components.

Customizing the template within a Directive

Here's what I ended up using.

I'm very new to AngularJS, so would love to see better / alternative solutions.

angular.module('formComponents', [])
    .directive('formInput', function() {
        return {
            restrict: 'E',
            scope: {},
            link: function(scope, element, attrs)
            {
                var type = attrs.type || 'text';
                var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
                var htmlText = '<div class="control-group">' +
                    '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                        '<div class="controls">' +
                        '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                        '</div>' +
                    '</div>';
                element.html(htmlText);
            }
        }
    })

Example usage:

<form-input label="Application Name" form-id="appName" required/></form-input>
<form-input type="email" label="Email address" form-id="emailAddress" required/></form-input>
<form-input type="password" label="Password" form-id="password" /></form-input>

How should the ViewModel close the form?

Here is the simple bug free solution (with source code), It is working for me.

  1. Derive your ViewModel from INotifyPropertyChanged

  2. Create a observable property CloseDialog in ViewModel

    public void Execute()
    {
        // Do your task here
    
        // if task successful, assign true to CloseDialog
        CloseDialog = true;
    }
    
    private bool _closeDialog;
    public bool CloseDialog
    {
        get { return _closeDialog; }
        set { _closeDialog = value; OnPropertyChanged(); }
    }
    
    public event PropertyChangedEventHandler PropertyChanged;
    
    private void OnPropertyChanged([CallerMemberName]string property = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
    

    }

  3. Attach a Handler in View for this property change

        _loginDialogViewModel = new LoginDialogViewModel();
        loginPanel.DataContext = _loginDialogViewModel;
        _loginDialogViewModel.PropertyChanged += OnPropertyChanged;
    
  4. Now you are almost done. In the event handler make DialogResult = true

    protected void OnPropertyChanged(object sender, PropertyChangedEventArgs args)
    {
        if (args.PropertyName == "CloseDialog")
        {
            DialogResult = true;
        }
    }
    

Python matplotlib multiple bars

I know that this is about matplotlib, but using pandas and seaborn can save you a lot of time:

df = pd.DataFrame(zip(x*3, ["y"]*3+["z"]*3+["k"]*3, y+z+k), columns=["time", "kind", "data"])
plt.figure(figsize=(10, 6))
sns.barplot(x="time", hue="kind", y="data", data=df)
plt.show()

enter image description here

Is there a CSS selector for text nodes?

Text nodes cannot have margins or any other style applied to them, so anything you need style applied to must be in an element. If you want some of the text inside of your element to be styled differently, wrap it in a span or div, for example.

How to prevent the "Confirm Form Resubmission" dialog?

After processing the POST page, redirect the user to the same page.

On http://test.com/test.php

header('Location: http://test.com/test.php');

This will get rid of the box, as refreshing the page will not resubmit the data.

Assert that a WebElement is not present using Selenium WebDriver with java

The way that I have found best - and also to show in Allure report as fail - is to try-catch the findelement and in the catch block, set the assertTrue to false, like this:

    try {
        element = driver.findElement(By.linkText("Test Search"));
    }catch(Exception e) {
        assertTrue(false, "Test Search link was not displayed");
    }

How does the 'binding' attribute work in JSF? When and how should it be used?

How does it work?

When a JSF view (Facelets/JSP file) get built/restored, a JSF component tree will be produced. At that moment, the view build time, all binding attributes are evaluated (along with id attribtues and taghandlers like JSTL). When the JSF component needs to be created before being added to the component tree, JSF will check if the binding attribute returns a precreated component (i.e. non-null) and if so, then use it. If it's not precreated, then JSF will autocreate the component "the usual way" and invoke the setter behind binding attribute with the autocreated component instance as argument.

In effects, it binds a reference of the component instance in the component tree to a scoped variable. This information is in no way visible in the generated HTML representation of the component itself. This information is in no means relevant to the generated HTML output anyway. When the form is submitted and the view is restored, the JSF component tree is just rebuilt from scratch and all binding attributes will just be re-evaluated like described in above paragraph. After the component tree is recreated, JSF will restore the JSF view state into the component tree.

Component instances are request scoped!

Important to know and understand is that the concrete component instances are effectively request scoped. They're newly created on every request and their properties are filled with values from JSF view state during restore view phase. So, if you bind the component to a property of a backing bean, then the backing bean should absolutely not be in a broader scope than the request scope. See also JSF 2.0 specitication chapter 3.1.5:

3.1.5 Component Bindings

...

Component bindings are often used in conjunction with JavaBeans that are dynamically instantiated via the Managed Bean Creation facility (see Section 5.8.1 “VariableResolver and the Default VariableResolver”). It is strongly recommend that application developers place managed beans that are pointed at by component binding expressions in “request” scope. This is because placing it in session or application scope would require thread-safety, since UIComponent instances depends on running inside of a single thread. There are also potentially negative impacts on memory management when placing a component binding in “session” scope.

Otherwise, component instances are shared among multiple requests, possibly resulting in "duplicate component ID" errors and "weird" behaviors because validators, converters and listeners declared in the view are re-attached to the existing component instance from previous request(s). The symptoms are clear: they are executed multiple times, one time more with each request within the same scope as the component is been bound to.

And, under heavy load (i.e. when multiple different HTTP requests (threads) access and manipulate the very same component instance at the same time), you may face sooner or later an application crash with e.g. Stuck thread at UIComponent.popComponentFromEL, or Java Threads at 100% CPU utilization using richfaces UIDataAdaptorBase and its internal HashMap, or even some "strange" IndexOutOfBoundsException or ConcurrentModificationException coming straight from JSF implementation source code while JSF is busy saving or restoring the view state (i.e. the stack trace indicates saveState() or restoreState() methods and like).

Using binding on a bean property is bad practice

Regardless, using binding this way, binding a whole component instance to a bean property, even on a request scoped bean, is in JSF 2.x a rather rare use case and generally not the best practice. It indicates a design smell. You normally declare components in the view side and bind their runtime attributes like value, and perhaps others like styleClass, disabled, rendered, etc, to normal bean properties. Then, you just manipulate exactly that bean property you want instead of grabbing the whole component and calling the setter method associated with the attribute.

In cases when a component needs to be "dynamically built" based on a static model, better is to use view build time tags like JSTL, if necessary in a tag file, instead of createComponent(), new SomeComponent(), getChildren().add() and what not. See also How to refactor snippet of old JSP to some JSF equivalent?

Or, if a component needs to be "dynamically rendered" based on a dynamic model, then just use an iterator component (<ui:repeat>, <h:dataTable>, etc). See also How to dynamically add JSF components.

Composite components is a completely different story. It's completely legit to bind components inside a <cc:implementation> to the backing component (i.e. the component identified by <cc:interface componentType>. See also a.o. Split java.util.Date over two h:inputText fields representing hour and minute with f:convertDateTime and How to implement a dynamic list with a JSF 2.0 Composite Component?

Only use binding in local scope

However, sometimes you'd like to know about the state of a different component from inside a particular component, more than often in use cases related to action/value dependent validation. For that, the binding attribute can be used, but not in combination with a bean property. You can just specify an in the local EL scope unique variable name in the binding attribute like so binding="#{foo}" and the component is during render response elsewhere in the same view directly as UIComponent reference available by #{foo}. Here are several related questions where such a solution is been used in the answer:

See also:

Call Stored Procedure within Create Trigger in SQL Server

The following should do the trick - Only SqlServer


Alter TRIGGER Catagory_Master_Date_update ON Catagory_Master AFTER delete,Update
AS
BEGIN

SET NOCOUNT ON;

Declare @id int
DECLARE @cDate as DateTime
    set @cDate =(select Getdate())

select @id=deleted.Catagory_id from deleted
print @cDate

execute dbo.psp_Update_Category @id

END

Alter PROCEDURE dbo.psp_Update_Category
@id int
AS
BEGIN

DECLARE @cDate as DateTime
    set @cDate =(select Getdate())
    --Update Catagory_Master Set Modify_date=''+@cDate+'' Where Catagory_ID=@id   --@UserID
    Insert into Catagory_Master (Catagory_id,Catagory_Name) values(12,'Testing11')
END 

Find all files in a folder

You can try with Directory.GetFiles and fix your pattern

 string[] files = Directory.GetFiles(@"c:\", "*.txt");

 foreach (string file in files)
 {
    File.Copy(file, "....");
 }

 Or Move

 foreach (string file in files)
 {
    File.Move(file, "....");
 }     

http://msdn.microsoft.com/en-us/library/wz42302f

Radio buttons and label to display in same line

I was having the similar issue of keeping all radio buttons on the same line. After trying all the things I could, nothing worked for me except the following. What I mean is simply using table resolved the issue allowing radio buttons to appear in the same line.

<table>
<tr>
    <td>
        <label>
            @Html.RadioButton("p_sortForPatch", "byName", new { @checked = "checked", @class = "radio" }) By Name
        </label>
    </td>
    <td>
        <label>
            @Html.RadioButton("p_sortForPatch", "byDate", new { @class = "radio" }) By Date
        </label>
    </td>
</tr>
</table>

Converting String to Int using try/except in Python

Here it is:

s = "123"
try:
  i = int(s)
except ValueError as verr:
  pass # do job to handle: s does not contain anything convertible to int
except Exception as ex:
  pass # do job to handle: Exception occurred while converting to int

What's the difference between nohup and ampersand

The nohup command is a signal masking utility and catches the hangup signal. Where as ampersand doesn’t catch the hang up signals. The shell will terminate the sub command with the hang up signal when running a command using & and exiting the shell. This can be prevented by using nohup, as it catches the signal. Nohup command accept hang up signal which can be sent to a process by the kernel and block them. Nohup command is helpful in when a user wants to start long running application log out or close the window in which the process was initiated. Either of these actions normally prompts the kernel to hang up on the application, but a nohup wrapper will allow the process to continue. Using the ampersand will run the command in a child process and this child of the current bash session. When you exit the session, all of the child processes of that process will be killed. The ampersand relates to job control for the active shell. This is useful for running a process in a session in the background.

'mvn' is not recognized as an internal or external command, operable program or batch file

This problem arise because there is no any environmental variable corresponding to installed maven in your OS. For fixing this problem, I always use Intellij's bundled Maven and do not install separate version of Maven again, for finding bundled Maven's path go to intellij and hit Ctrl+Alt+S -> Build, Execution, Deployment -> Build tool -> Maven -> Maven home directory you can find the intellij's bundled maven path there as below image demonstrates.

enter image description here

Then go to System environment variables and set these variables:

Variable name: MAVEN_HOME

Variable value: C:/Program Files/JetBrains/IntelliJ IDEA 2019.3.1/plugins/maven/lib/maven3

enter image description here

After defining system variable MAVEN_HOME find variable path and add this line to the list

%MAVEN_HOME%\bin

enter image description here

Work is done, open command prompt and test it by writing mvn -v. 99 percent of the time it work, if you're among 1 percent, you have to restart your computer.

If you want to use mvn command from intellij's internal terminal you have to restart intellij after setting environment variables, then you shouldn't have any problem running maven command from terminal.

How to get the Enum Index value in C#

Another way to convert an Enum-Type to an int:

enum E
{
    A = 1,   /* index 0 */
    B = 2,   /* index 1 */
    C = 4,   /* index 2 */
    D = 4    /* index 3, duplicate use of 4 */
}

void Main()
{
    E e = E.C;
    int index = Array.IndexOf(Enum.GetValues(e.GetType()), e);
    // index is 2

    E f = (E)(Enum.GetValues(e.GetType())).GetValue(index);
    // f is  E.C
}

More complex but independent from the INT values assigned to the enum values.

How is using OnClickListener interface different via XML and Java code?

Even though you define android:onClick = "DoIt" in XML, you need to make sure your activity (or view context) has public method defined with exact same name and View as parameter. Android wires your definitions with this implementation in activity. At the end, implementation will have same code which you wrote in anonymous inner class. So, in simple words instead of having inner class and listener attachement in activity, you will simply have a public method with implementation code.

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

For all those people stuck with this problem, but still couldn't solve it: I stumbled upon the same error and found the _id field being empty.

I described it here in more detail. Still have not found a solution except changing the fields in _id to not-ID fields which is a dirty hack to me. I'm probably going to file a bug report for mongoose. Any help would be appreciated!

Edit: I updated my thread. I filed a ticket and they confirmed the missing _id problem. It is going to be fixed in the 4.x.x version which has a release candidate available right now. The rc is not recommended for productive use!

Batch file to run a command in cmd within a directory

You Can Also Check It:

cmd /c cd /d C:\activiti-5.9\setup & ant demo.start

python int( ) function

Integers (int for short) are the numbers you count with 0, 1, 2, 3 ... and their negative counterparts ... -3, -2, -1 the ones without the decimal part.

So once you introduce a decimal point, your not really dealing with integers. You're dealing with rational numbers. The Python float or decimal types are what you want to represent or approximate these numbers.

You may be used to a language that automatically does this for you(Php). Python, though, has an explicit preference for forcing code to be explicit instead implicit.

UNIX export command

Unix

The commands env, set, and printenv display all environment variables and their values. env and set are also used to set environment variables and are often incorporated directly into the shell. printenv can also be used to print a single variable by giving that variable name as the sole argument to the command.

In Unix, the following commands can also be used, but are often dependent on a certain shell.

export VARIABLE=value  # for Bourne, bash, and related shells
setenv VARIABLE value  # for csh and related shells

You can have a look at this at

Define an <img>'s src attribute in CSS

CSS is not used to define values to DOM element attributes, javascript would be more suitable for this.

When should an IllegalArgumentException be thrown?

The API doc for IllegalArgumentException:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

From looking at how it is used in the JDK libraries, I would say:

  • It seems like a defensive measure to complain about obviously bad input before the input can get into the works and cause something to fail halfway through with a nonsensical error message.

  • It's used for cases where it would be too annoying to throw a checked exception (although it makes an appearance in the java.lang.reflect code, where concern about ridiculous levels of checked-exception-throwing is not otherwise apparent).

I would use IllegalArgumentException to do last ditch defensive argument checking for common utilities (trying to stay consistent with the JDK usage). Or where the expectation is that a bad argument is a programmer error, similar to an NullPointerException. I wouldn't use it to implement validation in business code. I certainly wouldn't use it for the email example.

Convert string to Color in C#

 Color red = Color.FromName("Red");   

The MSDN doesn't say one way or another, so there's a good chance that it is case-sensitive. (UPDATE: Apparently, it is not.)

As far as I can tell, ColorTranslator.FromHtml is also.

If Color.FromName cannot find a match, it returns new Color(0,0,0);

If ColorTranslator.FromHtml cannot find a match, it throws an exception.

UPDATE:

Since you're using Microsoft.Xna.Framework.Graphics.Color, this gets a bit tricky:

using XColor = Microsoft.Xna.Framework.Graphics.Color;
using CColor = System.Drawing.Color;

 CColor clrColor = CColor.FromName("Red"); 
 XColor xColor = new XColor(clrColor.R, clrColor.G, clrColor.B, clrColor.A);

How to gracefully handle the SIGKILL signal in Java

I would expect that the JVM gracefully interrupts (thread.interrupt()) all the running threads created by the application, at least for signals SIGINT (kill -2) and SIGTERM (kill -15).

This way, the signal will be forwarded to them, allowing a gracefully thread cancellation and resource finalization in the standard ways.

But this is not the case (at least in my JVM implementation: Java(TM) SE Runtime Environment (build 1.8.0_25-b17), Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode).

As other users commented, the usage of shutdown hooks seems mandatory.

So, how do I would handle it?

Well first, I do not care about it in all programs, only in those where I want to keep track of user cancellations and unexpected ends. For example, imagine that your java program is a process managed by other. You may want to differentiate whether it has been terminated gracefully (SIGTERM from the manager process) or a shutdown has occurred (in order to relaunch automatically the job on startup).

As a basis, I always make my long-running threads periodically aware of interrupted status and throw an InterruptedException if they interrupted. This enables execution finalization in way controlled by the developer (also producing the same outcome as standard blocking operations). Then, at the top level of the thread stack, InterruptedException is captured and appropriate clean-up performed. These threads are coded to known how to respond to an interruption request. High cohesion design.

So, in these cases, I add a shutdown hook, that does what I think the JVM should do by default: interrupt all the non-daemon threads created by my application that are still running:

Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
        System.out.println("Interrupting threads");
        Set<Thread> runningThreads = Thread.getAllStackTraces().keySet();
        for (Thread th : runningThreads) {
            if (th != Thread.currentThread() 
                && !th.isDaemon() 
                && th.getClass().getName().startsWith("org.brutusin")) {
                System.out.println("Interrupting '" + th.getClass() + "' termination");
                th.interrupt();
            }
        }
        for (Thread th : runningThreads) {
            try {
                if (th != Thread.currentThread() 
                && !th.isDaemon() 
                && th.isInterrupted()) {
                    System.out.println("Waiting '" + th.getName() + "' termination");
                    th.join();
                }
            } catch (InterruptedException ex) {
                System.out.println("Shutdown interrupted");
            }
        }
        System.out.println("Shutdown finished");
    }
});

Complete test application at github: https://github.com/idelvall/kill-test

How to stop VMware port error of 443 on XAMPP Control Panel v3.2.1

Say you let vmware use port 443, and use another ssl port in XAMPP Apache (httpd-ssl.conf) :

The red error will keep popping in XAMPP Control Panel. You also need to change the port in the XAMPP Control Panel configuration :

In XAMPP Control Panel, click the "Config" button (top-left). Then click "Service and Port Settings". There you can set the ports to match the ports used by Apache.

Adding external library into Qt Creator project

The error you mean is due to missing additional include path. Try adding it with: INCLUDEPATH += C:\path\to\include\files\ Hope it works. Regards.

Loading .sql files from within PHP

I hope the following code will solve your problem pretty well.

//Empty all tables' contents

$result_t = mysql_query("SHOW TABLES");
while($row = mysql_fetch_assoc($result_t))
{
mysql_query("TRUNCATE " . $row['Tables_in_' . $mysql_database]);
}
// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach ($lines as $line)
{
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
    continue;

// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
    // Perform the query
    mysql_query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />');
    // Reset temp variable to empty
    $templine = '';
}
}

?>

How to iterate a table rows with JQuery and access some cell values?

do this:

$("tr.item").each(function(i, tr) {
    var value = $("span.value", tr).text();
    var quantity = $("input.quantity", tr).val();
});

How to know if a Fragment is Visible?

You should be able to do the following:

MyFragmentClass test = (MyFragmentClass) getSupportFragmentManager().findFragmentByTag("testID");
if (test != null && test.isVisible()) {
     //DO STUFF
}
else {
    //Whatever
}

Java - sending HTTP parameters via POST method easily

Here is a simple example that submits a form then dumps the result page to System.out. Change the URL and the POST params as appropriate, of course:

import java.io.*;
import java.net.*;
import java.util.*;

class Test {
    public static void main(String[] args) throws Exception {
        URL url = new URL("http://example.net/new-message.php");
        Map<String,Object> params = new LinkedHashMap<>();
        params.put("name", "Freddie the Fish");
        params.put("email", "[email protected]");
        params.put("reply_to_thread", 10394);
        params.put("message", "Shark attacks in Botany Bay have gotten out of control. We need more defensive dolphins to protect the schools here, but Mayor Porpoise is too busy stuffing his snout with lobsters. He's so shellfish.");

        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String,Object> param : params.entrySet()) {
            if (postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");

        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);

        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        for (int c; (c = in.read()) >= 0;)
            System.out.print((char)c);
    }
}

If you want the result as a String instead of directly printed out do:

        StringBuilder sb = new StringBuilder();
        for (int c; (c = in.read()) >= 0;)
            sb.append((char)c);
        String response = sb.toString();

Constructor in an Interface?

An interface defines a contract for an API, that is a set of methods that both implementer and user of the API agree upon. An interface does not have an instanced implementation, hence no constructor.

The use case you describe is akin to an abstract class in which the constructor calls a method of an abstract method which is implemented in an child class.

The inherent problem here is that while the base constructor is being executed, the child object is not constructed yet, and therfore in an unpredictable state.

To summarize: is it asking for trouble when you call overloaded methods from parent constructors, to quote mindprod:

In general you must avoid calling any non-final methods in a constructor. The problem is that instance initialisers / variable initialisation in the derived class is performed after the constructor of the base class.

Retrieve list of tasks in a queue in Celery

I've come to the conclusion the best way to get the number of jobs on a queue is to use rabbitmqctl as has been suggested several times here. To allow any chosen user to run the command with sudo I followed the instructions here (I did skip editing the profile part as I don't mind typing in sudo before the command.)

I also grabbed jamesc's grep and cut snippet and wrapped it up in subprocess calls.

from subprocess import Popen, PIPE
p1 = Popen(["sudo", "rabbitmqctl", "list_queues", "-p", "[name of your virtula host"], stdout=PIPE)
p2 = Popen(["grep", "-e", "^celery\s"], stdin=p1.stdout, stdout=PIPE)
p3 = Popen(["cut", "-f2"], stdin=p2.stdout, stdout=PIPE)
p1.stdout.close()
p2.stdout.close()
print("number of jobs on queue: %i" % int(p3.communicate()[0]))

iOS download and save image inside app

Here is a Swift 5 solution for downloading and saving an image or in general a file to the documents directory by using Alamofire:

func dowloadAndSaveFile(from url: URL) {
    let destination: DownloadRequest.DownloadFileDestination = { _, _ in
        var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        documentsURL.appendPathComponent(url.lastPathComponent)
        return (documentsURL, [.removePreviousFile])
    }
    let request = SessionManager.default.download(url, method: .get, to: destination)
    request.validate().responseData { response in
        switch response.result {
        case .success:
            if let destinationURL = response.destinationURL {
                print(destinationURL)
            }
        case .failure(let error):
            print(error.localizedDescription)
        }
    }
}

JavaScript - Get Portion of URL Path

There is a property of the built-in window.location object that will provide that for the current window.

// If URL is http://www.somedomain.com/account/search?filter=a#top

window.location.pathname // /account/search

// For reference:

window.location.host     // www.somedomain.com (includes port if there is one)
window.location.hostname // www.somedomain.com
window.location.hash     // #top
window.location.href     // http://www.somedomain.com/account/search?filter=a#top
window.location.port     // (empty string)
window.location.protocol // http:
window.location.search   // ?filter=a  


Update, use the same properties for any URL:

It turns out that this schema is being standardized as an interface called URLUtils, and guess what? Both the existing window.location object and anchor elements implement the interface.

So you can use the same properties above for any URL — just create an anchor with the URL and access the properties:

var el = document.createElement('a');
el.href = "http://www.somedomain.com/account/search?filter=a#top";

el.host        // www.somedomain.com (includes port if there is one[1])
el.hostname    // www.somedomain.com
el.hash        // #top
el.href        // http://www.somedomain.com/account/search?filter=a#top
el.pathname    // /account/search
el.port        // (port if there is one[1])
el.protocol    // http:
el.search      // ?filter=a

[1]: Browser support for the properties that include port is not consistent, See: http://jessepollak.me/chrome-was-wrong-ie-was-right

This works in the latest versions of Chrome and Firefox. I do not have versions of Internet Explorer to test, so please test yourself with the JSFiddle example.

JSFiddle example

There's also a coming URL object that will offer this support for URLs themselves, without the anchor element. Looks like no stable browsers support it at this time, but it is said to be coming in Firefox 26. When you think you might have support for it, try it out here.

check if array is empty (vba excel)

Adding into this: it depends on what your array is defined as. Consider:

dim a() as integer
dim b() as string
dim c() as variant

'these doesn't work
if isempty(a) then msgbox "integer arrays can be empty"
if isempty(b) then msgbox "string arrays can be empty"

'this is because isempty can only be tested on classes which have an .empty property

'this do work
if isempty(c) then msgbox "variants can be empty"

So, what can we do? In VBA, we can see if we can trigger an error and somehow handle it, for example

dim a() as integer
dim bEmpty as boolean

bempty=false

on error resume next
bempty=not isnumeric(ubound(a))
on error goto 0

But this is really clumsy... A nicer solution is to declare a boolean variable (a public or module level is best). When the array is first initialised, then set this variable. Because it's a variable declared at the same time, if it loses it's value, then you know that you need to reinitialise your array. However, if it is initialised, then all you're doing is checking the value of a boolean, which is low cost. It depends on whether being low cost matters, and if you're going to be needing to check it often.

option explicit

'declared at module level
dim a() as integer
dim aInitialised as boolean

sub DoSomethingWithA()
if not aInitialised then InitialiseA
'you can now proceed confident that a() is intialised
end sub

sub InitialiseA()
'insert code to do whatever is required to initialise A
'e.g. 
redim a(10)
a(1)=123
'...
aInitialised=true
end sub

The last thing you can do is create a function; which in this case will need to be dependent on the clumsy on error method.

function isInitialised(byref a() as variant) as boolean
isInitialised=false
on error resume next
isinitialised=isnumeric(ubound(a))
end function

Object spread vs. Object.assign

This isn't necessarily exhaustive.

Spread syntax

options = {...optionsDefault, ...options};

Advantages:

  • If authoring code for execution in environments without native support, you may be able to just compile this syntax (as opposed to using a polyfill). (With Babel, for example.)

  • Less verbose.

Disadvantages:

  • When this answer was originally written, this was a proposal, not standardized. When using proposals consider what you'd do if you write code with it now and it doesn't get standardized or changes as it moves toward standardization. This has since been standardized in ES2018.

  • Literal, not dynamic.


Object.assign()

options = Object.assign({}, optionsDefault, options);

Advantages:

  • Standardized.

  • Dynamic. Example:

    var sources = [{a: "A"}, {b: "B"}, {c: "C"}];
    options = Object.assign.apply(Object, [{}].concat(sources));
    // or
    options = Object.assign({}, ...sources);
    

Disadvantages:

  • More verbose.
  • If authoring code for execution in environments without native support you need to polyfill.

This is the commit that made me wonder.

That's not directly related to what you're asking. That code wasn't using Object.assign(), it was using user code (object-assign) that does the same thing. They appear to be compiling that code with Babel (and bundling it with Webpack), which is what I was talking about: the syntax you can just compile. They apparently preferred that to having to include object-assign as a dependency that would go into their build.

How to get date and time from server

For enable PHP Extension intl , follow the Steps..

  1. Open the xampp/php/php.ini file in any editor.
  2. Search ";extension=php_intl.dll"
  3. kindly remove the starting semicolon ( ; ) Like : ;extension=php_intl.dll. to. extension=php_intl.dll.
  4. Save the xampp/php/php.ini file.
  5. Restart your xampp/wamp.