Programs & Examples On #Windows clustering

How to handle authentication popup with Selenium WebDriver using Java

Selenium 4 supports authenticating using Basic and Digest auth . It's using the CDP and currently only supports chromium-derived browsers

Java Example :

Webdriver driver = new ChromeDriver();

((HasAuthentication) driver).register(UsernameAndPassword.of("username", "pass"));

driver.get("http://sitewithauth");

Note : In Alpha-7 there is bug where it send username for both user/password. Need to wait for next release of selenium version as fix is available in trunk https://github.com/SeleniumHQ/selenium/commit/4917444886ba16a033a81a2a9676c9267c472894

What's the console.log() of java?

public class Console {

    public static void Log(Object obj){
        System.out.println(obj);
    }
}

to call and use as JavaScript just do this:

Console.Log (Object)

I think that's what you mean

How do I generate a random number between two variables that I have stored?

Really fast, really easy:

srand(time(NULL)); // Seed the time
int finalNum = rand()%(max-min+1)+min; // Generate the number, assign to variable.

And that is it. However, this is biased towards the lower end, but if you are using C++ TR1/C++11 you can do it using the random header to avoid that bias like so:

#include <random>

std::mt19937 rng(seed);
std::uniform_int_distribution<int> gen(min, max); // uniform, unbiased

int r = gen(rng);

But you can also remove the bias in normal C++ like this:

int rangeRandomAlg2 (int min, int max){
    int n = max - min + 1;
    int remainder = RAND_MAX % n;
    int x;
    do{
        x = rand();
    }while (x >= RAND_MAX - remainder);
    return min + x % n;
}

and that was gotten from this post.

Duplicate / Copy records in the same MySQL table

Alex's answer needs some care (e.g. locking or a transaction) in multi-client environments.

Assuming the AUTO ID field is the first one in the table (a usual case), we can make use of implicit transactions.

    CREATE TEMPORARY TABLE tmp SELECT * from invoices WHERE ...;
    ALTER TABLE tmp drop ID; # drop autoincrement field
    # UPDATE tmp SET ...; # just needed to change other unique keys
    INSERT INTO invoices SELECT 0,tmp.* FROM tmp;
    DROP TABLE tmp;

From the MySQL docs:

Using AUTO_INCREMENT: You can also explicitly assign NULL or 0 to the column to generate sequence numbers.

How to toggle a boolean?

If you don't mind the boolean being converted to a number (that is either 0 or 1), you can use the Bitwise XOR Assignment Operator. Like so:

bool ^= true;   //- toggle value.


This is especially good if you use long, descriptive boolean names, EG:

var inDynamicEditMode   = true;     // Value is: true (boolean)
inDynamicEditMode      ^= true;     // Value is: 0 (number)
inDynamicEditMode      ^= true;     // Value is: 1 (number)
inDynamicEditMode      ^= true;     // Value is: 0 (number)

This is easier for me to scan than repeating the variable in each line.

This method works in all (major) browsers (and most programming languages).

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

Under Linux there is pdfunite (part of poppler) that can concatenate the same pdf files to get one large pdf file:

pdfunite in.pdf in.pdf in.pdf out.pdf

see manpage

Why am I getting "Received fatal alert: protocol_version" or "peer not authenticated" from Maven Central?

The following command helped me (executing on bash before running mvn)

export MAVEN_OPTS=-Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2

Landscape printing from HTML

This also worked for me:

@media print and (orientation:landscape) { … }

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

As Alex Burtsev mentioned in a comment anything that’s only used in a XAML resource dictionary, or in my case, anything that’s only used in XAML and not in code behind, isn't deemed to be 'in use' by MSBuild.

So simply new-ing up a dummy reference to a class/component in the assembly in some code behind was enough convince MSBuild that the assembly was actually in use.

HTML5 Email input pattern attribute

Unfortunately, all suggestions except from B-Money are invalid for most cases.

Here is a lot of valid emails like:

Because of complexity to get validation right, I propose a very generic solution:

<input type="text" pattern="[^@\s]+@[^@\s]+\.[^@\s]+" title="Invalid email address" />

It checks if email contains at least one character (also number or whatever except another "@" or whitespace) before "@", at least two characters (or whatever except another "@" or whitespace) after "@" and one dot in between. This pattern does not accept addresses like lol@company, sometimes used in internal networks. But this one could be used, if required:

<input type="text" pattern="[^@\s]+@[^@\s]+" title="Invalid email address" />

Both patterns accepts also less valid emails, for example emails with vertical tab. But for me it's good enough. Stronger checks like trying to connect to mail-server or ping domain should happen anyway on the server side.

BTW, I just wrote angular directive (not well tested yet) for email validation with novalidate and without based on pattern above to support DRY-principle:

.directive('isEmail', ['$compile', '$q', 't', function($compile, $q, t) {
    var EMAIL_PATTERN = '^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$';
    var EMAIL_REGEXP = new RegExp(EMAIL_PATTERN, 'i');
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ngModel){
            function validate(value) {
                var valid = angular.isUndefined(value)
                    || value.length === 0
                    || EMAIL_REGEXP.test(value);
                ngModel.$setValidity('email', valid);
                return valid ? value : undefined;
            }
            ngModel.$formatters.unshift(validate);
            ngModel.$parsers.unshift(validate);
            elem.attr('pattern', EMAIL_PATTERN);
            elem.attr('title', 'Invalid email address');
        }
    };
}])

Usage:

<input type="text" is-email />

For B-Money's pattern is "@" just enough. But it decline two or more "@" and all spaces.

git checkout master error: the following untracked working tree files would be overwritten by checkout

Try git checkout -f master.

-f or --force

Source: https://www.kernel.org/pub/software/scm/git/docs/git-checkout.html

When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes.

When checking out paths from the index, do not fail upon unmerged entries; instead, unmerged entries are ignored.

Could not determine the dependencies of task ':app:crashlyticsStoreDeobsDebug' if I enable the proguard

You can run this command in your project directory. Basically it just cleans the build and gradle.

   cd android && rm -R .gradle && cd app && rm -R build

In my case, I was using react-native using this as a script in package.json

"scripts": { "clean-android": "cd android && rm -R .gradle && cd app && rm -R build" }

How can I update a row in a DataTable in VB.NET?

You can access columns by index, by name and some other ways:

dtResult.Rows(i)("columnName") = strVerse

You should probably make sure your DataTable has some columns first...

Catch an exception thrown by an async void method

It's somewhat weird to read but yes, the exception will bubble up to the calling code - but only if you await or Wait() the call to Foo.

public async Task Foo()
{
    var x = await DoSomethingAsync();
}

public async void DoFoo()
{
    try
    {
        await Foo();
    }
    catch (ProtocolException ex)
    {
          // The exception will be caught because you've awaited
          // the call in an async method.
    }
}

//or//

public void DoFoo()
{
    try
    {
        Foo().Wait();
    }
    catch (ProtocolException ex)
    {
          /* The exception will be caught because you've
             waited for the completion of the call. */
    }
} 

Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started. - https://msdn.microsoft.com/en-us/magazine/jj991977.aspx

Note that using Wait() may cause your application to block, if .Net decides to execute your method synchronously.

This explanation http://www.interact-sw.co.uk/iangblog/2010/11/01/csharp5-async-exceptions is pretty good - it discusses the steps the compiler takes to achieve this magic.

Full Screen DialogFragment in Android

Try this for common fragment dialog for multiple uses. Hope this will help you bettor

public class DialogFragment extends DialogFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_visit_history_main, container, false);

        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        initializeUI(rootView);
        return rootView;
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            int width = ViewGroup.LayoutParams.MATCH_PARENT;
            int height = ViewGroup.LayoutParams.MATCH_PARENT;
            dialog.getWindow().setLayout(width, height);
        }
    }
    private void initializeUI(View rootView) {
    //getChildFragmentManager().beginTransaction().replace(R.id.fv_container,FragmentVisitHistory.getInstance(), AppConstant.FRAGMENT_VISIT_HISTORY).commit();
    }
}

How to increment a variable on a for loop in jinja template?

I was struggle with this behavior too. I wanted to change div class in jinja based on counter. I was surprised that pythonic way did not work. Following code was reseting my counter on each iteration, so I had only red class.

{% if sloupec3: %}
    {% set counter = 1 %}
    {% for row in sloupec3: %}
        {% if counter == 3 %}
            {% set counter = 1 %}        
        {% endif %} 

        {% if  counter == 1: %}
           <div class="red"> some red div </div>
        {% endif %} 

        {% if counter == 2: %}
           <div class="gray"> some gray div </div>
        {% endif %} 

        {% set counter = counter + 1 %} 

    {% endfor %}

{% endif %}

I used loop.index like this and it works:

{% if sloupec3: %}

    {% for row in sloupec3: %} 

        {% if  loop.index % 2 == 1: %}
           <div class="red"> some red div </div>
        {% endif %} 

        {% if loop.index % 2 == 0: %}
           <div class="gray"> some gray div </div>
        {% endif %}  

    {% endfor %}

{% endif %}

What is the difference between MacVim and regular Vim?

unfortunately, with "mvim -v", ALT plus arrow windows still does not work. I have not found any way to enable it :-(

What is the HTML tabindex attribute?

the values you set determine the order that your keyboard focus will move between elements on the website.

In the following example, the first time you press tab, your cursor will move to #foo, then #awesome, then #bar

<input id="foo" tabindex="1"  />
<input id="bar" tabindex="3"  />
<input id="awesome" tabindex="2"  />

If you have not defined tab indexes anywhere, the keyboard focus will follow the HTML tags of you page in the order in which they are defined in the HTML document.

If you tab more times than you have specified tabindexes for, the focus will move as if there were no tabindexes, i.e. in the order of appearance of the HTML tags

How to disable button in React.js

In HTML,

<button disabled/>
<buttton disabled="true">
<buttton disabled="false">
<buttton disabled="21">

All of them boils down to disabled="true" that is because it returns true for a non-empty string. Hence, in order to return false, pass a empty string in a conditional statement like this.input.value?"true":"".

render() {
    return (
        <div className="add-item">
            <input type="text" className="add-item__input" ref={(input) => this.input = input} placeholder={this.props.placeholder} />
            <button disabled={this.input.value?"true":""} className="add-item__button" onClick={this.add.bind(this)}>Add</button>
        </div>
    );
}

How to remove package using Angular CLI?

You can use npm uninstall <package-name> will remove it from your package.json file and from node_modules.

If you do ng help command, you will see that there is no ng remove/delete supported command. So, basically you cannot revert the ng add behavior yet.

How to obtain the location of cacerts of the default java installation?

You can also consult readlink -f "which java". However it might not work for all binary wrappers. It is most likely better to actually start a Java class.

How to play a notification sound on websites?

Play cross browser compatible notifications

As adviced by @Tim Tisdall from this post , Check Howler.js Plugin.

Browsers like chrome disables javascript execution when minimized or inactive for performance improvements. But This plays notification sounds even if browser is inactive or minimized by the user.

  var sound =new Howl({
                     src: ['../sounds/rings.mp3','../sounds/rings.wav','../sounds/rings.ogg',
                           '../sounds/rings.aiff'],
                     autoplay: true,
                     loop: true
                    });

               sound.play();

Hope helps someone.

What are file descriptors, explained in simple terms?

Addition to above all simplified responses.

If you are working with files in bash script, it's better to use file descriptor.

For example: If you want to read and write from/to the file "test.txt", use the file descriptor as show below:

FILE=$1 # give the name of file in the command line
exec 5<>$FILE # '5' here act as the file descriptor

# Reading from the file line by line using file descriptor
while read LINE; do
    echo "$LINE"
done <&5

# Writing to the file using descriptor
echo "Adding the date: `date`" >&5 
exec 5<&- # Closing a file descriptor

Maven in Eclipse: step by step installation

I have just include Maven integration plug-in with Eclipse:

Just follow the bellow steps:

In eclipse, from upper menu item select- Help ->click on Install New Software..-> then click on Add button.

set the MavenAPI at name text box and http://download.eclipse.org/technology/m2e/releases at location text box.

press OK and select the Maven project and install by clicking next.

Encoding an image file with base64

The first answer will print a string with prefix b'. That means your string will be like this b'your_string' To solve this issue please add the following line of code.

encoded_string= base64.b64encode(img_file.read())
print(encoded_string.decode('utf-8'))

Difference between @click and v-on:click Vuejs

They may look a bit different from normal HTML, but : and @ are valid chars for attribute names and all Vue.js supported browsers can parse it correctly. In addition, they do not appear in the final rendered markup. The shorthand syntax is totally optional, but you will likely appreciate it when you learn more about its usage later.

Source: official documentation.

Formatting numbers (decimal places, thousands separators, etc) with CSS

You could use Jstl tag Library for formatting for JSP Pages

JSP Page
//import the jstl lib
<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>

<c:set var="balance" value="120000.2309" />
<p>Formatted Number (1): <fmt:formatNumber value="${balance}" 
        type="currency"/></p>
<p>Formatted Number (2): <fmt:formatNumber type="number" 
        maxIntegerDigits="3" value="${balance}" /></p>
<p>Formatted Number (3): <fmt:formatNumber type="number" 
        maxFractionDigits="3" value="${balance}" /></p>
<p>Formatted Number (4): <fmt:formatNumber type="number" 
        groupingUsed="false" value="${balance}" /></p>
<p>Formatted Number (5): <fmt:formatNumber type="percent" 
        maxIntegerDigits="3" value="${balance}" /></p>
<p>Formatted Number (6): <fmt:formatNumber type="percent" 
        minFractionDigits="10" value="${balance}" /></p>
<p>Formatted Number (7): <fmt:formatNumber type="percent" 
        maxIntegerDigits="3" value="${balance}" /></p>
<p>Formatted Number (8): <fmt:formatNumber type="number" 
        pattern="###.###E0" value="${balance}" /></p>

Result

Formatted Number (1): £120,000.23

Formatted Number (2): 000.231

Formatted Number (3): 120,000.231

Formatted Number (4): 120000.231

Formatted Number (5): 023%

Formatted Number (6): 12,000,023.0900000000%

Formatted Number (7): 023%

Formatted Number (8): 120E3

pandas: merge (join) two data frames on multiple columns

the problem here is that by using the apostrophes you are setting the value being passed to be a string, when in fact, as @Shijo stated from the documentation, the function is expecting a label or list, but not a string! If the list contains each of the name of the columns beings passed for both the left and right dataframe, then each column-name must individually be within apostrophes. With what has been stated, we can understand why this is inccorect:

new_df = pd.merge(A_df, B_df,  how='left', left_on='[A_c1,c2]', right_on = '[B_c1,c2]')

And this is the correct way of using the function:

new_df = pd.merge(A_df, B_df,  how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])

Viewing localhost website from mobile device

One of the easiest way to remotely access ASP.net local website, without messing with adding new rules to firewall, is to use this Visual Studio extension:

Conveyor by Keyoti (Visual Studio extension)

Just install it. Every time when you run your project, it will show you URL which can be used for remote access. No other configruration required.

enter image description here

Order by multiple columns with Doctrine

You have to add the order direction right after the column name:

$qb->orderBy('column1 ASC, column2 DESC');

As you have noted, multiple calls to orderBy do not stack, but you can make multiple calls to addOrderBy:

$qb->addOrderBy('column1', 'ASC')
   ->addOrderBy('column2', 'DESC');

How to generate a random String in Java

The first question you need to ask is whether you really need the ID to be random. Sometime, sequential IDs are good enough.

Now, if you do need it to be random, we first note a generated sequence of numbers that contain no duplicates can not be called random. :p Now that we get that out of the way, the fastest way to do this is to have a Hashtable or HashMap containing all the IDs already generated. Whenever a new ID is generated, check it against the hashtable, re-generate if the ID already occurs. This will generally work well if the number of students is much less than the range of the IDs. If not, you're in deeper trouble as the probability of needing to regenerate an ID increases, P(generate new ID) = number_of_id_already_generated / number_of_all_possible_ids. In this case, check back the first paragraph (do you need the ID to be random?).

Hope this helps.

The service cannot be started, either because it is disabled or because it has no enabled devices associated with it

This error can occur on anything that requires elevated privileges in Windows.

It happens when the "Application Information" service is disabled in Windows services. There are a few viruses that use this as an attack vector to prevent people from removing the virus. It also prevents people from installing software to remove viruses.

The normal way to fix this would be to run services.msc, or to go into Administrative Tools and run "Services". However, you will not be able to do that if the "Application Information" service is disabled.

Instead, reboot your computer into Safe Mode (reboot and press F8 until the Windows boot menu appears, select Safe Mode with Networking). Then run services.msc and look for services that are designated as "Disabled" in the Startup Type column. Change these "Disabled" services to "Automatic".

Make sure the "Application Information" service is set to a Startup Type of "Automatic".

When you are done enabling your services, click Ok at the bottom of the tool and reboot your computer back into normal mode. The problem should be resolved when Windows reboots.

How do I get the time difference between two DateTime objects using C#?

You need to use a TimeSpan. Here is some sample code:

TimeSpan sincelast = TimeSpan.FromTicks(DateTime.Now.Ticks - LastUpdate.Ticks);

Postman addon's like in firefox

I liked PostMan, it was the main reason why I kept using Chrome, now I'm good with HttpRequester

https://addons.mozilla.org/En-us/firefox/addon/httprequester/?src=search

Quicksort with Python

def quicksort(array):
 if len(array) < 2:
  return array
 else:
  pivot = array[0]

 less = [i for i in array[1:] if i <= pivot]
 greater = [i for i in array[1:] if i > pivot]
 return quicksort(less) + [pivot] + quicksort(greater)

What is the difference between Collection and List in Java?

List and Set are two subclasses of Collection.

In List, data is in particular order.

In Set, it can not contain the same data twice.

In Collection, it just stores data with no particular order and can contain duplicate data.

Remove spaces from a string in VB.NET

2015: Newer LINQ & lambda.

  1. As this is an old Q (and Answer), just thought to update it with newer 2015 methods.
  2. The original "space" can refer to non-space whitespace (ie, tab, newline, paragraph separator, line feed, carriage return, etc, etc).
  3. Also, Trim() only remove the spaces from the front/back of the string, it does not remove spaces inside the string; eg: " Leading and Trailing Spaces " will become "Leading and Trailing Spaces", but the spaces inside are still present.

Function RemoveWhitespace(fullString As String) As String
    Return New String(fullString.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray())
End Function

This will remove ALL (white)-space, leading, trailing and within the string.

jQuery Scroll to bottom of page/iframe

If you want a nice slow animation scroll, for any anchor with href="#bottom" this will scroll you to the bottom:

$("a[href='#bottom']").click(function() {
  $("html, body").animate({ scrollTop: $(document).height() }, "slow");
  return false;
});

Feel free to change the selector.

Calculate percentage Javascript

Try:

const result = Math.round((data.expense / data.income) * 100)

How do I create an abstract base class in JavaScript?

I think All Those answers specially first two (by some and jordão) answer the question clearly with conventional prototype base JS concept.
Now as you want the animal class constructor to behave according to the passed parameter to the construction, I think this is very much similar to basic behavior of Creational Patterns for example Factory Pattern.

Here i made a little approach to make it work that way.

var Animal = function(type) {
    this.type=type;
    if(type=='dog')
    {
        return new Dog();
    }
    else if(type=="cat")
    {
        return new Cat();
    }
};



Animal.prototype.whoAreYou=function()
{
    console.log("I am a "+this.type);
}

Animal.prototype.say = function(){
    console.log("Not implemented");
};




var Cat =function () {
    Animal.call(this);
    this.type="cat";
};

Cat.prototype=Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;

Cat.prototype.say=function()
{
    console.log("meow");
}



var Dog =function () {
    Animal.call(this);
    this.type="dog";
};

Dog.prototype=Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.say=function()
{
    console.log("bark");
}


var animal=new Animal();


var dog = new Animal('dog');
var cat=new Animal('cat');

animal.whoAreYou(); //I am a undefined
animal.say(); //Not implemented


dog.whoAreYou(); //I am a dog
dog.say(); //bark

cat.whoAreYou(); //I am a cat
cat.say(); //meow

psql: FATAL: database "<user>" does not exist

First off, it's helpful to create a database named the same as your current use, to prevent the error when you just want to use the default database and create new tables without declaring the name of a db explicitly.

Replace "skynotify" with your username:

psql -d postgres -c "CREATE DATABASE skynotify ENCODING 'UTF-8';"

-d explicitly declares which database to use as the default for SQL statements that don't explicitly include a db name during this interactive session.

BASICS FOR GETTING A CLEAR PICTURE OF WHAT YOUR PostgresQL SERVER has in it.

You must connect to an existing database to use psql interactively. Fortunately, you can ask psql for a list of databases:

psql -l

.

                                          List of databases
               Name               | Owner  | Encoding |   Collate   |    Ctype    | Access privileges 
----------------------------------+-----------+----------+-------------+-------------+-------------------
 skynotify                        | skynotify | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 myapp_dev                        | skynotify | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 postgres                         | skynotify | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 ruby-getting-started_development | skynotify | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 template0                        | skynotify | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/skynotify          +
                                  |           |          |             |             | skynotify=CTc/skynotify
 template1                        | skynotify | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/skynotify          +
                                  |           |          |             |             | skynotify=CTc/skynotify
(6 rows)

This does NOT start the interactive console, it just outputs a text based table to the terminal.

As another answers says, postgres is always created, so you should use it as your failsafe database when you just want to get the console started to work on other databases. If it isn't there, then list the databases and then use any one of them.

In a similar fashion, select tables from a database:

psql -d postgres -c "\dt;"

My "postgres" database has no tables, but any database that does will output a text based table to the terminal (standard out).

And for completeness, we can select all rows from a table too:

psql -d ruby-getting-started_development -c "SELECT * FROM widgets;"

.

 id | name | description | stock | created_at | updated_at 
----+------+-------------+-------+------------+------------
(0 rows)

Even if there are zero rows returned, you'll get the field names.

If your tables have more than a dozen rows, or you're not sure, it'll be more useful to start with a count of rows to understand how much data is in your database:

 psql -d ruby-getting-started_development -c "SELECT count(*) FROM widgets;"

.

 count 
-------
     0
(1 row)

And don't that that "1 row" confuse you, it just represents how many rows are returned by the query, but the 1 row contains the count you want, which is 0 in this example.

NOTE: a db created without an owner defined will be owned by the current user.

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

As far as I know there is no native WPF function to get dimensions of the current monitor. Instead you could PInvoke native multiple display monitors functions, wrap them in managed class and expose all properties you need to consume them from XAML.

How to set text color in submit button?

_x000D_
_x000D_
.button_x000D_
{_x000D_
    font-size: 13px;_x000D_
    color:green;_x000D_
}
_x000D_
<input type="submit" value="Fetch" class="button"/>
_x000D_
_x000D_
_x000D_

How to change color of Android ListView separator line?

using programetically

           // Set ListView divider color
            lv.setDivider(new ColorDrawable(Color.parseColor("#FF4A4D93")));

            // set ListView divider height
            lv.setDividerHeight(2);

using xml

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">

  <ListView 
    android:id="@+id/android:list"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:divider="#44CC00"
    android:dividerHeight="4px"/>

</LinearLayout>

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

It works, when you use both lines:

Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000") = Format(Date, "yyyy-mm-dd")
Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000").NumberFormat = "yyyy-mm-dd"

How to call JavaScript function instead of href in HTML

Try to make your javascript unobtrusive :

  • you should use a real link in href attribute
  • and add a listener on click event to handle ajax

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

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

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

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

Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

add the below with URL Suffix

/override-http-headers-default-settings-x-frame-options

Why am I getting an OPTIONS request instead of a GET request?

It's looking like Firefox and Opera (tested on mac as well) don't like the cross domainness of this (but Safari is fine with it).

You might have to call a local server side code to curl the remote page.

CodeIgniter: 404 Page Not Found on Live Server

You are using MVC with OOPS Concept. So there are some certain rules.

1) Your class name (ie: controller name) should be start with capital Letter.

e.g.: your controller name is 'icecream'. that should be 'Icecream'

In localhost it might not be compulsory, but in server it will check all these rules, else it can't detect the right class name.

socket connect() vs bind()

The one liner : bind() to own address, connect() to remote address.

Quoting from the man page of bind()

bind() assigns the address specified by addr to the socket referred to by the file descriptor sockfd. addrlen specifies the size, in bytes, of the address structure pointed to by addr. Traditionally, this operation is called "assigning a name to a socket".

and, from the same for connect()

The connect() system call connects the socket referred to by the file descriptor sockfd to the address specified by addr.

To clarify,

  • bind() associates the socket with its local address [that's why server side binds, so that clients can use that address to connect to server.]
  • connect() is used to connect to a remote [server] address, that's why is client side, connect [read as: connect to server] is used.

ASP.NET strange compilation error

I got this kind of error too, but the problem was very different explained here. So in my case I got compiler error from temp file that I was using non existing namespace like:

using ImaginaryNamespaces;

I was sure that code "using ImaginaryNamespaces;" dosn't exists in my solution so of course I doubt cache problem. Finally I figured out that the temporary file was some generated source file from configs. My Views/Web.Config had a line:

<add namespace="ImaginaryNamespaces"/>

After removing this it worked. So I recommend to make sure that there is not any data in configs that might be related to the compiler error.

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

How to split large text file in windows?

you can split using a third party software http://www.hjsplit.org/, for example give yours input that could be upto 9GB and then split, in my case I split 10 MB each enter image description here

How do I get milliseconds from epoch (1970-01-01) in Java?

How about System.currentTimeMillis()?

From the JavaDoc:

Returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC

Java 8 introduces the java.time framework, particularly the Instant class which "...models a ... point on the time-line...":

long now = Instant.now().toEpochMilli();

Returns: the number of milliseconds since the epoch of 1970-01-01T00:00:00Z -- i.e. pretty much the same as above :-)

Cheers,

'this' vs $scope in AngularJS controllers

I recommend you to read the following post: AngularJS: "Controller as" or "$scope"?

It describes very well the advantages of using "Controller as" to expose variables over "$scope".

I know you asked specifically about methods and not variables, but I think that it's better to stick to one technique and be consistent with it.

So for my opinion, because of the variables issue discussed in the post, it's better to just use the "Controller as" technique and also apply it to the methods.

What is IPV6 for localhost and 0.0.0.0?

For use in a /etc/hosts file as a simple ad blocking technique to cause a domain to fail to resolve, the 0.0.0.0 address has been widely used because it causes the request to immediately fail without even trying, because it's not a valid or routable address. This is in comparison to using 127.0.0.1 in that place, where it will at least check to see if your own computer is listening on the requested port 80 before failing with 'connection refused.' Either of those addresses being used in the hosts file for the domain will stop any requests from being attempted over the actual network, but 0.0.0.0 has gained favor because it's more 'optimal' for the above reason. "127" IPs will attempt to hit your own computer, and any other IP will cause a request to be sent to the router to try to route it, but for 0.0.0.0 there's nowhere to even send a request to.

All that being said, having any IP listed in your hosts file for the domain to be blocked is sufficient, and you wouldn't need or want to also put an ipv6 address in your hosts file unless -- possibly -- you don't have ipv4 enabled at all. I'd be really surprised if that was the case, though. And still though, I think having the host appear in /etc/hosts with a bad ipv4 address when you don't have ipv4 enabled would still give you the result you are looking for which is for it to fail, instead of looking up the real DNS of say, adserver-example.com and getting back either a v4 or v6 IP.

regex to remove all text before a character

I learned all my Regex from this website: http://www.zytrax.com/tech/web/regex.htm. Google on 'Regex tutorials' and you'll find loads of helful articles.

String regex = "[a-zA-Z]*\.jpg";
System.out.println ("somthing.jpg".matches (regex));

returns true.

How to convert a plain object into an ES6 Map?

const myMap = new Map(
    Object
        .keys(myObj)
        .map(
            key => [key, myObj[key]]
        )
)

laravel select where and where condition

$userRecord = Model::where([['email','=',$email],['password','=', $password]])->first();

or

$userRecord = self::where([['email','=',$email],['password','=', $password]])->first();

I` think this condition is better then 2 where. Its where condition array in array of where conditions;

SSL certificate is not trusted - on mobile only

The most likely reason for the error is that the certificate authority that issued your SSL certificate is trusted on your desktop, but not on your mobile.

If you purchased the certificate from a common certification authority, it shouldn't be an issue - but if it is a less common one it is possible that your phone doesn't have it. You may need to accept it as a trusted publisher (although this is not ideal if you are pushing the site to the public as they won't be willing to do this.)

You might find looking at a list of Trusted CAs for Android helps to see if yours is there or not.

Datatype for storing ip address in SQL Server

sys.dm_exec_connections uses varchar(48) after SQL Server 2005 SP1. Sounds good enough for me especially if you want to use it compare to your value.

Realistically, you won't see IPv6 as mainstream for a while yet, so I'd prefer the 4 tinyint route. Saying that, I'm using varchar(48) because I have to use sys.dm_exec_connections...

Otherwise. Mark Redman's answer mentions a previous SO debate question.

Why can't I display a pound (£) symbol in HTML?

You need to save your PHP script file in UTF-8 encoding, and leave the <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> in the HTML.

For text editor, I recommend Notepad++, because it can detect and display the actual encoding of the file (in the lower right corner of the editor), and you can convert it as well.

Python Socket Receive Large Amount of Data

Disclaimer: There are very rare cases in which you really need to do this. If possible use an existing application layer protocol or define your own eg. precede each message with a fixed length integer indicating the length of data that follows or terminate each message with a '\n' character. (Adam Rosenfield's answer does a really good job at explaining that)

With that said, there is a way to read all of the data available on a socket. However, it is a bad idea to rely on this kind of communication as it introduces the risk of loosing data. Use this solution with extreme caution and only after reading the explanation below.

def recvall(sock):
    BUFF_SIZE = 4096
    data = bytearray()
    while True:
        packet = sock.recv(BUFF_SIZE)
        if not packet:  # Important!!
            break
        data.extend(packet)
    return data

Now the if not packet: line is absolutely critical! Many answers here suggested using a condition like if len(packet) < BUFF_SIZE: which is broken and will most likely cause you to close your connection prematurely and loose data. It wrongly assumes that one send on one end of a TCP socket corresponds to one receive of sent number of bytes on the other end. It does not. There is a very good chance that sock.recv(BUFF_SIZE) will return a chunk smaller than BUFF_SIZE even if there's still data waiting to be received. There is a good explanation of the issue here and here.

By using the above solution you are still risking data loss if the other end of the connection is writing data slower than you are reading. You may just simply consume all data on your end and exit when more is on the way. There are ways around it that require the use of concurrent programming, but that's another topic of its own.

Neither BindingResult nor plain target object for bean name available as request attr

I have encountered this problem as well. Here is my solution:

Below is the error while running a small Spring Application:-

*HTTP Status 500 - 
--------------------------------------------------------------------------------
type Exception report
message 
description The server encountered an internal error () that prevented it from fulfilling this request.
exception 
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/employe.jsp at line 12
9: <form:form method="POST" commandName="command"  action="/SpringWeb/addEmploye">
10:    <table>
11:     <tr>
12:         <td><form:label path="name">Name</form:label></td>
13:         <td><form:input path="name" /></td>
14:     </tr>
15:     <tr>
Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:465)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause 
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
    org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
    org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
    org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:119)
    org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:89)
    org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
    org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspx_meth_form_005flabel_005f0(employe_jsp.java:185)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspx_meth_form_005fform_005f0(employe_jsp.java:120)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspService(employe_jsp.java:80)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.26 logs.*

In order to resolve this issue you need to do the following in the controller class:-

  1. Change the import package from "import org.springframework.web.portlet.ModelAndView;" to "import org.springframework.web.servlet.ModelAndView;"...
  2. Recompile and run the code... the problem should get resolved.

How to create an email form that can send email using html

Html by itself will not send email. You will need something that connects to a SMTP server to send an email. Hence Outlook pops up with mailto: else your form goes to the server which has a script that sends email.

How to get element value in jQuery

Did you want the HTML or text that is inside the li tag?

If so, use either:

$(this).html()

or:

$(this).text()

The val() is for form fields only.

What is @ModelAttribute in Spring MVC?

For my style, I always use @ModelAttribute to catch object from spring form jsp. for example, I design form on jsp page, that form exist with commandName

<form:form commandName="Book" action="" methon="post">
      <form:input type="text" path="title"></form:input>
</form:form>

and I catch the object on controller with follow code

public String controllerPost(@ModelAttribute("Book") Book book)

and every field name of book must be match with path in sub-element of form

How do I add slashes to a string in Javascript?

var str = "This is a single quote: ' and so is this: '";
console.log(str);

var replaced = str.replace(/'/g, "\\'");
console.log(replaced);

Gives you:

This is a single quote: ' and so is this: '
This is a single quote: \' and so is this: \'

How to iterate a loop with index and element in Swift

I found this answer while looking for a way to do that with a Dictionary, and it turns out it's quite easy to adapt it, just pass a tuple for the element.

// Swift 2

var list = ["a": 1, "b": 2]

for (index, (letter, value)) in list.enumerate() {
    print("Item \(index): \(letter) \(value)")
}

jQuery - prevent default, then continue default

Using this way You will do a endless Loop on Your JS. to do a better way you can use the following

var on_submit_function = function(evt){
    evt.preventDefault(); //The form wouln't be submitted Yet.
    (...yourcode...)

    $(this).off('submit', on_submit_function); //It will remove this handle and will submit the form again if it's all ok.
    $(this).submit();
}

$('form').on('submit', on_submit_function); //Registering on submit.

I hope it helps! Thanks!

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

Object.entries() returns an array whose elements are arrays corresponding to the enumerable property [key, value] pairs found directly upon object. The ordering of the properties is the same as that given by looping over the property values of the object manually.

- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries#Description

The Object.entries function returns almost the exact output you're asking for, except the keys are strings instead of numbers.

_x000D_
_x000D_
const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};_x000D_
_x000D_
console.log(Object.entries(obj));
_x000D_
_x000D_
_x000D_

If you need the keys to be numbers, you could map the result to a new array with a callback function that replaces the key in each pair with a number coerced from it.

_x000D_
_x000D_
const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};_x000D_
_x000D_
const toNumericPairs = input => {_x000D_
    const entries = Object.entries(input);_x000D_
    return entries.map(entry => Object.assign(entry, { 0: +entry[0] }));_x000D_
}_x000D_
_x000D_
console.log(toNumericPairs(obj));
_x000D_
_x000D_
_x000D_

I use an arrow function and Object.assign for the map callback in the example above so that I can keep it in one instruction by leveraging the fact that Object.assign returns the object being assigned to, and a single instruction arrow function's return value is the result of the instruction.

This is equivalent to:

entry => {
    entry[0] = +entry[0];
    return entry;
}

As mentioned by @TravisClarke in the comments, the map function could be shortened to:

entry => [ +entry[0], entry[1] ]

However, that would create a new array for each key-value pair, instead of modifying the existing array in place, hence doubling the amount of key-value pair arrays created. While the original entries array is still accessible, it and its entries will not be garbage collected.

Now, even though using our in-place method still uses two arrays that hold the key-value pairs (the input and the output arrays), the total number of arrays only changes by one. The input and output arrays aren't actually filled with arrays, but rather references to arrays and those references take up a negligible amount of space in memory.

  • Modifying each key-value pair in-place results in a negligible amount of memory growth, but requires typing a few more characters.
  • Creating a new array for each key-value pair results in doubling the amount of memory required, but requires typing a few less characters.

You could go one step further and eliminate growth altogether by modifying the entries array in-place instead of mapping it to a new array:

_x000D_
_x000D_
const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};_x000D_
_x000D_
const toNumericPairs = input => {_x000D_
  const entries = Object.entries(obj);_x000D_
  entries.forEach(entry => entry[0] = +entry[0]);_x000D_
  return entries;_x000D_
}_x000D_
_x000D_
console.log(toNumericPairs(obj));
_x000D_
_x000D_
_x000D_

How can I add new keys to a dictionary?

add dictionary key, value class.

class myDict(dict):

    def __init__(self):
        self = dict()

    def add(self, key, value):
        #self[key] = value # add new key and value overwriting any exiting same key
        if self.get(key)!=None:
            print('key', key, 'already used') # report if key already used
        self.setdefault(key, value) # if key exit do nothing


## example

myd = myDict()
name = "fred"

myd.add('apples',6)
print('\n', myd)
myd.add('bananas',3)
print('\n', myd)
myd.add('jack', 7)
print('\n', myd)
myd.add(name, myd)
print('\n', myd)
myd.add('apples', 23)
print('\n', myd)
myd.add(name, 2)
print(myd)

"echo -n" prints "-n"

Just for the most popular linux Ubuntu & it's bash:

  1. Check which shell are you using? Mostly below works, else see this:

    echo $0

  2. If above prints bash, then below will work:

    printf "hello with no new line printed at end"
    OR
    echo -n "hello with no new line printed at end"

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

Run the below commands as admin to install NuGet using Powershell:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Install-PackageProvider -Name NuGet

How can I export Excel files using JavaScript?

To answer your question with a working example:

<script type="text/javascript">
function DownloadJSON2CSV(objArray)
{
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

    var str = '';

    for (var i = 0; i < array.length; i++) {
        var line = new Array();

        for (var index in array[i]) {
           line.push('"' + array[i][index] + '"');
        }

        str += line.join(';');
        str += '\r\n';
    }
    window.open( "data:text/csv;charset=utf-8," + encodeURIComponent(str));
}
</script>

How do I create a self-signed certificate for code signing on Windows?

Updated Answer

If you are using the following Windows versions or later: Windows Server 2012, Windows Server 2012 R2, or Windows 8.1 then MakeCert is now deprecated, and Microsoft recommends using the PowerShell Cmdlet New-SelfSignedCertificate.

If you're using an older version such as Windows 7, you'll need to stick with MakeCert or another solution. Some people suggest the Public Key Infrastructure Powershell (PSPKI) Module.

Original Answer

While you can create a self-signed code-signing certificate (SPC - Software Publisher Certificate) in one go, I prefer to do the following:

Creating a self-signed certificate authority (CA)

makecert -r -pe -n "CN=My CA" -ss CA -sr CurrentUser ^
         -a sha256 -cy authority -sky signature -sv MyCA.pvk MyCA.cer

(^ = allow batch command-line to wrap line)

This creates a self-signed (-r) certificate, with an exportable private key (-pe). It's named "My CA", and should be put in the CA store for the current user. We're using the SHA-256 algorithm. The key is meant for signing (-sky).

The private key should be stored in the MyCA.pvk file, and the certificate in the MyCA.cer file.

Importing the CA certificate

Because there's no point in having a CA certificate if you don't trust it, you'll need to import it into the Windows certificate store. You can use the Certificates MMC snapin, but from the command line:

certutil -user -addstore Root MyCA.cer

Creating a code-signing certificate (SPC)

makecert -pe -n "CN=My SPC" -a sha256 -cy end ^
         -sky signature ^
         -ic MyCA.cer -iv MyCA.pvk ^
         -sv MySPC.pvk MySPC.cer

It is pretty much the same as above, but we're providing an issuer key and certificate (the -ic and -iv switches).

We'll also want to convert the certificate and key into a PFX file:

pvk2pfx -pvk MySPC.pvk -spc MySPC.cer -pfx MySPC.pfx

If you want to protect the PFX file, add the -po switch, otherwise PVK2PFX creates a PFX file with no passphrase.

Using the certificate for signing code

signtool sign /v /f MySPC.pfx ^
              /t http://timestamp.url MyExecutable.exe

(See why timestamps may matter)

If you import the PFX file into the certificate store (you can use PVKIMPRT or the MMC snapin), you can sign code as follows:

signtool sign /v /n "Me" /s SPC ^
              /t http://timestamp.url MyExecutable.exe

Some possible timestamp URLs for signtool /t are:

  • http://timestamp.verisign.com/scripts/timstamp.dll
  • http://timestamp.globalsign.com/scripts/timstamp.dll
  • http://timestamp.comodoca.com/authenticode

Full Microsoft documentation

Downloads

For those who are not .NET developers, you will need a copy of the Windows SDK and .NET framework. A current link is available here: SDK & .NET (which installs makecert in C:\Program Files\Microsoft SDKs\Windows\v7.1). Your mileage may vary.

MakeCert is available from the Visual Studio Command Prompt. Visual Studio 2015 does have it, and it can be launched from the Start Menu in Windows 7 under "Developer Command Prompt for VS 2015" or "VS2015 x64 Native Tools Command Prompt" (probably all of them in the same folder).

Running sites on "localhost" is extremely slow

Try to enable the Bypass proxy server for local addresses. This works for all browsers installed (Firefox, Chrome, etc).

  1. Open Internet Explorer by clicking the Start button Picture of the Start button. In the search box, type Internet Explorer, and then, in the list of results, click Internet Explorer.

  2. Click the Tools button, and then click Internet Options.

  3. Click the Connections tab, and then click LAN settings.

  4. Select the Use a proxy server for your LAN check box.

  5. Select the Bypass proxy server for local addresses

jquery background-color change on focus and blur

Tested Code:

$("input").css("background","red");

Complete:

$('input:text').focus(function () {
    $(this).css({ 'background': 'Black' });
});

$('input:text').blur(function () {
    $(this).css({ 'background': 'red' });
});

Tested in version:

jquery-1.9.1.js
jquery-ui-1.10.3.js

How to wait for a number of threads to complete?

As Martin K suggested java.util.concurrent.CountDownLatch seems to be a better solution for this. Just adding an example for the same

     public class CountDownLatchDemo
{

    public static void main (String[] args)
    {
        int noOfThreads = 5;
        // Declare the count down latch based on the number of threads you need
        // to wait on
        final CountDownLatch executionCompleted = new CountDownLatch(noOfThreads);
        for (int i = 0; i < noOfThreads; i++)
        {
            new Thread()
            {

                @Override
                public void run ()
                {

                    System.out.println("I am executed by :" + Thread.currentThread().getName());
                    try
                    {
                        // Dummy sleep
                        Thread.sleep(3000);
                        // One thread has completed its job
                        executionCompleted.countDown();
                    }
                    catch (InterruptedException e)
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }.start();
        }

        try
        {
            // Wait till the count down latch opens.In the given case till five
            // times countDown method is invoked
            executionCompleted.await();
            System.out.println("All over");
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }

}

Update MongoDB field using value of another field

(I would have posted this as a comment, but couldn't)

For anyone who lands here trying to update one field using another in the document with the c# driver... I could not figure out how to use any of the UpdateXXX methods and their associated overloads since they take an UpdateDefinition as an argument.

// we want to set Prop1 to Prop2
class Foo { public string Prop1 { get; set; } public string Prop2 { get; set;} } 

void Test()
{ 
     var update = new UpdateDefinitionBuilder<Foo>();
     update.Set(x => x.Prop1, <new value; no way to get a hold of the object that I can find>)
}

As a workaround, I found that you can use the RunCommand method on an IMongoDatabase (https://docs.mongodb.com/manual/reference/command/update/#dbcmd.update).

var command = new BsonDocument
        {
            { "update", "CollectionToUpdate" },
            { "updates", new BsonArray 
                 { 
                       new BsonDocument
                       {
                            // Any filter; here the check is if Prop1 does not exist
                            { "q", new BsonDocument{ ["Prop1"] = new BsonDocument("$exists", false) }}, 
                            // set it to the value of Prop2
                            { "u", new BsonArray { new BsonDocument { ["$set"] = new BsonDocument("Prop1", "$Prop2") }}},
                            { "multi", true }
                       }
                 }
            }
        };

 database.RunCommand<BsonDocument>(command);

PHP convert date format dd/mm/yyyy => yyyy-mm-dd

Try Using DateTime::createFromFormat

$date = DateTime::createFromFormat('d/m/Y', "24/04/2012");
echo $date->format('Y-m-d');

Output

2012-04-24

EDIT:

If the date is 5/4/2010 (both D/M/YYYY or DD/MM/YYYY), this below method is used to convert 5/4/2010 to 2010-4-5 (both YYYY-MM-DD or YYYY-M-D) format.

$old_date = explode('/', '5/4/2010'); 
$new_data = $old_date[2].'-'.$old_date[1].'-'.$old_date[0];

OUTPUT:

2010-4-5

Using Javascript: How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

You cannot check window.history.length as it contains the amount of pages in you visited in total in a given session:

window.history.length (Integer)

Read-only. Returns the number of elements in the session history, including the currently loaded page. For example, for a page loaded in a new tab this property returns 1. Cite 1

Lets say a user visits your page, clicks on some links and goes back:

www.mysite.com/index.html <-- first page and now current page                  <----+
www.mysite.com/about.html                                                           |
www.mysite.com/about.html#privacy                                                   | 
www.mysite.com/terms.html <-- user uses backbutton or your provided solution to go back

Now window.history.length is 4. You cannot traverse through the history items due to security reasons. Otherwise on could could read the user's history and get his online banking session id or other sensitive information.

You can set a timeout, that will enable you to act if the previous page isn't loaded in a given time. However, if the user has a slow Internet connection and the timeout is to short, this method will redirect him to your default location all the time:

window.goBack = function (e){
    var defaultLocation = "http://www.mysite.com";
    var oldHash = window.location.hash;

    history.back(); // Try to go back

    var newHash = window.location.hash;

    /* If the previous page hasn't been loaded in a given time (in this case
    * 1000ms) the user is redirected to the default location given above.
    * This enables you to redirect the user to another page.
    *
    * However, you should check whether there was a referrer to the current
    * site. This is a good indicator for a previous entry in the history
    * session.
    *
    * Also you should check whether the old location differs only in the hash,
    * e.g. /index.html#top --> /index.html# shouldn't redirect to the default
    * location.
    */

    if(
        newHash === oldHash &&
        (typeof(document.referrer) !== "string" || document.referrer  === "")
    ){
        window.setTimeout(function(){
            // redirect to default location
            window.location.href = defaultLocation;
        },1000); // set timeout in ms
    }
    if(e){
        if(e.preventDefault)
            e.preventDefault();
        if(e.preventPropagation)
            e.preventPropagation();
    }
    return false; // stop event propagation and browser default event
}
<span class="goback" onclick="goBack();">Go back!</span>

Note that typeof(document.referrer) !== "string" is important, as browser vendors can disable the referrer due to security reasons (session hashes, custom GET URLs). But if we detect a referrer and it's empty, it's probaly save to say that there's no previous page (see note below). Still there could be some strange browser quirk going on, so it's safer to use the timeout than to use a simple redirection.

EDIT: Don't use <a href='#'>...</a>, as this will add another entry to the session history. It's better to use a <span> or some other element. Note that typeof document.referrer is always "string" and not empty if your page is inside of a (i)frame.

See also:

CSS3 transform not working

In webkit-based browsers(Safari and Chrome), -webkit-transform is ignored on inline elements.. Set display: inline-block; to make it work. For demonstration/testing purposes, you may also want to use a negative angle or a transformation-origin lest the text is rotated out of the visible area.

How do I install a custom font on an HTML site

You can use @font-face in most modern browsers.

Here's some articles on how it works:

Here is a good syntax for adding the font to your app:

Here are a couple of places to convert fonts for use with @font-face:

Also cufon will work if you don't want to use font-face, and it has good documentation on the web site:

Apache: The requested URL / was not found on this server. Apache

Non-trivial reasons:

  • if your .htaccess is in DOS format, change it to UNIX format (in Notepad++, click Edit>Convert )
  • if your .htaccess is in UTF8 Without-BOM, make it WITH BOM.

Change application's starting activity

 <application
    android:icon="@drawable/YOUR_ICON"    <!-- THIS ICON(IMAGE) WILL BE SHOWN IN YOUR APPS -->
    android:label="MY APP NAME " >    <!-- HERE LABEL(APP NAME) -->
    <activity
        android:name=".application's starting activity"  <!-- (.)dot means current dir, if your activity is in another package then give full package name ex: com.xxx.Activity  -->
        android:label="LABEL FOR ACTIVITY "
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

ggplot with 2 y axes on each side and different scales

We definitely could build a plot with dual Y-axises using base R funtion plot.

# pseudo dataset
df <- data.frame(x = seq(1, 1000, 1), y1 = sample.int(100, 1000, replace=T), y2 = sample(50, 1000, replace = T))

# plot first plot 
with(df, plot(y1 ~ x, col = "red"))

# set new plot
par(new = T) 

# plot second plot, but without axis
with(df, plot(y2 ~ x, type = "l", xaxt = "n", yaxt = "n", xlab = "", ylab = ""))

# define y-axis and put y-labs
axis(4)
with(df, mtext("y2", side = 4))

Ignoring a class property in Entity Framework 4.1 Code First

As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema namespace.

Escape double quotes in parameter

Another way to escape quotes (though probably not preferable), which I've found used in certain places is to use multiple double-quotes. For the purpose of making other people's code legible, I'll explain.

Here's a set of basic rules:

  1. When not wrapped in double-quoted groups, spaces separate parameters:
    program param1 param2 param 3 will pass four parameters to program.exe:
         param1, param2, param, and 3.
  2. A double-quoted group ignores spaces as value separators when passing parameters to programs:
    program one two "three and more" will pass three parameters to program.exe:
         one, two, and three and more.
  3. Now to explain some of the confusion:
  4. Double-quoted groups that appear directly adjacent to text not wrapped with double-quotes join into one parameter:
    hello"to the entire"world acts as one parameter: helloto the entireworld.
  5. Note: The previous rule does NOT imply that two double-quoted groups can appear directly adjacent to one another.
  6. Any double-quote directly following a closing quote is treated as (or as part of) plain unwrapped text that is adjacent to the double-quoted group, but only one double-quote:
    "Tim says, ""Hi!""" will act as one parameter: Tim says, "Hi!"

Thus there are three different types of double-quotes: quotes that open, quotes that close, and quotes that act as plain-text.
Here's the breakdown of that last confusing line:

"   open double-quote group
T   inside ""s
i   inside ""s
m   inside ""s
    inside ""s - space doesn't separate
s   inside ""s
a   inside ""s
y   inside ""s
s   inside ""s
,   inside ""s
    inside ""s - space doesn't separate
"   close double-quoted group
"   quote directly follows closer - acts as plain unwrapped text: "
H   outside ""s - gets joined to previous adjacent group
i   outside ""s - ...
!   outside ""s - ...
"   open double-quote group
"   close double-quote group
"   quote directly follows closer - acts as plain unwrapped text: "

Thus, the text effectively joins four groups of characters (one with nothing, however):
Tim says,  is the first, wrapped to escape the spaces
"Hi! is the second, not wrapped (there are no spaces)
 is the third, a double-quote group wrapping nothing
" is the fourth, the unwrapped close quote.

As you can see, the double-quote group wrapping nothing is still necessary since, without it, the following double-quote would open up a double-quoted group instead of acting as plain-text.

From this, it should be recognizable that therefore, inside and outside quotes, three double-quotes act as a plain-text unescaped double-quote:

"Tim said to him, """What's been happening lately?""""

will print Tim said to him, "What's been happening lately?" as expected. Therefore, three quotes can always be reliably used as an escape.
However, in understanding it, you may note that the four quotes at the end can be reduced to a mere two since it technically is adding another unnecessary empty double-quoted group.

Here are a few examples to close it off:

program a b                       REM sends (a) and (b)
program """a"""                   REM sends ("a")
program """a b"""                 REM sends ("a) and (b")
program """"Hello,""" Mike said." REM sends ("Hello," Mike said.)
program ""a""b""c""d""            REM sends (abcd) since the "" groups wrap nothing
program "hello to """quotes""     REM sends (hello to "quotes")
program """"hello world""         REM sends ("hello world")
program """hello" world""         REM sends ("hello world")
program """hello "world""         REM sends ("hello) and (world")
program "hello ""world"""         REM sends (hello "world")
program "hello """world""         REM sends (hello "world")

Final note: I did not read any of this from any tutorial - I came up with all of it by experimenting. Therefore, my explanation may not be true internally. Nonetheless all the examples above evaluate as given, thus validating (but not proving) my theory.

I tested this on Windows 7, 64bit using only *.exe calls with parameter passing (not *.bat, but I would suppose it works the same).

Try-catch block in Jenkins pipeline script

try/catch is scripted syntax. So any time you are using declarative syntax to use something from scripted in general you can do so by enclosing the scripted syntax in the scripts block in a declarative pipeline. So your try/catch should go inside stage >steps >script.

This holds true for any other scripted pipeline syntax you would like to use in a declarative pipeline as well.

How do I POST XML data with curl

-H "text/xml" isn't a valid header. You need to provide the full header:

-H "Content-Type: text/xml" 

Repeating a function every few seconds

Use a timer. Keep in mind that .NET comes with a number of different timers. This article covers the differences.

Check if one date is between two dates

Here is a Date Prototype method written in typescript:

Date.prototype.isBetween = isBetween;
interface Date { isBetween: typeof isBetween }
function isBetween(minDate: Date, maxDate: Date): boolean {
  if (!this.getTime) throw new Error('isBetween() was called on a non Date object');
  return !minDate ? true : this.getTime() >= minDate.getTime()
    && !maxDate ? true : this.getTime() <= maxDate.getTime();
};

How to get the height of a body element

Simply use

$(document).height() // - $('body').offset().top

and / or

$(window).height()

instead of $('body').height();

Setting attribute disabled on a SPAN element does not prevent click events

The best method is to wrap the span inside a button and disable the button

_x000D_
_x000D_
$("#buttonD").click(function(){_x000D_
  alert("button clicked");_x000D_
})_x000D_
_x000D_
$("#buttonS").click(function(){_x000D_
  alert("span clicked");_x000D_
})
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
_x000D_
<button class="btn btn-success" disabled="disabled" id="buttonD">_x000D_
    <span>Disabled button</span>_x000D_
</button>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
 <span class="btn btn-danger" disabled="disabled" id="buttonS">Disabled span</span>
_x000D_
_x000D_
_x000D_

How to git-cherry-pick only changes to certain files?

Merge a branch into new one (squash) and remove the files not needed:

git checkout master
git checkout -b <branch>
git merge --squash <source-branch-with-many-commits>
git reset HEAD <not-needed-file-1>
git checkout -- <not-needed-file-1>
git reset HEAD <not-needed-file-2>
git checkout -- <not-needed-file-2>
git commit

Combine two arrays

This works:

$output = $array1 + $array2;

How can I do GUI programming in C?

The most famous library to create some GUI in C language is certainly GTK.

With this library you can easily create some buttons (for your example). When a user clicks on the button, a signal is emitted and you can write a handler to do some actions.

Why does an onclick property set with setAttribute fail to work in IE?

I did this to get around it and move on, in my case I'm not using an 'input' element, instead I use an image, when I tried setting the "onclick" attribute for this image I experienced the same problem, so I tried wrapping the image with an "a" element and making the reference point to the function like this.

var rowIndex = 1;
var linkDeleter = document.createElement('a');
linkDeleter.setAttribute('href', "javascript:function(" + rowIndex + ");");

var imgDeleter = document.createElement('img');
imgDeleter.setAttribute('alt', "Delete");
imgDeleter.setAttribute('src', "Imagenes/DeleteHS.png");
imgDeleter.setAttribute('border', "0");

linkDeleter.appendChild(imgDeleter);

Save classifier to disk in scikit-learn

sklearn.externals.joblib has been deprecated since 0.21 and will be removed in v0.23:

/usr/local/lib/python3.7/site-packages/sklearn/externals/joblib/init.py:15: FutureWarning: sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23. Please import this functionality directly from joblib, which can be installed with: pip install joblib. If this warning is raised when loading pickled models, you may need to re-serialize those models with scikit-learn 0.21+.
warnings.warn(msg, category=FutureWarning)


Therefore, you need to install joblib:

pip install joblib

and finally write the model to disk:

import joblib
from sklearn.datasets import load_digits
from sklearn.linear_model import SGDClassifier


digits = load_digits()
clf = SGDClassifier().fit(digits.data, digits.target)

with open('myClassifier.joblib.pkl', 'wb') as f:
    joblib.dump(clf, f, compress=9)

Now in order to read the dumped file all you need to run is:

with open('myClassifier.joblib.pkl', 'rb') as f:
    my_clf = joblib.load(f)

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

Are you using jQuery?

Because I did a quickly search on the jQuery plugings and they seem to have some plugin to do this, check this one, should work:

http://plugins.jquery.com/project/jquery-afterresize

EDIT:

This is the CSS solution, I just add a style="width: 100%", and works for me at least in chrome and Safari. I dont have ie, so just test there, and let me know, here is the code:

            <div id="gallery" style="width: 100%">
                <img src="images/fullsize.jpg" alt="" id="fullsize" />
                <a href="#" id="prev">prev</a>
                <a href="#" id="next">next</a>
            </div>

How to add an image to a JPanel?

  1. There shouldn't be any problem (other than any general problems you might have with very large images).
  2. If you're talking about adding multiple images to a single panel, I would use ImageIcons. For a single image, I would think about making a custom subclass of JPanel and overriding its paintComponent method to draw the image.
  3. (see 2)

When do we need curly braces around shell variables?

You use {} for grouping. The braces are required to dereference array elements. Example:

dir=(*)           # store the contents of the directory into an array
echo "${dir[0]}"  # get the first entry.
echo "$dir[0]"    # incorrect

Split string with JavaScript

Like this:

var myString = "19 51 2.108997";
var stringParts = myString.split(" ");
var html = "<span>" + stringParts[0] + " " + stringParts[1] + "</span> <span>" + stringParts[2] + "</span";

Linux bash script to extract IP address

  /sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'

React JS Error: is not defined react/jsx-no-undef

The Syntax for the importing any module is

import {  } from "module";

or

import module-name from "module";

Before error (cakeContainer with small "c")

cakeContainer with small c

After Fix

Fixed with the changing the case

server error:405 - HTTP verb used to access this page is not allowed

I've been pulling my hair out over this one for a couple of hours also. fakeartist appears correct though - I changed the file extension from .htm to .php and I can now see my page in Facebook! It also works if you change the extension to .aspx - perhaps it just needs to be a server side extension (I've not tried with .jsp).

Delete rows containing specific strings in R

You can use it in the same datafram (df) using the previously provided code

df[!grepl("REVERSE", df$Name),]

or you might assign a different name to the datafram using this code

df1<-df[!grepl("REVERSE", df$Name),]

how to increase java heap memory permanently?

Please note that increasing the Java heap size following an java.lang.OutOfMemoryError: Java heap space is quite often just a short term solution.

This means that even if you increase the default Java heap size from 512 MB to let's say 2048 MB, you may still get this error at some point if you are dealing with a memory leak. The main question to ask is why are you getting this OOM error at the first place? Is it really a Xmx value too low or just a symptom of another problem?

When developing a Java application, it is always crucial to understand its static and dynamic memory footprint requirement early on, this will help prevent complex OOM problems later on. Proper sizing of JVM Xms & Xmx settings can be achieved via proper application profiling and load testing.

How to convert int[] to Integer[] in Java?

If you want to convert an int[] to an Integer[], there isn't an automated way to do it in the JDK. However, you can do something like this:

int[] oldArray;

... // Here you would assign and fill oldArray

Integer[] newArray = new Integer[oldArray.length];
int i = 0;
for (int value : oldArray) {
    newArray[i++] = Integer.valueOf(value);
}

If you have access to the Apache lang library, then you can use the ArrayUtils.toObject(int[]) method like this:

Integer[] newArray = ArrayUtils.toObject(oldArray);

Benefits of using the conditional ?: (ternary) operator

The advantage of the conditional operator is that it is an operator. In other words, it returns a value. Since if is a statement, it cannot return a value.

What does the exclamation mark do before the function?

It returns whether the statement can evaluate to false. eg:

!false      // true
!true       // false
!isValid()  // is not valid

You can use it twice to coerce a value to boolean:

!!1    // true
!!0    // false

So, to more directly answer your question:

var myVar = !function(){ return false; }();  // myVar contains true

Edit: It has the side effect of changing the function declaration to a function expression. E.g. the following code is not valid because it is interpreted as a function declaration that is missing the required identifier (or function name):

function () { return false; }();  // syntax error

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

Logically OLAP functions are calculated after GROUP BY/HAVING, so you can only access columns in GROUP BY or columns with an aggregate function. Following looks strange, but is Standard SQL:

SELECT employee_number,
       MAX(MAX(course_completion_date)) 
           OVER (PARTITION BY course_code) AS max_course_date,
       MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

And as Teradata allows re-using an alias this also works:

SELECT employee_number,
       MAX(max_date) 
           OVER (PARTITION BY course_code) AS max_course_date,
       MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

I landed here because of an XCTestCase, in which I'd disabled most of the tests by prefixing them with 'no_' as in no_testBackgroundAdding. Once I noticed that most of the answers had something to do with locks and threading, I realized the test contained a few instances of XCTestExpectation with corresponding waitForExpectations. They were all in the disabled tests, but apparently Xcode was still evaluating them at some level.

In the end I found an XCTestExpectation that was defined as @property but lacked the @synthesize. Once I added the synthesize directive, the EXC_BAD_INSTRUCTION disappeared.

How to destroy a JavaScript object?

You can't delete objects, they are removed when there are no more references to them. You can delete references with delete.

However, if you have created circular references in your objects you may have to de-couple some things.

SQL: Two select statements in one query

You can do something like this:

 (SELECT
    name, games, goals
    FROM tblMadrid WHERE name = 'ronaldo')
 UNION
 (SELECT
    name, games, goals
    FROM tblBarcelona WHERE name = 'messi')
ORDER BY goals;

See, for example: https://dev.mysql.com/doc/refman/5.0/en/union.html

jQuery check if it is clicked or not

Using jQuery, I would suggest a shorter solution.

var elementClicked;
$("element").click(function(){
   elementClicked = true;
});
if( elementClicked != true ) {
    alert("element not clicked");
}else{
    alert("element clicked");
}

("element" here is to be replaced with the actual name tag)

How to exclude file only from root folder in Git

Older versions of git require you first define an ignore pattern and immediately (on the next line) define the exclusion. [tested on version 1.9.3 (Apple Git-50)]

/config.php
!/*/config.php

Later versions only require the following [tested on version 2.2.1]

/config.php

Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

I had to use dynamic views (setup views and constraints by code) and when I wanted to set preferredMaxLayoutWidth label's width was 0. So I've got wrong cell height.

Then I added

[cell layoutSubviews];

before executing

[cell setNeedsUpdateConstraints];
[cell updateConstraintsIfNeeded];

After that label's width was as expected and dynamic height was calculating right.

Setting the filter to an OpenFileDialog to allow the typical image formats?

Complete solution in C# is here:

private void btnSelectImage_Click(object sender, RoutedEventArgs e)
{
    // Configure open file dialog box 
    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
    dlg.Filter = "";

    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
    string sep = string.Empty;

    foreach (var c in codecs)
    {
       string codecName = c.CodecName.Substring(8).Replace("Codec", "Files").Trim();
       dlg.Filter = String.Format("{0}{1}{2} ({3})|{3}", dlg.Filter, sep, codecName, c.FilenameExtension);
       sep = "|";
    }

    dlg.Filter = String.Format("{0}{1}{2} ({3})|{3}", dlg.Filter, sep, "All Files", "*.*"); 

    dlg.DefaultExt = ".png"; // Default file extension 

    // Show open file dialog box 
    Nullable<bool> result = dlg.ShowDialog();

    // Process open file dialog box results 
    if (result == true)
    {
       // Open document 
       string fileName  = dlg.FileName;
       // Do something with fileName  
    }
} 

SQL Server: Database stuck in "Restoring" state

Ran into a similar issue while restoring the database using SQL server management studio and it got stuck into restoring mode. After several hours of issue tracking, the following query worked for me. The following query restores the database from an existing backup to a previous state. I believe, the catch is the to have the .mdf and .log file in the same directory.

RESTORE DATABASE aqua_lc_availability
FROM DISK = 'path to .bak file'
WITH RECOVERY

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

It can't take a file handle. The install_requires argument can only be a string or a list of strings.

You can, of course, read your file in the setup script and pass it as a list of strings to install_requires.

import os
from setuptools import setup

with open('requirements.txt') as f:
    required = f.read().splitlines()

setup(...
install_requires=required,
...)

What is the difference between synchronous and asynchronous programming (in node.js)

Synchronous functions are blocking while asynchronous functions are not. In synchronous functions, statements complete before the next statement is run. In this case, the program is evaluated exactly in order of the statements and execution of the program is paused if one of the statements take a very long time.

Asynchronous functions usually accept a callback as a parameter and execution continue on the next line immediately after the asynchronous function is invoked. The callback is only invoked when the asynchronous operation is complete and the call stack is empty. Heavy duty operations such as loading data from a web server or querying a database should be done asynchronously so that the main thread can continue executing other operations instead of blocking until that long operation to complete (in the case of browsers, the UI will freeze).

Orginal Posted on Github: Link

webpack: Module not found: Error: Can't resolve (with relative path)

I had a different problem. some of my includes were set to 'app/src/xxx/yyy' instead of '../xxx/yyy'

pandas dataframe columns scaling with sklearn

df = pd.DataFrame(scale.fit_transform(df.values), columns=df.columns, index=df.index)

This should work without depreciation warnings.

runOnUiThread in fragment

I used this for getting Date and Time in a fragment.

private Handler mHandler = new Handler(Looper.getMainLooper());
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View root = inflater.inflate(R.layout.fragment_head_screen, container, false);

    dateTextView =  root.findViewById(R.id.dateView);
    hourTv = root.findViewById(R.id.hourView);

        Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(1000);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            //Calendario para obtener fecha & hora
                            Date currentTime = Calendar.getInstance().getTime();
                            SimpleDateFormat date_sdf = new SimpleDateFormat("dd/MM/yyyy");
                            SimpleDateFormat hour_sdf = new SimpleDateFormat("HH:mm a");

                            String currentDate = date_sdf.format(currentTime);
                            String currentHour = hour_sdf.format(currentTime);

                            dateTextView.setText(currentDate);
                            hourTv.setText(currentHour);
                        }
                    });
                }
            } catch (InterruptedException e) {
                Log.v("InterruptedException", e.getMessage());
            }
        }
    };
}

Object comparison in JavaScript

Here is my version, pretty much stuff from this thread is integrated (same counts for the test cases):

Object.defineProperty(Object.prototype, "equals", {
    enumerable: false,
    value: function (obj) {
        var p;
        if (this === obj) {
            return true;
        }

        // some checks for native types first

        // function and sring
        if (typeof(this) === "function" || typeof(this) === "string" || this instanceof String) { 
            return this.toString() === obj.toString();
        }

        // number
        if (this instanceof Number || typeof(this) === "number") {
            if (obj instanceof Number || typeof(obj) === "number") {
                return this.valueOf() === obj.valueOf();
            }
            return false;
        }

        // null.equals(null) and undefined.equals(undefined) do not inherit from the 
        // Object.prototype so we can return false when they are passed as obj
        if (typeof(this) !== typeof(obj) || obj === null || typeof(obj) === "undefined") {
            return false;
        }

        function sort (o) {
            var result = {};

            if (typeof o !== "object") {
                return o;
            }

            Object.keys(o).sort().forEach(function (key) {
                result[key] = sort(o[key]);
            });

            return result;
        }

        if (typeof(this) === "object") {
            if (Array.isArray(this)) { // check on arrays
                return JSON.stringify(this) === JSON.stringify(obj);                
            } else { // anyway objects
                for (p in this) {
                    if (typeof(this[p]) !== typeof(obj[p])) {
                        return false;
                    }
                    if ((this[p] === null) !== (obj[p] === null)) {
                        return false;
                    }
                    switch (typeof(this[p])) {
                    case 'undefined':
                        if (typeof(obj[p]) !== 'undefined') {
                            return false;
                        }
                        break;
                    case 'object':
                        if (this[p] !== null 
                                && obj[p] !== null 
                                && (this[p].constructor.toString() !== obj[p].constructor.toString() 
                                        || !this[p].equals(obj[p]))) {
                            return false;
                        }
                        break;
                    case 'function':
                        if (this[p].toString() !== obj[p].toString()) {
                            return false;
                        }
                        break;
                    default:
                        if (this[p] !== obj[p]) {
                            return false;
                        }
                    }
                };

            }
        }

        // at least check them with JSON
        return JSON.stringify(sort(this)) === JSON.stringify(sort(obj));
    }
});

Here is my TestCase:

    assertFalse({}.equals(null));
    assertFalse({}.equals(undefined));

    assertTrue("String", "hi".equals("hi"));
    assertTrue("Number", new Number(5).equals(5));
    assertFalse("Number", new Number(5).equals(10));
    assertFalse("Number+String", new Number(1).equals("1"));

    assertTrue([].equals([]));
    assertTrue([1,2].equals([1,2]));
    assertFalse([1,2].equals([2,1]));
    assertFalse([1,2].equals([1,2,3]));

    assertTrue(new Date("2011-03-31").equals(new Date("2011-03-31")));
    assertFalse(new Date("2011-03-31").equals(new Date("1970-01-01")));

    assertTrue({}.equals({}));
    assertTrue({a:1,b:2}.equals({a:1,b:2}));
    assertTrue({a:1,b:2}.equals({b:2,a:1}));
    assertFalse({a:1,b:2}.equals({a:1,b:3}));

    assertTrue({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}.equals({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}));
    assertFalse({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}.equals({1:{name:"mhc",age:28}, 2:{name:"arb",age:27}}));

    assertTrue("Function", (function(x){return x;}).equals(function(x){return x;}));
    assertFalse("Function", (function(x){return x;}).equals(function(y){return y+2;}));

    var a = {a: 'text', b:[0,1]};
    var b = {a: 'text', b:[0,1]};
    var c = {a: 'text', b: 0};
    var d = {a: 'text', b: false};
    var e = {a: 'text', b:[1,0]};
    var f = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
    var g = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
    var h = {a: 'text', b:[1,0], f: function(){ this.a = this.b; }};
    var i = {
        a: 'text',
        c: {
            b: [1, 0],
            f: function(){
                this.a = this.b;
            }
        }
    };
    var j = {
        a: 'text',
        c: {
            b: [1, 0],
            f: function(){
                this.a = this.b;
            }
        }
    };
    var k = {a: 'text', b: null};
    var l = {a: 'text', b: undefined};

    assertTrue(a.equals(b));
    assertFalse(a.equals(c));
    assertFalse(c.equals(d));
    assertFalse(a.equals(e));
    assertTrue(f.equals(g));
    assertFalse(h.equals(g));
    assertTrue(i.equals(j));
    assertFalse(d.equals(k));
    assertFalse(k.equals(l));

Read entire file in Scala?

The obvious question being "why do you want to read in the entire file?" This is obviously not a scalable solution if your files get very large. The scala.io.Source gives you back an Iterator[String] from the getLines method, which is very useful and concise.

It's not much of a job to come up with an implicit conversion using the underlying java IO utilities to convert a File, a Reader or an InputStream to a String. I think that the lack of scalability means that they are correct not to add this to the standard API.

Adding options to a <select> using jQuery?

You can do this in ES6:

$.each(json, (i, val) => {
    $('.js-country-of-birth').append(`<option value="${val.country_code}"> ${val.country} </option>`);
  });

What is the difference between String and StringBuffer in Java?

A StringBuffer or its younger and faster brother StringBuilder is preferred whenever you're going do to a lot of string concatenations in flavor of

string += newString;

or equivalently

string = string + newString;

because the above constructs implicitly creates new string everytime which will be a huge performance and drop. A StringBuffer / StringBuilder is under the hoods best to be compared with a dynamically expansible List<Character>.

I want to compare two lists in different worksheets in Excel to locate any duplicates

Without VBA...

If you can use a helper column, you can use the MATCH function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match

To simply identify duplicates, use a helper column

Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:

=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")

Drag/copy this forumla down, and it should identify the duplicates.

To highlight cells, use conditional formatting:

With some tinkering, you can use this MATCH function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.

Something like:

=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))

Conditional formatting for Excel 2010

For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:

=B1="Duplicate"

This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.

Conditional formatting using helper column for rule

Using Mockito's generic "any()" method

This should work

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;

verify(bar).DoStuff(any(Foo[].class));

Binding IIS Express to an IP Address

In order for IIS Express answer on any IP address, just leave the address blank, i.e:

bindingInformation=":8080:"

Don't forget to restart the IIS express before the changes can take place.

ASP.NET 4.5 has not been registered on the Web server

tl;dr; Clicking OK is the workaround, everything will work fine after that.

I also received this error message.

Configuring Web http://localhost:xxxxx/ for ASP.NET 4.5 failed. You must manually configure this site for ASP.NET 4.5 in order for the site to run correctly. ASP.NET 4.0 has not been registered on the Web server. You need to manually configure your Web server for ASP.NET 4.0 in order for your site to run correctly.

Environment: Windows 10, IIS8, VS 2012 Web.

After finding this page, along with several seemingly invasive solutions, I read through the hotfix option at https://support.microsoft.com/en-us/help/3002339/unexpected-dialog-box-appears-when-you-open-projects-in-visual-studio as suggested here.

Please avoid doing anything too drastic, and note the section of that page marked "Workaround" as shown below:

Workaround


To work around this issue, click OK when the dialog box appears after you either create a new project or open an existing Web Site Project or Windows Azure project. After you do this, the project works as expected.

In other words, click OK on the dialog box one time, and the message is gone forever. The project will work just fine.

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

This works fine

public class DateDemo {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm");
        String date = "16-08-2018 12:10";
        LocalDate localDate = LocalDate.parse(date, formatter);
        System.out.println("VALUE="+localDate);

        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
        LocalDateTime parse = LocalDateTime.parse(date, formatter1);
        System.out.println("VALUE1="+parse);
    }
}

output:

VALUE=2018-08-16
VALUE1=2018-08-16T12:10

Excel tab sheet names vs. Visual Basic sheet names

Actually "Sheet1" object / code name can be changed. In VBA, click on Sheet1 in Excel Objects list. In the properties window, you can change Sheet1 to say rng.

Then you can reference rng as a global object without having to create a variable first. So debug.print rng.name works just fine. No more Worksheets("rng").name.

Unlike the tab, the object name has same restrictions as other variables (i.e. no spaces).

Twitter Bootstrap 3.0 how do I "badge badge-important" now

Well, this is a terribly late answer but I think I'll still put my two cents in... I could have posted this as a comment because this answer doesn't essentially add any new solution but it does add value to the post as yet another alternative. But in a comment I wouldn't be able to give all the details because of character limit.

NOTE: This needs an edit to bootstrap CSS file - move style definitions for .badge above .label-default. Couldn't find any practical side effects due to the change in my limited testing.

While broc.seib's solution is probably the best way to achieve the requirement of OP with minimal addition to CSS, it is possible to achieve the same effect without any extra CSS at all just like Jens A. Koch's solution or by using .label-xxx contextual classes because they are easy to remember compared to progress-bar-xxx classes. I don't think that .alert-xxx classes give the same effect.

All you have to do is just use .badge and .label-xxx classes together (but in this order). Don't forget to make the changes mentioned in NOTE above.

<a href="#">Inbox <span class="badge label-warning">42</span></a> looks like this:

Badge with warning bg

IMPORTANT: This solution may break your styles if you decide to upgrade and forget to make the changes in your new local CSS file. My solution for this challenge was to copy all .label-xxx styles in my custom CSS file and load it after all other CSS files. This approach also helps when I use a CDN for loading BS3.

**P.S: ** Both the top rated answers have their pros and cons. It's just the way you prefer to do your CSS because there is no "only correct way" to do it.

Setting Django up to use MySQL

python3 -m pip install mysql-connector
pip install mysqlclient

These commands helpful to settingup the mysql db in django without errors

How to list active connections on PostgreSQL?

Oh, I just found that command on PostgreSQL forum:

SELECT * FROM pg_stat_activity;

How to properly seed random number generator

OK why so complex!

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed( time.Now().UnixNano())
    var bytes int

    for i:= 0 ; i < 10 ; i++{ 
        bytes = rand.Intn(6)+1
        fmt.Println(bytes)
        }
    //fmt.Println(time.Now().UnixNano())
}

This is based off the dystroy's code but fitted for my needs.

It's die six (rands ints 1 =< i =< 6)

func randomInt (min int , max int  ) int {
    var bytes int
    bytes = min + rand.Intn(max)
    return int(bytes)
}

The function above is the exactly same thing.

I hope this information was of use.

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

javax.websocket client simple example

Have a look at this Java EE 7 examples from Arun Gupta.

I forked it on github.

Main

/**
 * @author Arun Gupta
 */
public class Client {

    final static CountDownLatch messageLatch = new CountDownLatch(1);

    public static void main(String[] args) {
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            String uri = "ws://echo.websocket.org:80/";
            System.out.println("Connecting to " + uri);
            container.connectToServer(MyClientEndpoint.class, URI.create(uri));
            messageLatch.await(100, TimeUnit.SECONDS);
        } catch (DeploymentException | InterruptedException | IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

ClientEndpoint

/**
 * @author Arun Gupta
 */
@ClientEndpoint
public class MyClientEndpoint {
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Connected to endpoint: " + session.getBasicRemote());
        try {
            String name = "Duke";
            System.out.println("Sending message to endpoint: " + name);
            session.getBasicRemote().sendText(name);
        } catch (IOException ex) {
            Logger.getLogger(MyClientEndpoint.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @OnMessage
    public void processMessage(String message) {
        System.out.println("Received message in client: " + message);
        Client.messageLatch.countDown();
    }

    @OnError
    public void processError(Throwable t) {
        t.printStackTrace();
    }
}

Where can I find MySQL logs in phpMyAdmin?

Use performance_schema database and the tables:

  1. events_statements_current
  2. events_statemenets_history
  3. events_statemenets_history_long

Check the manual here

How to get difference between two dates in Year/Month/Week/Day?

Days: (endDate - startDate).Days
Weeks: (endDate - startDate).Days / 7
Years: Months / 12
Months: A TimeSpan only provides Days, so use the following code to get the number of whole months between a specified start and end date. For example, the number of whole months between 01/10/2000 and 02/10/2000 is 1. The the number of whole months between 01/10/2000 and 02/09/2000 is 0.

    public int getMonths(DateTime startDate, DateTime endDate)
    {
        int months = 0;

        if (endDate.Month <= startDate.Month)
        {
            if (endDate.Day < startDate.Day)
            {
                months = (12 * (endDate.Year - startDate.Year - 1))
                       + (12 - startDate.Month + endDate.Month - 1);
            }
            else if (endDate.Month < startDate.Month)
            {
                months = (12 * (endDate.Year - startDate.Year - 1))
                       + (12 - startDate.Month + endDate.Month);
            }
            else  // (endDate.Month == startDate.Month) && (endDate.Day >= startDate.Day)
            {
                months = (12 * (endDate.Year - startDate.Year));
            }
        }
        else if (endDate.Day < startDate.Day)
        {
            months = (12 * (endDate.Year - startDate.Year))
                   + (endDate.Month - startDate.Month) - 1;
        }
        else  // (endDate.Month > startDate.Month) && (endDate.Day >= startDate.Day)
        {
            months = (12 * (endDate.Year - startDate.Year))
                   + (endDate.Month - startDate.Month);
        }

        return months;
    }

How can foreign key constraints be temporarily disabled using T-SQL?

SET NOCOUNT ON

DECLARE @table TABLE(
   RowId INT PRIMARY KEY IDENTITY(1, 1),
   ForeignKeyConstraintName NVARCHAR(200),
   ForeignKeyConstraintTableSchema NVARCHAR(200),
   ForeignKeyConstraintTableName NVARCHAR(200),
   ForeignKeyConstraintColumnName NVARCHAR(200),
   PrimaryKeyConstraintName NVARCHAR(200),
   PrimaryKeyConstraintTableSchema NVARCHAR(200),
   PrimaryKeyConstraintTableName NVARCHAR(200),
   PrimaryKeyConstraintColumnName NVARCHAR(200),
   UpdateRule NVARCHAR(100),
   DeleteRule NVARCHAR(100)   
)

INSERT INTO @table(ForeignKeyConstraintName, ForeignKeyConstraintTableSchema, ForeignKeyConstraintTableName, ForeignKeyConstraintColumnName)
SELECT 
   U.CONSTRAINT_NAME, 
   U.TABLE_SCHEMA, 
   U.TABLE_NAME, 
   U.COLUMN_NAME
FROM 
   INFORMATION_SCHEMA.KEY_COLUMN_USAGE U
      INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C
         ON U.CONSTRAINT_NAME = C.CONSTRAINT_NAME
WHERE
   C.CONSTRAINT_TYPE = 'FOREIGN KEY'

UPDATE @table SET
   T.PrimaryKeyConstraintName = R.UNIQUE_CONSTRAINT_NAME,
   T.UpdateRule = R.UPDATE_RULE,
   T.DeleteRule = R.DELETE_RULE
FROM 
   @table T
      INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS R
         ON T.ForeignKeyConstraintName = R.CONSTRAINT_NAME

UPDATE @table SET
   PrimaryKeyConstraintTableSchema  = TABLE_SCHEMA,
   PrimaryKeyConstraintTableName  = TABLE_NAME
FROM @table T
   INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C
      ON T.PrimaryKeyConstraintName = C.CONSTRAINT_NAME

UPDATE @table SET
   PrimaryKeyConstraintColumnName = COLUMN_NAME
FROM @table T
   INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE U
      ON T.PrimaryKeyConstraintName = U.CONSTRAINT_NAME

--SELECT * FROM @table

SELECT '
BEGIN TRANSACTION
BEGIN TRY'

--DROP CONSTRAINT:
SELECT
   '
 ALTER TABLE [' + ForeignKeyConstraintTableSchema + '].[' + ForeignKeyConstraintTableName + '] 
 DROP CONSTRAINT ' + ForeignKeyConstraintName + '
   '
FROM
   @table

SELECT '
END TRY

BEGIN CATCH
   ROLLBACK TRANSACTION
   RAISERROR(''Operation failed.'', 16, 1)
END CATCH

IF(@@TRANCOUNT != 0)
BEGIN
   COMMIT TRANSACTION
   RAISERROR(''Operation completed successfully.'', 10, 1)
END
'

--ADD CONSTRAINT:
SELECT '
BEGIN TRANSACTION
BEGIN TRY'

SELECT
   '
   ALTER TABLE [' + ForeignKeyConstraintTableSchema + '].[' + ForeignKeyConstraintTableName + '] 
   ADD CONSTRAINT ' + ForeignKeyConstraintName + ' FOREIGN KEY(' + ForeignKeyConstraintColumnName + ') REFERENCES [' + PrimaryKeyConstraintTableSchema + '].[' + PrimaryKeyConstraintTableName + '](' + PrimaryKeyConstraintColumnName + ') ON UPDATE ' + UpdateRule + ' ON DELETE ' + DeleteRule + '
   '
FROM
   @table

SELECT '
END TRY

BEGIN CATCH
   ROLLBACK TRANSACTION
   RAISERROR(''Operation failed.'', 16, 1)
END CATCH

IF(@@TRANCOUNT != 0)
BEGIN
   COMMIT TRANSACTION
   RAISERROR(''Operation completed successfully.'', 10, 1)
END'

GO

matplotlib does not show my drawings although I call pyplot.show()

%matplotlib inline

For me working with notebook, adding the above line before the plot works.

How to permanently export a variable in Linux?

You can add it to your shell configuration file, e.g. $HOME/.bashrc or more globally in /etc/environment. After adding these lines the changes won't reflect instantly in GUI based system's you have to exit the terminal or create a new one and in server logout the session and login to reflect these changes.

RegEx: Grabbing values between quotation marks

I would go for:

"([^"]*)"

The [^"] is regex for any character except '"'
The reason I use this over the non greedy many operator is that I have to keep looking that up just to make sure I get it correct.

Is it still valid to use IE=edge,chrome=1?

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> serves two purposes.

  1. IE=edge: specifies that IE should run in the highest mode available to that version of IE as opposed to a compatability mode; IE8 can support up to IE8 modes, IE9 can support up to IE9 modes, and so on.
  2. chrome=1: specifies that Google Chrome frame should start if the user has it installed

The IE=edge flag is still relevant for IE versions 10 and below. IE11 sets this mode as the default.

As for the chrome flag, you can leave it if your users still use Chrome Frame. Despite support and updates for Chrome Frame ending, one can still install and use the final release. If you remove the flag, Chrome Frame will not be activated when installed. For other users, chrome=1 will do nothing more than consume a few bytes of bandwidth.

I recommend you analyze your audience and see if their browsers prohibit any needed features and then decide. Perhaps it might be better to encourage them to use a more modern, evergreen browser.

Note, the W3C validator will flag chrome=1 as an error:

Error: A meta element with an http-equiv attribute whose value is
X-UA-Compatible must have a content attribute with the value IE=edge.

PHP array: count or sizeof?

I would use count() if they are the same, as in my experience it is more common, and therefore will cause less developers reading your code to say "sizeof(), what is that?" and having to consult the documentation.

I think it means sizeof() does not work like it does in C (calculating the size of a datatype). It probably made this mention explicitly because PHP is written in C, and provides a lot of identically named wrappers for C functions (strlen(), printf(), etc)

The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'

This is how I was able to solve the problem when I faced it

  1. Start SQL Management Studio.
  2. Expand the Server Node (in the 'Object Explorer').
  3. Expand the Databases Node and then expand the specific Database which you are trying to access using the specific user.
  4. Expand the Users node under the Security node for the database.
  5. Right click the specific user and click 'properties'. You will get a dialog box.
  6. Make sure the user is a member of the db_owner group (please read the comments below before you use go this path) and other required changes using the view. (I used this for 2016. Not sure how the specific dialog look like in other version and hence not being specific)

JavaScriptSerializer.Deserialize - how to change field names

By creating a custom JavaScriptConverter you can map any name to any property. But it does require hand coding the map, which is less than ideal.

public class DataObjectJavaScriptConverter : JavaScriptConverter
{
    private static readonly Type[] _supportedTypes = new[]
    {
        typeof( DataObject )
    };

    public override IEnumerable<Type> SupportedTypes 
    { 
        get { return _supportedTypes; } 
    }

    public override object Deserialize( IDictionary<string, object> dictionary, 
                                        Type type, 
                                        JavaScriptSerializer serializer )
    {
        if( type == typeof( DataObject ) )
        {
            var obj = new DataObject();
            if( dictionary.ContainsKey( "user_id" ) )
                obj.UserId = serializer.ConvertToType<int>( 
                                           dictionary["user_id"] );
            if( dictionary.ContainsKey( "detail_level" ) )
                obj.DetailLevel = serializer.ConvertToType<DetailLevel>(
                                           dictionary["detail_level"] );

            return obj;
        }

        return null;
    }

    public override IDictionary<string, object> Serialize( 
            object obj, 
            JavaScriptSerializer serializer )
    {
        var dataObj = obj as DataObject;
        if( dataObj != null )
        {
            return new Dictionary<string,object>
            {
                {"user_id", dataObj.UserId },
                {"detail_level", dataObj.DetailLevel }
            }
        }
        return new Dictionary<string, object>();
    }
}

Then you can deserialize like so:

var serializer = new JavaScriptSerializer();
serialzer.RegisterConverters( new[]{ new DataObjectJavaScriptConverter() } );
var dataObj = serializer.Deserialize<DataObject>( json );

Capturing window.onbeforeunload

There seems to be a lot of misinformation about how to use this event going around (even in upvoted answers on this page).

The onbeforeunload event API is supplied by the browser for a specific purpose: The only thing you can do that's worth doing in this method is to return a string which the browser will then prompt to the user to indicate to them that action should be taken before they navigate away from the page. You CANNOT prevent them from navigating away from a page (imagine what a nightmare that would be for the end user).

Because browsers use a confirm prompt to show the user the string you returned from your event listener, you can't do anything else in the method either (like perform an ajax request).

In an application I wrote, I want to prompt the user to let them know they have unsaved changes before they leave the page. The browser prompts them with the message and, after that, it's out of my hands, the user can choose to stay or leave, but you no longer have control of the application at that point.

An example of how I use it (pseudo code):

onbeforeunload = function() {

  if(Application.hasUnsavedChanges()) {
    return 'You have unsaved changes. Please save them before leaving this page';
  }


};

If (and only if) the application has unsaved changes, then the browser prompts the user to either ignore my message (and leave the page anyway) or to not leave the page. If they choose to leave the page anyway, too bad, there's nothing you can do (nor should be able to do) about it.

Why .NET String is immutable?

Strings are passed as reference types in .NET.

Reference types place a pointer on the stack, to the actual instance that resides on the managed heap. This is different to Value types, who hold their entire instance on the stack.

When a value type is passed as a parameter, the runtime creates a copy of the value on the stack and passes that value into a method. This is why integers must be passed with a 'ref' keyword to return an updated value.

When a reference type is passed, the runtime creates a copy of the pointer on the stack. That copied pointer still points to the original instance of the reference type.

The string type has an overloaded = operator which creates a copy of itself, instead of a copy of the pointer - making it behave more like a value type. However, if only the pointer was copied, a second string operation could accidently overwrite the value of a private member of another class causing some pretty nasty results.

As other posts have mentioned, the StringBuilder class allows for the creation of strings without the GC overhead.

Get connection status on Socket.io client

These days, socket.on('connect', ...) is not working for me. I use the below code to check at 1st connecting.

if (socket.connected)
  console.log('socket.io is connected.')

and use this code when reconnected.

socket.on('reconnect', ()=>{
  //Your Code Here
});

Why does viewWillAppear not get called when an app comes back from the background?

Swift 4.2 / 5

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground),
                                           name: Notification.Name.UIApplicationWillEnterForeground,
                                           object: nil)
}

@objc func willEnterForeground() {
   // do what's needed
}

.gitignore is ignored by Git

I had this problem, with a .gitignore file containing this line:

lib/ext/

I just realized that in fact, this directory is a symbolic link to a folder somewhere else:

ls -la lib/ext/
lrwxr-xr-x 1 roipoussiere users 47 Feb  6 14:16 lib/ext -> /home/roipoussiere/real/path/to/the/lib

On the line lib/ext/, Git actually looks for a folder, but a symbolic link is a file, so my lib folder is not ignored.

I fixed this by replacing lib/ext/ by lib/ext in my .gitignore file.

How do I select the "last child" with a specific class name in CSS?

You can use the adjacent sibling selector to achieve something similar, that might help.

.list-item.other-class + .list-item:not(.other-class)

Will effectively target the immediately following element after the last element with the class other-class.

Read more here: https://css-tricks.com/almanac/selectors/a/adjacent-sibling/

Make REST API call in Swift

In swift 3.3 and 4. I crated APIManager class with two public methods. Just pass required parameter, api name and request type. You will get response then pass it to the closure.

 import UIKit   

    struct RequestType {
      static let  POST = "POST"
      static let  GET = "GET"
    }

    enum HtttpType: String {
      case POST = "POST"
      case GET  = "GET"
    }

    class APIManager: NSObject {


      static let sharedInstance: APIManager = {

        let instance = APIManager()
        return instance
      }()
     private init() {}
        // First Method

          public func requestApiWithDictParam(dictParam: Dictionary<String,Any>, apiName: String,requestType: String, isAddCookie: Bool, completionHendler:@escaping (_ response:Dictionary<String,AnyObject>?, _ error: NSError?, _ success: Bool)-> Void) {

            var apiUrl = “” // Your api url
            apiUrl =  apiUrl.appendingFormat("%@", apiName)
            let config = URLSessionConfiguration.default
            let session = URLSession(configuration: config)
            let url = URL(string: apiUrl)!
            let HTTPHeaderField_ContentType  = "Content-Type"
            let ContentType_ApplicationJson  = "application/json"
            var request = URLRequest.init(url: url)

            request.timeoutInterval = 60.0
            request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
            request.addValue(ContentType_ApplicationJson, forHTTPHeaderField: HTTPHeaderField_ContentType)
            request.httpMethod = requestType

            print(apiUrl)
            print(dictParam)

            let dataTask = session.dataTask(with: request) { (data, response, error) in

              if error != nil   {
                completionHendler(nil, error as NSError?, false)
              } do {
                let resultJson = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]
                print("Request API = ", apiUrl)
                print("API Response = ",resultJson ?? "")
                completionHendler(resultJson, nil, true)

              } catch {
                completionHendler(nil, error as NSError?, false)
              }
            }
            dataTask.resume()
          }

           // Second Method
           public func requestApiWithUrlString(param: String, apiName: String,requestType: String, isAddCookie: Bool, completionHendler:@escaping (_ response:Dictionary<String,AnyObject>?, _ error: NSError?, _ success: Bool)-> Void ) {
                var apiUrl = "" // Your api url
                let config = URLSessionConfiguration.default
                let session = URLSession(configuration: config)            
                var request: URLRequest?

                if requestType == "GET" {

                  apiUrl =  String(format: "%@%@&%@", YourAppBaseUrl,apiName,param)
                  apiUrl = apiUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
                  print("URL=",apiUrl)

                  let url = URL(string: apiUrl)!
                  request = URLRequest.init(url: url)
                  request?.httpMethod = "GET"

                } else {

                  apiUrl =  String(format: "%@%@", YourAppBaseUrl,apiName)
                  apiUrl = apiUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
                  print("URL=",apiUrl)

                  let bodyParameterData = param.data(using: .utf8)
                  let url = URL(string: apiUrl)!

                  request = URLRequest(url: url)
                  request?.httpBody = bodyParameterData
                  request?.httpMethod = "POST"
                }

                request?.timeoutInterval = 60.0
                request?.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
                request?.httpShouldHandleCookies = true

                let dataTask = session.dataTask(with: request!) { (data, response, error) in

                  if error != nil {
                    completionHendler(nil, error as NSError?, false)
                  } do {
                    if data != nil  {
                      let resultJson = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]

                      print("Request API = ", apiUrl)
                      print("API Response = ",resultJson ?? "")
                      completionHendler(resultJson, nil, true) 
                    } else  {
                      completionHendler(nil, error as NSError?, false)
                    }
                  } catch {
                    completionHendler(nil, error as NSError?, false)
                  }
                }
                dataTask.resume()
              }
    }

    // Here is example of calling Post API from any class

     let bodyParameters = String(format: "appid=%@&appversion=%@","1","1")
            APIManager.sharedInstance.requestApiWithUrlString(param: bodyParameters, apiName: "PASS_API_NAME", requestType: HtttpType.POST.rawValue, isAddCookie: false) { (dictResponse, error, success) in

                if success {
                    if let dictMessage = dictResponse?["message"] as? Dictionary<String, AnyObject> {
                // do you work
                    }

                }  else {
                    print("Something went wrong...")
                }
            }
        }


/// Or just use simple function 

func dataRequest() {
    let urlToRequest = "" // Your API url

    let url = URL(string: urlToRequest)!
    let session4 = URLSession.shared
    let request = NSMutableURLRequest(url: url)
    request.httpMethod = "POST"
    request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
    let paramString = "data=Hello"
    request.httpBody = paramString.data(using: String.Encoding.utf8)
    let task = session4.dataTask(with: request as URLRequest) { (data, response, error) in
      guard let _: Data = data, let _: URLResponse = response, error == nil else {
        print("*****error")
        return
      }
      if let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) {
          print("****Data: \(dataString)") //JSONSerialization
      }
    }
    task.resume()
  }

Convert Data URI to File then append to FormData

Thanks to @Stoive and @vava720 I combined the two in this way, avoiding to use the deprecated BlobBuilder and ArrayBuffer

function dataURItoBlob(dataURI) {
    'use strict'
    var byteString, 
        mimestring 

    if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
        byteString = atob(dataURI.split(',')[1])
    } else {
        byteString = decodeURI(dataURI.split(',')[1])
    }

    mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]

    var content = new Array();
    for (var i = 0; i < byteString.length; i++) {
        content[i] = byteString.charCodeAt(i)
    }

    return new Blob([new Uint8Array(content)], {type: mimestring});
}

Display rows with one or more NaN values in pandas dataframe

Can try this too, almost similar previous answers.

    d = {'filename': ['M66_MI_NSRh35d32kpoints.dat', 'F71_sMI_DMRI51d.dat', 'F62_sMI_St22d7.dat', 'F41_Car_HOC498d.dat', 'F78_MI_547d.dat'], 'alpha1': [0.8016, 0.0, 1.721, 1.167, 1.897], 'alpha2': [0.9283, 0.0, 3.833, 2.809, 5.459], 'gamma1': [1.0, np.nan, 0.23748000000000002, 0.36419, 0.095319], 'gamma2': [0.074804, 0.0, 0.15, 0.3, np.nan], 'chi2min': [39.855990000000006, 1e+25, 10.91832, 7.966335000000001, 25.93468]}
    df = pd.DataFrame(d).set_index('filename')

enter image description here

Count of null values in each column.

df.isnull().sum()

enter image description here

df.isnull().any(axis=1)

enter image description here

Copy array items into another array

Found an elegant way from MDN

var vegetables = ['parsnip', 'potato'];
var moreVegs = ['celery', 'beetroot'];

// Merge the second array into the first one
// Equivalent to vegetables.push('celery', 'beetroot');
Array.prototype.push.apply(vegetables, moreVegs);

console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']

Or you can use the spread operator feature of ES6:

let fruits = [ 'apple', 'banana'];
const moreFruits = [ 'orange', 'plum' ];

fruits.push(...moreFruits); // ["apple", "banana", "orange", "plum"]

How to view user privileges using windows cmd?

You can use the following commands:

whoami /priv
whoami /all

For more information, check whoami @ technet.

Java - What does "\n" mean?

In the specific case of the code example from the original question, the

System.out.print("\n");

is there to move to a new line between incrementing i.

So the first print statement prints all of the elements of Grid[0][j]. When the innermost for loop has completed, the "\n" gets printed and then all of the elements of Grid[1][j] are printed on the next line, and this is repeated until you have a 10x10 grid of the elements of the 2-dimensional array, Grid.

Run a .bat file using python code

Probably the simplest way to do this is ->

import os
os.chdir("X:\Enter location of .bat file")
os.startfile("ask.bat")

How to succinctly write a formula with many variables from a data frame?

There is a special identifier that one can use in a formula to mean all the variables, it is the . identifier.

y <- c(1,4,6)
d <- data.frame(y = y, x1 = c(4,-1,3), x2 = c(3,9,8), x3 = c(4,-4,-2))
mod <- lm(y ~ ., data = d)

You can also do things like this, to use all variables but one (in this case x3 is excluded):

mod <- lm(y ~ . - x3, data = d)

Technically, . means all variables not already mentioned in the formula. For example

lm(y ~ x1 * x2 + ., data = d)

where . would only reference x3 as x1 and x2 are already in the formula.

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

What you have is a parse error. Those are thrown before any code is executed. A PHP file needs to be parsed in its entirety before any code in it can be executed. If there's a parse error in the file where you're setting your error levels, they won't have taken effect by the time the error is thrown.

Either break your files up into smaller parts, like setting the error levels in one file and then includeing another file which contains the actual code (and errors), or set the error levels outside PHP using php.ini or .htaccess directives.

Secure random token in Node.js

The npm module anyid provides flexible API to generate various kinds of string ID / code.

To generate random string in A-Za-z0-9 using 48 random bytes:

const id = anyid().encode('Aa0').bits(48 * 8).random().id();
// G4NtiI9OYbSgVl3EAkkoxHKyxBAWzcTI7aH13yIUNggIaNqPQoSS7SpcalIqX0qGZ

To generate fixed length alphabet only string filled by random bytes:

const id = anyid().encode('Aa').length(20).random().id();
// qgQBBtDwGMuFHXeoVLpt

Internally it uses crypto.randomBytes() to generate random.

Intercept a form submit in JavaScript and prevent normal submission

You cannot attach events before the elements you attach them to has loaded

This works -

Plain JS

DEMO

Recommended to use eventListener

_x000D_
_x000D_
// Should only be triggered on first page load
console.log('ho');

window.addEventListener("load", function() {
  document.getElementById('my-form').addEventListener("submit", function(e) {
    e.preventDefault(); // before the code
    /* do what you want with the form */

    // Should be triggered on form submit
    console.log('hi');
  })
});
_x000D_
<form id="my-form">
  <input type="text" name="in" value="some data" />
  <button type="submit">Go</button>
</form>
_x000D_
_x000D_
_x000D_

but if you do not need more than one listener you can use onload and onsubmit

_x000D_
_x000D_
// Should only be triggered on first page load
console.log('ho');

window.onload = function() {
  document.getElementById('my-form').onsubmit = function() {
    /* do what you want with the form */

    // Should be triggered on form submit
    console.log('hi');
    // You must return false to prevent the default form behavior
    return false;
  }
}
_x000D_
    <form id="my-form">
      <input type="text" name="in" value="some data" />
      <button type="submit">Go</button>
    </form>
_x000D_
_x000D_
_x000D_

jQuery

_x000D_
_x000D_
// Should only be triggered on first page load
console.log('ho');

$(function() {
  $('#my-form').on("submit", function(e) {
    e.preventDefault(); // cancel the actual submit

    /* do what you want with the form */

    // Should be triggered on form submit

    console.log('hi');
  });
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="my-form">
  <input type="text" name="in" value="some data" />
  <button type="submit">Go</button>
</form>
_x000D_
_x000D_
_x000D_

How to open a new tab in GNOME Terminal from command line?

#!/bin/sh

WID=$(xprop -root | grep "_NET_ACTIVE_WINDOW(WINDOW)"| awk '{print $5}')
xdotool windowfocus $WID
xdotool key ctrl+shift+t
wmctrl -i -a $WID

This will auto determine the corresponding terminal and opens the tab accordingly.

Stylesheet not loaded because of MIME-type

In my angular-ionic project I've a css entry like this for a component which would only load when I request.

 .searchBar {
    // --placeholder-color: white;
    // --color: white;
    // --icon-color: white;
    // --border-radius: 20px;
    // --background: color:rgba(73,76,67,1.0);
    // --placeholder-opacity: 100%;
    // background-color: red;
  }

as soon as I commented out all the values inside the css class entry it started working again.

I think this was happening due to having these properties background-color with --background together.

Generate a random date between two other dates

Convert your dates into timestamps and call random.randint with the timestamps, then convert the randomly generated timestamp back into a date:

from datetime import datetime
import random

def random_date(first_date, second_date):
    first_timestamp = int(first_date.timestamp())
    second_timestamp = int(second_date.timestamp())
    random_timestamp = random.randint(first_timestamp, second_timestamp)
    return datetime.fromtimestamp(random_timestamp)

Then you can use it like this

from datetime import datetime

d1 = datetime.strptime("1/1/2018 1:30 PM", "%m/%d/%Y %I:%M %p")
d2 = datetime.strptime("1/1/2019 4:50 AM", "%m/%d/%Y %I:%M %p")

random_date(d1, d2)

random_date(d2, d1)  # ValueError because the first date comes after the second date

If you care about timezones you should just use date_time_between_dates from the Faker library, where I stole this code from, as a different answer already suggests.

MySQL delete multiple rows in one query conditions unique to each row

You were very close, you can use this:

DELETE FROM table WHERE (col1,col2) IN ((1,2),(3,4),(5,6))

Please see this fiddle.

How to calculate the angle between a line and the horizontal axis?

First find the difference between the start point and the end point (here, this is more of a directed line segment, not a "line", since lines extend infinitely and don't start at a particular point).

deltaY = P2_y - P1_y
deltaX = P2_x - P1_x

Then calculate the angle (which runs from the positive X axis at P1 to the positive Y axis at P1).

angleInDegrees = arctan(deltaY / deltaX) * 180 / PI

But arctan may not be ideal, because dividing the differences this way will erase the distinction needed to distinguish which quadrant the angle is in (see below). Use the following instead if your language includes an atan2 function:

angleInDegrees = atan2(deltaY, deltaX) * 180 / PI

EDIT (Feb. 22, 2017): In general, however, calling atan2(deltaY,deltaX) just to get the proper angle for cos and sin may be inelegant. In those cases, you can often do the following instead:

  1. Treat (deltaX, deltaY) as a vector.
  2. Normalize that vector to a unit vector. To do so, divide deltaX and deltaY by the vector's length (sqrt(deltaX*deltaX+deltaY*deltaY)), unless the length is 0.
  3. After that, deltaX will now be the cosine of the angle between the vector and the horizontal axis (in the direction from the positive X to the positive Y axis at P1).
  4. And deltaY will now be the sine of that angle.
  5. If the vector's length is 0, it won't have an angle between it and the horizontal axis (so it won't have a meaningful sine and cosine).

EDIT (Feb. 28, 2017): Even without normalizing (deltaX, deltaY):

  • The sign of deltaX will tell you whether the cosine described in step 3 is positive or negative.
  • The sign of deltaY will tell you whether the sine described in step 4 is positive or negative.
  • The signs of deltaX and deltaY will tell you which quadrant the angle is in, in relation to the positive X axis at P1:
    • +deltaX, +deltaY: 0 to 90 degrees.
    • -deltaX, +deltaY: 90 to 180 degrees.
    • -deltaX, -deltaY: 180 to 270 degrees (-180 to -90 degrees).
    • +deltaX, -deltaY: 270 to 360 degrees (-90 to 0 degrees).

An implementation in Python using radians (provided on July 19, 2015 by Eric Leschinski, who edited my answer):

from math import *
def angle_trunc(a):
    while a < 0.0:
        a += pi * 2
    return a

def getAngleBetweenPoints(x_orig, y_orig, x_landmark, y_landmark):
    deltaY = y_landmark - y_orig
    deltaX = x_landmark - x_orig
    return angle_trunc(atan2(deltaY, deltaX))

angle = getAngleBetweenPoints(5, 2, 1,4)
assert angle >= 0, "angle must be >= 0"
angle = getAngleBetweenPoints(1, 1, 2, 1)
assert angle == 0, "expecting angle to be 0"
angle = getAngleBetweenPoints(2, 1, 1, 1)
assert abs(pi - angle) <= 0.01, "expecting angle to be pi, it is: " + str(angle)
angle = getAngleBetweenPoints(2, 1, 2, 3)
assert abs(angle - pi/2) <= 0.01, "expecting angle to be pi/2, it is: " + str(angle)
angle = getAngleBetweenPoints(2, 1, 2, 0)
assert abs(angle - (pi+pi/2)) <= 0.01, "expecting angle to be pi+pi/2, it is: " + str(angle)
angle = getAngleBetweenPoints(1, 1, 2, 2)
assert abs(angle - (pi/4)) <= 0.01, "expecting angle to be pi/4, it is: " + str(angle)
angle = getAngleBetweenPoints(-1, -1, -2, -2)
assert abs(angle - (pi+pi/4)) <= 0.01, "expecting angle to be pi+pi/4, it is: " + str(angle)
angle = getAngleBetweenPoints(-1, -1, -1, 2)
assert abs(angle - (pi/2)) <= 0.01, "expecting angle to be pi/2, it is: " + str(angle)

All tests pass. See https://en.wikipedia.org/wiki/Unit_circle

How to run php files on my computer

In short:

  1. Install WAMP

  2. Put this file to C:\wamp\www\ProjectName\filename.php

  3. Go to browser: http://localhost/ProjectName/filename.php

How to execute logic on Optional if not present?

For those of you who want to execute a side-effect only if an optional is absent

i.e. an equivalent of ifAbsent() or ifNotPresent() here is a slight modification to the great answers already provided.

myOptional.ifPresentOrElse(x -> {}, () -> {
  // logic goes here
})

Postgresql, update if row with some unique value exists, else insert

Firstly It tries insert. If there is a conflict on url column then it updates content and last_analyzed fields. If updates are rare this might be better option.

INSERT INTO URLs (url, content, last_analyzed)
VALUES
    (
        %(url)s,
        %(content)s,
        NOW()
    ) 
ON CONFLICT (url) 
DO
UPDATE
SET content=%(content)s, last_analyzed = NOW();

Android: alternate layout xml for landscape mode

You can group your specific layout under the correct folder structure as follows.

layout-land-target_version

ie

layout-land-19 // target KitKat

likewise you can create your layouts.

Hope this will help you

C# Linq Group By on multiple columns

var consolidatedChildren =
    from c in children
    group c by new
    {
        c.School,
        c.Friend,
        c.FavoriteColor,
    } into gcs
    select new ConsolidatedChild()
    {
        School = gcs.Key.School,
        Friend = gcs.Key.Friend,
        FavoriteColor = gcs.Key.FavoriteColor,
        Children = gcs.ToList(),
    };

var consolidatedChildren =
    children
        .GroupBy(c => new
        {
            c.School,
            c.Friend,
            c.FavoriteColor,
        })
        .Select(gcs => new ConsolidatedChild()
        {
            School = gcs.Key.School,
            Friend = gcs.Key.Friend,
            FavoriteColor = gcs.Key.FavoriteColor,
            Children = gcs.ToList(),
        });

Could pandas use column as index?

You can set the column index using index_col parameter available while reading from spreadsheet in Pandas.

Here is my solution:

  1. Firstly, import pandas as pd: import pandas as pd

  2. Read in filename using pd.read_excel() (if you have your data in a spreadsheet) and set the index to 'Locality' by specifying the index_col parameter.

    df = pd.read_excel('testexcel.xlsx', index_col=0)

    At this stage if you get a 'no module named xlrd' error, install it using pip install xlrd.

  3. For visual inspection, read the dataframe using df.head() which will print the following output sc

  4. Now you can fetch the values of the desired columns of the dataframe and print it

    sc2

Getting today's date in YYYY-MM-DD in Python?

To get day number from date is in python

for example:19-12-2020(dd-mm-yyy)order_date we need 19 as output

order['day'] = order['Order_Date'].apply(lambda x: x.day)

Dart: mapping a list (list.map)

you can use

moviesTitles.map((title) => Tab(text: title)).toList()

example:

    bottom: new TabBar(
      controller: _controller,
      isScrollable: true,
      tabs:
        moviesTitles.map((title) => Tab(text: title)).toList()
      ,
    ),

How do I force Postgres to use a particular index?

Probably the only valid reason for using

set enable_seqscan=false

is when you're writing queries and want to quickly see what the query plan would actually be were there large amounts of data in the table(s). Or of course if you need to quickly confirm that your query is not using an index simply because the dataset is too small.

Android: show/hide status bar/power bar

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //hide status bar
    requestWindowFeature( Window.FEATURE_NO_TITLE );
    getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN );


    setContentView(R.layout.activity_main);
}

Highlight a word with jQuery

Here's a variation that ignores and preserves case:

jQuery.fn.highlight = function (str, className) {
    var regex = new RegExp("\\b"+str+"\\b", "gi");

    return this.each(function () {
        this.innerHTML = this.innerHTML.replace(regex, function(matched) {return "<span class=\"" + className + "\">" + matched + "</span>";});
    });
};

Why doesn't Mockito mock static methods?

Mockito [3.4.0] can mock static methods!

  1. Replace mockito-core dependency with mockito-inline:3.4.0.

  2. Class with static method:

    class Buddy {
      static String name() {
        return "John";
      }
    }
    
  3. Use new method Mockito.mockStatic():

    @Test
    void lookMomICanMockStaticMethods() {
      assertThat(Buddy.name()).isEqualTo("John");
    
      try (MockedStatic<Buddy> theMock = Mockito.mockStatic(Buddy.class)) {
        theMock.when(Buddy::name).thenReturn("Rafael");
        assertThat(Buddy.name()).isEqualTo("Rafael");
      }
    
      assertThat(Buddy.name()).isEqualTo("John");
    }
    

    Mockito replaces the static method within the try block only.

How can I find the maximum value and its index in array in MATLAB?

In case of a 2D array (matrix), you can use:

[val, idx] = max(A, [], 2);

The idx part will contain the column number of containing the max element of each row.

Yahoo Finance All Currencies quote API Documentation

From the research that I've done, there doesn't appear to be any documentation available for the API you're using. Depending on the data you're trying to get, I'd recommend using Yahoo's YQL API for accessing Yahoo Finance (An example can be found here). Alternatively, you could try using this well documented way to get CSV data from Yahoo Finance.

EDIT:

There has been some discussion on the Yahoo developer forums and it looks like there is no documentation (emphasis mine):

The reason for the lack of documentation is that we don't have a Finance API. It appears some have reverse engineered an API that they use to pull Finance data, but they are breaking our Terms of Service (no redistribution of Finance data) in doing this so I would encourage you to avoid using these webservices.

At the same time, the URL you've listed can be accessed using the YQL console, though I'm not savvy enough to know how to extract URL parameters with it.

Render HTML in React Native

 <WebView ref={'webview'} automaticallyAdjustContentInsets={false} source={require('../Assets/aboutus.html')} />

This worked for me :) I have html text aboutus file.

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

Ahah! Checkout the previous commit, then checkout the master.

git checkout HEAD^
git checkout -f master

Import SQL file into mysql

You are almost there use

mysql> \. c:/nitm.sql;

You may also access help by

mysql> \?

Where do I mark a lambda expression async?

And for those of you using an anonymous expression:

await Task.Run(async () =>
{
   SQLLiteUtils slu = new SQLiteUtils();
   await slu.DeleteGroupAsync(groupname);
});

How to debug ORA-01775: looping chain of synonyms?

If you are compiling a PROCEDURE, possibly this is referring to a table or view that does not exist as it is created in the same PROCEDURE. In this case the solution is to make the query declared as String eg v_query: = 'insert into table select * from table2 and then execute immediate on v_query;

This is because the compiler does not yet recognize the object and therefore does not find the reference. Greetings.

How to solve a timeout error in Laravel 5

try

ini_set('max_execution_time', $time);
$articles = Article::all();

where $time is in seconds, set it to 0 for no time. make sure to make it 60 back after your function finish

Dynamic function name in javascript?

I might be missing the obvious here, but what's wrong with just adding the name? functions are invoked regardless of their name. names are just used for scoping reasons. if you assign it to a variable, and it's in scope, it can be called. hat happens is your are executing a variable which happens to be a function. if you must have a name for identification reasons when debugging, insert it between the keyword function and the opening brace.

_x000D_
_x000D_
var namedFunction = function namedFunction (a,b) {return a+b};_x000D_
_x000D_
alert(namedFunction(1,2));_x000D_
alert(namedFunction.name);_x000D_
alert(namedFunction.toString());
_x000D_
_x000D_
_x000D_

an alternative approach is to wrap the function in an outer renamed shim, which you can also pass into an outer wrapper, if you don't want to dirty the surrounding namespace. if you are wanting to actually dynamically create the function from strings (which most of these examples do), it's trivial to rename the source to do what you want. if however you want to rename existing functions without affecting their functionality when called elsewhere, a shim is the only way to achieve it.

_x000D_
_x000D_
(function(renamedFunction) {_x000D_
_x000D_
  alert(renamedFunction(1,2));_x000D_
  alert(renamedFunction.name);_x000D_
  alert(renamedFunction.toString());_x000D_
  alert(renamedFunction.apply(this,[1,2]));_x000D_
_x000D_
_x000D_
})(function renamedFunction(){return namedFunction.apply(this,arguments);});_x000D_
_x000D_
function namedFunction(a,b){return a+b};
_x000D_
_x000D_
_x000D_

Changing the Git remote 'push to' default

Just a clarification (using git version 1.7.9.5 on ubuntu 12.04):

Git will add/remove remotes. These are remote instances of git with a server attached.

git remote add myremote git://remoteurl

You can then fetch said git repository like so:

git fetch myremote

It seems this creates a branch named 'myremote', however the remote for the branch is not automatically set. To do this, you must do the following:

First, verify that you have this problem, i.e.

git config -l | grep myremote

You should see something like:

remote.myremote.url=git://remoteurl
remote.myremote.fetch=+refs/heads/*:refs/remotes/myremote/*
branch.myremote.remote=.
branch.myremote.merge=refs/heads/master

If you see branch.myremote.remote=. , then you should proceed:

git config branch.myremote.remote myremote
git checkout myremote
git pull

You should now be up to date with the remote repository, and your pulls/pushes should be tied to the appropriate remote. You can switch remotes in this manner, per branch. [Note][1]

According to a The Official Git Config Documentation, you can set up a default push branch (just search remote.pushdefault on that page), however keep in mind that this will not affect repositories/branches which already exist, so this will work but only for new repositories/branches. You should remember that --global will set user-specific repository defaults (~/.gitconfig), --system will set system-wide repository defaults (/etc/gitconfig), and no flag will set configuration options for the current repository (./.gitconfig).

Also it should be noted that the push.default config option is for configuring ref-spec behavior, not remote behavior.

[1]: git branch --set-upstream myotherremote would usually work here, however git will complain that it will not set a branch as its own remote if git branch --set-upstream myremote is used. I believe however that this is incorrect behavior.

capture div into image using html2canvas

you can try this code to capture a div When the div is very wide or offset relative to the screen

var div = $("#div")[0];
var rect = div.getBoundingClientRect();

var canvas = document.createElement("canvas");
canvas.width = rect.width;
canvas.height = rect.height;

var ctx = canvas.getContext("2d");
ctx.translate(-rect.left,-rect.top);

html2canvas(div, {
    canvas:canvas,
    height:rect.height,
    width:rect.width,
    onrendered: function(canvas) {
        var image = canvas.toDataURL("image/png");
        var pHtml = "<img src="+image+" />";
        $("#parent").append(pHtml);
    }
});