Programs & Examples On #Imaplib

Python module to provide an Internet Message Access Protocol (IMAP) client implementation. This protocol lets you access mail folders stored on a central mail server, as if they were local.

'str' object has no attribute 'decode'. Python 3 error?

If you land here using jwt authentication after the PyJWT v2.0.0 release (22/12/2020), you might want to freeze your version of PyJWT to the previous release in your requirements.txt file.

PyJWT==1.7.1

Iterating through list of list in Python

This traverse generator function can be used to iterate over all the values:

def traverse(o, tree_types=(list, tuple)):
    if isinstance(o, tree_types):
        for value in o:
            for subvalue in traverse(value, tree_types):
                yield subvalue
    else:
        yield o

data = [(1,1,(1,1,(1,"1"))),(1,1,1),(1,),1,(1,(1,("1",)))]
print list(traverse(data))
# prints [1, 1, 1, 1, 1, '1', 1, 1, 1, 1, 1, 1, 1, '1']

for value in traverse(data):
    print repr(value)
# prints
# 1
# 1
# 1
# 1
# 1
# '1'
# 1
# 1
# 1
# 1
# 1
# 1
# 1
# '1'

Nginx: Job for nginx.service failed because the control process exited

change the port may help as 80 port is already using somewhere

vi /etc/nginx/sites-available/default

Change the port:

listen 8080 default_server;
listen [::]:8080 default_server;

And then restart the nginx server

nginx -t
service nginx restart

How do I convert from a money datatype in SQL server?

You can try like this:

SELECT PARSENAME('$'+ Convert(varchar,Convert(money,@MoneyValue),1),2)

SQL ROWNUM how to return rows between a specific range

SELECT  *
FROM    (
        SELECT  q.*, rownum rn
        FROM    (
                SELECT  *
                FROM    maps006
                ORDER BY
                        id
                ) q
        )
WHERE   rn BETWEEN 50 AND 100

Note the double nested view. ROWNUM is evaluated before ORDER BY, so it is required for correct numbering.

If you omit ORDER BY clause, you won't get consistent order.

The Web Application Project [...] is configured to use IIS. The Web server [...] could not be found.

Open the project folder and delete {Project}.csproj.user, then reload the project on Visual Studio.

Invoking a static method using reflection

public class Add {
    static int add(int a, int b){
        return (a+b);
    }
}

In the above example, 'add' is a static method that takes two integers as arguments.

Following snippet is used to call 'add' method with input 1 and 2.

Class myClass = Class.forName("Add");
Method method = myClass.getDeclaredMethod("add", int.class, int.class);
Object result = method.invoke(null, 1, 2);

Reference link.

basic authorization command for curl

How do I set up the basic authorization?

All you need to do is use -u, --user USER[:PASSWORD]. Behind the scenes curl builds the Authorization header with base64 encoded credentials for you.

Example:

curl -u username:password -i -H 'Accept:application/json' http://example.com

Parse JSON in C#

[Update]
I've just realized why you weren't receiving results back... you have a missing line in your Deserialize method. You were forgetting to assign the results to your obj :

public static T Deserialize<T>(string json)
{
    using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
        return (T)serializer.ReadObject(ms);
    } 
}

Also, just for reference, here is the Serialize method :

public static string Serialize<T>(T obj)
{
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    using (MemoryStream ms = new MemoryStream())
    {
        serializer.WriteObject(ms, obj);
        return Encoding.Default.GetString(ms.ToArray());
    }
}

Edit

If you want to use Json.NET here are the equivalent Serialize/Deserialize methods to the code above..

Deserialize:

JsonConvert.DeserializeObject<T>(string json);

Serialize:

JsonConvert.SerializeObject(object o);

This are already part of Json.NET so you can just call them on the JsonConvert class.

Link: Serializing and Deserializing JSON with Json.NET



Now, the reason you're getting a StackOverflow is because of your Properties.

Take for example this one :

[DataMember]
public string unescapedUrl
{
    get { return unescapedUrl; } // <= this line is causing a Stack Overflow
    set { this.unescapedUrl = value; }
}

Notice that in the getter, you are returning the actual property (ie the property's getter is calling itself over and over again), and thus you are creating an infinite recursion.


Properties (in 2.0) should be defined like such :

string _unescapedUrl; // <= private field

[DataMember]
public string unescapedUrl
{
    get { return _unescapedUrl; } 
    set { _unescapedUrl = value; }
}

You have a private field and then you return the value of that field in the getter, and set the value of that field in the setter.


Btw, if you're using the 3.5 Framework, you can just do this and avoid the backing fields, and let the compiler take care of that :

public string unescapedUrl { get; set;}

Change status bar color with AppCompat ActionBarActivity

Try this, I used this and it works very good with v21.

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
    <item name="colorPrimaryDark">@color/blue</item>
</style>

Chrome sendrequest error: TypeError: Converting circular structure to JSON

I normally use the circular-json npm package to solve this.

// Felix Kling's example
var a = {};
a.b = a;
// load circular-json module
var CircularJSON = require('circular-json');
console.log(CircularJSON.stringify(a));
//result
{"b":"~"}

Note: circular-json has been deprecated, I now use flatted (from the creator of CircularJSON):

// ESM
import {parse, stringify} from 'flatted/esm';

// CJS
const {parse, stringify} = require('flatted/cjs');

const a = [{}];
a[0].a = a;
a.push(a);

stringify(a); // [["1","0"],{"a":"0"}]

from: https://www.npmjs.com/package/flatted

JSON to TypeScript class instance?

The best solution I found when dealing with Typescript classes and json objects: add a constructor in your Typescript class that takes the json data as parameter. In that constructor you extend your json object with jQuery, like this: $.extend( this, jsonData). $.extend allows keeping the javascript prototypes while adding the json object's properties.

export class Foo
{
    Name: string;
    getName(): string { return this.Name };

    constructor( jsonFoo: any )
    {
        $.extend( this, jsonFoo);
    }
}

In your ajax callback, translate your jsons in a your typescript object like this:

onNewFoo( jsonFoos : any[] )
{
  let receviedFoos = $.map( jsonFoos, (json) => { return new Foo( json ); } );

  // then call a method:
  let firstFooName = receviedFoos[0].GetName();
}

If you don't add the constructor, juste call in your ajax callback:

let newFoo = new Foo();
$.extend( newFoo, jsonData);
let name = newFoo.GetName()

...but the constructor will be useful if you want to convert the children json object too. See my detailed answer here.

How to differentiate single click event and double click event?

Use the excellent jQuery Sparkle plugin. The plugin gives you the option to detect first and last click. You can use it to differentiate between click and dblclick by detecting if another click was followed by the first click.

Check it out at http://balupton.com/sandbox/jquery-sparkle/demo/

Best way to Format a Double value to 2 Decimal places

No, there is no better way.

Actually you have an error in your pattern. What you want is:

DecimalFormat df = new DecimalFormat("#.00"); 

Note the "00", meaning exactly two decimal places.

If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".

How to send a Post body in the HttpClient request in Windows Phone 8?

I implemented it in the following way. I wanted a generic MakeRequest method that could call my API and receive content for the body of the request - and also deserialise the response into the desired type. I create a Dictionary<string, string> object to house the content to be submitted, and then set the HttpRequestMessage Content property with it:

Generic method to call the API:

    private static T MakeRequest<T>(string httpMethod, string route, Dictionary<string, string> postParams = null)
    {
        using (var client = new HttpClient())
        {
            HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), $"{_apiBaseUri}/{route}");

            if (postParams != null)
                requestMessage.Content = new FormUrlEncodedContent(postParams);   // This is where your content gets added to the request body


            HttpResponseMessage response = client.SendAsync(requestMessage).Result;

            string apiResponse = response.Content.ReadAsStringAsync().Result;
            try
            {
                // Attempt to deserialise the reponse to the desired type, otherwise throw an expetion with the response from the api.
                if (apiResponse != "")
                    return JsonConvert.DeserializeObject<T>(apiResponse);
                else
                    throw new Exception();
            }
            catch (Exception ex)
            {
                throw new Exception($"An error ocurred while calling the API. It responded with the following message: {response.StatusCode} {response.ReasonPhrase}");
            }
        }
    }

Call the method:

    public static CardInformation ValidateCard(string cardNumber, string country = "CAN")
    { 
        // Here you create your parameters to be added to the request content
        var postParams = new Dictionary<string, string> { { "cardNumber", cardNumber }, { "country", country } };
        // make a POST request to the "cards" endpoint and pass in the parameters
        return MakeRequest<CardInformation>("POST", "cards", postParams);
    }

Connecting to TCP Socket from browser using javascript

The solution you are really looking for is web sockets. However, the chromium project has developed some new technologies that are direct TCP connections TCP chromium

localhost refused to connect Error in visual studio

I had to add https bindings in my local IIS

Why was the name 'let' chosen for block-scoped variable declarations in JavaScript?

I think JavaScript's indebtedness to Scheme is obvious here. Scheme not only has let, but has let*, let*-values, let-syntax, and let-values. (See, The Scheme Programming Language, 4th Ed.).

((The choice adds further credence to the notion that JavaScript is Lispy, but--before we get carried away--not homoiconic.))))

Netbeans - class does not have a main method

  1. Check for correct method declaration

public static void main(String [ ] args)

  1. Check netbeans project properties in Run > main Class

Typescript: React event types

For those who are looking for a solution to get an event and store something, in my case a HTML 5 element, on a useState here's my solution:

const [anchorElement, setAnchorElement] = useState<HTMLButtonElement | null>(null);

const handleMenu = (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) : void => {
    setAnchorElement(event.currentTarget);
};

Java: Date from unix timestamp

Looks like Calendar is the new way to go:

Calendar mydate = Calendar.getInstance();
mydate.setTimeInMillis(timestamp*1000);
out.println(mydate.get(Calendar.DAY_OF_MONTH)+"."+mydate.get(Calendar.MONTH)+"."+mydate.get(Calendar.YEAR));

The last line is just an example how to use it, this one would print eg "14.06.2012".

If you have used System.currentTimeMillis() to save the Timestamp you don't need the "*1000" part.

If you have the timestamp in a string you need to parse it first as a long: Long.parseLong(timestamp).

https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

Address already in use: JVM_Bind java

please try following options for JVM binding exception:

  1. start and stop the server. and check the server process ids and kill and stop the server.
  2. go to control panel->administrative tool-> service-> check all server and stop all the servers and then start your own server.
  3. change the Browser which your using. for example if your using IE ,change it to Mozilla firefox.

Replace new line/return with space using regex

You May use first split and rejoin it using white space. it will work sure.

String[] Larray = L.split("[\\n]+");
L = "";
for(int i = 0; i<Larray.lengh; i++){
   L = L+" "+Larray[i];  
}

how to set select element as readonly ('disabled' doesnt pass select value on server)

see this answer - HTML form readonly SELECT tag/input

You should keep the select element disabled but also add another hidden input with the same name and value.

If you reenable your SELECT, you should copy it's value to the hidden input in an onchange event.

see this fiddle to demnstrate how to extract the selected value in a disabled select into a hidden field that will be submitted in the form.

<select disabled="disabled" id="sel_test">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

<input type="hidden" id="hdn_test" />
<div id="output"></div>

$(function(){
    var select_val = $('#sel_test option:selected').val();
    $('#hdn_test').val(select_val);
    $('#output').text('Selected value is: ' + select_val);
});

hope that helps.

Error: allowDefinition='MachineToApplication' beyond application level

In Visual Studio 2013 I struggled with this for a while and it is pretty much easy to solve just follow what the exceptions says "virtual directory not being configured as an application in IIS"

In my case I had WebService planted inside IIS website so

  1. I opened the website in IIS manager
  2. right clicked the WCF folder
  3. clicked Convert to Application
  4. and then submitted with Ok

WCF is back and running.

Execute command on all files in a directory

I needed to copy all .md files from one directory into another, so here is what I did.

for i in **/*.md;do mkdir -p ../docs/"$i" && rm -r ../docs/"$i" && cp "$i" "../docs/$i" && echo "$i -> ../docs/$i"; done

Which is pretty hard to read, so lets break it down.

first cd into the directory with your files,

for i in **/*.md; for each file in your pattern

mkdir -p ../docs/"$i"make that directory in a docs folder outside of folder containing your files. Which creates an extra folder with the same name as that file.

rm -r ../docs/"$i" remove the extra folder that is created as a result of mkdir -p

cp "$i" "../docs/$i" Copy the actual file

echo "$i -> ../docs/$i" Echo what you did

; done Live happily ever after

Get column value length, not column max length of value

LENGTH() does return the string length (just verified). I suppose that your data is padded with blanks - try

SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;

instead.

As OraNob mentioned, another cause could be that CHAR is used in which case LENGTH() would also return the column width, not the string length. However, the TRIM() approach also works in this case.

Using :: in C++

look at it is informative [Qualified identifiers

A qualified id-expression is an unqualified id-expression prepended by a scope resolution operator ::, and optionally, a sequence of enumeration, (since C++11)class or namespace names or decltype expressions (since C++11) separated by scope resolution operators. For example, the expression std::string::npos is an expression that names the static member npos in the class string in namespace std. The expression ::tolower names the function tolower in the global namespace. The expression ::std::cout names the global variable cout in namespace std, which is a top-level namespace. The expression boost::signals2::connection names the type connection declared in namespace signals2, which is declared in namespace boost.

The keyword template may appear in qualified identifiers as necessary to disambiguate dependent template names]1

chrome : how to turn off user agent stylesheet settings?

https://developers.google.com/chrome-developer-tools/docs/settings

  1. Open Chrome dev tools
  2. Click gear icon on bottom right
  3. In General section, check or uncheck "Show user agent styles".

Grep for beginning and end of line?

It should be noted that not only will the caret (^) behave differently within the brackets, it will have the opposite result of placing it outside of the brackets. Placing the caret where you have it will search for all strings NOT beginning with the content you placed within the brackets. You also would want to place a period before the asterisk in between your brackets as with grep, it also acts as a "wildcard".

grep ^[.rwx].*[0-9]$

This should work for you, I noticed that some posters used a character class in their expressions which is an effective method as well, but you were not using any in your original expression so I am trying to get one as close to yours as possible explaining every minor change along the way so that it is better understood. How can we learn otherwise?

Best place to insert the Google Analytics code

As google says:

Paste it into your web page, just before the closing </head> tag.

One of the main advantages of the asynchronous snippet is that you can position it at the top of the HTML document. This increases the likelihood that the tracking beacon will be sent before the user leaves the page. It is customary to place JavaScript code in the <head> section, and we recommend placing the snippet at the bottom of the <head> section for best performance

How to open a second activity on click of button in android app

Replace the below line code:

import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener{
   Button button;
    @Override
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button)findViewById(R.id.button1);
        button.setOnClickListener(this);
      }
       public void onClick(View v) {
        if(v.getId==R.id.button1){
      Intent i = new Intent(FromActivity.this, ToActivity.class);
               startActivity(i);
            }
        }
     }

Add the below lines in your manifest file:

   <activity android:name="com.packagename.FromActivity"></activity>
   <activity android:name="com.packagename.ToActivity"></activity>

includes() not working in all browsers

IE11 does implement String.prototype.includes so why not using the official Polyfill?

Source: polyfill source

  if (!String.prototype.includes) {
    String.prototype.includes = function(search, start) {
      if (typeof start !== 'number') {
        start = 0;
      }

      if (start + search.length > this.length) {
        return false;
      } else {
        return this.indexOf(search, start) !== -1;
      }
    };
  }

Default string initialization: NULL or Empty?

+1 for distinguishing between "empty" and NULL. I agree that "empty" should mean "valid, but blank" and "NULL" should mean "invalid."

So I'd answer your question like this:

empty when I want a valid default value that may or may not be changed, for example, a user's middle name.

NULL when it is an error if the ensuing code does not set the value explicitly.

Path.Combine absolute with relative path strings

For windows universal apps Path.GetFullPath() is not available, you can use the System.Uri class instead:

 Uri uri = new Uri(Path.Combine(@"C:\blah\",@"..\bling"));
 Console.WriteLine(uri.LocalPath);

MySQL my.cnf file - Found option without preceding group

Missing config header

Just add [mysqld] as first line in the /etc/mysql/my.cnf file.

Example

[mysqld]
default-time-zone = "+08:00"

Afterwards, remember to restart your MySQL Service.

sudo mysqld stop
sudo mysqld start

How do I determine the size of my array in C?

A more elegant solution will be

size_t size = sizeof(a) / sizeof(*a);

Mapping list in Yaml to list of objects in Spring Boot

I had much issues with this one too. I finally found out what's the final deal.

Referring to @Gokhan Oner answer, once you've got your Service class and the POJO representing your object, your YAML config file nice and lean, if you use the annotation @ConfigurationProperties, you have to explicitly get the object for being able to use it. Like :

@ConfigurationProperties(prefix = "available-payment-channels-list")
//@Configuration  <-  you don't specificly need this, instead you're doing something else
public class AvailableChannelsConfiguration {

    private String xyz;
    //initialize arraylist
    private List<ChannelConfiguration> channelConfigurations = new ArrayList<>();

    public AvailableChannelsConfiguration() {
        for(ChannelConfiguration current : this.getChannelConfigurations()) {
            System.out.println(current.getName()); //TADAAA
        }
    }

    public List<ChannelConfiguration> getChannelConfigurations() {
        return this.channelConfigurations;
    }

    public static class ChannelConfiguration {
        private String name;
        private String companyBankAccount;
    }

}

And then here you go. It's simple as hell, but we have to know that we must call the object getter. I was waiting at initialization, wishing the object was being built with the value but no. Hope it helps :)

What is the equivalent of Select Case in Access SQL?

You can use IIF for a similar result.

Note that you can nest the IIF statements to handle multiple cases. There is an example here: http://forums.devshed.com/database-management-46/query-ms-access-iif-statement-multiple-conditions-358130.html

SELECT IIf([Combinaison] = "Mike", 12, IIf([Combinaison] = "Steve", 13)) As Answer 
FROM MyTable;

Ignore outliers in ggplot2 boxplot

The "coef" option of the geom_boxplot function allows to change the outlier cutoff in terms of interquartile ranges. This option is documented for the function stat_boxplot. To deactivate outliers (in other words they are treated as regular data), one can instead of using the default value of 1.5 specify a very high cutoff value:

library(ggplot2)
# generate data with outliers:
df = data.frame(x=1, y = c(-10, rnorm(100), 10)) 
# generate plot with increased cutoff for outliers:
ggplot(df, aes(x, y)) + geom_boxplot(coef=1e30)

Pass connection string to code-first DbContext

from here

 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
      optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["BloggingDatabase"].ConnectionString);
    }

note you may need to add Microsoft.EntityFrameworkCore.SqlServer

How do you get the "object reference" of an object in java when toString() and hashCode() have been overridden?

we can simply copy the code from tostring of object class to get the reference of string

class Test
{
  public static void main(String args[])
  {
    String a="nikhil";     // it stores in String constant pool
    String s=new String("nikhil");    //with new stores in heap
    System.out.println(Integer.toHexString(System.identityHashCode(a)));
    System.out.println(Integer.toHexString(System.identityHashCode(s)));
  }
}

How to use lodash to find and return an object from Array?

The argument passed to the callback is one of the elements of the array. The elements of your array are objects of the form {description: ..., id: ...}.

var delete_id = _.result(_.find(savedViews, function(obj) {
    return obj.description === view;
}), 'id');

Yet another alternative from the docs you linked to (lodash v3):

_.find(savedViews, 'description', view);

Lodash v4:

_.find(savedViews, ['description', view]);

How to retrieve an element from a set without removing it?

Another option is to use a dictionary with values you don't care about. E.g.,


poor_man_set = {}
poor_man_set[1] = None
poor_man_set[2] = None
poor_man_set[3] = None
...

You can treat the keys as a set except that they're just an array:


keys = poor_man_set.keys()
print "Some key = %s" % keys[0]

A side effect of this choice is that your code will be backwards compatible with older, pre-set versions of Python. It's maybe not the best answer but it's another option.

Edit: You can even do something like this to hide the fact that you used a dict instead of an array or set:


poor_man_set = {}
poor_man_set[1] = None
poor_man_set[2] = None
poor_man_set[3] = None
poor_man_set = poor_man_set.keys()

Update a dataframe in pandas while iterating row by row

You should assign value by df.ix[i, 'exp']=X or df.loc[i, 'exp']=X instead of df.ix[i]['ifor'] = x.

Otherwise you are working on a view, and should get a warming:

-c:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_index,col_indexer] = value instead

But certainly, loop probably should better be replaced by some vectorized algorithm to make the full use of DataFrame as @Phillip Cloud suggested.

Python: Converting from ISO-8859-1/latin1 to UTF-8

For Python 3:

bytes(apple,'iso-8859-1').decode('utf-8')

I used this for a text incorrectly encoded as iso-8859-1 (showing words like VeÅ\x99ejné) instead of utf-8. This code produces correct version Verejné.

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices
;

For more information on the format models you can use with TO_CHAR on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.

Construct a manual legend for a complicated plot

You need to map attributes to aesthetics (colours within the aes statement) to produce a legend.

cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h, fill = "BAR"),colour="#333333")+ #green
  geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +   #red
  geom_point(aes(y=b, colour="LINE1"),size=3) +           #red
  geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) + 
  geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +   #blue 
  geom_point(aes(y=c,colour="LINE2"),size=3) +           #blue
  geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) + 
  scale_colour_manual(name="Error Bars",values=cols) + scale_fill_manual(name="Bar",values=cols) +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

enter image description here

I understand where Roland is coming from, but since this is only 3 attributes, and complications arise from superimposing bars and error bars this may be reasonable to leave the data in wide format like it is. It could be slightly reduced in complexity by using geom_pointrange.


To change the background color for the error bars legend in the original, add + theme(legend.key = element_rect(fill = "white",colour = "white")) to the plot specification. To merge different legends, you typically need to have a consistent mapping for all elements, but it is currently producing an artifact of a black background for me. I thought guide = guide_legend(fill = NULL,colour = NULL) would set the background to null for the legend, but it did not. Perhaps worth another question.

ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) +           #red
  geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) + 
  geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) +           #blue
  geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) + 
  scale_colour_manual(name="Error Bars",values=cols, guide = guide_legend(fill = NULL,colour = NULL)) + 
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

enter image description here


To get rid of the black background in the legend, you need to use the override.aes argument to the guide_legend. The purpose of this is to let you specify a particular aspect of the legend which may not be being assigned correctly.

ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) +           #red
  geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) + 
  geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) +           #blue
  geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) + 
  scale_colour_manual(name="Error Bars",values=cols, 
                      guide = guide_legend(override.aes=aes(fill=NA))) + 
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

enter image description here

How to see the proxy settings on windows?

An update to @rleelr:
It's possible to view proxy settings in Google Chrome:

chrome://net-internals/#http2

Then select

View live HTTP/2 sessions

Then select one of the live sessions (you need to have some tabs open). There you find:

[...]
t=504112 [st= 0] +HTTP2_SESSION  [dt=?]
                  --> host = "play.google.com:443"
                  --> proxy = "PROXY www.xxx.yyy.zzz:8080"
[...]
                              ============================

How to use new PasswordEncoder from Spring Security

If you haven't actually registered any users with your existing format then you would be best to switch to using the BCrypt password encoder instead.

It's a lot less hassle, as you don't have to worry about salt at all - the details are completely encapsulated within the encoder. Using BCrypt is stronger than using a plain hash algorithm and it's also a standard which is compatible with applications using other languages.

There's really no reason to choose any of the other options for a new application.

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

In our case, the reason was invalid header. As mentioned in Edit 4:

  • take the logs
  • in the viewer choose Events
  • chose HTTP2_SESSION

Look for something similar:

HTTP2_SESSION_RECV_INVALID_HEADER

--> error = "Invalid character in header name."

--> header_name = "charset=utf-8"

"Press Any Key to Continue" function in C

Use getch():

printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getch();

Windows alternative should be _getch().

If you're using Windows, this should be the full example:

#include <conio.h>
#include <ctype.h>

int main( void )
{
    printf("Let the Battle Begin!\n");
    printf("Press Any Key to Continue\n");
    _getch();
}

P.S. as @Rörd noted, if you're on POSIX system, you need to make sure that curses library is setup right.

Synchronously waiting for an async operation, and why does Wait() freeze the program here

Here is what I did

private void myEvent_Handler(object sender, SomeEvent e)
{
  // I dont know how many times this event will fire
  Task t = new Task(() =>
  {
    if (something == true) 
    {
        DoSomething(e);  
    }
  });
  t.RunSynchronously();
}

working great and not blocking UI thread

How to remove an element slowly with jQuery?

$('#ur_id').slideUp("slow", function() { $('#ur_id').remove();});

Laravel Controller Subfolder routing

In my case I had a prefix that had to be added for each route in the group, otherwise response would be that the UserController class was not found.

Route::prefix('/user')->group(function() {
    Route::post('/login', [UserController::class, 'login'])->prefix('/user');
    Route::post('/register', [UserController::class, 'register'])->prefix('/user');
});

How to convert a const char * to std::string

What you want is this constructor: std::string ( const string& str, size_t pos, size_t n = npos ), passing pos as 0. Your const char* c-style string will get implicitly cast to const string for the first parameter.

const char *c_style = "012abd";
std::string cpp_style = new std::string(c_style, 0, 10);

What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

I would be very careful if you are considering adopting this hashbang convention.

Once you hashbang, you can’t go back. This is probably the stickiest issue. Ben’s post put forward the point that when pushState is more widely adopted then we can leave hashbangs behind and return to traditional URLs. Well, fact is, you can’t. Earlier I stated that URLs are forever, they get indexed and archived and generally kept around. To add to that, cool URLs don’t change. We don’t want to disconnect ourselves from all the valuable links to our content. If you’ve implemented hashbang URLs at any point then want to change them without breaking links the only way you can do it is by running some JavaScript on the root document of your domain. Forever. It’s in no way temporary, you are stuck with it.

You really want to use pushState instead of hashbangs, because making your URLs ugly and possibly broken -- forever -- is a colossal and permanent downside to hashbangs.

correct PHP headers for pdf file download

$name = 'file.pdf';
//file_get_contents is standard function
$content = file_get_contents($name);
header('Content-Type: application/pdf');
header('Content-Length: '.strlen( $content ));
header('Content-disposition: inline; filename="' . $name . '"');
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
echo $content;

Base64: java.lang.IllegalArgumentException: Illegal character

The Base64.Encoder.encodeToString method automatically uses the ISO-8859-1 character set.

For an encryption utility I am writing, I took the input string of cipher text and Base64 encoded it for transmission, then reversed the process. Relevant parts shown below. NOTE: My file.encoding property is set to ISO-8859-1 upon invocation of the JVM so that may also have a bearing.

static String getBase64EncodedCipherText(String cipherText) {
    byte[] cText = cipherText.getBytes();
    // return an ISO-8859-1 encoded String
    return Base64.getEncoder().encodeToString(cText);
}

static String getBase64DecodedCipherText(String encodedCipherText) throws IOException {
    return new String((Base64.getDecoder().decode(encodedCipherText)));
}

public static void main(String[] args) {
    try {
        String cText = getRawCipherText(null, "Hello World of Encryption...");

        System.out.println("Text to encrypt/encode: Hello World of Encryption...");
        // This output is a simple sanity check to display that the text
        // has indeed been converted to a cipher text which 
        // is unreadable by all but the most intelligent of programmers.
        // It is absolutely inhuman of me to do such a thing, but I am a
        // rebel and cannot be trusted in any way.  Please look away.
        System.out.println("RAW CIPHER TEXT: " + cText);
        cText = getBase64EncodedCipherText(cText);
        System.out.println("BASE64 ENCODED: " + cText);
        // There he goes again!!
        System.out.println("BASE64 DECODED:  " + getBase64DecodedCipherText(cText));
        System.out.println("DECODED CIPHER TEXT: " + decodeRawCipherText(null, getBase64DecodedCipherText(cText)));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

The output looks like:

Text to encrypt/encode: Hello World of Encryption...
RAW CIPHER TEXT: q$;?C?l??<8??U???X[7l
BASE64 ENCODED: HnEPJDuhQ+qDbInUCzw4gx0VDqtVwef+WFs3bA==
BASE64 DECODED:  q$;?C?l??<8??U???X[7l``
DECODED CIPHER TEXT: Hello World of Encryption...

How do I format a number in Java?

There are two approaches in the standard library. One is to use java.text.DecimalFormat. The other more cryptic methods (String.format, PrintStream.printf, etc) based around java.util.Formatter should keep C programmers happy(ish).

How do I revert a Git repository to a previous commit?

You can do this by the following two commands:

git reset --hard [previous Commit SHA id here]
git push origin [branch Name] -f

It will remove your previous Git commit.

If you want to keep your changes, you can also use:

git reset --soft [previous Commit SHA id here]

Then it will save your changes.

Can a background image be larger than the div itself?

You can use a css3 psuedo element (:before and/or :after) as shown in this article

https://www.exratione.com/2011/09/how-to-overflow-a-background-image-using-css3/

Good Luck...

How to view the SQL queries issued by JPA?

EclipseLink to output the SQL(persistence.xml config):

<property name="eclipselink.logging.level.sql" value="FINE" />

How to run Unix shell script from Java code?

You can use Apache Commons exec library also.

Example :

package testShellScript;

import java.io.IOException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;

public class TestScript {
    int iExitValue;
    String sCommandString;

    public void runScript(String command){
        sCommandString = command;
        CommandLine oCmdLine = CommandLine.parse(sCommandString);
        DefaultExecutor oDefaultExecutor = new DefaultExecutor();
        oDefaultExecutor.setExitValue(0);
        try {
            iExitValue = oDefaultExecutor.execute(oCmdLine);
        } catch (ExecuteException e) {
            System.err.println("Execution failed.");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("permission denied.");
            e.printStackTrace();
        }
    }

    public static void main(String args[]){
        TestScript testScript = new TestScript();
        testScript.runScript("sh /root/Desktop/testScript.sh");
    }
}

For further reference, An example is given on Apache Doc also.

Multiple file upload in php

This is what worked for me. I had to upload files, store filenames and I had additional inof from input fields to store as well and one record per multiple file names. I used serialize() then added that to the main sql query.

  class addReminder extends dbconn {
    public function addNewReminder(){

           $this->exdate = $_POST['exdate'];
           $this->name = $_POST['name'];
           $this->category = $_POST['category'];
           $this->location = $_POST['location'];
           $this->notes = $_POST['notes'];



           try {

                     if(isset($_POST['submit'])){
                       $total = count($_FILES['fileUpload']['tmp_name']);
                       for($i=0;$i<$total;$i++){
                         $fileName = $_FILES['fileUpload']['name'][$i];
                         $ext = pathinfo($fileName, PATHINFO_EXTENSION);
                         $newFileName = md5(uniqid());
                         $fileDest = 'filesUploaded/'.$newFileName.'.'.$ext;
                         $justFileName = $newFileName.'.'.$ext;
                         if($ext === 'pdf' || 'jpeg' || 'JPG'){
                             move_uploaded_file($_FILES['fileUpload']['tmp_name'][$i], $fileDest);
                             $this->fileName = array($justFileName);
                             $this->encodedFileNames = serialize($this->fileName);
                             var_dump($this->encodedFileNames);
                         }else{
                           echo $fileName . ' Could not be uploaded. Pdfs and jpegs only please';
                         }
                       }

                    $sql = "INSERT INTO reminders (exdate, name, category, location, fileUpload, notes) VALUES (:exdate,:name,:category,:location,:fileName,:notes)";
                    $stmt = $this->connect()->prepare($sql);
                    $stmt->bindParam(':exdate', $this->exdate);
                    $stmt->bindParam(':name', $this->name);
                    $stmt->bindParam(':category', $this->category);
                    $stmt->bindParam(':location', $this->location);
                    $stmt->bindParam(':fileName', $this->encodedFileNames);
                    $stmt->bindParam(':notes', $this->notes);
                    $stmt->execute();
                  }

           }catch(PDOException $e){
             echo $e->getMessage();
           }
      }
    }

Quickly reading very large tables as dataframes

Often times I think it is just good practice to keep larger databases inside a database (e.g. Postgres). I don't use anything too much larger than (nrow * ncol) ncell = 10M, which is pretty small; but I often find I want R to create and hold memory intensive graphs only while I query from multiple databases. In the future of 32 GB laptops, some of these types of memory problems will disappear. But the allure of using a database to hold the data and then using R's memory for the resulting query results and graphs still may be useful. Some advantages are:

(1) The data stays loaded in your database. You simply reconnect in pgadmin to the databases you want when you turn your laptop back on.

(2) It is true R can do many more nifty statistical and graphing operations than SQL. But I think SQL is better designed to query large amounts of data than R.

# Looking at Voter/Registrant Age by Decade

library(RPostgreSQL);library(lattice)

con <- dbConnect(PostgreSQL(), user= "postgres", password="password",
                 port="2345", host="localhost", dbname="WC2014_08_01_2014")

Decade_BD_1980_42 <- dbGetQuery(con,"Select PrecinctID,Count(PrecinctID),extract(DECADE from Birthdate) from voterdb where extract(DECADE from Birthdate)::numeric > 198 and PrecinctID in (Select * from LD42) Group By PrecinctID,date_part Order by Count DESC;")

Decade_RD_1980_42 <- dbGetQuery(con,"Select PrecinctID,Count(PrecinctID),extract(DECADE from RegistrationDate) from voterdb where extract(DECADE from RegistrationDate)::numeric > 198 and PrecinctID in (Select * from LD42) Group By PrecinctID,date_part Order by Count DESC;")

with(Decade_BD_1980_42,(barchart(~count | as.factor(precinctid))));
mtext("42LD Birthdays later than 1980 by Precinct",side=1,line=0)

with(Decade_RD_1980_42,(barchart(~count | as.factor(precinctid))));
mtext("42LD Registration Dates later than 1980 by Precinct",side=1,line=0)

How do you set CMAKE_C_COMPILER and CMAKE_CXX_COMPILER for building Assimp for iOS?

SOLUTIONS

  1. Sometimes the project is created before installing g++. So install g++ first and then recreate your project. This worked for me.
  2. Paste the following line in CMakeCache.txt: CMAKE_CXX_COMPILER:FILEPATH=/usr/bin/c++

Note the path to g++ depends on OS. I have used my fedora path obtained using which g++

How do I sort a Set to a List in Java?

You can convert a set into an ArrayList, where you can sort the ArrayList using Collections.sort(List).

Here is the code:

keySet = (Set) map.keySet();
ArrayList list = new ArrayList(keySet);     
Collections.sort(list);

How to build jars from IntelliJ properly?

My problem was this: I used Intellij IDEA (tried different versions) + Gradle. When I compiled the project and builded artifacf jar, as indicated in the above responses, I received an error - "no main manifest attrubute ..."

This solution worked for me (special thanks to Thilina Ashen Gamage (see above) for tip):

Excerpt - if you use external libraries and build a project through Project Settings - Artifacts - Add (+) - Jar - From modules with dependencies, then probably because of a program bug the META-INF folder with MANIFEST_MF file not including to jar. To avoid it create EMPTY jar file.

Project Settings - Artifacts - Add (+) - Jar - EMPTY JAR. META-INF folder will added to resources folder. Then select your main class. You will see following jar structure: note the presence of a folder META-INF Note the presence of a folder META-INF Then you can build your project and build artifacts. This solution worked for javaFX applications too.

Pass variables by reference in JavaScript

If you want to pass variables by reference, a better way to do that is by passing your arguments in an object and then start changing the value by using window:

window["varName"] = value;

Example:

// Variables with first values
var x = 1, b = 0, f = 15;


function asByReference (
    argumentHasVars = {},   // Passing variables in object
    newValues = [])         // Pass new values in array
{
    let VarsNames = [];

    // Getting variables names one by one
    for(let name in argumentHasVars)
        VarsNames.push(name);

    // Accessing variables by using window one by one
    for(let i = 0; i < VarsNames.length; i += 1)
        window[VarsNames[i]] = newValues[i]; // Set new value
}

console.log(x, b, f); // Output with first values

asByReference({x, b, f}, [5, 5, 5]); // Passing as by reference

console.log(x, b, f); // Output after changing values

Shortcut for changing font size

You'll probably find these shortcuts useful:

Ctrl+Shift+. to zoom in.

Ctrl+Shift+, to zoom out.

Those characters are period and comma, respectively.

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

Phonegap is pretty slow: clicking a button can take up to 3 sec to display the next screen. iscroll is slow and jumpy.

There other funny bugs and issues that i was able to overcome, but in total - not fully matured.

EDIT: Per Grumpy comment, it is not Phonegap who is actually slow, it is the JS/Browser native engine

CSS image resize percentage of itself?

function shrinkImage(idOrClass, className, percentShrinkage){
'use strict';
    $(idOrClass+className).each(function(){
        var shrunkenWidth=this.naturalWidth;
        var shrunkenHeight=this.naturalHeight;
        $(this).height(shrunkenWidth*percentShrinkage);
        $(this).height(shrunkenHeight*percentShrinkage);
    });
};

$(document).ready(function(){
    'use strict';
     shrinkImage(".","anyClass",.5);  //CHANGE THE VALUES HERE ONLY. 
});

This solution uses js and jquery and resizes based only on the image properties and not on the parent. It can resize a single image or a group based using class and id parameters.

for more, go here: https://gist.github.com/jennyvallon/eca68dc78c3f257c5df5

read subprocess stdout line by line

The following modification of Rômulo's answer works for me on Python 2 and 3 (2.7.12 and 3.6.1):

import os
import subprocess

process = subprocess.Popen(command, stdout=subprocess.PIPE)
while True:
  line = process.stdout.readline()
  if line != '':
    os.write(1, line)
  else:
    break

Keyboard shortcut to comment lines in Sublime Text 2

Seems like some kind of keyboard mapping bug. I'm Portuguese, so I'm using a PT/PT keyboard. Sublime Text 3 apparently is handling / as ~.

Finding import static statements for Mockito constructs

The problem is that static imports from Hamcrest and Mockito have similar names, but return Matchers and real values, respectively.

One work-around is to simply copy the Hamcrest and/or Mockito classes and delete/rename the static functions so they are easier to remember and less show up in the auto complete. That's what I did.

Also, when using mocks, I try to avoid assertThat in favor other other assertions and verify, e.g.

assertEquals(1, 1);
verify(someMock).someMethod(eq(1));

instead of

assertThat(1, equalTo(1));
verify(someMock).someMethod(eq(1));

If you remove the classes from your Favorites in Eclipse, and type out the long name e.g. org.hamcrest.Matchers.equalTo and do CTRL+SHIFT+M to 'Add Import' then autocomplete will only show you Hamcrest matchers, not any Mockito matchers. And you can do this the other way so long as you don't mix matchers.

Current time formatting with Javascript

For this true mysql style use this function below: 2019/02/28 15:33:12

  • If you click the
  • 'Run code snippet' button below
  • It will show your an simple realtime digital clock example The demo will appear below the code snippet.

_x000D_
_x000D_
function getDateTime() {_x000D_
        var now     = new Date(); _x000D_
        var year    = now.getFullYear();_x000D_
        var month   = now.getMonth()+1; _x000D_
        var day     = now.getDate();_x000D_
        var hour    = now.getHours();_x000D_
        var minute  = now.getMinutes();_x000D_
        var second  = now.getSeconds(); _x000D_
        if(month.toString().length == 1) {_x000D_
             month = '0'+month;_x000D_
        }_x000D_
        if(day.toString().length == 1) {_x000D_
             day = '0'+day;_x000D_
        }   _x000D_
        if(hour.toString().length == 1) {_x000D_
             hour = '0'+hour;_x000D_
        }_x000D_
        if(minute.toString().length == 1) {_x000D_
             minute = '0'+minute;_x000D_
        }_x000D_
        if(second.toString().length == 1) {_x000D_
             second = '0'+second;_x000D_
        }   _x000D_
        var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;   _x000D_
         return dateTime;_x000D_
    }_x000D_
_x000D_
    // example usage: realtime clock_x000D_
    setInterval(function(){_x000D_
        currentTime = getDateTime();_x000D_
        document.getElementById("digital-clock").innerHTML = currentTime;_x000D_
    }, 1000);
_x000D_
<div id="digital-clock"></div>
_x000D_
_x000D_
_x000D_

Search and replace a line in a file in Python

fileinput is quite straightforward as mentioned on previous answers:

import fileinput

def replace_in_file(file_path, search_text, new_text):
    with fileinput.input(file_path, inplace=True) as f:
        for line in f:
            new_line = line.replace(search_text, new_text)
            print(new_line, end='')

Explanation:

  • fileinput can accept multiple files, but I prefer to close each single file as soon as it is being processed. So placed single file_path in with statement.
  • print statement does not print anything when inplace=True, because STDOUT is being forwarded to the original file.
  • end='' in print statement is to eliminate intermediate blank new lines.

Can be used as follows:

file_path = '/path/to/my/file'
replace_in_file(file_path, 'old-text', 'new-text')

Convert JSONArray to String Array

public static String[] getStringArray(JSONArray jsonArray) {
    String[] stringArray = null;
    if (jsonArray != null) {
        int length = jsonArray.length();
        stringArray = new String[length];
        for (int i = 0; i < length; i++) {
            stringArray[i] = jsonArray.optString(i);
        }
    }
    return stringArray;
}

Is there any option to limit mongodb memory usage?

This can be done with cgroups, by combining knowledge from these two articles: https://www.percona.com/blog/2015/07/01/using-cgroups-to-limit-mysql-and-mongodb-memory-usage/
http://frank2.net/cgroups-ubuntu-14-04/

You can find here a small shell script which will create config and init files for Ubuntu 14.04: http://brainsuckerna.blogspot.com.by/2016/05/limiting-mongodb-memory-usage-with.html

Just like that:

sudo bash -c 'curl -o- http://brains.by/misc/mongodb_memory_limit_ubuntu1404.sh | bash'

React Native Responsive Font Size

Need to use this way I have used this one and it's working fine.

react-native-responsive-screen npm install react-native-responsive-screen --save

Just like I have a device 1080x1920

The vertical number we calculate from height **hp**
height:200
200/1920*100 = 10.41% - height:hp("10.41%")


The Horizontal number we calculate from width **wp**
width:200
200/1080*100 = 18.51% - Width:wp("18.51%")

It's working for all device

How to find length of a string array?

As all the above answers have suggested it will throw a NullPointerException.

Please initialise it with some value(s) and then you can use the length property correctly. For example:

String[] str = { "plastic", "paper", "use", "throw" };
System.out.println("Length is:::" + str.length);

The array 'str' is now defined, and so it's length also has a defined value.

How to Execute a Python File in Notepad ++?

In Notepad++, go to Run ? Run..., select the path and idle.py file of your Python installation:

C:\Python27\Lib\idlelib\idle.py

add a space and this:

"$(FULL_CURRENT_PATH)"

and here you are!

Video demostration:

https://www.youtube.com/watch?v=sJipYE1JT38

How do I get some variable from another class in Java?

Your example is perfect: the field is private and it has a getter. This is the normal way to access a field. If you need a direct access to an object field, use reflection. Using reflection to get a field's value is a hack and should be used in extreme cases such as using a library whose code you cannot change.

Invalid default value for 'dateAdded'

mysql version 5.5 set datetime default value as CURRENT_TIMESTAMP will be report error you can update to version 5.6 , it set datetime default value as CURRENT_TIMESTAMP

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

Adding my two cents, based on a performance issue I observed.

If simple queries are getting parellelized unnecessarily, it can bring more problems than solving one. However, before adding MAXDOP into the query as "knee-jerk" fix, there are some server settings to check.

In Jeremiah Peschka - Five SQL Server Settings to Change, MAXDOP and "COST THRESHOLD FOR PARALLELISM" (CTFP) are mentioned as important settings to check.

Note: Paul White mentioned max server memory aslo as a setting to check, in a response to Performance problem after migration from SQL Server 2005 to 2012. A good kb article to read is Using large amounts of memory can result in an inefficient plan in SQL Server

Jonathan Kehayias - Tuning ‘cost threshold for parallelism’ from the Plan Cache helps to find out good value for CTFP.

Why is cost threshold for parallelism ignored?

Aaron Bertrand - Six reasons you should be nervous about parallelism has a discussion about some scenario where MAXDOP is the solution.

Parallelism-Inhibiting Components are mentioned in Paul White - Forcing a Parallel Query Execution Plan

Handling the null value from a resultset in JAVA

output = rs.getString("column");// if data is null `output` would be null, so there is no chance of NPE unless `rs` is `null`

if(output == null){// if you fetched null value then initialize output with blank string
  output= "";
}

Is there a way to get rid of accents and convert a whole string to regular letters?

I suggest Junidecode . It will handle not only 'L' and 'Ø', but it also works well for transcribing from other alphabets, such as Chinese, into Latin alphabet.

Make git automatically remove trailing whitespace before committing

To delete trailing whitespace at end of line in a file portably, use ed:

test -s file &&
   printf '%s\n' H ',g/[[:space:]]*$/s///' 'wq' | ed -s file

get one item from an array of name,value JSON

To answer your exact question you can get the exact behaviour you want by extending the Array prototype with:

Array.prototype.get = function(name) {
    for (var i=0, len=this.length; i<len; i++) {
        if (typeof this[i] != "object") continue;
        if (this[i].name === name) return this[i].value;
    }
};

this will add the get() method to all arrays and let you do what you want, i.e:

arr.get('k1'); //= abc

Edit a specific Line of a Text File in C#

You need to Open the output file for write access rather than using a new StreamReader, which always overwrites the output file.

StreamWriter stm = null;
fi = new FileInfo(@"C:\target.xml");
if (fi.Exists)
   stm = fi.OpenWrite();

Of course, you will still have to seek to the correct line in the output file, which will be hard since you can't read from it, so unless you already KNOW the byte offset to seek to, you probably really want read/write access.

FileStream stm = fi.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);

with this stream, you can read until you get to the point where you want to make changes, then write. Keep in mind that you are writing bytes, not lines, so to overwrite a line you will need to write the same number of characters as the line you want to change.

How do I set an absolute include path in PHP?

I've come up with a single line of code to set at top of my every php script as to compensate:

<?php if(!$root) for($i=count(explode("/",$_SERVER["PHP_SELF"]));$i>2;$i--) $root .= "../"; ?>

By this building $root to bee "../" steps up in hierarchy from wherever the file is placed. Whenever I want to include with an absolut path the line will be:

<?php include($root."some/include/directory/file.php"); ?>

I don't really like it, seems as an awkward way to solve it, but it seem to work whatever system php runs on and wherever the file is placed, making it system independent. To reach files outside the web directory add some more ../ after $root, e.g. $root."../external/file.txt".

Overloading operators in typedef structs (c++)

try this:

struct Pos{
    int x;
    int y;

    inline Pos& operator=(const Pos& other){
        x=other.x;
        y=other.y;
        return *this;
    }

    inline Pos operator+(const Pos& other) const {
        Pos res {x+other.x,y+other.y};
        return res;
    }

    const inline bool operator==(const Pos& other) const {
        return (x==other.x and y == other.y);
    }
 };  

Adding extra zeros in front of a number using jQuery?

Note: see Update 2 if you are using latest ECMAScript...


Here a solution I liked for its simplicity from an answer to a similar question:

var n = 123

String('00000' + n).slice(-5); // returns 00123
('00000' + n).slice(-5);       // returns 00123

UPDATE

As @RWC suggested you can wrap this of course nicely in a generic function like this:

function leftPad(value, length) { 
    return ('0'.repeat(length) + value).slice(-length); 
}

leftPad(123, 5); // returns 00123

And for those who don't like the slice:

function leftPad(value, length) {
    value = String(value);
    length = length - value.length;
    return ('0'.repeat(length) + value)
}

But if performance matters I recommend reading through the linked answer before choosing one of the solutions suggested.

UPDATE 2

In ES6 the String class now comes with a inbuilt padStart method which adds leading characters to a string. Check MDN here for reference on String.prototype.padStart(). And there is also a padEnd method for ending characters.

So with ES6 it became as simple as:

var n = 123;
n.padStart(5, '0'); // returns 00123

What are the differences between stateless and stateful systems, and how do they impact parallelism?

A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]

A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.

From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.

Is not an enclosing class Java

No need to make the nested class as static but it must be public

public class Test {
    public static void main(String[] args) {
        Shape shape = new Shape();
        Shape s = shape.new Shape.ZShape();
    }
}

How to store .pdf files into MySQL as BLOBs using PHP?

In regards to Gordon M's answer above, the 1st and 2nd parameter in mysqli_real_escape_string () call should be swapped for the newer php versions, according to: http://php.net/manual/en/mysqli.real-escape-string.php

Getting Hour and Minute in PHP

print date('H:i');
$var = date('H:i');

Should do it, for the current time. Use a lower case h for 12 hour clock instead of 24 hour.

More date time formats listed here.

How to convert R Markdown to PDF?

If you don't want to install anything you can output html. Then open the html file - it should open in a browser window, then right click to print. In the print window, select "save as pdf" in the bottom right hand corner if you're on a Mac. Voila!

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

can you try if.else

> col2=ifelse(df1$col=="true",1,0)
> df1
$col
[1] "true"  "false"

> cbind(df1$col)
     [,1]   
[1,] "true" 
[2,] "false"
> cbind(df1$col,col2)
             col2
[1,] "true"  "1" 
[2,] "false" "0" 

How to switch to another domain and get-aduser

get-aduser -Server "servername" -Identity %username% -Properties *

get-aduser -Server "testdomain.test.net" -Identity testuser -Properties *

These work when you have the username. Also less to type than using the -filter property.

EDIT: Formatting.

JQuery Parsing JSON array

var dataArray = [];
var obj = jQuery.parseJSON(response);
  for( key in obj ) 
  dataArray.push([key.toString(), obj [key]]);
};

In Python, how do you convert seconds since epoch to a `datetime` object?

Note that datetime.datetime.fromtimestamp(timestamp) and .utcfromtimestamp(timestamp) fail on windows for dates before Jan. 1, 1970 while negative unix timestamps seem to work on unix-based platforms. The docs say this:

"This may raise ValueError, if the timestamp is out of the range of values supported by the platform C gmtime() function. It’s common for this to be restricted to years in 1970 through 2038"

See also Issue1646728

Preprocessing in scikit learn - single sample - Depreciation warning

I faced the same issue and got the same deprecation warning. I was using a numpy array of [23, 276] when I got the message. I tried reshaping it as per the warning and end up in nowhere. Then I select each row from the numpy array (as I was iterating over it anyway) and assigned it to a list variable. It worked then without any warning.

array = []
array.append(temp[0])

Then you can use the python list object (here 'array') as an input to sk-learn functions. Not the most efficient solution, but worked for me.

Find TODO tags in Eclipse

Go TO Window>Show View >Markers

than you will get java task .

java task have all TODOs of your project

How can I convert a Word document to PDF?

Using JACOB call Office Word is a 100% perfect solution. But it only supports on Windows platform because need Office Word installed.

  1. Download JACOB archive (the latest version is 1.19);
  2. Add jacob.jar to your project classpath;
  3. Add jacob-1.19-x32.dll or jacob-1.19-x64.dll (depends on your jdk version) to ...\Java\jdk1.x.x_xxx\jre\bin
  4. Using JACOB API call Office Word to convert doc/docx to pdf.

    public void convertDocx2pdf(String docxFilePath) {
    File docxFile = new File(docxFilePath);
    String pdfFile = docxFilePath.substring(0, docxFilePath.lastIndexOf(".docx")) + ".pdf";
    
    if (docxFile.exists()) {
        if (!docxFile.isDirectory()) { 
            ActiveXComponent app = null;
    
            long start = System.currentTimeMillis();
            try {
                ComThread.InitMTA(true); 
                app = new ActiveXComponent("Word.Application");
                Dispatch documents = app.getProperty("Documents").toDispatch();
                Dispatch document = Dispatch.call(documents, "Open", docxFilePath, false, true).toDispatch();
                File target = new File(pdfFile);
                if (target.exists()) {
                    target.delete();
                }
                Dispatch.call(document, "SaveAs", pdfFile, 17);
                Dispatch.call(document, "Close", false);
                long end = System.currentTimeMillis();
                logger.info("============Convert Finished:" + (end - start) + "ms");
            } catch (Exception e) {
                logger.error(e.getLocalizedMessage(), e);
                throw new RuntimeException("pdf convert failed.");
            } finally {
                if (app != null) {
                    app.invoke("Quit", new Variant[] {});
                }
                ComThread.Release();
            }
        }
    }
    

    }

Amazon S3 direct file upload from client browser - private key disclosure

I think what you want is Browser-Based Uploads Using POST.

Basically, you do need server-side code, but all it does is generate signed policies. Once the client-side code has the signed policy, it can upload using POST directly to S3 without the data going through your server.

Here's the official doc links:

Diagram: http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingHTTPPOST.html

Example code: http://docs.aws.amazon.com/AmazonS3/latest/dev/HTTPPOSTExamples.html

The signed policy would go in your html in a form like this:

<html>
  <head>
    ...
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    ...
  </head>
  <body>
  ...
  <form action="http://johnsmith.s3.amazonaws.com/" method="post" enctype="multipart/form-data">
    Key to upload: <input type="input" name="key" value="user/eric/" /><br />
    <input type="hidden" name="acl" value="public-read" />
    <input type="hidden" name="success_action_redirect" value="http://johnsmith.s3.amazonaws.com/successful_upload.html" />
    Content-Type: <input type="input" name="Content-Type" value="image/jpeg" /><br />
    <input type="hidden" name="x-amz-meta-uuid" value="14365123651274" />
    Tags for File: <input type="input" name="x-amz-meta-tag" value="" /><br />
    <input type="hidden" name="AWSAccessKeyId" value="AKIAIOSFODNN7EXAMPLE" />
    <input type="hidden" name="Policy" value="POLICY" />
    <input type="hidden" name="Signature" value="SIGNATURE" />
    File: <input type="file" name="file" /> <br />
    <!-- The elements after this will be ignored -->
    <input type="submit" name="submit" value="Upload to Amazon S3" />
  </form>
  ...
</html>

Notice the FORM action is sending the file directly to S3 - not via your server.

Every time one of your users wants to upload a file, you would create the POLICY and SIGNATURE on your server. You return the page to the user's browser. The user can then upload a file directly to S3 without going through your server.

When you sign the policy, you typically make the policy expire after a few minutes. This forces your users to talk to your server before uploading. This lets you monitor and limit uploads if you desire.

The only data going to or from your server is the signed URLs. Your secret keys stay secret on the server.

shell-script headers (#!/bin/sh vs #!/bin/csh)

The #! line tells the kernel (specifically, the implementation of the execve system call) that this program is written in an interpreted language; the absolute pathname that follows identifies the interpreter. Programs compiled to machine code begin with a different byte sequence -- on most modern Unixes, 7f 45 4c 46 (^?ELF) that identifies them as such.

You can put an absolute path to any program you want after the #!, as long as that program is not itself a #! script. The kernel rewrites an invocation of

./script arg1 arg2 arg3 ...

where ./script starts with, say, #! /usr/bin/perl, as if the command line had actually been

/usr/bin/perl ./script arg1 arg2 arg3

Or, as you have seen, you can use #! /bin/sh to write a script intended to be interpreted by sh.

The #! line is only processed if you directly invoke the script (./script on the command line); the file must also be executable (chmod +x script). If you do sh ./script the #! line is not necessary (and will be ignored if present), and the file does not have to be executable. The point of the feature is to allow you to directly invoke interpreted-language programs without having to know what language they are written in. (Do grep '^#!' /usr/bin/* -- you will discover that a great many stock programs are in fact using this feature.)

Here are some rules for using this feature:

  • The #! must be the very first two bytes in the file. In particular, the file must be in an ASCII-compatible encoding (e.g. UTF-8 will work, but UTF-16 won't) and must not start with a "byte order mark", or the kernel will not recognize it as a #! script.
  • The path after #! must be an absolute path (starts with /). It cannot contain space, tab, or newline characters.
  • It is good style, but not required, to put a space between the #! and the /. Do not put more than one space there.
  • You cannot put shell variables on the #! line, they will not be expanded.
  • You can put one command-line argument after the absolute path, separated from it by a single space. Like the absolute path, this argument cannot contain space, tab, or newline characters. Sometimes this is necessary to get things to work (#! /usr/bin/awk -f), sometimes it's just useful (#! /usr/bin/perl -Tw). Unfortunately, you cannot put two or more arguments after the absolute path.
  • Some people will tell you to use #! /usr/bin/env interpreter instead of #! /absolute/path/to/interpreter. This is almost always a mistake. It makes your program's behavior depend on the $PATH variable of the user who invokes the script. And not all systems have env in the first place.
  • Programs that need setuid or setgid privileges can't use #!; they have to be compiled to machine code. (If you don't know what setuid is, don't worry about this.)

Regarding csh, it relates to sh roughly as Nutrimat Advanced Tea Substitute does to tea. It has (or rather had; modern implementations of sh have caught up) a number of advantages over sh for interactive usage, but using it (or its descendant tcsh) for scripting is almost always a mistake. If you're new to shell scripting in general, I strongly recommend you ignore it and focus on sh. If you are using a csh relative as your login shell, switch to bash or zsh, so that the interactive command language will be the same as the scripting language you're learning.

How to compare two dates to find time difference in SQL Server 2005, date manipulation

If you trying to get worked hours with some accuracy, try this (tested in SQL Server 2016)

SELECT DATEDIFF(MINUTE,job_start, job_end)/60.00;

Various DATEDIFF functionalities are:

SELECT DATEDIFF(year,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(quarter,     '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(month,       '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(dayofyear,   '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(day,         '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(week,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(hour,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(minute,      '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(second,      '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(millisecond, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');

Ref: https://docs.microsoft.com/en-us/sql/t-sql/functions/datediff-transact-sql?view=sql-server-2017

TypeError: 'list' object is not callable while trying to access a list

Even I got the same error, but I solved it, I had used many list in my work so I just restarted my kernel (meaning if you are using a notebook such as Jupyter or Google Colab you can just restart and again run all the cells, by doing this your problem will be solved and the error vanishes.

Thank you.

DateTimeFormat in TypeScript

This should work...

var displayDate = new Date().toLocaleDateString();

alert(displayDate);

But I suspect you are trying it on something else, for example:

var displayDate = Date.now.toLocaleDateString(); // No!

alert(displayDate);

INFO: No Spring WebApplicationInitializer types detected on classpath

I had this info message "No Spring WebApplicationInitializer types detected on classpath" while deploying a WAR with spring integration beans in WebLogic server. Actually, I could observe that the servlet URL returned 404 Not Found and beside that info message with a negative tone "No Spring ...etc" in Server logs, nothing else was seemingly in error in my spring config; no build or deployment errors, no complaints. Indeed, I suspected that the beans.xml (spring context XML) was actually not picked up at all and that was bound to the very specific organizing of artefacts in Oracle's jDeveloper. The solution is to play carefully with the 'contributors' and 'filters' for the WEB-INF/classes category when you edit your deployment profile under the 'deployment' topic in project properties.

Precisely, I would advise to name your spring context by the jDeveloper default "beans.xml" and place it side by side to the WEB-INF subdirectory itself (under your web Apllication source path, e.g. like <...your project path>/public_html/). Then in the WEB-INF/classes category (when editing the deployment profile) your can check the Project HTML root directory in the 'contributor' list, and then select the beans.xml in filters, and then ensure your web.xml features a context-param value like classpath:beans.xml.

Once that was fixed, I was able to progress and after some more bean config changes and implementations, the message "No Spring WebApplicationInitializer types detected on classpath" came back! Actually, I did not notice when and why exactly it came back. This second time, I added a

public class HttpGatewayInit implements WebApplicationInitializer { ... }

which implements empty inherited methods, and the whole application works fine!

...If you feel that java EE development has been getting a bit too crazy with cascades of XML configuration files (some edited manually, others through wizards) intepreted by cascades of variant initializers, let me insist that I fully share your point.

How to style a checkbox using CSS

You can simply use appearance: none on modern browsers, so that there is no default styling and all your styles are applied properly:

input[type=checkbox] {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  display: inline-block;
  width: 2em;
  height: 2em;
  border: 1px solid gray;
  outline: none;
  vertical-align: middle;
}

input[type=checkbox]:checked {
  background-color: blue;
}

What's the best way to set a single pixel in an HTML5 canvas?

What about a rectangle? That's got to be more efficient than creating an ImageData object.

Immediate exit of 'while' loop in C++

cin >> choice;
while(choice!=99) {
    cin>>gNum;
    cin >> choice
}

You don't need a break, in that case.

Java: int[] array vs int array[]

Both are the same. I usually use int[] array = new int[10];, because of better (contiguous) readability of the type int[].

How to install pip for Python 3.6 on Ubuntu 16.10?

Let's suppose that you have a system running Ubuntu 16.04, 16.10, or 17.04, and you want Python 3.6 to be the default Python.

If you're using Ubuntu 16.04 LTS, you'll need to use a PPA:

sudo add-apt-repository ppa:jonathonf/python-3.6  # (only for 16.04 LTS)

Then, run the following (this works out-of-the-box on 16.10 and 17.04):

sudo apt update
sudo apt install python3.6
sudo apt install python3.6-dev
sudo apt install python3.6-venv
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.6 get-pip.py
sudo ln -s /usr/bin/python3.6 /usr/local/bin/python3
sudo ln -s /usr/local/bin/pip /usr/local/bin/pip3

# Do this only if you want python3 to be the default Python
# instead of python2 (may be dangerous, esp. before 2020):
# sudo ln -s /usr/bin/python3.6 /usr/local/bin/python

When you have completed all of the above, each of the following shell commands should indicate Python 3.6.1 (or a more recent version of Python 3.6):

python --version   # (this will reflect your choice, see above)
python3 --version
$(head -1 `which pip` | tail -c +3) --version
$(head -1 `which pip3` | tail -c +3) --version

MySQL how to join tables on two fields

JOIN t2 ON t1.id=t2.id AND t1.date=t2.date

Specifying onClick event type with Typescript and React.Konva

You should be using event.currentTarget. React is mirroring the difference between currentTarget (element the event is attached to) and target (the element the event is currently happening on). Since this is a mouse event, type-wise the two could be different, even if it doesn't make sense for a click.

https://github.com/facebook/react/issues/5733 https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget

Calling an API from SQL Server stored procedure

Simple SQL triggered API call without building a code project

I know this is far from perfect or architectural purity, but I had a customer with a short term, critical need to integrate with a third party product via an immature API (no wsdl) I basically needed to call the API when a database event occurred. I was given basic call info - URL, method, data elements and Token, but no wsdl or other start to import into a code project. All recommendations and solutions seemed start with that import.

I used the ARC (Advanced Rest Client) Chrome extension and JaSON to test the interaction with the Service from a browser and refine the call. That gave me the tested, raw call structure and response and let me play with the API quickly. From there, I started trying to generate the wsdl or xsd from the json using online conversions but decided that was going to take too long to get working, so I found cURL (clouds part, music plays). cURL allowed me to send the API calls to a local manager from anywhere. I then broke a few more design rules and built a trigger that queued the DB events and a SQL stored procedure and scheduled task to pass the parameters to cURL and make the calls. I initially had the trigger calling XP_CMDShell (I know, booo) but didn't like the transactional implications or security issues, so switched to the Stored Procedure method.

In the end, DB insert matching the API call case triggers write to Queue table with parameters for API call Stored procedure run every 5 seconds runs Cursor to pull each Queue table entry, send the XP_CMDShell call to the bat file with parameters Bat file contains Curl call with parameters inserted sending output to logs. Works well.

Again, not perfect, but for a tight timeline, and a system used short term, and that can be closely monitored to react to connectivity and unforeseen issues, it worked.

Hope that helps someone struggling with limited API info get a solution going quickly.

How to set shadows in React Native for android?

Also i'd like to add that if one's trying to apply shadow in a TouchableHighlight Component in which child has borderRadius, the parent element (TouchableHighlight) also need the radius set in order to elevation prop work on Android.

How to achieve function overloading in C?

If your compiler is gcc and you don't mind doing hand updates every time you add a new overload you can do some macro magic and get the result you want in terms of callers, it's not as nice to write... but it's possible

look at __builtin_types_compatible_p, then use it to define a macro that does something like

#define foo(a) \
((__builtin_types_compatible_p(int, a)?foo(a):(__builtin_types_compatible_p(float, a)?foo(a):)

but yea nasty, just don't

EDIT: C1X will be getting support for type generic expressions they look like this:

#define cbrt(X) _Generic((X), long double: cbrtl, \
                              default: cbrt, \
                              float: cbrtf)(X)

Checking if an object is a given type in Swift

Just for the sake of completeness based on the accepted answer and some others:

let items : [Any] = ["Hello", "World", 1]

for obj in items where obj is String {
   // obj is a String. Do something with str
}

But you can also (compactMap also "maps" the values which filter doesn't):

items.compactMap { $0 as? String }.forEach{ /* do something with $0 */ ) }

And a version using switch:

for obj in items {
    switch (obj) {
        case is Int:
           // it's an integer
        case let stringObj as String:
           // you can do something with stringObj which is a String
        default:
           print("\(type(of: obj))") // get the type
    }
}

But sticking to the question, to check if it's an array (i.e. [String]):

let items : [Any] = ["Hello", "World", 1, ["Hello", "World", "of", "Arrays"]]

for obj in items {
  if let stringArray = obj as? [String] {
    print("\(stringArray)")
  }
}

Or more generally (see this other question answer):

for obj in items {
  if obj is [Any] {
    print("is [Any]")
  }

  if obj is [AnyObject] {
    print("is [AnyObject]")
  }

  if obj is NSArray {
    print("is NSArray")
  }
}

What does the "+=" operator do in Java?

You can take a look at the bytecode whenever you want to understand how java operators work. Here if you compile:

int x = 0;
x += 0.1;

the bytecode will be accessible with jdk command javap -c [*.class]:(you can refer to Java bytecode instruction listings for more explanation about bytecode)

0: iconst_0 //  load the int value 0 onto the stack
1: istore_1 //  store int value into variable 1 (x)
2: iload_1 // load an int value from local variable 1 (x)
3: i2d // convert an int into a double (cast x to double)
4: ldc2_w        #2                  // double 0.1d -> push a constant value (0.1) from a constant pool onto the stack
7: dadd //  add two doubles (pops two doubles from stack, adds them, and pushes the answer onto stack)
8: d2i // convert a double to an int (pops a value from stack, casts it to int and pushes it onto stack)
9: istore_1 // store int value into variable 1 (x)

Now it is clear that java compiler promotes x to double and then adds it with 0.1.
Finally it casts the answer to integer .
There is one interesting fact I found out that when you write:

byte b = 10;
b += 0.1;

compiler casts b to double, adds it with 0.1, casts the result which is double to integer, and finally casts it to byte and that is because there is no instruction to cast double to byte directly.
You can check the bytecode if you doubt :)

Div with horizontal scrolling only

For horizontal scroll, keep these two properties in mind:

overflow-x:scroll;
white-space: nowrap;

See working link : click me

HTML

<p>overflow:scroll</p>
<div class="scroll">You can use the overflow property when you want to have better   control of the layout. The default value is visible.You can use the overflow property when you want     to have better control of the layout. The default value is visible.</div>

CSS

div.scroll
{
background-color:#00FFFF;
height:40px;
overflow-x:scroll;
white-space: nowrap;
}

Output in a table format in Java's System.out

Because most of solutions is bit outdated I could also suggest asciitable which already available in maven (de.vandermeer:asciitable:0.3.2) and may produce very complicated configurations.

Features (by offsite):

  • Text table with some flexibility for rules and content, alignment, format, padding, margins, and frames:
  • add text, as often as required in many different formats (string, text provider, render provider, ST, clusters),
  • removes all excessive white spaces (tabulators, extra blanks, combinations of carriage return and line feed),
  • 6 different text alignments: left, right, centered, justified, justified last line left, justified last line right,
  • flexible width, set for text and calculated in many different ways for rendering
  • padding characters for left and right padding (configurable separately)
  • padding characters for top and bottom padding (configurable separately)
  • several options for drawing grids
  • rules with different styles (as supported by the used grid theme: normal, light, strong, heavy)
  • top/bottom/left/right margins outside a frame
  • character conversion to generated text suitable for further process, e.g. for LaTeX and HTML

And usage still looks easy:

AsciiTable at = new AsciiTable();

at.addRule();
at.addRow("row 1 col 1", "row 1 col 2");
at.addRule();
at.addRow("row 2 col 1", "row 2 col 2");
at.addRule();

System.out.println(at.render()); // Finally, print the table to standard out.

What should be in my .gitignore for an Android Studio project?

I use this .gitignore. I found it at: http://th4t.net/android-studio-gitignore.html

*.iml
*.iws
*.ipr
.idea/
.gradle/
local.properties

*/build/

*~
*.swp

How does Spring autowire by name when more than one matching bean is found?

Another way of achieving the same result is to use the @Value annotation:

public class Main {
     private Country country;

     @Autowired
     public void setCountry(@Value("#{country}") Country country) {
          this.country = country;
     }
}

In this case, the "#{country} string is an Spring Expression Language (SpEL) expression which evaluates to a bean named country.

Insert into C# with SQLCommand

You can use dapper library:

conn2.Execute(@"INSERT INTO klant(klant_id,naam,voornaam) VALUES (@p1,@p2,@p3)", 
                new { p1 = klantId, p2 = klantNaam, p3 = klantVoornaam });

BTW Dapper is a Stack Overflow project :)

UPDATE: I believe you can't do it simpler without something like EF. Also try to use using statements when you are working with database connections. This will close connection automatically, even in case of exception. And connection will be returned to connections pool.

private readonly string _spionshopConnectionString;

private void Form1_Load(object sender, EventArgs e)
{            
    _spionshopConnectionString = ConfigurationManager
          .ConnectionStrings["connSpionshopString"].ConnectionString;
}

private void button4_Click(object sender, EventArgs e)
{
    using(var connection = new SqlConnection(_spionshopConnectionString))
    {
         connection.Execute(@"INSERT INTO klant(klant_id,naam,voornaam) 
                              VALUES (@klantId,@klantNaam,@klantVoornaam)",
                              new { 
                                      klantId = Convert.ToInt32(textBox1.Text), 
                                      klantNaam = textBox2.Text, 
                                      klantVoornaam = textBox3.Text 
                                  });
    }
}

ERROR in Cannot find module 'node-sass'

I met same issue installing node-sass when I am on Node 12.9.0

Once switching to Node 10.19.0, the issue is gone.

Reference: https://github.com/sass/node-sass/issues/2632

jQuery event to trigger action when a div is made visible

There is no native event you can hook into for this however you can trigger an event from your script after you have made the div visible using the .trigger function

e.g

//declare event to run when div is visible
function isVisible(){
   //do something

}

//hookup the event
$('#someDivId').bind('isVisible', isVisible);

//show div and trigger custom event in callback when div is visible
$('#someDivId').show('slow', function(){
    $(this).trigger('isVisible');
});

Calculate business days

Here's a function from the user comments on the date() function page in the PHP manual. It's an improvement of an earlier function in the comments that adds support for leap years.

Enter the starting and ending dates, along with an array of any holidays that might be in between, and it returns the working days as an integer:

<?php
//The function returns the no. of business days between two dates and it skips the holidays
function getWorkingDays($startDate,$endDate,$holidays){
    // do strtotime calculations just once
    $endDate = strtotime($endDate);
    $startDate = strtotime($startDate);


    //The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
    //We add one to inlude both dates in the interval.
    $days = ($endDate - $startDate) / 86400 + 1;

    $no_full_weeks = floor($days / 7);
    $no_remaining_days = fmod($days, 7);

    //It will return 1 if it's Monday,.. ,7 for Sunday
    $the_first_day_of_week = date("N", $startDate);
    $the_last_day_of_week = date("N", $endDate);

    //---->The two can be equal in leap years when february has 29 days, the equal sign is added here
    //In the first case the whole interval is within a week, in the second case the interval falls in two weeks.
    if ($the_first_day_of_week <= $the_last_day_of_week) {
        if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--;
        if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--;
    }
    else {
        // (edit by Tokes to fix an edge case where the start day was a Sunday
        // and the end day was NOT a Saturday)

        // the day of the week for start is later than the day of the week for end
        if ($the_first_day_of_week == 7) {
            // if the start date is a Sunday, then we definitely subtract 1 day
            $no_remaining_days--;

            if ($the_last_day_of_week == 6) {
                // if the end date is a Saturday, then we subtract another day
                $no_remaining_days--;
            }
        }
        else {
            // the start date was a Saturday (or earlier), and the end date was (Mon..Fri)
            // so we skip an entire weekend and subtract 2 days
            $no_remaining_days -= 2;
        }
    }

    //The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder
//---->february in none leap years gave a remainder of 0 but still calculated weekends between first and last day, this is one way to fix it
   $workingDays = $no_full_weeks * 5;
    if ($no_remaining_days > 0 )
    {
      $workingDays += $no_remaining_days;
    }

    //We subtract the holidays
    foreach($holidays as $holiday){
        $time_stamp=strtotime($holiday);
        //If the holiday doesn't fall in weekend
        if ($startDate <= $time_stamp && $time_stamp <= $endDate && date("N",$time_stamp) != 6 && date("N",$time_stamp) != 7)
            $workingDays--;
    }

    return $workingDays;
}

//Example:

$holidays=array("2008-12-25","2008-12-26","2009-01-01");

echo getWorkingDays("2008-12-22","2009-01-02",$holidays)
// => will return 7
?>

How can I compare two dates in PHP?

Here's a way on how to get the difference between two dates in minutes.

// set dates
$date_compare1= date("d-m-Y h:i:s a", strtotime($date1));
// date now
$date_compare2= date("d-m-Y h:i:s a", strtotime($date2));

// calculate the difference
$difference = strtotime($date_compare1) - strtotime($date_compare2);
$difference_in_minutes = $difference / 60;

echo $difference_in_minutes;

Failure [INSTALL_FAILED_ALREADY_EXISTS] when I tried to update my application

If you install the application on your device via adb install you should look for the reinstall option which should be -r. So if you do adb install -r you should be able to install without uninstalling before.

What does "dereferencing" a pointer mean?

Reviewing the basic terminology

It's usually good enough - unless you're programming assembly - to envisage a pointer containing a numeric memory address, with 1 referring to the second byte in the process's memory, 2 the third, 3 the fourth and so on....

  • What happened to 0 and the first byte? Well, we'll get to that later - see null pointers below.
  • For a more accurate definition of what pointers store, and how memory and addresses relate, see "More about memory addresses, and why you probably don't need to know" at the end of this answer.

When you want to access the data/value in the memory that the pointer points to - the contents of the address with that numerical index - then you dereference the pointer.

Different computer languages have different notations to tell the compiler or interpreter that you're now interested in the pointed-to object's (current) value - I focus below on C and C++.

A pointer scenario

Consider in C, given a pointer such as p below...

const char* p = "abc";

...four bytes with the numerical values used to encode the letters 'a', 'b', 'c', and a 0 byte to denote the end of the textual data, are stored somewhere in memory and the numerical address of that data is stored in p. This way C encodes text in memory is known as ASCIIZ.

For example, if the string literal happened to be at address 0x1000 and p a 32-bit pointer at 0x2000, the memory content would be:

Memory Address (hex)    Variable name    Contents
1000                                     'a' == 97 (ASCII)
1001                                     'b' == 98
1002                                     'c' == 99
1003                                     0
...
2000-2003               p                1000 hex

Note that there is no variable name/identifier for address 0x1000, but we can indirectly refer to the string literal using a pointer storing its address: p.

Dereferencing the pointer

To refer to the characters p points to, we dereference p using one of these notations (again, for C):

assert(*p == 'a');  // The first character at address p will be 'a'
assert(p[1] == 'b'); // p[1] actually dereferences a pointer created by adding
                     // p and 1 times the size of the things to which p points:
                     // In this case they're char which are 1 byte in C...
assert(*(p + 1) == 'b');  // Another notation for p[1]

You can also move pointers through the pointed-to data, dereferencing them as you go:

++p;  // Increment p so it's now 0x1001
assert(*p == 'b');  // p == 0x1001 which is where the 'b' is...

If you have some data that can be written to, then you can do things like this:

int x = 2;
int* p_x = &x;  // Put the address of the x variable into the pointer p_x
*p_x = 4;       // Change the memory at the address in p_x to be 4
assert(x == 4); // Check x is now 4

Above, you must have known at compile time that you would need a variable called x, and the code asks the compiler to arrange where it should be stored, ensuring the address will be available via &x.

Dereferencing and accessing a structure data member

In C, if you have a variable that is a pointer to a structure with data members, you can access those members using the -> dereferencing operator:

typedef struct X { int i_; double d_; } X;
X x;
X* p = &x;
p->d_ = 3.14159;  // Dereference and access data member x.d_
(*p).d_ *= -1;    // Another equivalent notation for accessing x.d_

Multi-byte data types

To use a pointer, a computer program also needs some insight into the type of data that is being pointed at - if that data type needs more than one byte to represent, then the pointer normally points to the lowest-numbered byte in the data.

So, looking at a slightly more complex example:

double sizes[] = { 10.3, 13.4, 11.2, 19.4 };
double* p = sizes;
assert(p[0] == 10.3);  // Knows to look at all the bytes in the first double value
assert(p[1] == 13.4);  // Actually looks at bytes from address p + 1 * sizeof(double)
                       // (sizeof(double) is almost always eight bytes)
++p;                   // Advance p by sizeof(double)
assert(*p == 13.4);    // The double at memory beginning at address p has value 13.4
*(p + 2) = 29.8;       // Change sizes[3] from 19.4 to 29.8
                       // Note earlier ++p and + 2 here => sizes[3]

Pointers to dynamically allocated memory

Sometimes you don't know how much memory you'll need until your program is running and sees what data is thrown at it... then you can dynamically allocate memory using malloc. It is common practice to store the address in a pointer...

int* p = (int*)malloc(sizeof(int)); // Get some memory somewhere...
*p = 10;            // Dereference the pointer to the memory, then write a value in
fn(*p);             // Call a function, passing it the value at address p
(*p) += 3;          // Change the value, adding 3 to it
free(p);            // Release the memory back to the heap allocation library

In C++, memory allocation is normally done with the new operator, and deallocation with delete:

int* p = new int(10); // Memory for one int with initial value 10
delete p;

p = new int[10];      // Memory for ten ints with unspecified initial value
delete[] p;

p = new int[10]();    // Memory for ten ints that are value initialised (to 0)
delete[] p;

See also C++ smart pointers below.

Losing and leaking addresses

Often a pointer may be the only indication of where some data or buffer exists in memory. If ongoing use of that data/buffer is needed, or the ability to call free() or delete to avoid leaking the memory, then the programmer must operate on a copy of the pointer...

const char* p = asprintf("name: %s", name);  // Common but non-Standard printf-on-heap

// Replace non-printable characters with underscores....
for (const char* q = p; *q; ++q)
    if (!isprint(*q))
        *q = '_';

printf("%s\n", p); // Only q was modified
free(p);

...or carefully orchestrate reversal of any changes...

const size_t n = ...;
p += n;
...
p -= n;  // Restore earlier value...
free(p);

C++ smart pointers

In C++, it's best practice to use smart pointer objects to store and manage the pointers, automatically deallocating them when the smart pointers' destructors run. Since C++11 the Standard Library provides two, unique_ptr for when there's a single owner for an allocated object...

{
    std::unique_ptr<T> p{new T(42, "meaning")};
    call_a_function(p);
    // The function above might throw, so delete here is unreliable, but...
} // p's destructor's guaranteed to run "here", calling delete

...and shared_ptr for share ownership (using reference counting)...

{
    auto p = std::make_shared<T>(3.14, "pi");
    number_storage1.may_add(p); // Might copy p into its container
    number_storage2.may_add(p); // Might copy p into its container    } // p's destructor will only delete the T if neither may_add copied it

Null pointers

In C, NULL and 0 - and additionally in C++ nullptr - can be used to indicate that a pointer doesn't currently hold the memory address of a variable, and shouldn't be dereferenced or used in pointer arithmetic. For example:

const char* p_filename = NULL; // Or "= 0", or "= nullptr" in C++
int c;
while ((c = getopt(argc, argv, "f:")) != -1)
    switch (c) {
      case f: p_filename = optarg; break;
    }
if (p_filename)  // Only NULL converts to false
    ...   // Only get here if -f flag specified

In C and C++, just as inbuilt numeric types don't necessarily default to 0, nor bools to false, pointers are not always set to NULL. All these are set to 0/false/NULL when they're static variables or (C++ only) direct or indirect member variables of static objects or their bases, or undergo zero initialisation (e.g. new T(); and new T(x, y, z); perform zero-initialisation on T's members including pointers, whereas new T; does not).

Further, when you assign 0, NULL and nullptr to a pointer the bits in the pointer are not necessarily all reset: the pointer may not contain "0" at the hardware level, or refer to address 0 in your virtual address space. The compiler is allowed to store something else there if it has reason to, but whatever it does - if you come along and compare the pointer to 0, NULL, nullptr or another pointer that was assigned any of those, the comparison must work as expected. So, below the source code at the compiler level, "NULL" is potentially a bit "magical" in the C and C++ languages...

More about memory addresses, and why you probably don't need to know

More strictly, initialised pointers store a bit-pattern identifying either NULL or a (often virtual) memory address.

The simple case is where this is a numeric offset into the process's entire virtual address space; in more complex cases the pointer may be relative to some specific memory area, which the CPU may select based on CPU "segment" registers or some manner of segment id encoded in the bit-pattern, and/or looking in different places depending on the machine code instructions using the address.

For example, an int* properly initialised to point to an int variable might - after casting to a float* - access memory in "GPU" memory quite distinct from the memory where the int variable is, then once cast to and used as a function pointer it might point into further distinct memory holding machine opcodes for the program (with the numeric value of the int* effectively a random, invalid pointer within these other memory regions).

3GL programming languages like C and C++ tend to hide this complexity, such that:

  • If the compiler gives you a pointer to a variable or function, you can dereference it freely (as long as the variable's not destructed/deallocated meanwhile) and it's the compiler's problem whether e.g. a particular CPU segment register needs to be restored beforehand, or a distinct machine code instruction used

  • If you get a pointer to an element in an array, you can use pointer arithmetic to move anywhere else in the array, or even to form an address one-past-the-end of the array that's legal to compare with other pointers to elements in the array (or that have similarly been moved by pointer arithmetic to the same one-past-the-end value); again in C and C++, it's up to the compiler to ensure this "just works"

  • Specific OS functions, e.g. shared memory mapping, may give you pointers, and they'll "just work" within the range of addresses that makes sense for them

  • Attempts to move legal pointers beyond these boundaries, or to cast arbitrary numbers to pointers, or use pointers cast to unrelated types, typically have undefined behaviour, so should be avoided in higher level libraries and applications, but code for OSes, device drivers, etc. may need to rely on behaviour left undefined by the C or C++ Standard, that is nevertheless well defined by their specific implementation or hardware.

Disable button in angular with two conditions?

Using the ternary operator is possible like following.[disabled] internally required true or false for its operation.

<button type="button" 
  [disabled]="(testVariable1 != 0 || testVariable2!=0)? true:false"
  mat-button>Button</button>

OperationalError: database is locked

A very unusual scenario, which happened to me.

There was infinite recursion, which kept creating the objects.

More specifically, using DRF, I was overriding create method in a view, and I did

def create(self, request, *args, **kwargs):
    ....
    ....

    return self.create(request, *args, **kwargs)

Run a shell script with an html button

This is how it look like in pure bash

cat /usr/lib/cgi-bin/index.cgi

#!/bin/bash
echo Content-type: text/html
echo ""
## make POST and GET stings
## as bash variables available
if [ ! -z $CONTENT_LENGTH ] && [ "$CONTENT_LENGTH" -gt 0 ] && [ $CONTENT_TYPE != "multipart/form-data" ]; then
read -n $CONTENT_LENGTH POST_STRING <&0
eval `echo "${POST_STRING//;}"|tr '&' ';'`
fi
eval `echo "${QUERY_STRING//;}"|tr '&' ';'`

echo  "<!DOCTYPE html>"
echo  "<html>"
echo  "<head>"
echo  "</head>"

if [[ "$vote" = "a" ]];then
echo "you pressed A"
  sudo /usr/local/bin/run_a.sh
elif [[ "$vote" = "b" ]];then
echo "you pressed B"
  sudo /usr/local/bin/run_b.sh
fi

echo  "<body>"
echo  "<div id=\"content-container\">"
echo  "<div id=\"content-container-center\">"
echo  "<form id=\"choice\" name='form' method=\"POST\" action=\"/\">"
echo  "<button id=\"a\" type=\"submit\" name=\"vote\" class=\"a\" value=\"a\">A</button>"
echo  "<button id=\"b\" type=\"submit\" name=\"vote\" class=\"b\" value=\"b\">B</button>"
echo  "</form>"
echo  "<div id=\"tip\">"
echo  "</div>"
echo  "</div>"
echo  "</div>"
echo  "</div>"
echo  "</body>"
echo  "</html>"

Build with https://github.com/tinoschroeter/bash_on_steroids

Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

Just try a different Internet connection. I tried all the solutions above but none worked. However, when I tried using my cellular connection (instead of my DSL connection that stands behind a firewall), it worked immediately.

What SOAP client libraries exist for Python, and where is the documentation for them?

As I suggested here I recommend you roll your own. It's actually not that difficult and I suspect that's the reason there aren't better Python SOAP libraries out there.

Service Temporarily Unavailable Magento?

If removing the flag shows service temporary unavailable. Go to "http://localhost.com/downloader" and unisntall slider banner,BusinessDecision_Interaktingslider,lightbox2 and anotherone that I dont remember.

VC++ fatal error LNK1168: cannot open filename.exe for writing

I also had this same issue. My console window was no longer open, but I was able to see my application running by going to processes within task manager. The process name was the name of my application. Once I ended the process I was able to build and compile my code with no issues.

OnClick vs OnClientClick for an asp:CheckBox?

You can assign function to all checkboxes then ask for confirmation inside of it. If they choose yes, checkbox is allowed to be changed if no it remains unchanged.

In my case I am also using ASP .Net checkbox inside a repeater (or grid) with Autopostback="True" attribute, so on server side I need to compare the value submitted vs what's currently in db in order to know what confirmation value they chose and update db only if it was "yes".

$(document).ready(function () {
    $('input[type=checkbox]').click(function(){                
        var areYouSure = confirm('Are you sure you want make this change?');
        if (areYouSure) {
            $(this).prop('checked', this.checked);
        } else {
            $(this).prop('checked', !this.checked);
        }
    });
}); 


<asp:CheckBox ID="chk" AutoPostBack="true" onCheckedChanged="chk_SelectedIndexChanged" runat="server" Checked='<%#Eval("FinancialAid") %>' />

protected void chk_SelectedIndexChanged(Object sender, EventArgs e)
{
    using (myDataContext db = new myDataDataContext())
    {
        CheckBox chk = (CheckBox)sender;
        RepeaterItem row = (RepeaterItem) chk.NamingContainer;            
        var studentID = ((Label) row.FindControl("lblID")).Text;
        var z = (from b in db.StudentApplicants
        where b.StudentID == studentID
        select b).FirstOrDefault();                
        if(chk != null && chk.Checked != z.FinancialAid){
            z.FinancialAid = chk.Checked;                
            z.ModifiedDate = DateTime.Now;
            db.SubmitChanges();
            BindGrid();
        }
        gvData.DataBind();
    }
}

Multiline TextView in Android?

for me non of the solutions did not work. I know it is not a complete answer for this question, but sometimes it can help.

I put 4 textviews in a vertical linearlayout.

<Linearlayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation:"vertical"

    ...>
    <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text:"line1"
       .../>
    <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text:"line2"
       .../>
    <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text:"line3"
       .../>
    <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text:"line4"
       .../>
</LinearLayout>

This solution is good for cases that the text view text is constant, like labels.

PHP passing $_GET in linux command prompt

If you need to pass $_GET, $_REQUEST, $_POST, or anything else you can also use PHP interactive mode:

php -a

Then type:

<?php
$_GET['a']=1;
$_POST['b']=2;
include("/somefolder/some_file_path.php");

This will manually set any variables you want and then run your php file with those variables set.

ansible: lineinfile for several lines?

If you need to configure a set of unique property=value lines, I recommend a more concise loop. For example:

- name: Configure kernel parameters
  lineinfile:
    dest: /etc/sysctl.conf
    regexp: "^{{ item.property | regex_escape() }}="
    line: "{{ item.property }}={{ item.value }}"
  with_items:
    - { property: 'kernel.shmall', value: '2097152' }
    - { property: 'kernel.shmmax', value: '134217728' }
    - { property: 'fs.file-max', value: '65536' }

Using a dict as suggested by Alix Axel and adding automatic removing of matching commented out entries,

- name: Configure IPV4 Forwarding
  lineinfile:
    path: /etc/sysctl.conf
    regexp: "^#? *{{ item.key | regex_escape() }}="
    line: "{{ item.key }}={{ item.value }}"
  with_dict:
    'net.ipv4.ip_forward': 1

ascending/descending in LINQ - can one change the order via parameter?

In addition to the beautiful solution given by @Jon Skeet, I also needed ThenBy and ThenByDescending, so I am adding it based on his solution:

    public static IOrderedEnumerable<TSource> ThenByWithDirection<TSource, TKey>(
         this IOrderedEnumerable<TSource> source, 
         Func<TSource, TKey> keySelector,  
         bool descending)
    {
        return descending ? 
               source.ThenByDescending(keySelector) :
               source.ThenBy(keySelector);
    }

Automatic HTTPS connection/redirect with node.js/express

The idea is to check if the incoming request is made with https, if so simply don't redirect it again to https but continue as usual. Else, if it is http, redirect it with appending https.

app.use (function (req, res, next) {
  if (req.secure) {
          next();
  } else {
          res.redirect('https://' + req.headers.host + req.url);
  }
});

How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?

If you want to set a max width or height (so that it will not be very large) while keeping the images aspect-ratio, you can do this:

img{
   object-fit: contain;
   max-height: 70px;
}

Sending Arguments To Background Worker?

you can try this out if you want to pass more than one type of arguments, first add them all to an array of type Object and pass that object to RunWorkerAsync() here is an example :

   some_Method(){
   List<string> excludeList = new List<string>(); // list of strings
   string newPath ="some path";  // normal string
   Object[] args = {newPath,excludeList };
            backgroundAnalyzer.RunWorkerAsync(args);
      }

Now in the doWork method of background worker

backgroundAnalyzer_DoWork(object sender, DoWorkEventArgs e)
      {
        backgroundAnalyzer.ReportProgress(50);
        Object[] arg = e.Argument as Object[];
        string path= (string)arg[0];
        List<string> lst = (List<string>) arg[1];
        .......
        // do something......
        //.....
       }

Can you blur the content beneath/behind a div?

If you want to enable unblur, you cannot just add the blur CSS to the body, you need to blur each visible child one level directly under the body and then remove the CSS to unblur. The reason is because of the "Cascade" in CSS, you cannot undo the cascading of the CSS blur effect for a child of the body. Also, to blur the body's background image you need to use the pseudo element :before

//HTML

<div id="fullscreen-popup" style="position:absolute;top:50%;left:50%;">
    <div class="morph-button morph-button-overlay morph-button-fixed">
        <button id="user-interface" type="button">MORE INFO</button>
        <!--a id="user-interface" href="javascript:void(0)">popup</a-->
        <div class="morph-content">
            <div>
                <div class="content-style-overlay">
                    <span class="icon icon-close">Close the overlay</span>
                    <h2>About Parsley</h2>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                </div>
            </div>
        </div>
    </div>
</div>

//CSS

/* Blur - doesn't work on IE */

.blur-on, .blur-element {
    -webkit-filter: blur(10px);
    -moz-filter: blur(10px);
    -o-filter: blur(10px);
    -ms-filter: blur(10px);
    filter: blur(10px);

    -webkit-transition: all 5s linear;
    transition        : all 5s linear;
    -moz-transition   : all 5s linear;
    -webkit-transition: all 5s linear;
    -o-transition     : all 5s linear;
}
.blur-off {
    -webkit-filter: blur(0px) !important;
    -moz-filter   : blur(0px) !important;
    -o-filter     : blur(0px) !important;
    -ms-filter    : blur(0px) !important;
    filter        : blur(0px) !important;
}
.blur-bgimage:before {
    content: "";
    position: absolute;
    height: 20%; width: 20%;
    background-size: cover;
    background: inherit;
    z-index: -1;

    transform: scale(5);
    transform-origin: top left;
    filter: blur(2px);       
    -moz-transform: scale(5);
    -moz-transform-origin: top left;
    -moz-filter: blur(2px);       
    -webkit-transform: scale(5);
    -webkit-transform-origin: top left;
    -webkit-filter: blur(2px);
    -o-transform: scale(5);
    -o-transform-origin: top left;
    -o-filter: blur(2px);       

    transition        : all 5s linear;
    -moz-transition   : all 5s linear;
    -webkit-transition: all 5s linear;
    -o-transition     : all 5s linear;
}


//Javascript

function blurBehindPopup() {
    if(blurredElements.length == 0) {
        for(var i=0; i < document.body.children.length; i++) {
            var element = document.body.children[i];
            if(element.id && element.id != 'fullscreen-popup' && element.isVisible == true) {
                classie.addClass( element, 'blur-element' );
                blurredElements.push(element);
            }
        }
    } else {
        for(var i=0; i < blurredElements.length; i++) {
            classie.addClass( blurredElements[i], 'blur-element' );
        }
    }
}
function unblurBehindPopup() {
    for(var i=0; i < blurredElements.length; i++) {
        classie.removeClass( blurredElements[i], 'blur-element' );
    }
}

Full Working Example Link

Changing Jenkins build number

If you have access to the script console (Manage Jenkins -> Script Console), then you can do this following:

Jenkins.instance.getItemByFullName("YourJobName").updateNextBuildNumber(45)

Converting any string into camel case

I think this should work..

function cammelCase(str){
    let arr = str.split(' ');
    let words = arr.filter(v=>v!='');
    words.forEach((w, i)=>{
        words[i] = w.replace(/\w\S*/g, function(txt){
            return txt.charAt(0).toUpperCase() + txt.substr(1);
        });
    });
    return words.join('');
}

angular2: how to copy object into another object

Try this.

Copy an Array :

const myCopiedArray  = Object.assign([], myArray);

Copy an object :

const myCopiedObject = Object.assign({}, myObject);

Warning: Permanently added the RSA host key for IP address

From: https://github.blog/changelog/2019-04-09-webhooks-ip-changes/

April 9, 2019

Webhooks IP changes

The IP addresses we use to send webhooks from are broadening to encompass a larger range.

We are adding IP’s within 140.82.112.0/20 to the current pool from 192.30.252.0/22.

Learn more about GitHub’s IP addresses

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

If you not use maven, try to put your jars to WEB-INF/lib, it worked for me.

How do I create a local database inside of Microsoft SQL Server 2014?

Warning! SQL Server 14 Express, SQL Server Management Studio, and SQL 2014 LocalDB are separate downloads, make sure you actually installed SQL Server and not just the Management Studio! SQL Server 14 express with LocalDB download link

Youtube video about entire process.
Writeup with pictures about installing SQL Server

How to select a local server:

When you are asked to connect to a 'database server' right when you open up SQL Server Management Studio do this:

1) Make sure you have Server Type: Database

2) Make sure you have Authentication: Windows Authentication (no username & password)

3) For the server name field look to the right and select the drop down arrow, click 'browse for more'

4) New window pops up 'Browse for Servers', make sure to pick 'Local Servers' tab and under 'Database Engine' you will have the local server you set up during installation of SQL Server 14

How do I create a local database inside of Microsoft SQL Server 2014?

1) After you have connected to a server, bring up the Object Explorer toolbar under 'View' (Should open by default)

2) Now simply right click on 'Databases' and then 'Create new Database' to be taken through the database creation tools!

Convert NVARCHAR to DATETIME in SQL Server 2008

As your data is nvarchar there is no guarantee it will convert to datetime (as it may hold invalid date/time information) - so a way to handle this is to use ISDATE which I would use within a cross apply. (Cross apply results are reusable hence making is easier for the output formats.)

|                     YOUR_DT |             SQL2008 |
|-----------------------------|---------------------|
|         2013-08-29 13:55:48 | 29-08-2013 13:55:48 |
|    2013-08-29 13:55:48 blah |              (null) |
| 2013-08-29 13:55:48 rubbish |              (null) |

SELECT
  [Your_Dt]
, convert(varchar, ca1.dt_converted ,105) + ' ' + convert(varchar, ca1.dt_converted ,8) AS sql2008
FROM your_table
CROSS apply ( SELECT CASE WHEN isdate([Your_Dt]) = 1
                        THEN convert(datetime,[Your_Dt])
                        ELSE NULL
                     END
            ) AS ca1 (dt_converted)
;

Notes:

You could also introduce left([Your_Dt],19) to only get a string like '2013-08-29 13:55:48' from '2013-08-29 13:55:48 rubbish'

For that specific output I think you will need 2 sql 2008 date styles (105 & 8) sql2012 added for comparison

declare @your_dt as datetime2
set @your_dt = '2013-08-29 13:55:48'

select
  FORMAT(@your_dt, 'dd-MM-yyyy H:m:s') as sql2012
, convert(varchar, @your_dt ,105) + ' ' + convert(varchar, @your_dt ,8) as sql2008

|             SQL2012 |             SQL2008 |
|---------------------|---------------------|
| 29-08-2013 13:55:48 | 29-08-2013 13:55:48 | 

How to check if an integer is in a given range?

 Range<Long> timeRange = Range.create(model.getFrom(), model.getTo());
    if(timeRange.contains(systemtime)){
        Toast.makeText(context, "green!!", Toast.LENGTH_SHORT).show();
    }

jQuery If DIV Doesn't Have Class "x"

jQuery has the hasClass() function that returns true if any element in the wrapped set contains the specified class

if (!$(this).hasClass("selected")) {
    //do stuff
}

Take a look at my example of use

  • If you hover over a div, it fades as normal speed to 100% opacity if the div does not contain the 'selected' class
  • If you hover out of a div, it fades at slow speed to 30% opacity if the div does not contain the 'selected' class
  • Clicking the button adds 'selected' class to the red div. The fading effects no longer work on the red div

Here is the code for it

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #FFF; font: 16px Helvetica, Arial; color: #000; }
</style>


<!-- jQuery code here -->
<script type="text/javascript">
$(function() {

$('#myButton').click(function(e) {
$('#div2').addClass('selected');
});

$('.thumbs').bind('click',function(e) { alert('You clicked ' + e.target.id ); } );

$('.thumbs').hover(fadeItIn, fadeItOut);


});

function fadeItIn(e) {
if (!$(e.target).hasClass('selected')) 
 { 
    $(e.target).fadeTo('normal', 1.0); 
  } 
}

function fadeItOut(e) { 
  if (!$(e.target).hasClass('selected'))
  { 
    $(e.target).fadeTo('slow', 0.3); 
 } 
}
</script>


</head>
<body>
<div id="div1" class="thumbs" style=" background-color: #0f0; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both;"> 
One div with a thumbs class
</div>
<div id="div2" class="thumbs" style=" background-color: #f00; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both;">
Another one with a thumbs class
</div>
<input type="button" id="myButton" value="add 'selected' class to red div" />
</body>
</html>

EDIT:

this is just a guess, but are you trying to achieve something like this?

  • Both divs start at 30% opacity
  • Hovering over a div fades to 100% opacity, hovering out fades back to 30% opacity. Fade effects only work on elements that don't have the 'selected' class
  • Clicking a div adds/removes the 'selected' class

jQuery Code is here-

$(function() {

$('.thumbs').bind('click',function(e) { $(e.target).toggleClass('selected'); } );
$('.thumbs').hover(fadeItIn, fadeItOut);
$('.thumbs').css('opacity', 0.3);

});

function fadeItIn(e) {
if (!$(e.target).hasClass('selected')) 
 { 
    $(e.target).fadeTo('normal', 1.0); 
  } 
}

function fadeItOut(e) { 
  if (!$(e.target).hasClass('selected'))
  { 
    $(e.target).fadeTo('slow', 0.3); 
 } 
}

<div id="div1" class="thumbs" style=" background-color: #0f0; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both; cursor:pointer;"> 
One div with a thumbs class
</div>
<div id="div2" class="thumbs" style=" background-color: #f00; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both; cursor:pointer;">
Another one with a thumbs class
</div>

How can a query multiply 2 cell for each row MySQL?

Use this:

SELECT 
    Pieces, Price, 
    Pieces * Price as 'Total' 
FROM myTable

Aggregate / summarize multiple variables per group (e.g. sum, mean)

With the dplyr version >= 1.0.0, we can also use summarise to apply function on multiple columns with across

library(dplyr)
df1 %>% 
    group_by(year, month) %>%
    summarise(across(starts_with('x'), sum))
# A tibble: 24 x 4
# Groups:   year [2]
#    year month     x1     x2
#   <dbl> <dbl>  <dbl>  <dbl>
# 1  2000     1   11.7  52.9 
# 2  2000     2  -74.1 126.  
# 3  2000     3 -132.  149.  
# 4  2000     4 -130.    4.12
# 5  2000     5  -91.6 -55.9 
# 6  2000     6  179.   73.7 
# 7  2000     7   95.0 409.  
# 8  2000     8  255.  283.  
# 9  2000     9  489.  331.  
#10  2000    10  719.  305.  
# … with 14 more rows

How to add multiple values to a dictionary key in python?

Make the value a list, e.g.

a["abc"] = [1, 2, "bob"]

UPDATE:

There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.

key = "somekey"
a.setdefault(key, [])
a[key].append(1)

Results:

>>> a
{'somekey': [1]}

Next, try:

key = "somekey"
a.setdefault(key, [])
a[key].append(2)

Results:

>>> a
{'somekey': [1, 2]}

The magic of setdefault is that it initializes the value for that key if that key is not defined, otherwise it does nothing. Now, noting that setdefault returns the key you can combine these into a single line:

a.setdefault("somekey",[]).append("bob")

Results:

>>> a
{'somekey': [1, 2, 'bob']}

You should look at the dict methods, in particular the get() method, and do some experiments to get comfortable with this.

What is the best open source help ticket system?

I recommend OTRS, its very easily customizable, and we also use it for hundreds of employees (University).

Not equal <> != operator on NULL

I just don't see the functional and seamless reason for nulls not to be comparable to other values or other nulls, cause we can clearly compare it and say they are the same or not in our context. It's funny. Just because of some logical conclusions and consistency we need to bother constantly with it. It's not functional, make it more functional and leave it to philosophers and scientists to conclude if it's consistent or not and does it hold "universal logic". :) Someone may say that it's because of indexes or something else, I doubt that those things couldn't be made to support nulls same as values. It's same as comparing two empty glasses, one is vine glass and other is beer glass, we are not comparing the types of objects but values they contain, same as you could compare int and varchar, with null it's even easier, it's nothing and what two nothingness have in common, they are the same, clearly comparable by me and by everyone else that write sql, because we are constantly breaking that logic by comparing them in weird ways because of some ANSI standards. Why not use computer power to do it for us and I doubt it would slow things down if everything related is constructed with that in mind. "It's not null it's nothing", it's not apple it's apfel, come on... Functionally is your friend and there is also logic here. In the end only thing that matter is functionality and does using nulls in that way brings more or less functionality and ease of use. Is it more useful?

Consider this code:

SELECT CASE WHEN NOT (1 = null or (1 is null and null is null)) THEN 1 ELSE 0 end

How many of you knows what will this code return? With or without NOT it returns 0. To me that is not functional and it's confusing. In c# it's all as it should be, comparison operations return value, logically this too produces value, because if it didn't there is nothing to compare (except. nothing :) ). They just "said": anything compared to null "returns" 0 and that creates many workarounds and headaches.

This is the code that brought me here:

where a != b OR (a is null and b IS not null) OR (a IS not null and b IS null)

I just need to compare if two fields (in where) have different values, I could use function, but...

How to remove hashbang from url?

Open the file in src->router->index.js

At the bottom of this file:

const router = new VueRouter({
  mode: "history",
  routes,
});

How can I find the version of php that is running on a distinct domain name?

By chance: Default error pages often contain detailed information, e.g.

Apache/{Version} ({OS}) {Modules} PHP/{Version} {Modules} Server at {Domain}

Not so easy: Find out which versions of PHP applications run on the server and which version of PHP they require.

Another approach, only mentioned for the sake of completeness; please forget after reading: You could (but you won't!) detect the PHP version by trying known exploits.

How to print all information from an HTTP request to the screen, in PHP

in addition, you can use get_headers(). it doesn't depend on apache..

print_r(get_headers());

How do I read text from the clipboard?

You can use the module called win32clipboard, which is part of pywin32.

Here is an example that first sets the clipboard data then gets it:

import win32clipboard

# set clipboard data
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText('testing 123')
win32clipboard.CloseClipboard()

# get clipboard data
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
print data

An important reminder from the documentation:

When the window has finished examining or changing the clipboard, close the clipboard by calling CloseClipboard. This enables other windows to access the clipboard. Do not place an object on the clipboard after calling CloseClipboard.

What is the Swift equivalent of isEqualToString in Objective-C?

I addition to @JJSaccolo answer, you can create custom equals method as new String extension like:

extension String {
     func isEqualToString(find: String) -> Bool {
        return String(format: self) == find
    }
}

And usage:

let a = "abc"
let b = "abc"

if a.isEqualToString(b) {
     println("Equals")
}

For sure original operator == might be better (works like in Javascript) but for me isEqual method gives some code clearness that we compare Strings

Hope it will help to someone,

How do I get column names to print in this C# program?

You need to loop over loadDT.Columns, like this:

foreach (DataColumn column in loadDT.Columns)
{
    Console.Write("Item: ");
    Console.Write(column.ColumnName);
    Console.Write(" ");
    Console.WriteLine(row[column]);
}

How to convert upper case letters to lower case

To convert a string to lower case in Python, use something like this.

list.append(sentence.lower())

I found this in the first result after searching for "python upper to lower case".

WordPress - Check if user is logged in

get_current_user_id() will return the current user id (an integer), or will return 0 if the user is not logged in.

if (get_current_user_id()) {
   // display navbar here
}

More details here get_current_user_id().

java.math.BigInteger cannot be cast to java.lang.Long

Imagine d.getId is a Long, then wrap like this:

BigInteger l  = BigInteger.valueOf(d.getId());

How to make html <select> element look like "disabled", but pass values?

if you don't want add the attr disabled can do it programmatically

can disable the edition into the <select class="yourClass"> element with this code:

//bloqueo selects
  //block all selects
  jQuery(document).on("focusin", 'select.yourClass', function (event) {
    var $selectDiabled = jQuery(this).attr('disabled', 'disabled');
    setTimeout(function(){ $selectDiabled.removeAttr("disabled"); }, 30);
  });

if you want try it can see it here: https://jsfiddle.net/9kjqjLyq/

Failed to load resource: net::ERR_INSECURE_RESPONSE

Sometimes Google Chrome throws this error, even if it should not. I experienced it when Chrome had a new version, and it needed to be restarted. After restarting the same page worked without any errors. The error in the console was:

net::ERR_INSECURE_RESPONSE

Output a NULL cell value in Excel

I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:

1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)

2: Run your formula

3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank

4: Replace All

Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.

SQL Query - Change date format in query to DD/MM/YYYY

If DB is SQL Server then

select Convert(varchar(10),CONVERT(date,YourDateColumn,106),103)

Build the full path filename in Python

If you are fortunate enough to be running Python 3.4+, you can use pathlib:

>>> from pathlib import Path
>>> dirname = '/home/reports'
>>> filename = 'daily'
>>> suffix = '.pdf'
>>> Path(dirname, filename).with_suffix(suffix)
PosixPath('/home/reports/daily.pdf')

Convert string to hex-string in C#

According to this snippet here, this approach should be good for long strings:

private string StringToHex(string hexstring)
{
    StringBuilder sb = new StringBuilder();
    foreach (char t in hexstring)
    { 
        //Note: X for upper, x for lower case letters
        sb.Append(Convert.ToInt32(t).ToString("x")); 
    }
    return sb.ToString();
}

usage:

string result = StringToHex("Hello world"); //returns "48656c6c6f20776f726c64"

Another approach in one line

string input = "Hello world";
string result = String.Concat(input.Select(x => ((int)x).ToString("x")));

Fatal error: Namespace declaration statement has to be the very first statement in the script in

Make sure there is no whitespace before your php tag

// whitespace
<?php
    namespace HelloWorld
?>

Remove the white space before your php tag starts

<?php
    namespace HelloWorld
?>

PHP Convert String into Float/Double

Try using

$string = "2968789218";
$float = (double)$string;

Oracle Differences between NVL and Coalesce

NVL: Replace the null with value.

COALESCE: Return the first non-null expression from expression list.

Table: PRICE_LIST

+----------------+-----------+
| Purchase_Price | Min_Price |
+----------------+-----------+
| 10             | null      |
| 20             |           |
| 50             | 30        |
| 100            | 80        |
| null           | null      |
+----------------+-----------+   

Below is the example of

[1] Set sales price with adding 10% profit to all products.
[2] If there is no purchase list price, then the sale price is the minimum price. For clearance sale.
[3] If there is no minimum price also, then set the sale price as default price "50".

SELECT
     Purchase_Price,
     Min_Price,
     NVL(Purchase_Price + (Purchase_Price * 0.10), Min_Price)    AS NVL_Sales_Price,
COALESCE(Purchase_Price + (Purchase_Price * 0.10), Min_Price,50) AS Coalesce_Sales_Price
FROM 
Price_List

Explain with real life practical example.

+----------------+-----------+-----------------+----------------------+
| Purchase_Price | Min_Price | NVL_Sales_Price | Coalesce_Sales_Price |
+----------------+-----------+-----------------+----------------------+
| 10             | null      | 11              |                   11 |
| null           | 20        | 20              |                   20 |
| 50             | 30        | 55              |                   55 |
| 100            | 80        | 110             |                  110 |
| null           | null      | null            |                   50 |
+----------------+-----------+-----------------+----------------------+

You can see that with NVL we can achieve rules [1],[2]
But with COALSECE we can achieve all three rules.

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

In addition to answer above, I could say that just try to run Maven from the terminal (outside of Eclipse). In this way, if it builds from outside but not in Eclipse, you can understand that the problem should be in Eclipse.

How to stop the Timer in android?

I had a similar problem: every time I push a particular button, I create a new Timer.

my_timer = new Timer("MY_TIMER");
my_timer.schedule(new TimerTask() {
...
}

Exiting from that activity I deleted the timer:

if(my_timer!=null){
my_timer.cancel();
my_timer = null;
}

But it was not enough because the cancel() method only canceled the latest Timer. The older ones were ignored an didn't stop running. The purge() method was not useful for me. I solved the problem just checking the Timer instantiation:

if(my_timer == null){
my_timer = new Timer("MY_TIMER");
my_timer.schedule(new TimerTask() {
...
}
}

open failed: EACCES (Permission denied)

In my case it was permissions issue. The catch is that on device with Android 4.0.4 I got access to file without any error or exception. And on device with Android 5.1 it failed with ACCESS exception (open failed: EACCES (Permission denied)). Handled it with adding follow permission to manifest file:

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

So I guess that it's the difference between permissions management in OS versions that causes to failures.

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I've gotten same problem. The servers logs showed:

DEBUG: <-- origin: null

I've investigated that and it occurred that this is not populated when I've been calling from file from local drive. When I've copied file to the server and used it from server - the request worked perfectly fine

How to link an image and target a new window

<a href="http://www.google.com" target="_blank">
  <img width="220" height="250" border="0" align="center"  src=""/>
</a>

VSCode cannot find module '@angular/core' or any other modules

If we get this type of error just use the command:

 npm i @anglar/core,
 npm i @angular/common,
 npm i @angular/http,
 npm i @angular/router

After installing this also showing error just remove few words then again add that word its working.

Redirecting to a new page after successful login

Javascript redirection generated with php code:

 if($match > 0){
     $msg = 'Login Complete! Thanks';
     echo "<script> window.location.assign('index.php'); </script>";
 }
 else{
     $msg = 'Login Failed!<br /> Please make sure that you enter the correct  details and that you have activated your account.';
 }

Php redirection only:

<?php
    header("Location: index.php"); 
    exit;
?>

css - position div to bottom of containing div

Assign position:relative to .outside, and then position:absolute; bottom:0; to your .inside.

Like so:

.outside {
    position:relative;
}
.inside {
    position: absolute;
    bottom: 0;
}

How to use Class<T> in Java?

Using the generified version of class Class allows you, among other things, to write things like

Class<? extends Collection> someCollectionClass = someMethod();

and then you can be sure that the Class object you receive extends Collection, and an instance of this class will be (at least) a Collection.

How do I get information about an index and table owner in Oracle?

 select index_name, column_name
 from user_ind_columns
 where table_name = 'NAME';

OR use this:

select TABLE_NAME, OWNER 
from SYS.ALL_TABLES 
order by OWNER, TABLE_NAME 

And for Indexes:

select INDEX_NAME, TABLE_NAME, TABLE_OWNER 
from SYS.ALL_INDEXES 
order by TABLE_OWNER, TABLE_NAME, INDEX_NAME

JavaScript, get date of the next day

Using Date object guarantees that. For eg if you try to create April 31st :

new Date(2014,3,31)        // Thu May 01 2014 00:00:00

Please note that it's zero indexed, so Jan. is 0, Feb. is 1 etc.

How to get html table td cell value by JavaScript?

I gave the table an id so I could find it. On onload (when the page is loaded by the browser), I set onclick event handlers to all rows of the table. Those handlers alert the content of the first cell.

<!DOCTYPE html>
<html>
    <head>
        <script>
            var p = {
                onload: function() {
                    var rows = document.getElementById("mytable").rows;
                    for(var i = 0, ceiling = rows.length; i < ceiling; i++) {
                        rows[i].onclick = function() {
                            alert(this.cells[0].innerHTML);
                        }
                    }
                }
            };
        </script>
    </head>
    <body onload="p.onload()">
        <table id="mytable">
            <tr>
                <td>0</td>
                <td>row 1 cell 2</td>
            </tr>
            <tr>
                <td>1</td>
                <td>row 2 cell 2</td>
            </tr>
        </table>    
    </body>
</html> 

What is difference between sjlj vs dwarf vs seh?

SJLJ (setjmp/longjmp): – available for 32 bit and 64 bit – not “zero-cost”: even if an exception isn’t thrown, it incurs a minor performance penalty (~15% in exception heavy code) – allows exceptions to traverse through e.g. windows callbacks

DWARF (DW2, dwarf-2) – available for 32 bit only – no permanent runtime overhead – needs whole call stack to be dwarf-enabled, which means exceptions cannot be thrown over e.g. Windows system DLLs.

SEH (zero overhead exception) – will be available for 64-bit GCC 4.8.

source: https://wiki.qt.io/MinGW-64-bit

Using .htaccess to make all .html pages to run as .php files?

Using @Marc-François approach Firefox prompted me to download the html file

Finally the following is working for me (using both):

AddType application/x-httpd-php .htm .html AddHandler x-httpd-php .htm .html

How to put scroll bar only for modal-body?

For Bootstrap versions >= 4.3

Bootstrap 4.3 added new built-in scroll feature to modals. This makes only the modal-body content scroll if the size of the content would otherwise make the page scroll. To use it, just add the class modal-dialog-scrollable to the same div that has the modal-dialog class.

Here is an example:

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<!-- Button trigger modal -->_x000D_
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalScrollable">_x000D_
  Launch demo modal_x000D_
</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="exampleModalScrollable" tabindex="-1" role="dialog" aria-labelledby="exampleModalScrollableTitle" aria-hidden="true">_x000D_
  <div class="modal-dialog modal-dialog-scrollable" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <h5 class="modal-title" id="exampleModalScrollableTitle">Modal title</h5>_x000D_
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">_x000D_
          <span aria-hidden="true">&times;</span>_x000D_
        </button>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        the<br>quick<br>brown<br>fox<br>_x000D_
        the<br>quick<br>brown<br>fox<br>_x000D_
        the<br>quick<br>brown<br>fox<br>_x000D_
        the<br>quick<br>brown<br>fox<br>_x000D_
        the<br>quick<br>brown<br>fox<br>_x000D_
        the<br>quick<br>brown<br>fox<br>_x000D_
        the<br>quick<br>brown<br>fox<br>_x000D_
        the<br>quick<br>brown<br>fox<br>_x000D_
        the<br>quick<br>brown<br>fox<br>_x000D_
        the<br>quick<br>brown<br>fox<br>_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>_x000D_
        <button type="button" class="btn btn-primary">Save changes</button>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_