Programs & Examples On #Assistive

Uncaught ReferenceError: jQuery is not defined

jQuery needs to be the first script you import. The first script on your page

<script type="text/javascript" src="/test/wp-content/themes/child/script/jquery.jcarousel.min.js"></script>

appears to be a jQuery plugin, which is likely generating an error since jQuery hasn't been loaded on the page yet.

jquery Ajax call - data parameters are not being passed to MVC Controller action

You need add -> contentType: "application/json; charset=utf-8",

<script type="text/javascript">
    $(document).ready( function() {
      $('#btnTest').click( function() {
        $.ajax({
          type: "POST", 
          url: "/Login/Test",
          data: { ListID: '1', ItemName: 'test' },
          dataType: "json",
          contentType: "application/json; charset=utf-8",
          success: function(response) { alert(response); },
          error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
        });
      });
    });
</script>

Better way to find last used row

This is the best way I've seen to find the last cell.

MsgBox ActiveSheet.UsedRage.SpecialCells(xlCellTypeLastCell).Row

One of the disadvantages to using this is that it's not always accurate. If you use it then delete the last few rows and use it again, it does not always update. Saving your workbook before using this seems to force it to update though.

Using the next bit of code after updating the table (or refreshing the query that feeds the table) forces everything to update before finding the last row. But, it's been reported that it makes excel crash. Either way, calling this before trying to find the last row will ensure the table has finished updating first.

Application.CalculateUntilAsyncQueriesDone

Another way to get the last row for any given column, if you don't mind the overhead.

Function GetLastRow(col, row)
    ' col and row are where we will start.
    ' We will find the last row for the given column.
    Do Until ActiveSheet.Cells(row, col) = ""
        row = row + 1
    Loop
    GetLastRow = row
End Function

XML Error: Extra content at the end of the document

You need a root node

<?xml version="1.0" encoding="ISO-8859-1"?>    
<documents>
    <document>
        <name>Sample Document</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;wordcount3=0</url>
    </document>

    <document>
        <name>Sample</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;</url>
    </document>
</documents>

dropzone.js - how to do something after ALL files are uploaded

Just use queuecomplete that's what its there for and its so so simple. Check the docs http://www.dropzonejs.com/

queuecomplete > Called when all files in the queue finished uploading.

      this.on("queuecomplete", function (file) {
          alert("All files have uploaded ");
      });

Android Emulator Error Message: "PANIC: Missing emulator engine program for 'x86' CPUS."

Simply follow the below steps specific to mac:

  1. go to: /Users/{username}/Library/Android/sdk/emulator

  2. ./emulator -list-avds

  3. ./emulator @avdName

How to define optional methods in Swift protocol?

I think that before asking how you can implement an optional protocol method, you should be asking why you should implement one.

If we think of swift protocols as an Interface in classic object oriented programming, optional methods do not make much sense, and perhaps a better solution would be to create default implementation, or separate the protocol into a set of protocols (perhaps with some inheritance relations between them) to represent the possible combination of methods in the protocol.

For further reading, see https://useyourloaf.com/blog/swift-optional-protocol-methods/, which gives an excellent overview on this matter.

Read only the first line of a file?

To go back to the beginning of an open file and then return the first line, do this:

my_file.seek(0)
first_line = my_file.readline()

SSL Error: unable to get local issuer certificate

jww is right — you're referencing the wrong intermediate certificate.

As you have been issued with a SHA256 certificate, you will need the SHA256 intermediate. You can grab it from here: http://secure2.alphassl.com/cacert/gsalphasha2g2r1.crt

WCF named pipe minimal example

I created this simple example from different search results on the internet.

public static ServiceHost CreateServiceHost(Type serviceInterface, Type implementation)
{
  //Create base address
  string baseAddress = "net.pipe://localhost/MyService";

  ServiceHost serviceHost = new ServiceHost(implementation, new Uri(baseAddress));

  //Net named pipe
  NetNamedPipeBinding binding = new NetNamedPipeBinding { MaxReceivedMessageSize = 2147483647 };
  serviceHost.AddServiceEndpoint(serviceInterface, binding, baseAddress);

  //MEX - Meta data exchange
  ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
  serviceHost.Description.Behaviors.Add(behavior);
  serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexNamedPipeBinding(), baseAddress + "/mex/");

  return serviceHost;
}

Using the above URI I can add a reference in my client to the web service.

Pagination response payload from a RESTful API

generally, I make by simple way, whatever, I create a restAPI endpoint for example "localhost/api/method/:lastIdObtained/:countDateToReturn" with theses parameters, you can do it a simple request. in the service, eg. .net

jsonData function(lastIdObtained,countDatetoReturn){
'... write your code as you wish..'
and into select query make a filter
select top countDatetoreturn tt.id,tt.desc
 from tbANyThing tt
where id > lastIdObtained
order by id
}

In Ionic, when I scroll from bottom to top, I pass the zero value, when I get the answer, I set the value of the last id obtained, and when I slide from top to bottom, I pass the last registration id I got

SQL - IF EXISTS UPDATE ELSE INSERT INTO

Try this:

INSERT INTO `center_course_fee` (`fk_course_id`,`fk_center_code`,`course_fee`) VALUES ('69', '4920153', '6000') ON DUPLICATE KEY UPDATE `course_fee` = '6000';

Codeigniter unset session

$this->session->unset_userdata('session_value');

curl_init() function not working

This answer is for https request:

Curl doesn't have built-in root certificates (like most modern browser do). You need to explicitly point it to a cacert.pem file:

  curl_setopt($ch, CURLOPT_CAINFO, '/path/to/cert/file/cacert.pem');

Without this, curl cannot verify the certificate sent back via ssl. This same root certificate file can be used every time you use SSL in curl.

You can get the cacert.pem file here: http://curl.haxx.se/docs/caextract.html

Reference PHP cURL Not Working with HTTPS

"unrecognized selector sent to instance" error in Objective-C

This happened to my because accidentally erase the " @IBAction func... " inside my UIViewcontroller class code, so in the Storyboard was created the Reference Outlet, but at runtime there was any function to process it.

The solution was to delete the Outlet reference inside the property inspector and then recreate it dragging with command key to the class code.

Hope it helps!

Simple prime number generator in Python

Similar to user107745, but using 'all' instead of double negation (a little bit more readable, but I think same performance):

import math
[x for x in xrange(2,10000) if all(x%t for t in xrange(2,int(math.sqrt(x))+1))]

Basically it iterates over the x in range of (2, 100) and picking only those that do not have mod == 0 for all t in range(2,x)

Another way is probably just populating the prime numbers as we go:

primes = set()
def isPrime(x):
  if x in primes:
    return x
  for i in primes:
    if not x % i:
      return None
  else:
    primes.add(x)
    return x

filter(isPrime, range(2,10000))

CSS3 selector to find the 2nd div of the same class

.parent_class div:first-child + div

I just used the above to find the second div by chaining first-child with the + selector.

Postgresql: Scripting psql execution with password

This also works for other postgresql clis for example you can run pgbench in non-interactive mode.

export PGPASSWORD=yourpassword
/usr/pgsql-9.5/bin/pgbench -h $REMOTE_PG_HOST -p 5432 -U postgres -c 12 -j 4 -t 10000 example > pgbench.out 2>&1 &

How to do a num_rows() on COUNT query in codeigniter?

    $list_data = $this->Estimate_items_model->get_details(array("estimate_id" => $id))->result();
    $result = array();
    $counter = 0;
    $templateProcessor->cloneRow('Title', count($list_data));
    foreach($list_data as $row) {
        $counter++;
        $templateProcessor->setValue('Title#'.$counter, $row->title);
        $templateProcessor->setValue('Description#'.$counter, $row->description);
        $type = $row->unit_type ? $row->unit_type : "";
        $templateProcessor->setValue('Quantity#'.$counter, to_decimal_format($row->quantity) . " " . $type);
        $templateProcessor->setValue('Rate#'.$counter, to_currency($row->rate, $row->currency_symbol));
        $templateProcessor->setValue('Total#'.$counter, to_currency($row->total, $row->currency_symbol));   
    }

Change Title of Javascript Alert

It's not possible, sorry. If really needed, you could use a jQuery plugin to have a custom alert.

What's is the difference between include and extend in use case diagram?

The include relationship allows one use case to include the steps of another use case.

For example, suppose you have an Amazon Account and you want to check on an order, well it is impossible to check on the order without first logging into your account. So the flow of events would like so...

enter image description here

The extend relationship is used to add an extra step to the flow of a use case, that is usually an optional step...

enter image description here

Imagine that we are still talking about your amazon account. Lets assume the base case is Order and the extension use case is Amazon Prime. The user can choose to just order the item regularly, or, the user has the option to select Amazon Prime which ensure his order will arrive faster at higher cost.

However, note that the user does not have to select Amazon Prime, this is just an option, they can choose to ignore this use case.

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.

#1071 - Specified key was too long; max key length is 1000 bytes

run this query before creating or altering table.

SET @@global.innodb_large_prefix = 1;

this will set max key length to 3072 bytes

Full examples of using pySerial package

I have not used pyserial but based on the API documentation at https://pyserial.readthedocs.io/en/latest/shortintro.html it seems like a very nice interface. It might be worth double-checking the specification for AT commands of the device/radio/whatever you are dealing with.

Specifically, some require some period of silence before and/or after the AT command for it to enter into command mode. I have encountered some which do not like reads of the response without some delay first.

How to check if an object is defined?

You check if it's null in C# like this:

if(MyObject != null) {
  //do something
}

If you want to check against default (tough to understand the question on the info given) check:

if(MyObject != default(MyObject)) {
 //do something
}

How can I center <ul> <li> into div

<div id="container">
  <table width="100%" height="100%">
    <tr>
      <td align="center" valign="middle">
        <ul>
          <li>item 1</li>
          <li>item 2</li>
          <li>item 3</li>
        </ul>
      </td>
    </tr>
  </table>
</div>

What is a wrapper class?

I currently used a wrapper class for my project and the main benefits I get (just a single benefit to widen the topic explanation):

Exception handling: My main class ,that another class wraps, has methods that are throwing exceptions if occurs any, so I created a wrapper class that handles the exceptions and logs them immediately. So, in my main scope, there is no exception handling. I just call a method and do something.

Easy Usage: I can easily initiate the object. Normally initiating phase is constructed of a lot of steps.

Code Readability: When another programmer opens my code, the code will seem very clear and easy to manipulate.

Hiding the Details: If you are generating a class that another programmer is going to use, then you can wrap the details like "error handling, exception handling, logging messages and etc..." so that the programmer will not be have to handle the chaos, just simply uses the methods.

LDAP filter for blank (empty) attribute

This article http://technet.microsoft.com/en-us/library/ee198810.aspx led me to the solution. The only change is the placement of the exclamation mark.

(!manager=*)

It seems to be working just as wanted.

-didSelectRowAtIndexPath: not being called

Just in case someone made the same stupid mistake as I did:

Check out if the method name of what you expect of being didSelect may accidentally be gotten didDeselect in some way. It took about two hours for me to find out ...

What is the best way to give a C# auto-property an initial value?

Use the constructor because "When the constructor is finished, Construction should be finished". properties are like states your classes hold, if you had to initialize a default state, you would do that in your constructor.

Check if EditText is empty.

this function work for me

private void checkempForm() {

    EditText[] allFields = { field1_txt, field2_txt, field3_txt, field4_txt};
    List<EditText> ErrorFields =new ArrayList<EditText>();//empty Edit text arraylist
            for(EditText edit : allFields){
                if(TextUtils.isEmpty(edit.getText())){ 

            // EditText was empty
             ErrorFields.add(edit);//add empty Edittext only in this ArayList
            for(int i = 0; i < ErrorFields.size(); i++)
            {
                EditText currentField = ErrorFields.get(i);
                currentField.setError("this field required");
                currentField.requestFocus();
            }
            }
            }

Cannot read property 'getContext' of null, using canvas

You don't have to include JQuery.

In the index.html:
<canvas id="canvas" width="640" height="480"></canvas><script src="javascript/game.js"> This should work without JQuery...

Edit: You should put the script tag IN the body tag...

How to convert any Object to String?

I've written a few methods for convert by Gson library and java 1.8 .
thay are daynamic model for convert.

string to object

object to string

List to string

string to List

HashMap to String

String to JsonObj

//saeedmpt 
public static String convertMapToString(Map<String, String> data) {
    //convert Map  to String
    return new GsonBuilder().setPrettyPrinting().create().toJson(data);
}
public static <T> List<T> convertStringToList(String strListObj) {
    //convert string json to object List
    return new Gson().fromJson(strListObj, new TypeToken<List<Object>>() {
    }.getType());
}
public static <T> T convertStringToObj(String strObj, Class<T> classOfT) {
    //convert string json to object
    return new Gson().fromJson(strObj, (Type) classOfT);
}

public static JsonObject convertStringToJsonObj(String strObj) {
    //convert string json to object
    return new Gson().fromJson(strObj, JsonObject.class);
}

public static <T> String convertListObjToString(List<T> listObj) {
    //convert object list to string json for
    return new Gson().toJson(listObj, new TypeToken<List<T>>() {
    }.getType());
}

public static String convertObjToString(Object clsObj) {
    //convert object  to string json
    String jsonSender = new Gson().toJson(clsObj, new TypeToken<Object>() {
    }.getType());
    return jsonSender;
}

How to check if an array is empty?

you may use yourArray.length to findout number of elements in an array.

Make sure yourArray is not null before doing yourArray.length, otherwise you will end up with NullPointerException.

Java collections maintaining insertion order

Theres's a section in the O'Reilly Java Cookbook called "Avoiding the urge to sort" The question you should be asking is actually the opposite of your original question ... "Do we gain something by sorting?" It take a lot of effort to sort and maintain that order. Sure sorting is easy but it usually doesn't scale in most programs. If you're going to be handling thousands or tens of thousands of requests (insrt,del,get,etc) per second whether not you're using a sorted or non sorted data structure is seriously going to matter.

Sum all values in every column of a data.frame in R

We can use dplyr to select only numeric columns and purr to get sum for all columns. (can be used to get what ever value for all columns, such as mean, min, max, etc. )

library("dplyr")
library("purrr")

people %>%
    select_if(is.numeric) %>%
    map_dbl(sum)

Or another easy way by only using dplyr

library("dplyr")
people %>%
    summarize_if(is.numeric, sum, na.rm=TRUE)

How to check if Location Services are enabled?

i use first code begin create method isLocationEnabled

 private LocationManager locationManager ;

protected boolean isLocationEnabled(){
        String le = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) getSystemService(le);
        if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
            return false;
        } else {
            return true;
        }
    }

and i check Condition if ture Open the map and false give intent ACTION_LOCATION_SOURCE_SETTINGS

    if (isLocationEnabled()) {
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        locationClient = getFusedLocationProviderClient(this);
        locationClient.getLastLocation()
                .addOnSuccessListener(new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {
                        // GPS location can be null if GPS is switched off
                        if (location != null) {
                            onLocationChanged(location);

                            Log.e("location", String.valueOf(location.getLongitude()));
                        }
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.e("MapDemoActivity", e.toString());
                        e.printStackTrace();
                    }
                });


        startLocationUpdates();

    }
    else {
        new AlertDialog.Builder(this)
                .setTitle("Please activate location")
                .setMessage("Click ok to goto settings else exit.")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(intent);
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        System.exit(0);
                    }
                })
                .show();
    }

enter image description here

How to completely uninstall Android Studio from windows(v10)?

To Completely Remove Android Studio from Windows:

Step 1: Run the Android Studio uninstaller

The first step is to run the uninstaller. Open the Control Panel and under Programs, select Uninstall a Program. After that, click on "Android Studio" and press Uninstall. If you have multiple versions, uninstall them as well.

Step 2: Remove the Android Studio files

To delete any remains of Android Studio setting files, in File Explorer, go to your user folder (%USERPROFILE%), and delete .android, .AndroidStudio and any analogous directories with versions on the end, i.e. .AndroidStudio1.2, as well as .gradle and .m2 if they exist.

Then go to %APPDATA% and delete the JetBrains directory.

Finally, go to C:\Program Files and delete the Android directory.

Step 3: Remove SDK

To delete any remains of the SDK, go to %LOCALAPPDATA% and delete the Android directory.

Step 4: Delete Android Studio projects

Android Studio creates projects in a folder %USERPROFILE%\AndroidStudioProjects, which you may want to delete.

How to calculate mean, median, mode and range from a set of numbers

Yes, there does seem to be 3rd libraries (none in Java Math). Two that have come up are:

http://opsresearch.com/app/

http://www.iro.umontreal.ca/~simardr/ssj/indexe.html

but, it is actually not that difficult to write your own methods to calculate mean, median, mode and range.

MEAN

public static double mean(double[] m) {
    double sum = 0;
    for (int i = 0; i < m.length; i++) {
        sum += m[i];
    }
    return sum / m.length;
}

MEDIAN

// the array double[] m MUST BE SORTED
public static double median(double[] m) {
    int middle = m.length/2;
    if (m.length%2 == 1) {
        return m[middle];
    } else {
        return (m[middle-1] + m[middle]) / 2.0;
    }
}

MODE

public static int mode(int a[]) {
    int maxValue, maxCount;

    for (int i = 0; i < a.length; ++i) {
        int count = 0;
        for (int j = 0; j < a.length; ++j) {
            if (a[j] == a[i]) ++count;
        }
        if (count > maxCount) {
            maxCount = count;
            maxValue = a[i];
        }
    }

    return maxValue;
}

UPDATE

As has been pointed out by Neelesh Salpe, the above does not cater for multi-modal collections. We can fix this quite easily:

public static List<Integer> mode(final int[] numbers) {
    final List<Integer> modes = new ArrayList<Integer>();
    final Map<Integer, Integer> countMap = new HashMap<Integer, Integer>();

    int max = -1;

    for (final int n : numbers) {
        int count = 0;

        if (countMap.containsKey(n)) {
            count = countMap.get(n) + 1;
        } else {
            count = 1;
        }

        countMap.put(n, count);

        if (count > max) {
            max = count;
        }
    }

    for (final Map.Entry<Integer, Integer> tuple : countMap.entrySet()) {
        if (tuple.getValue() == max) {
            modes.add(tuple.getKey());
        }
    }

    return modes;
}

ADDITION

If you are using Java 8 or higher, you can also determine the modes like this:

public static List<Integer> getModes(final List<Integer> numbers) {
    final Map<Integer, Long> countFrequencies = numbers.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    final long maxFrequency = countFrequencies.values().stream()
            .mapToLong(count -> count)
            .max().orElse(-1);

    return countFrequencies.entrySet().stream()
            .filter(tuple -> tuple.getValue() == maxFrequency)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());
}

how do I insert a column at a specific column index in pandas?

df.insert(loc, column_name, value)

This will work if there is no other column with the same name. If a column, with your provided name already exists in the dataframe, it will raise a ValueError.

You can pass an optional parameter allow_duplicates with True value to create a new column with already existing column name.

Here is an example:



    >>> df = pd.DataFrame({'b': [1, 2], 'c': [3,4]})
    >>> df
       b  c
    0  1  3
    1  2  4
    >>> df.insert(0, 'a', -1)
    >>> df
       a  b  c
    0 -1  1  3
    1 -1  2  4
    >>> df.insert(0, 'a', -2)
    Traceback (most recent call last):
      File "", line 1, in 
      File "C:\Python39\lib\site-packages\pandas\core\frame.py", line 3760, in insert
        self._mgr.insert(loc, column, value, allow_duplicates=allow_duplicates)
      File "C:\Python39\lib\site-packages\pandas\core\internals\managers.py", line 1191, in insert
        raise ValueError(f"cannot insert {item}, already exists")
    ValueError: cannot insert a, already exists
    >>> df.insert(0, 'a', -2,  allow_duplicates = True)
    >>> df
       a  a  b  c
    0 -2 -1  1  3
    1 -2 -1  2  4

executing a function in sql plus

As another answer already said, call select myfunc(:y) from dual; , but you might find declaring and setting a variable in sqlplus a little tricky:

sql> var y number

sql> begin
  2  select 7 into :y from dual;
  3  end;
  4  /

PL/SQL procedure successfully completed.

sql> print :y

         Y
----------
         7

sql> select myfunc(:y) from dual;

Convert timestamp long to normal date format

I tried this and worked for me.

Date = (long)(DateTime.Now.Subtract(new DateTime(1970, 1, 1, 0, 0, 0))).TotalSeconds

Android Studio with Google Play Services

I've got this working after doing the following:

  • Have the google-play-services-lib as a module (note difference between module and project), then add the google-play-services.jar to your models "libs" directory.
  • After that add the jar to your build path through making a library or add the jar to another library. I generally have a single IDEA library which I add all my /libs/*.jar files to.
  • Add the library to your modules build path through Module Settings (F4).
  • Add the google-play-services-lib as a module dependency to your project.
  • Done!

Note: This doesn't give me the runtime exceptions either, it works.

JavaScript push to array

That is an object, not an array. So you would do:

var json = { cool: 34.33, alsocool: 45454 };
json.supercool = 3.14159;
console.dir(json);

HTML: Image won't display?

Just to expand niko's answer:

You can reference any image via its URL. No matter where it is, as long as it's accesible you can use it as the src. Example:

Relative location:

<img src="images/image.png">

The image is sought relative to the document's location. If your document is at http://example.com/site/document.html, then your images folder should be on the same directory where your document.html file is.

Absolute location:

<img src="/site/images/image.png">
<img src="http://example.com/site/images/image.png">

or

<img src="http://another-example.com/images/image.png">

In this case, your image will be sought from the document site's root, so, if your document.html is at http://example.com/site/document.html, the root would be at http://example.com/ (or it's respective directory on the server's filesystem, commonly www/). The first two examples are the same, since both point to the same host, Think of the first / as an alias for your server's root. In the second case, the image is located in another host, so you'd have to specify the complete URL of the image.

Regarding /, . and ..:

The / symbol will always return the root of a filesystem or site.

The single point ./ points to the same directory where you are.

And the double point ../ will point to the upper directory, or the one that contains the actual working directory.

So you can build relative routes using them.

Examples given the route http://example.com/dir/one/two/three/ and your calling document being inside three/:

"./pictures/image.png"

or just

"pictures/image.png"

Will try to find a directory named pictures inside http://example.com/dir/one/two/three/.

"../pictures/image.png"

Will try to find a directory named pictures inside http://example.com/dir/one/two/.

"/pictures/image.png"

Will try to find a directory named pictures directly at / or example.com (which are the same), on the same level as directory.

How to add http:// if it doesn't exist in the URL

The best answer for this would be something like this:

function addhttp($url, $scheme="http://" )
{
  return $url = empty(parse_url($url)['scheme']) ? $scheme . ltrim($url, '/') : $url;
}

The protocol flexible, so the same function can be used with ftp, https, etc.

Run as java application option disabled in eclipse

Run As > Java Application wont show up if the class that you want to run does not contain the main method. Make sure that the class you trying to run has main defined in it.

What is the difference between instanceof and Class.isAssignableFrom(...)?

When using instanceof, you need to know the class of B at compile time. When using isAssignableFrom() it can be dynamic and change during runtime.

R: Select values from data table in range

Lots of options here, but one of the easiest to follow is subset. Consider:

> set.seed(43)
> df <- data.frame(name = sample(letters, 100, TRUE), date = sample(1:500, 100, TRUE))
> 
> subset(df, date > 5 & date < 15)
   name date
11    k   10
67    y   12
86    e    8

You can also insert logic directly into the index for your data.frame. The comma separates the rows from columns. We just have to remember that R indexes rows first, then columns. So here we are saying rows with date > 5 & < 15 and then all columns:

df[df$date > 5 & df$date < 15 ,]

I'd also recommend checking out the help pages for subset, ?subset and the logical operators ?"&"

XAMPP - Error: MySQL shutdown unexpectedly

For anyone that searched and pressed on this link, i solved it by simply searching for mysql notifier and stop mysql from running there, Then run mysql in xampp again and it runs. why this works ? iam not expert, but i think it is easy : port was taken already by mysql notifier so had to stop it there and run it here.

Store output of sed into a variable

In general,

variable=$(command)

or

variable=`command`

The latter one is the old syntax, prefer $(command).

Note: variable = .... means execute the command variable with the first argument =, the second ....

How to check if object has any properties in JavaScript?

You can use the following:

Double bang !! property lookup

var a = !![]; // true
var a = !!null; // false

hasOwnProperty This is something that I used to use:

var myObject = {
  name: 'John',
  address: null
};
if (myObject.hasOwnProperty('address')) { // true
  // do something if it exists.
}

However, JavaScript decided not to protect the method’s name, so it could be tampered with.

var myObject = {
  hasOwnProperty: 'I will populate it myself!'
};

prop in myObject

var myObject = {
  name: 'John',
  address: null,
  developer: false
};
'developer' in myObject; // true, remember it's looking for exists, not value.

typeof

if (typeof myObject.name !== 'undefined') {
  // do something
}

However, it doesn't check for null.

I think this is the best way.

in operator

var myObject = {
  name: 'John',
  address: null
};

if('name' in myObject) {
  console.log("Name exists in myObject");
}else{
  console.log("Name does not exist in myObject");
}

result:

Name exists in myObject

Here is a link that goes into more detail on the in operator: Determining if an object property exists

ASP.NET MVC: What is the correct way to redirect to pages/actions in MVC?

1) When the user logs out (Forms signout in Action) I want to redirect to a login page.

public ActionResult Logout() {
    //log out the user
    return RedirectToAction("Login");
}

2) In a Controller or base Controller event eg Initialze, I want to redirect to another page (AbsoluteRootUrl + Controller + Action)

Why would you want to redirect from a controller init?

the routing engine automatically handles requests that come in, if you mean you want to redirect from the index action on a controller simply do:

public ActionResult Index() {
    return RedirectToAction("whateverAction", "whateverController");
}

What is the best data type to use for money in C#?

Create your own class. This seems odd, but a .Net type is inadequate to cover different currencies.

How to install Python MySQLdb module using pip?

The above answer is great, but there may be some problems when we using pip to install MySQL-python in Windows

for example,It needs some files that are associated with Visual Stdio .One solution is installing VS2008 or 2010……Obviously,it cost too much.

Another way is the answer of @bob90937 . I am here to do something to add.

with http://www.lfd.uci.edu/~gohlke/pythonlibs, u can download many Windows binaries of many scientific open-source extension packages for the official CPython distribution of the Python programming language.

Back to topic,we can choose the MySQL-python(py2) or Mysqlclient(py3) and use pip install to install. it gives us Great convenience!

ALTER TABLE on dependent column

I believe that you will have to drop the foreign key constraints first. Then update all of the appropriate tables and remap them as they were.

ALTER TABLE [dbo.Details_tbl] DROP CONSTRAINT [FK_Details_tbl_User_tbl];
-- Perform more appropriate alters
ALTER TABLE [dbo.Details_tbl] ADD FOREIGN KEY (FK_Details_tbl_User_tbl) 
    REFERENCES User_tbl(appId);
-- Perform all appropriate alters to bring the key constraints back

However, unless memory is a really big issue, I would keep the identity as an INT. Unless you are 100% positive that your keys will never grow past the TINYINT restraints. Just a word of caution :)

How do I remove the top margin in a web page?

For opera just add this in header

<link rel='stylesheet' media='handheld' href='body.css' />

This makes opera use most of your customised css.

How do I line up 3 divs on the same row?

Why don't try to use bootstrap's solutions. They are perfect if you don't want to meddle with tables and floats.

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/> <!--- This line is just linking the bootstrap thingie in the file. The real thing starts below -->_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-sm-4">_x000D_
      One of three columns_x000D_
    </div>_x000D_
    <div class="col-sm-4">_x000D_
      One of three columns_x000D_
    </div>_x000D_
    <div class="col-sm-4">_x000D_
      One of three columns_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

No meddling with complex CSS, and the best thing is that you can edit the width of the columns by changing the number. You can find more examples at https://getbootstrap.com/docs/4.0/layout/grid/

Measuring the distance between two coordinates in PHP

For the ones who like shorter and faster(not calling deg2rad()).

function circle_distance($lat1, $lon1, $lat2, $lon2) {
  $rad = M_PI / 180;
  return acos(sin($lat2*$rad) * sin($lat1*$rad) + cos($lat2*$rad) * cos($lat1*$rad) * cos($lon2*$rad - $lon1*$rad)) * 6371;// Kilometers
}

C# ListView Column Width Auto

It is also worth noting that ListView may not display as expected without first changing the property:

myListView.View = View.Details; // or View.List

For me Visual Studio seems to default it to View.LargeIcon for some reason so nothing appears until it is changed.

Complete code to show a single column in a ListView and allow space for a vertical scroll bar.

lisSerials.Items.Clear();
lisSerials.View = View.Details;
lisSerials.FullRowSelect = true;

// add column if not already present
if(lisSerials.Columns.Count==0)
{
    int vw = SystemInformation.VerticalScrollBarWidth;
    lisSerials.Columns.Add("Serial Numbers", lisSerials.Width-vw-5);
}

foreach (string s in stringArray)
{
    ListViewItem lvi = new ListViewItem(new string[] { s });
    lisSerials.Items.Add(lvi);
}

Pass correct "this" context to setTimeout callback?

If you're using underscore, you can use bind.

E.g.

if (this.options.destroyOnHide) {
     setTimeout(_.bind(this.tip.destroy, this), 1000);
}

Is there a typical state machine implementation pattern?

You can use minimalist UML state machine framework in c. https://github.com/kiishor/UML-State-Machine-in-C

It supports both finite and hierarchical state machine. It has only 3 API's, 2 structures and 1 enumeration.

The State machine is represented by state_machine_t structure. It is an abstract structure that can be inherited to create a state machine.

//! Abstract state machine structure
struct state_machine_t
{
   uint32_t Event;          //!< Pending Event for state machine
   const state_t* State;    //!< State of state machine.
};

State is represented by pointer to state_t structure in the framework.

If framework is configured for finite state machine then state_t contains,

typedef struct finite_state_t state_t;

// finite state structure
typedef struct finite_state_t{
  state_handler Handler;        //!< State handler function (function pointer)
  state_handler Entry;          //!< Entry action for state (function pointer)
  state_handler Exit;           //!< Exit action for state (function pointer)
}finite_state_t;

The framework provides an API dispatch_event to dispatch the event to the state machine and two API's for the state traversal.

state_machine_result_t dispatch_event(state_machine_t* const pState_Machine[], uint32_t quantity);
state_machine_result_t switch_state(state_machine_t* const, const state_t*);

state_machine_result_t traverse_state(state_machine_t* const, const state_t*);

For further details on how to implement hierarchical state machine refer the GitHub repository.

code examples
https://github.com/kiishor/UML-State-Machine-in-C/blob/master/demo/simple_state_machine/readme.md
https://github.com/kiishor/UML-State-Machine-in-C/blob/master/demo/simple_state_machine_enhanced/readme.md

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

<table>
     <ng-container *ngFor="let group of groups">
         <tr><td><h2>{{group.name}}</h2></td></tr>
         <tr *ngFor="let item of group.items"><td>{{item}}</td></tr>
     </ng-container>
</table>

Prolog "or" operator, query

you can 'invoke' alternative bindings on Y this way:

...registered(X, Y), (Y=ct101; Y=ct102; Y=ct103).

Note the parenthesis are required to keep the correct execution control flow. The ;/2 it's the general or operator. For your restricted use you could as well choice the more idiomatic

...registered(X, Y), member(Y, [ct101,ct102,ct103]).

that on backtracking binds Y to each member of the list.

edit I understood with a delay your last requirement. If you want that Y match all 3 values the or is inappropriate, use instead

...registered(X, ct101), registered(X, ct102), registered(X, ct103).

or the more compact

...findall(Y, registered(X, Y), L), sort(L, [ct101,ct102,ct103]).

findall/3 build the list in the very same order that registered/2 succeeds. Then I use sort to ensure the matching.

...setof(Y, registered(X, Y), [ct101,ct102,ct103]).

setof/3 also sorts the result list

Draggable div without jQuery UI

$(document).ready(function() {
    var $startAt = null;

    $(document.body).live("mousemove", function(e) {
        if ($startAt) {
            $("#someDiv").offset({
                top: e.pageY,
                left: $("#someDiv").position().left-$startAt+e.pageX
            });
            $startAt = e.pageX; 
        }
    });

    $("#someDiv").live("mousedown", function (e) {$startAt = e.pageX;});
    $(document.body).live("mouseup", function (e) {$startAt = null;});
});

Null vs. False vs. 0 in PHP

It's language specific, but in PHP :

Null means "nothing". The var has not been initialized.

False means "not true in a boolean context". Used to explicitly show you are dealing with logical issues.

0 is an int. Nothing to do with the rest above, used for mathematics.

Now, what is tricky, it's that in dynamic languages like PHP, all of them have a value in a boolean context, which (in PHP) is False.

If you test it with ==, it's testing the boolean value, so you will get equality. If you test it with ===, it will test the type, and you will get inequality.

So why are they useful ?

Well, look at the strrpos() function. It returns False if it did not found anything, but 0 if it has found something at the beginning of the string !

<?php
// pitfall :
if (strrpos("Hello World", "Hello")) { 
    // never exectuted
}

// smart move :
if (strrpos("Hello World", "Hello") !== False) {
    // that works !
}
?>

And of course, if you deal with states:

You want to make a difference between DebugMode = False (set to off), DebugMode = True (set to on) and DebugMode = Null (not set at all, will lead to hard debugging ;-)).

How do you set a JavaScript onclick event to a class with css

Many 3rd party JavaScript libraries allow you to select all elements that have a CSS class of a particular name applied to them. Then you can iterate those elements and dynamically attach the handler.

There is no CSS-specific manner to do this.

In JQuery, you can do:

$(".myCssClass").click(function() { alert("hohoho"); });

Mail multipart/alternative vs multipart/mixed

I hit this issue. This architecture (from Lain's answer) worked for me. Here is the solution in Python.

  • mixed
    • alternative
      • text
      • related
        • html
        • inline image
        • inline image
    • attachment
    • attachment

Here is the main email creation function:

def create_message_with_attachment(
    sender, to, subject, msgHtml, msgPlain, attachmentFile):
    """Create a message for an email.

    Args:
      sender: Email address of the sender.
      to: Email address of the receiver.
      subject: The subject of the email message.
      message_text: The text of the email message.
      file: The path to the file to be attached.

    Returns:
      An object containing a base64url encoded email object.
    """
    message = MIMEMultipart('mixed')
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    message_alternative = MIMEMultipart('alternative')
    message_related = MIMEMultipart('related')

    message_related.attach(MIMEText(msgHtml, 'html'))
    message_alternative.attach(MIMEText(msgPlain, 'plain'))
    message_alternative.attach(message_related)

    message.attach(message_alternative)

    print "create_message_with_attachment: file:", attachmentFile
    content_type, encoding = mimetypes.guess_type(attachmentFile)

    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(attachmentFile, 'rb')
        msg = MIMEText(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(attachmentFile, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(attachmentFile, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(attachmentFile, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(attachmentFile)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)

    return {'raw': base64.urlsafe_b64encode(message.as_string())}

Here is the full code for sending an email containing html/text/attachment:

import httplib2
import os
import oauth2client
from oauth2client import client, tools
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from apiclient import errors, discovery
import mimetypes
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase

SCOPES = 'https://www.googleapis.com/auth/gmail.send'
CLIENT_SECRET_FILE1 = 'client_secret.json'
location = os.path.realpath(
    os.path.join(os.getcwd(), os.path.dirname(__file__)))
CLIENT_SECRET_FILE = os.path.join(location, CLIENT_SECRET_FILE1)
APPLICATION_NAME = 'Gmail API Python Send Email'

def get_credentials():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'gmail-python-email-send.json')
    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        credentials = tools.run_flow(flow, store)
        print 'Storing credentials to ' + credential_path
    return credentials

def SendMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachmentFile):
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=http)
    message1 = create_message_with_attachment(sender, to, subject, msgHtml, msgPlain, attachmentFile)
    SendMessageInternal(service, "me", message1)

def SendMessageInternal(service, user_id, message):
    try:
        message = (service.users().messages().send(userId=user_id, body=message).execute())
        print 'Message Id: %s' % message['id']
        return message
    except errors.HttpError, error:
        print 'An error occurred: %s' % error
        return "error"

def create_message_with_attachment(
    sender, to, subject, msgHtml, msgPlain, attachmentFile):
    """Create a message for an email.

    Args:
      sender: Email address of the sender.
      to: Email address of the receiver.
      subject: The subject of the email message.
      message_text: The text of the email message.
      file: The path to the file to be attached.

    Returns:
      An object containing a base64url encoded email object.
    """
    message = MIMEMultipart('mixed')
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    message_alternative = MIMEMultipart('alternative')
    message_related = MIMEMultipart('related')

    message_related.attach(MIMEText(msgHtml, 'html'))
    message_alternative.attach(MIMEText(msgPlain, 'plain'))
    message_alternative.attach(message_related)

    message.attach(message_alternative)

    print "create_message_with_attachment: file:", attachmentFile
    content_type, encoding = mimetypes.guess_type(attachmentFile)

    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(attachmentFile, 'rb')
        msg = MIMEText(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(attachmentFile, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(attachmentFile, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(attachmentFile, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(attachmentFile)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)

    return {'raw': base64.urlsafe_b64encode(message.as_string())}


def main():
    to = "[email protected]"
    sender = "[email protected]"
    subject = "subject"
    msgHtml = "Hi<br/>Html Email"
    msgPlain = "Hi\nPlain Email"
    attachment = "/path/to/file.pdf"
    SendMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachment)

if __name__ == '__main__':
    main()

Property 'value' does not exist on type 'EventTarget'

Here is another simple approach, I used;

    inputChange(event: KeyboardEvent) {      
    const target = event.target as HTMLTextAreaElement;
    var activeInput = target.id;
    }

how to convert string into time format and add two hours

Basic program of adding two times:
You can modify hour:min:sec as per your need using if else.
This program shows you how you can add values from two objects and return in another object.

class demo
{private int hour,min,sec;
    void input(int hour,int min,int sec)
    {this.hour=hour;
    this.min=min;
    this.sec=sec;

    }
    demo add(demo d2)//demo  because we are returning object
    {   demo obj=new demo();
    obj.hour=hour+d2.hour;
    obj.min=min+d2.min;
    obj.sec=sec+d2.sec;
    return obj;//Returning object and later on it gets allocated to demo d3                    
    }
    void display()
    {
        System.out.println(hour+":"+min+":"+sec);
    }
    public static  void main(String args[])
    {
        demo d1=new demo();
        demo d2=new demo();
        d1.input(2, 5, 10);
        d2.input(3, 3, 3);
        demo d3=d1.add(d2);//Note another object is created
        d3.display();


    }

}

Modified Time Addition Program

class demo {private int hour,min,sec; void input(int hour,int min,int sec) {this.hour=(hour>12&&hour<24)?(hour-12):hour; this.min=(min>60)?0:min; this.sec=(sec>60)?0:sec; } demo add(demo d2) { demo obj=new demo(); obj.hour=hour+d2.hour; obj.min=min+d2.min; obj.sec=sec+d2.sec; if(obj.sec>60) {obj.sec-=60; obj.min++; } if(obj.min>60) { obj.min-=60; obj.hour++; } return obj; } void display() { System.out.println(hour+":"+min+":"+sec); } public static void main(String args[]) { demo d1=new demo(); demo d2=new demo(); d1.input(12, 55, 55); d2.input(12, 7, 6); demo d3=d1.add(d2); d3.display(); } }

Difference between <? super T> and <? extends T> in Java

When to use extends and super

Wildcards are most useful in method parameters. They allow for the necessary flexibility in method interfaces.

People are often confused when to use extends and when to use super bounds. The rule of thumb is the get-put principle. If you get something from a parametrized container, use extends.

int totalFuel(List<? extends Vehicle> list) {
int total = 0;
for(Vehicle v : list) {
    total += v.getFuel();
}
return total;}

The method totalFuel gets Vehicles from the list, asks them about how much fuel they have, and computes the total. If you put objects into a parameterized container, use super.

int totalValue(Valuer<? super Vehicle> valuer) {
int total = 0;
for(Vehicle v : vehicles) {
    total += valuer.evaluate(v);
}
return total;}

The method totalValue puts Vehicles into the Valuer. It's useful to know that extends bound is much more common than super.

How to use google maps without api key

Note : This answer is now out-of-date. You are now required to have an API key to use google maps. Read More


you need to change your API from V2 to V3, Since Google Map Version 3 don't required API Key

Check this out..

write your script as

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

Creating a recursive method for Palindrome

Some of the codes are string heavy. Instead of creating substring which creates new object, we can just pass on indexes in recursive calls like below:

private static boolean isPalindrome(String str, int left, int right) {
    if(left >= right) {
        return true;
    }
    else {
        if(str.charAt(left) == str.charAt(right)) {

            return isPalindrome(str, ++left, --right);
        }
        else {
            return false;
        }
    }
}


 public static void main(String []args){
    String str = "abcdcbb"; 
    System.out.println(isPalindrome(str, 0, str.length()-1));
 }

postgresql COUNT(DISTINCT ...) very slow

I was also searching same answer, because at some point of time I needed total_count with distinct values along with limit/offset.

Because it's little tricky to do- To get total count with distinct values along with limit/offset. Usually it's hard to get total count with limit/offset. Finally I got the way to do -

SELECT DISTINCT COUNT(*) OVER() as total_count, * FROM table_name limit 2 offset 0;

Query performance is also high.

Actionbar notification count icon (badge) like Google has

I am not sure if this is the best solution or not, but it is what I need.

Please tell me if you know what is need to be changed for better performance or quality. In my case, I have a button.

Custom item on my menu - main.xml

<item
    android:id="@+id/badge"
    android:actionLayout="@layout/feed_update_count"
    android:icon="@drawable/shape_notification"
    android:showAsAction="always">
</item>

Custom shape drawable (background square) - shape_notification.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="rectangle">
    <stroke android:color="#22000000" android:width="2dp"/>
    <corners android:radius="5dp" />
    <solid android:color="#CC0001"/>
</shape>

Layout for my view - feed_update_count.xml

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/notif_count"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:minWidth="32dp"
     android:minHeight="32dp"
     android:background="@drawable/shape_notification"
     android:text="0"
     android:textSize="16sp"
     android:textColor="@android:color/white"
     android:gravity="center"
     android:padding="2dp"
     android:singleLine="true">    
</Button>

MainActivity - setting and updating my view

static Button notifCount;
static int mNotifCount = 0;    

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getSupportMenuInflater();
    inflater.inflate(R.menu.main, menu);

    View count = menu.findItem(R.id.badge).getActionView();
    notifCount = (Button) count.findViewById(R.id.notif_count);
    notifCount.setText(String.valueOf(mNotifCount));
    return super.onCreateOptionsMenu(menu);
}

private void setNotifCount(int count){
    mNotifCount = count;
    invalidateOptionsMenu();
}

Putting text in top left corner of matplotlib plot

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 6))
plt.text(0.1, 0.9, 'text', size=15, color='purple')

# or 

fig, axe = plt.subplots(figsize=(6, 6))
axe.text(0.1, 0.9, 'text', size=15, color='purple')

Output of Both

enter image description here

import matplotlib.pyplot as plt

# Build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
ax = plt.gca()
p = plt.Rectangle((left, bottom), width, height, fill=False)
p.set_transform(ax.transAxes)
p.set_clip_on(False)
ax.add_patch(p)


ax.text(left, bottom, 'left top',
        horizontalalignment='left',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, bottom, 'left bottom',
        horizontalalignment='left',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right bottom',
        horizontalalignment='right',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right top',
        horizontalalignment='right',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(right, bottom, 'center top',
        horizontalalignment='center',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'right center',
        horizontalalignment='right',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'left center',
        horizontalalignment='left',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(0.5 * (left + right), 0.5 * (bottom + top), 'middle',
        horizontalalignment='center',
        verticalalignment='center',
        transform=ax.transAxes)

ax.text(right, 0.5 * (bottom + top), 'centered',
        horizontalalignment='center',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, top, 'rotated\nwith newlines',
        horizontalalignment='center',
        verticalalignment='center',
        rotation=45,
        transform=ax.transAxes)

plt.axis('off')

plt.show()

enter image description here

Inserting values to SQLite table in Android

You'll find debugging errors like this a lot easier if you catch any errors thrown from the execSQL call. eg:

 try 
 {
      db.execSQL(Create_CashBook);  
 }
 catch (Exception e) 
 {
       Log.e("ERROR", e.toString());
 }

PHP multidimensional array search by value

In later versions of PHP (>= 5.5.0) you can use this one-liner:

$key = array_search('100', array_column($userdb, 'uid'));

Asynchronous Process inside a javascript for loop

ES2017: You can wrap the async code inside a function(say XHRPost) returning a promise( Async code inside the promise).

Then call the function(XHRPost) inside the for loop but with the magical Await keyword. :)

_x000D_
_x000D_
let http = new XMLHttpRequest();_x000D_
let url = 'http://sumersin/forum.social.json';_x000D_
_x000D_
function XHRpost(i) {_x000D_
  return new Promise(function(resolve) {_x000D_
    let params = 'id=nobot&%3Aoperation=social%3AcreateForumPost&subject=Demo' + i + '&message=Here%20is%20the%20Demo&_charset_=UTF-8';_x000D_
    http.open('POST', url, true);_x000D_
    http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');_x000D_
    http.onreadystatechange = function() {_x000D_
    console.log("Done " + i + "<<<<>>>>>" + http.readyState);_x000D_
          if(http.readyState == 4){_x000D_
              console.log('SUCCESS :',i);_x000D_
              resolve();_x000D_
          }_x000D_
         }_x000D_
    http.send(params);       _x000D_
    });_x000D_
 }_x000D_
 _x000D_
(async () => {_x000D_
    for (let i = 1; i < 5; i++) {_x000D_
        await XHRpost(i);_x000D_
       }_x000D_
})();
_x000D_
_x000D_
_x000D_

Laravel Request::all() Should Not Be Called Statically

use Illuminate\Http\Request;
public function store(Request $request){
   dd($request->all());
}

is same in context saying

use Request;
public function store(){
   dd(Request::all());
}

Relative paths in Python

It's 2018 now, and Python have already evolve to the __future__ long time ago. So how about using the amazing pathlib coming with Python 3.4 to accomplish the task instead of struggling with os, os.path, glob, shutil, etc.

So we have 3 paths here (possibly duplicated):

  • mod_path: which is the path of the simple helper script
  • src_path: which contains a couple of template files waiting to be copied.
  • cwd: current directory, the destination of those template files.

and the problem is: we don't have the full path of src_path, only know it's relative path to the mod_path.

Now let's solve this with the the amazing pathlib:

# Hope you don't be imprisoned by legacy Python code :)
from pathlib import Path

# `cwd`: current directory is straightforward
cwd = Path.cwd()

# `mod_path`: According to the accepted answer and combine with future power
# if we are in the `helper_script.py`
mod_path = Path(__file__).parent
# OR if we are `import helper_script`
mod_path = Path(helper_script.__file__).parent

# `src_path`: with the future power, it's just so straightforward
relative_path_1 = 'same/parent/with/helper/script/'
relative_path_2 = '../../or/any/level/up/'
src_path_1 = (mod_path / relative_path_1).resolve()
src_path_2 = (mod_path / relative_path_2).resolve()

In the future, it just that simple. :D


Moreover, we can select and check and copy/move those template files with pathlib:

if src_path != cwd:
    # When we have different types of files in the `src_path`
    for template_path in src_path.glob('*.ini'):
        fname = template_path.name
        target = cwd / fname
        if not target.exists():
            # This is the COPY action
            with target.open(mode='wb') as fd:
                fd.write(template_path.read_bytes())
            # If we want MOVE action, we could use:
            # template_path.replace(target)

Min width in window resizing

You can set min-width property of CSS for body tag. Since this property is not supported by IE6, you can write like:

body{
   min-width:1000px;        /* Suppose you want minimum width of 1000px */
   width: auto !important;  /* Firefox will set width as auto */
   width:1000px;            /* As IE6 ignores !important it will set width as 1000px; */
}

Or:

body{
   min-width:1000px; // Suppose you want minimum width of 1000px
   _width: expression( document.body.clientWidth > 1000 ? "1000px" : "auto" ); /* sets max-width for IE6 */
}

Show a popup/message box from a Windows batch file

Might display a little flash, but no temp files required. Should work all the way back to somewhere in the (IIRC) IE5 era.

mshta javascript:alert("Message\n\nMultiple\nLines\ntoo!");close();

Don't forget to escape your parentheses if you're using if:

if 1 == 1 (
   mshta javascript:alert^("1 is equal to 1, amazing."^);close^(^);
)

How do you add a JToken to an JObject?

TL;DR: You should add a JProperty to a JObject. Simple. The index query returns a JValue, so figure out how to get the JProperty instead :)


The accepted answer is not answering the question as it seems. What if I want to specifically add a JProperty after a specific one? First, lets start with terminologies which really had my head worked up.

  • JToken = The mother of all other types. It can be A JValue, JProperty, JArray, or JObject. This is to provide a modular design to the parsing mechanism.
  • JValue = any Json value type (string, int, boolean).
  • JProperty = any JValue or JContainer (see below) paired with a name (identifier). For example "name":"value".
  • JContainer = The mother of all types which contain other types (JObject, JValue).
  • JObject = a JContainer type that holds a collection of JProperties
  • JArray = a JContainer type that holds a collection JValue or JContainer.

Now, when you query Json item using the index [], you are getting the JToken without the identifier, which might be a JContainer or a JValue (requires casting), but you cannot add anything after it, because it is only a value. You can change it itself, query more deep values, but you cannot add anything after it for example.

What you actually want to get is the property as whole, and then add another property after it as desired. For this, you use JOjbect.Property("name"), and then create another JProperty of your desire and then add it after this using AddAfterSelf method. You are done then.

For more info: http://www.newtonsoft.com/json/help/html/ModifyJson.htm

This is the code I modified.

public class Program
{
  public static void Main()
  {
    try
    {
      string jsonText = @"
      {
        ""food"": {
          ""fruit"": {
            ""apple"": {
              ""colour"": ""red"",
              ""size"": ""small""
            },
            ""orange"": {
              ""colour"": ""orange"",
              ""size"": ""large""
            }
          }
        }
      }";

      var foodJsonObj = JObject.Parse(jsonText);
      var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}}");

      var fruitJObject = foodJsonObj["food"]["fruit"] as JObject;
      fruitJObject.Property("orange").AddAfterSelf(new JProperty("banana", fruitJObject));

      Console.WriteLine(foodJsonObj.ToString());
    }
    catch (Exception ex)
    {
      Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
    }
  }
}

Jquery $.ajax fails in IE on cross domain calls

For IE8 & IE9 you need to use XDomainRequest (XDR). If you look below you'll see it's in a sort of similar formatting as $.ajax. As far as my research has got me I can't get this cross-domain working in IE6 & 7 (still looking for a work-around for this). XDR first came out in IE8 (it's in IE9 also). So basically first, I test for 6/7 and do no AJAX.

IE10+ is able to do cross-domain normally like all the other browsers (congrats Microsoft... sigh)

After that the else if tests for 'XDomainRequest in window (apparently better than browser sniffing) and does the JSON AJAX request that way, other wise the ELSE does it normally with $.ajax.

Hope this helps!! Took me forever to get this all figured out originally

Information on the XDomainRequest object

// call with your url (with parameters) 
// 2nd param is your callback function (which will be passed the json DATA back)

crossDomainAjax('http://www.somecrossdomaincall.com/?blah=123', function (data) {
    // success logic
});

function crossDomainAjax (url, successCallback) {

    // IE8 & 9 only Cross domain JSON GET request
    if ('XDomainRequest' in window && window.XDomainRequest !== null) {

        var xdr = new XDomainRequest(); // Use Microsoft XDR
        xdr.open('get', url);
        xdr.onload = function () {
            var dom  = new ActiveXObject('Microsoft.XMLDOM'),
                JSON = $.parseJSON(xdr.responseText);

            dom.async = false;

            if (JSON == null || typeof (JSON) == 'undefined') {
                JSON = $.parseJSON(data.firstChild.textContent);
            }

            successCallback(JSON); // internal function
        };

        xdr.onerror = function() {
            _result = false;  
        };

        xdr.send();
    } 

    // IE7 and lower can't do cross domain
    else if (navigator.userAgent.indexOf('MSIE') != -1 &&
             parseInt(navigator.userAgent.match(/MSIE ([\d.]+)/)[1], 10) < 8) {
       return false;
    }    

    // Do normal jQuery AJAX for everything else          
    else {
        $.ajax({
            url: url,
            cache: false,
            dataType: 'json',
            type: 'GET',
            async: false, // must be set to false
            success: function (data, success) {
                successCallback(data);
            }
        });
    }
}

Offset a background image from the right using CSS

The CSS3 specification allowing different origins for background-position is now supported in Firefox 14 but still not in Chrome 21 (apparently IE9 partly supports them, but I've not tested it myself)

In addition to the Chrome issue that @MattyF referenced there's a more succinct summary here: http://code.google.com/p/chromium/issues/detail?id=95085

SQL Server Error : String or binary data would be truncated

this type of error generally occurs when you have to put characters or values more than that you have specified in Database table like in this case: you specify transaction_status varchar(10) but you actually trying to store
_transaction_status which contain 19 characters. that's why you faced this type of error in this code..

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

On Swift 3. You can create an extension and add after your view class.

extension UITextField
{
    func setBottomBorder(borderColor: UIColor)
    {

        self.borderStyle = UITextBorderStyle.none
        self.backgroundColor = UIColor.clear
        let width = 1.0

        let borderLine = UIView()
        borderLine.frame = CGRect(x: 0, y: Double(self.frame.height) - width, width: Double(self.frame.width), height: width)

        borderLine.backgroundColor = borderColor
        self.addSubview(borderLine)
    }
}

compareTo with primitives -> Integer / int

Wrapping int primitive into Integer object will cost you some memory, but the difference will be only significant in very rare(memory demand) cases (array with 1000+ elements). I will not recommend using new Integer(int a) constructor this way. This will suffice :

Integer a = 3; 

About comparision there is Math.signum(double d).

compare= (int) Math.signum(a-b); 

Convert UTC/GMT time to local time

In answer to Dana's suggestion:

The code sample now looks like:

string date = "Web service date"..ToString("R", ci);
DateTime convertedDate = DateTime.Parse(date);            
DateTime dt = TimeZone.CurrentTimeZone.ToLocalTime(convertedDate);

The original date was 20/08/08; the kind was UTC.

Both "convertedDate" and "dt" are the same:

21/08/08 10:00:26; the kind was local

How to get the system uptime in Windows?

I use this little PowerShell snippet:

function Get-SystemUptime {
    $operatingSystem = Get-WmiObject Win32_OperatingSystem
    "$((Get-Date) - ([Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)))"
}

which then yields something like the following:

PS> Get-SystemUptime
6.20:40:40.2625526

What does the "On Error Resume Next" statement do?

On Error Resume Next means that On Error, It will resume to the next line to resume.

e.g. if you try the Try block, That will stop the script if a error occurred

Regex Until But Not Including

Try this

(.*?quick.*?)z

jQuery Loop through each div

$('div.target').each(function() {
   /* Measure the width of each image. */
   var test = $(this).find('.scrolling img').width();

   /* Find out how many images there are. */
   var testimg = $(this).find('.scrolling img').length;

   /* Do the maths. */
   var final = (test* testimg)*1.2;

   /* Apply the maths to the CSS. */
   $(this).find('scrolling').width(final); 
});

Here you loop through all your div's with class target and you do the calculations. Within this loop you can simply use $(this) to indicate the currently selected <div> tag.

Switch case with fallthrough?

Recent bash versions allow fall-through by using ;& in stead of ;;: they also allow resuming the case checks by using ;;& there.

for n in 4 14 24 34
do
  echo -n "$n = "
  case "$n" in
   3? )
     echo -n thirty-
     ;;&   #resume (to find ?4 later )
   "24" )
     echo -n twenty-
     ;&   #fallthru
   "4" | [13]4)
     echo -n four 
     ;;&  # resume ( to find teen where needed )
   "14" )
     echo -n teen
  esac
  echo 
done

sample output

4 = four
14 = fourteen
24 = twenty-four
34 = thirty-four

Finding the index of elements based on a condition using python list comprehension

Maybe another question is, "what are you going to do with those indices once you get them?" If you are going to use them to create another list, then in Python, they are an unnecessary middle step. If you want all the values that match a given condition, just use the builtin filter:

matchingVals = filter(lambda x : x>2, a)

Or write your own list comprhension:

matchingVals = [x for x in a if x > 2]

If you want to remove them from the list, then the Pythonic way is not to necessarily remove from the list, but write a list comprehension as if you were creating a new list, and assigning back in-place using the listvar[:] on the left-hand-side:

a[:] = [x for x in a if x <= 2]

Matlab supplies find because its array-centric model works by selecting items using their array indices. You can do this in Python, certainly, but the more Pythonic way is using iterators and generators, as already mentioned by @EliBendersky.

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

The IE9 "version" of the WebBrowser control, like the IE8 version, is actually several browsers in one. Unlike the IE8 version, you do have a little more control over the rendering mode inside the page by changing the doctype. Of course, to change the browser mode you have to set your registry like the earlier answer. Here is a reg file fragment for FEATURE_BROWSER_EMULATION:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION]
"contoso.exe"=dword:00002328

Here is the complete set of codes:

  • 9999 (0x270F) - Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the !DOCTYPE directive.
  • 9000 (0x2328) - Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode.
  • 8888 (0x22B8) -Webpages are displayed in IE8 Standards mode, regardless of the !DOCTYPE directive.
  • 8000 (0x1F40) - Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode.
  • 7000 (0x1B58) - Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode.

The full docs:

http://msdn.microsoft.com/en-us/library/ee330730%28VS.85%29.aspx#browser_emulation

E: Unable to locate package mongodb-org

I faced same issue but fix it by the changing the package file section command. The whole step that i followed was:

At first try with this command: sudo apt-get install -y mongodb

This is the unofficial mongodb package provided by Ubuntu and it is not maintained by MongoDB and conflict with MongoDB’s offically supported packages.

If the above command not working then you can fix the issue by one of the bellow procedure:

#Step 1:  Import the MongoDB public key
#In Ubuntu 18.*+, you may get invalid signatures. --recv value may need to be updated to EA312927. 
#See here for more details on the invalid signature issue: [https://stackoverflow.com/questions/34733340/mongodb-gpg-invalid-signatures][1]

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

#Step 2: Generate a file with the MongoDB repository url
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list

#Step 3: Refresh the local database with the packages
sudo apt-get update

#Step 4: Install the last stable MongoDB version and all the necessary packages on our system
sudo apt-get install mongodb-org

         #Or
# The unofficial mongodb package provided by Ubuntu is not maintained by MongoDB and conflict with MongoDB’s offically supported packages. Use the official MongoDB mongodb-org packages, which are kept up-to-date with the most recent major and minor MongoDB releases.
sudo apt-get install -y mongodb 

Hope this will work for you also. You can follow this MongoDB

Update The above instruction will install mongodb 2.6 version, if you want to install latest version for Uubuntu 12.04 then just replace above step 2 and follow bellow instruction instead of that:

#Step 2: Generate a file with the MongoDB repository url
echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb.list

If you are using Ubuntu 14.04 then use bellow step instead of above step 2

#Step 2: Generate a file with the MongoDB repository url
echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list

Create PostgreSQL ROLE (user) if it doesn't exist

The accepted answer suffers from a race condition if two such scripts are executed concurrently on the same Postgres cluster (DB server), as is common in continuous-integration environments.

It's generally safer to try to create the role and gracefully deal with problems when creating it:

DO $$
BEGIN
  CREATE ROLE my_role WITH NOLOGIN;
  EXCEPTION WHEN DUPLICATE_OBJECT THEN
  RAISE NOTICE 'not creating role my_role -- it already exists';
END
$$;

Disable browsers vertical and horizontal scrollbars

In case you need possibility to hide and show scrollbars dynamically you could use

$("body").css("overflow", "hidden");

and

$("body").css("overflow", "auto");

somewhere in your code.

How do you remove columns from a data.frame?

The select() function from dplyr is powerful for subsetting columns. See ?select_helpers for a list of approaches.

In this case, where you have a common prefix and sequential numbers for column names, you could use num_range:

library(dplyr)

df1 <- data.frame(first = 0, col1 = 1, col2 = 2, col3 = 3, col4 = 4)
df1 %>%
  select(num_range("col", c(1, 4)))
#>   col1 col4
#> 1    1    4

More generally you can use the minus sign in select() to drop columns, like:

mtcars %>%
   select(-mpg, -wt)

Finally, to your question "is there an easy way to create a workable vector of column names?" - yes, if you need to edit a list of names manually, use dput to get a comma-separated, quoted list you can easily manipulate:

dput(names(mtcars))
#> c("mpg", "cyl", "disp", "hp", "drat", "wt", "qsec", "vs", "am", 
#> "gear", "carb")

Disabling enter key for form

You can try something like this, if you use jQuery.

$("form").bind("keydown", function(e) {
   if (e.keyCode === 13) return false;
 });

That will wait for a keydown, if it is Enter, it will do nothing.

How do I load a file into the python console?

If you're using IPython, you can simply run:

%load path/to/your/file.py

See http://ipython.org/ipython-doc/rel-1.1.0/interactive/tutorial.html

How to open an elevated cmd using command line for Windows?

Make the batch file save the credentials of the actual administrator account by using the /savecred switch. This will prompt for credentials the first time and then store the encrypted password in credential manager. Then for all subsequent times the batch runs it will run as the full admin but not prompt for credentials because they are stored encrypted in credential manager and the end user is unable to get the password. The following should open an elevated CMD with full administrator privileges and will only prompt for password the first time:

START c:\Windows\System32\runas.exe /user:Administrator /savecred cmd.exe

Can I have an IF block in DOS batch file?

I ran across this article in the results returned by a search related to the IF command in a batch file, and I couldn't resist the opportunity to correct the misconception that IF blocks are limited to single commands. Following is a portion of a production Windows NT command script that runs daily on the machine on which I am composing this reply.

    if "%COPYTOOL%" equ "R" (
    WWLOGGER.exe "%APPDATA%\WizardWrx\%~n0.LOG" "Using RoboCopy to make a backup of %USERPROFILE%\My Documents\Outlook Files\*"
    %TOOLPATH% %SRCEPATH% %DESTPATH% /copyall %RCLOGSTR% /m /np /r:0 /tee
    C:\BIN\ExitCodeMapper.exe C:\BIN\ExitCodeMapper.INI[Robocopy] %TEMP%\%~n0.TMP %ERRORLEVEL%
) else (
    WWLOGGER.exe "%APPDATA%\WizardWrx\%~n0.LOG" "Using XCopy to make a backup of %USERPROFILE%\My Documents\Outlook Files\*"
    call %TOOLPATH%  "%USERPROFILE%\My Documents\Outlook Files\*" "%USERPROFILE%\My Documents\Outlook Files\_backups" /f /m /v /y
    C:\BIN\ExitCodeMapper.exe C:\BIN\ExitCodeMapper.INI[Xcopy] %TEMP%\%~n0.TMP %ERRORLEVEL%
)

Perhaps blocks of two or more lines applies exclusively to Windows NT command scripts (.CMD files), because a search of the production scripts directory of an application that is restricted to old school batch (.BAT) files, revealed only one-command blocks. Since the application has gone into extended maintenance (meaning that I am not actively involved in supporting it), I can't say whether that is because I didn't need more than one line, or that I couldn't make them work.

Regardless, if the latter is true, there is a simple workaround; move the multiple lines into either a separate batch file or a batch file subroutine. I know that the latter works in both kinds of scripts.

How to check if string input is a number?

For Python 3 the following will work.

userInput = 0
while True:
  try:
     userInput = int(input("Enter something: "))       
  except ValueError:
     print("Not an integer!")
     continue
  else:
     print("Yes an integer!")
     break 

adding 1 day to a DATETIME format value

There's more then one way to do this with DateTime which was introduced in PHP 5.2. Unlike using strtotime() this will account for daylight savings time and leap year.

$datetime = new DateTime('2013-01-29');
$datetime->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');

// Available in PHP 5.3

$datetime = new DateTime('2013-01-29');
$datetime->add(new DateInterval('P1D'));
echo $datetime->format('Y-m-d H:i:s');

// Available in PHP 5.4

echo (new DateTime('2013-01-29'))->add(new DateInterval('P1D'))->format('Y-m-d H:i:s');

// Available in PHP 5.5

$start = new DateTimeImmutable('2013-01-29');
$datetime = $start->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');

Rails select helper - Default selected value, how?

The problem with all of these answers is they set the field to the default value even if you're trying to edit your record.

You need to set the default to your existing value and then only set it to the actual default if you don't have a value. Like so:

f.select :field, options_for_select(value_array, f.object.field || default_value)

For anyone not familiar with f.object.field you always use f.object then add your field name to the end of that.

How to use multiple conditions (With AND) in IIF expressions in ssrs

You don't need an IIF() at all here. The comparisons return true or false anyway.

Also, since this row visibility is on a group row, make sure you use the same aggregate function on the fields as you use in the fields in the row. So if your group row shows sums, then you'd put this in the Hidden property.

=Sum(Fields!OpeningStock.Value) = 0 And
Sum(Fields!GrossDispatched.Value) = 0 And 
Sum(Fields!TransferOutToMW.Value) = 0 And
Sum(Fields!TransferOutToDW.Value) = 0 And
Sum(Fields!TransferOutToOW.Value) = 0 And
Sum(Fields!NetDispatched.Value) = 0 And
Sum(Fields!QtySold.Value) = 0 And
Sum(Fields!StockAdjustment.Value) = 0 And
Sum(Fields!ClosingStock.Value) = 0

But with the above version, if one record has value 1 and one has value -1 and all others are zero then sum is also zero and the row could be hidden. If that's not what you want you could write a more complex expression:

=Sum(
    IIF(
        Fields!OpeningStock.Value=0 AND
        Fields!GrossDispatched.Value=0 AND
        Fields!TransferOutToMW.Value=0 AND
        Fields!TransferOutToDW.Value=0 AND 
        Fields!TransferOutToOW.Value=0 AND
        Fields!NetDispatched.Value=0 AND
        Fields!QtySold.Value=0 AND
        Fields!StockAdjustment.Value=0 AND
        Fields!ClosingStock.Value=0,
        0,
        1
    )
) = 0

This is essentially a fancy way of counting the number of rows in which any field is not zero. If every field is zero for every row in the group then the expression returns true and the row is hidden.

Getting list of lists into pandas DataFrame

With approach explained by EdChum above, the values in the list are shown as rows. To show the values of lists as columns in DataFrame instead, simply use transpose() as following:

table = [[1 , 2], [3, 4]]
df = pd.DataFrame(table)
df = df.transpose()
df.columns = ['Heading1', 'Heading2']

The output then is:

      Heading1  Heading2
0         1        3
1         2        4

How to see full absolute path of a symlink

You can use awk with a system call readlink to get the equivalent of an ls output with full symlink paths. For example:

ls | awk '{printf("%s ->", $1); system("readlink -f " $1)}'

Will display e.g.

thin_repair ->/home/user/workspace/boot/usr/bin/pdata_tools
thin_restore ->/home/user/workspace/boot/usr/bin/pdata_tools
thin_rmap ->/home/user/workspace/boot/usr/bin/pdata_tools
thin_trim ->/home/user/workspace/boot/usr/bin/pdata_tools
touch ->/home/user/workspace/boot/usr/bin/busybox
true ->/home/user/workspace/boot/usr/bin/busybox

Common HTTPclient and proxy

I had a similar problem with HttpClient version 4.

I couldn't connect to the server because of a SOCKS proxy error and I fixed it using the below configuration:

client.getParams().setParameter("socksProxyHost",proxyHost);
client.getParams().setParameter("socksProxyPort",proxyPort);

How to pop an alert message box using PHP?

See this example :

<?php
echo "<div id='div1'>text</div>"
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="js/jquery1.3.2/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            $('#div1').click(function () {
                alert('I clicked');
            });
        });
</script>
</head>
<body>

</body>
</html>

Check list of words in another string

If your list of words is of substantial length, and you need to do this test many times, it may be worth converting the list to a set and using set intersection to test (with the added benefit that you wil get the actual words that are in both lists):

>>> long_word_list = 'some one long two phrase three about above along after against'
>>> long_word_set = set(long_word_list.split())
>>> set('word along river'.split()) & long_word_set
set(['along'])

Calculating distance between two geographic locations

I wanted to implement myself this, i ended up reading the Wikipedia page on Great-circle distance formula, because no code was readable enough for me to use as basis.

C# example

    /// <summary>
    /// Calculates the distance between two locations using the Great Circle Distance algorithm
    /// <see cref="https://en.wikipedia.org/wiki/Great-circle_distance"/>
    /// </summary>
    /// <param name="first"></param>
    /// <param name="second"></param>
    /// <returns></returns>
    private static double DistanceBetween(GeoLocation first, GeoLocation second)
    {
        double longitudeDifferenceInRadians = Math.Abs(ToRadians(first.Longitude) - ToRadians(second.Longitude));

        double centralAngleBetweenLocationsInRadians = Math.Acos(
            Math.Sin(ToRadians(first.Latitude)) * Math.Sin(ToRadians(second.Latitude)) +
            Math.Cos(ToRadians(first.Latitude)) * Math.Cos(ToRadians(second.Latitude)) *
            Math.Cos(longitudeDifferenceInRadians));

        const double earthRadiusInMeters = 6357 * 1000;

        return earthRadiusInMeters * centralAngleBetweenLocationsInRadians;
    }

    private static double ToRadians(double degrees)
    {
        return degrees * Math.PI / 180;
    }

How to Create a real one-to-one relationship in SQL Server

A 1 to 1 relationship is very much possible. Even if the relationship diagram doesn't show the 1 to 1 relationship explicitly. If you implement it as below, it will function as a one to one relationship.

I will use a basic example to explain the concept where a single person can only have a single passport. This example works perfectly in MS Access. For the SQL Server version follow this link.

Remember that in MS Access, SQL scripts can only be run one at a time and not as displayed here in sequence.

CREATE TABLE Person
(
Pk_Person_Id INT PRIMARY KEY,
Name VARCHAR(255),
EmailId VARCHAR(255),
);

CREATE TABLE PassportDetails
(
Pk_Passport_Id INT PRIMARY KEY,
Passport_Number VARCHAR(255),
Fk_Person_Id INT NOT NULL UNIQUE, 
FOREIGN KEY(Fk_Person_Id) REFERENCES Person(Pk_Person_Id)
);

How to dump only specific tables from MySQL?

Usage: mysqldump [OPTIONS] database [tables]

i.e.

mysqldump -u username -p db_name table1_name table2_name table3_name > dump.sql

Java Inheritance - calling superclass method

You can't call alpha's alphaMethod1() by using beta's object But you have two solutions:

solution 1: call alpha's alphaMethod1() from beta's alphaMethod1()

class Beta extends Alpha
{
  public void alphaMethod1()
  {
    super.alphaMethod1();
  }
}

or from any other method of Beta like:

class Beta extends Alpha
{
  public void foo()
  {
     super.alphaMethod1();
  }
}

class Test extends Beta 
{
   public static void main(String[] args)
   {
      Beta beta = new Beta();
      beta.foo();
   }
}

solution 2: create alpha's object and call alpha's alphaMethod1()

class Test extends Beta
{
   public static void main(String[] args)
   {
      Alpha alpha = new Alpha();
      alpha.alphaMethod1();
   }
}

How to deep merge instead of shallow merge?

I found only 2 line solution to get deep merge in javascript. Do let me know how this works out for you.

const obj1 = { a: { b: "c", x: "y" } }
const obj2 = { a: { b: "d", e: "f" } }
temp = Object.assign({}, obj1, obj2)
Object.keys(temp).forEach(key => {
    temp[key] = (typeof temp[key] === 'object') ? Object.assign(temp[key], obj1[key], obj2[key]) : temp[key])
}
console.log(temp)

Temp object will print { a: { b: 'd', e: 'f', x: 'y' } }

Invalid http_host header

The error log is straightforward. As it suggested,You need to add 198.211.99.20 to your ALLOWED_HOSTS setting.

In your project settings.py file,set ALLOWED_HOSTS like this :

ALLOWED_HOSTS = ['198.211.99.20', 'localhost', '127.0.0.1']

For further reading read from here.

The term 'ng' is not recognized as the name of a cmdlet

Please also make sure that the node_modules folder also exists there in the project directory. If it is not there you will get a similar issue. so please run npm install as well.

Request Permission for Camera and Library in iOS 10 - Info.plist

Use the plist settings mentioned above and the appropriate accessor (AVCaptureDevice or PHPhotoLibrary), but also alert them and send them to settings if you really need this, like so:

Swift 4.0 and 4.1

func proceedWithCameraAccess(identifier: String){
    // handler in .requestAccess is needed to process user's answer to our request
    AVCaptureDevice.requestAccess(for: .video) { success in
      if success { // if request is granted (success is true)
        DispatchQueue.main.async {
          self.performSegue(withIdentifier: identifier, sender: nil)
        }
      } else { // if request is denied (success is false)
        // Create Alert
        let alert = UIAlertController(title: "Camera", message: "Camera access is absolutely necessary to use this app", preferredStyle: .alert)

        // Add "OK" Button to alert, pressing it will bring you to the settings app
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
          UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!)
        }))
        // Show the alert with animation
        self.present(alert, animated: true)
      }
    }
  }

Get domain name from given url

I wrote a method (see below) which extracts a url's domain name and which uses simple String matching. What it actually does is extract the bit between the first "://" (or index 0 if there's no "://" contained) and the first subsequent "/" (or index String.length() if there's no subsequent "/"). The remaining, preceding "www(_)*." bit is chopped off. I'm sure there'll be cases where this won't be good enough but it should be good enough in most cases!

Mike Samuel's post above says that the java.net.URI class could do this (and was preferred to the java.net.URL class) but I encountered problems with the URI class. Notably, URI.getHost() gives a null value if the url does not include the scheme, i.e. the "http(s)" bit.

/**
 * Extracts the domain name from {@code url}
 * by means of String manipulation
 * rather than using the {@link URI} or {@link URL} class.
 *
 * @param url is non-null.
 * @return the domain name within {@code url}.
 */
public String getUrlDomainName(String url) {
  String domainName = new String(url);

  int index = domainName.indexOf("://");

  if (index != -1) {
    // keep everything after the "://"
    domainName = domainName.substring(index + 3);
  }

  index = domainName.indexOf('/');

  if (index != -1) {
    // keep everything before the '/'
    domainName = domainName.substring(0, index);
  }

  // check for and remove a preceding 'www'
  // followed by any sequence of characters (non-greedy)
  // followed by a '.'
  // from the beginning of the string
  domainName = domainName.replaceFirst("^www.*?\\.", "");

  return domainName;
}

Negative regex for Perl string pattern match

What's wrong with using two regexs (or three)? This makes your intentions more clear and may even improve your performance:

if ($string =~ /^(Clinton|Reagan)/i && $string !~ /Bush/i) { ... }

if (($string =~ /^Clinton/i || $string =~ /^Reagan/i)
        && $string !~ /Bush/i) {
    print "$string\n"
}

Moment JS start and end of given month

const dates = getDatesFromDateRange("2014-05-02", "2018-05-12", "YYYY/MM/DD", 1);           
console.log(dates);
// you get the whole from-to date ranges as per parameters
var onlyStartDates = dates.map(dateObj => dateObj["to"]);
console.log(onlyStartDates);
// moreover, if you want only from dates then you can grab by "map" function

function getDatesFromDateRange( startDate, endDate, format, counter ) {
    startDate = moment(startDate, format);
    endDate = moment(endDate, format);

    let dates = [];
    let fromDate = startDate.clone();
    let toDate = fromDate.clone().add(counter, "month").startOf("month").add(-1, "day");
    do {
        dates.push({
            "from": fromDate.format(format),
            "to": ( toDate < endDate ) ? toDate.format(format) : endDate.format(format)
        });
        fromDate = moment(toDate, format).add(1, "day").clone();
        toDate = fromDate.clone().add(counter, "month").startOf("month").add(-1, "day");
    } while ( fromDate < endDate );
    return dates;
}

Please note, .clone() is essential in momentjs else it'll override the value. It seems in your case.

It's more generic, to get bunch of dates that fall between dates.

How to change Toolbar home icon color

Well there is a more easy way to do this

drawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.open_drawer, R.string.close_drawer);
arrow = drawerToggle.getDrawerArrowDrawable();

And then

arrow.setColor(getResources().getColor(R.color.blue);

can't start MySql in Mac OS 10.6 Snow Leopard

open Terminal

cd /usr/local/mysql/support-files
sudo nano mysql.server

Find the lines:

basedir=
datadir=

change them to

basedir=/usr/local/mysql
datadir=/usr/local/mysql/data

Variable used in lambda expression should be final or effectively final

Although other answers prove the requirement, they don't explain why the requirement exists.

The JLS mentions why in §15.27.2:

The restriction to effectively final variables prohibits access to dynamically-changing local variables, whose capture would likely introduce concurrency problems.

To lower risk of bugs, they decided to ensure captured variables are never mutated.

How do I remove duplicates from a C# array?

Add all the strings to a dictionary and get the Keys property afterwards. This will produce each unique string, but not necessarily in the same order your original input had them in.

If you require the end result to have the same order as the original input, when you consider the first occurance of each string, use the following algorithm instead:

  1. Have a list (final output) and a dictionary (to check for duplicates)
  2. For each string in the input, check if it exists in the dictionary already
  3. If not, add it both to the dictionary and to the list

At the end, the list contains the first occurance of each unique string.

Make sure you consider things like culture and such when constructing your dictionary, to make sure you handle duplicates with accented letters correctly.

Set space between divs

You need a gutter between two div gutter can be made as following

margin(gutter) = width - gutter size E.g margin = calc(70% - 2em)

<body bgcolor="gray">
<section id="main">
        <div id="left">
            Something here     
        </div>
        <div id="right">
                Someone there
        </div>
</section>
</body>
<style>
body{
    font-size: 10px;
}

#main div{
    float: left;
    background-color:#ffffff;
    width: calc(50% - 1.5em);
    margin-left: 1.5em;
}
</style>

How to convert all tables from MyISAM into InnoDB?

You can execute this statement in the mysql command line tool:

echo "SELECT concat('ALTER TABLE `',TABLE_NAME,'` ENGINE=InnoDB;')
FROM Information_schema.TABLES 
WHERE ENGINE != 'InnoDB' AND TABLE_TYPE='BASE TABLE' 
AND TABLE_SCHEMA='name-of-database'" | mysql > convert.sql

You may need to specify username and password using: mysql -u username -p The result is an sql script that you can pipe back into mysql:

mysql name-of-database < convert.sql

Replace "name-of-database" in the above statement and command line.

Angular: conditional class with *ngClass

ngClass syntax:

[ngClass]="{'classname' : conditionFlag}"

You can use like this:

<ol class="breadcrumb">
  <li [ngClass]="{'active': step==='step1'}" (click)="step='step1'">Step1</li>
  <li [ngClass]="{'active': step==='step2'}" (click)="step='step2'">Step2</li>
  <li [ngClass]="{'active': step==='step3'}" (click)="step='step3'">Step3</li>
</ol>

Substitute a comma with a line break in a cell

Windows (unlike some other OS's, like Linux), uses CR+LF for line breaks:

  • CR = 13 = 0x0D = ^M = \r = carriage return

  • LF = 10 = 0x0A = ^J = \n = new line

The characters need to be in that order, if you want the line breaks to be consistently visible when copied to other Windows programs. So the Excel function would be:

=SUBSTITUTE(A1,",",CHAR(13) & CHAR(10))

Java word count program

This could be as simple as using split and count variable.

public class SplitString {

    public static void main(String[] args) {
        int count=0;        
        String s1="Hi i love to code";

        for(String s:s1.split(" "))
        {
            count++;
        }
        System.out.println(count);
    }
}

How to set a default entity property value with Hibernate

Working with Oracle, I was trying to insert a default value for an Enum

I found the following to work the best.

@Column(nullable = false)
@Enumerated(EnumType.STRING)
private EnumType myProperty = EnumType.DEFAULT_VALUE;

Iframe transparent background

Why not just load the frame off screen or hidden and then display it once it has finished loading. You could show a loading icon in its place to begin with to give the user immediate feedback that it's loading.

A non well formed numeric value encountered

This error occurs when you perform calculations with variables that use letters combined with numbers (alphanumeric), for example 24kb, 886ab ...

I had the error in the following function

function get_config_bytes($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);       
    switch($last) {
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }
    return $this->fix_integer_overflow($val);
}

The application uploads images but it didn't work, it showed the following warning:

enter image description here

Solution: The intval() function extracts the integer value of a variable with alphanumeric data and creates a new variable with the same value but converted to an integer with the intval() function. Here is the code:

function get_config_bytes($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    $intval = intval(trim($val));
    switch($last) {
        case 'g':
            $intval *= 1024;
        case 'm':
            $intval *= 1024;
        case 'k':
            $intval *= 1024;
    }
    return $this->fix_integer_overflow($intval);
}

Default value of function parameter

Default arguments must be specified with the first occurrence of the function name—typically, in the function prototype. If the function prototype is omitted because the function definition also serves as the prototype, then the default arguments should be specified in the function header.

How do I write to a Python subprocess' stdin?

To clarify some points:

As jro has mentioned, the right way is to use subprocess.communicate.

Yet, when feeding the stdin using subprocess.communicate with input, you need to initiate the subprocess with stdin=subprocess.PIPE according to the docs.

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

Also qed has mentioned in the comments that for Python 3.4 you need to encode the string, meaning you need to pass Bytes to the input rather than a string. This is not entirely true. According to the docs, if the streams were opened in text mode, the input should be a string (source is the same page).

If streams were opened in text mode, input must be a string. Otherwise, it must be bytes.

So, if the streams were not opened explicitly in text mode, then something like below should work:

import subprocess
command = ['myapp', '--arg1', 'value_for_arg1']
p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = p.communicate(input='some data'.encode())[0]

I've left the stderr value above deliberately as STDOUT as an example.

That being said, sometimes you might want the output of another process rather than building it up from scratch. Let's say you want to run the equivalent of echo -n 'CATCH\nme' | grep -i catch | wc -m. This should normally return the number characters in 'CATCH' plus a newline character, which results in 6. The point of the echo here is to feed the CATCH\nme data to grep. So we can feed the data to grep with stdin in the Python subprocess chain as a variable, and then pass the stdout as a PIPE to the wc process' stdin (in the meantime, get rid of the extra newline character):

import subprocess

what_to_catch = 'catch'
what_to_feed = 'CATCH\nme'

# We create the first subprocess, note that we need stdin=PIPE and stdout=PIPE
p1 = subprocess.Popen(['grep', '-i', what_to_catch], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

# We immediately run the first subprocess and get the result
# Note that we encode the data, otherwise we'd get a TypeError
p1_out = p1.communicate(input=what_to_feed.encode())[0]

# Well the result includes an '\n' at the end, 
# if we want to get rid of it in a VERY hacky way
p1_out = p1_out.decode().strip().encode()

# We create the second subprocess, note that we need stdin=PIPE
p2 = subprocess.Popen(['wc', '-m'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

# We run the second subprocess feeding it with the first subprocess' output.
# We decode the output to convert to a string
# We still have a '\n', so we strip that out
output = p2.communicate(input=p1_out)[0].decode().strip()

This is somewhat different than the response here, where you pipe two processes directly without adding data directly in Python.

Hope that helps someone out.

How to redirect a URL path in IIS?

Here's the config for ISAPI_Rewrite 3:

RewriteBase /

RewriteCond %{HTTP_HOST} ^mysite.org.uk$ [NC]

RewriteRule ^stuff/(.+)$ http://stuff.mysite.org.uk/$1 [NC,R=301,L]

How to silence output in a Bash script?

All output:

scriptname &>/dev/null

Portable:

scriptname >/dev/null 2>&1

Portable:

scriptname >/dev/null 2>/dev/null

For newer bash (no portable):

scriptname &>-

Mythical man month 10 lines per developer day - how close on large projects?

I think project size and the number of developers involved are big factors in this. I'm far above this over my career but I've worked alone all that time so there's no loss to working with other programmers.

How to format DateTime in Flutter , How to get current time in flutter?

You can also use this syntax. For YYYY-MM-JJ HH-MM:

var now = DateTime.now();
var month = now.month.toString().padLeft(2, '0');
var day = now.day.toString().padLeft(2, '0');
var text = '${now.year}-$month-$day ${now.hour}:${now.minute}';

Adding 1 hour to time variable

You can try this code:

$time = '10:09';

echo date( 'H:i', strtotime( '+1 hour' , strtotime($time) ) );

What exactly is a Maven Snapshot and why do we need it?

understanding the context of SDLC will help understand the difference between snapshot and the release. During the dev process developers all contribute their features to a baseline branch. At some point the lead thinks enough features have accumulated then he will cut a release branch from the baseline branch. Any builds prior to this time point are snapshots. Builds post to this point are releases. Be noted, release builds could change too before going to production if any defect spot during the release testing.

"R cannot be resolved to a variable"?

For me, there was a missing slash at the end of my SDK. In Eclipse > Preferences > Android > SDK Location

For example, change

/home/matt/android-sdk-linux

to

/home/matt/android-sdk-linux/

Bootstrap 4 - Inline List?

The html code you written is absolutely perfect

<ul class="nav navbar-nav list-inline">
 <li class="list-inline-item">FB</li>
 <li class="list-inline-item">G+</li>
 <li class="list-inline-item">T</li>
 </ul>

The reasons that could be possible is
1. Check out the CSS for class name "nav" or "navbar-nav" may be over writing it, try to remove and debug the class names in the ul element.
2. Check any of the child element(a tag or "social-icon" class) is using block level CSS style
3. Check out your using a HTML5 !DOCTYPE html
4. Place your bootstrap.css link at the last before closing your head tag
5. Change text-xs-center to text-center because xs is dropped in Bootstrap 4.

This One will work perfectly fine

<!-- Use this inside Head tag-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>



<!-- Use this inside Body tag-->
<div  class="container">
<ul class="list-inline">
<li class="list-inline-item"><a class="social-icon text-center" target="_blank" href="#">FB</a></li>
<li class="list-inline-item"><a class="social-icon text-center" target="_blank" href="#">G+</a></li>
<li class="list-inline-item"><a class="social-icon text-center" target="_blank" href="#">T</a></li>
</ul>
</div>

Android Respond To URL in Intent

I did it! Using <intent-filter>. Put the following into your manifest file:

<intent-filter>
  <action android:name="android.intent.action.VIEW" />
  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.BROWSABLE" />
  <data android:host="www.youtube.com" android:scheme="http" />
</intent-filter>

This works perfectly!

How do I detect the Python version at runtime?

Try this code, this should work:

import platform
print(platform.python_version())

How to reference a .css file on a razor view?

You can this structure in Layout.cshtml file

<link href="~/YourCssFolder/YourCssStyle.css" rel="stylesheet" type="text/css" />

Laravel Eloquent update just if changes have been made

You're already doing it!

save() will check if something in the model has changed. If it hasn't it won't run a db query.

Here's the relevant part of code in Illuminate\Database\Eloquent\Model@performUpdate:

protected function performUpdate(Builder $query, array $options = [])
{
    $dirty = $this->getDirty();

    if (count($dirty) > 0)
    {
        // runs update query
    }

    return true;
}

The getDirty() method simply compares the current attributes with a copy saved in original when the model is created. This is done in the syncOriginal() method:

public function __construct(array $attributes = array())
{
    $this->bootIfNotBooted();

    $this->syncOriginal();

    $this->fill($attributes);
}

public function syncOriginal()
{
    $this->original = $this->attributes;

    return $this;
}

If you want to check if the model is dirty just call isDirty():

if($product->isDirty()){
    // changes have been made
}

Or if you want to check a certain attribute:

if($product->isDirty('price')){
    // price has changed
}

android: data binding error: cannot find symbol class

Make sure the name for your model and the reference have the same name:

For example, name="item" must match android:checked="@={item.checked}"

<data>
    <variable
        name="item"
        type="com.simone.mywordlist.model.MyModel" />
</data>

            <Switch
                android:id="@+id/my_switch"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="@={item.checked}"
            />

Arrays vs Vectors: Introductory Similarities and Differences

Those reference pretty much answered your question. Simply put, vectors' lengths are dynamic while arrays have a fixed size. when using an array, you specify its size upon declaration:

int myArray[100];
myArray[0]=1;
myArray[1]=2;
myArray[2]=3;

for vectors, you just declare it and add elements

vector<int> myVector;
myVector.push_back(1);
myVector.push_back(2);
myVector.push_back(3);
...

at times you wont know the number of elements needed so a vector would be ideal for such a situation.

How to get the sign, mantissa and exponent of a floating point number

Cast a pointer to the floating point variable as something like an unsigned int. Then you can shift and mask the bits to get each component.

float foo;
unsigned int ival, mantissa, exponent, sign;

foo = -21.4f;
ival = *((unsigned int *)&foo);
mantissa = ( ival & 0x7FFFFF);
ival = ival >> 23;
exponent = ( ival  & 0xFF );
ival = ival >> 8;
sign = ( ival & 0x01 );

Obviously you probably wouldn't use unsigned ints for the exponent and sign bits but this should at least give you the idea.

Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

I use this way with Resource file (don't need Prompt anymore !)

@Html.TextBoxFor(m => m.Name, new 
{
     @class = "form-control",
     placeholder = @Html.DisplayName(@Resource.PleaseTypeName),
     autofocus = "autofocus",
     required = "required"
})

Detect changes in the DOM

I have recently written a plugin that does exactly that - jquery.initialize

You use it the same way as .each function

$(".some-element").initialize( function(){
    $(this).css("color", "blue"); 
});

The difference from .each is - it takes your selector, in this case .some-element and wait for new elements with this selector in the future, if such element will be added, it will be initialized too.

In our case initialize function just change element color to blue. So if we'll add new element (no matter if with ajax or even F12 inspector or anything) like:

$("<div/>").addClass('some-element').appendTo("body"); //new element will have blue color!

Plugin will init it instantly. Also plugin makes sure one element is initialized only once. So if you add element, then .detach() it from body and then add it again, it will not be initialized again.

$("<div/>").addClass('some-element').appendTo("body").detach()
    .appendTo(".some-container");
//initialized only once

Plugin is based on MutationObserver - it will work on IE9 and 10 with dependencies as detailed on the readme page.

Regular expression for checking if capital letters are found consecutively in a string?

Aside from tchrists excellent post concerning unicode, I think you don't need the complex solution with a negative lookahead... Your definition requires an Uppercase-letter followed by at least one group of (a lowercase letter optionally followed by an Uppercase-letter)

^
[A-Z]    // Start with an uppercase Letter
(        // A Group of:
  [a-z]  // mandatory lowercase letter
  [A-Z]? // an optional Uppercase Letter at the end
         // or in between lowercase letters
)+       // This group at least one time
$

Just a bit more compact and easier to read I think...

What is a good naming convention for vars, methods, etc in C++?

There are many different sytles/conventions that people use when coding C++. For example, some people prefer separating words using capitals (myVar or MyVar), or using underscores (my_var). Typically, variables that use underscores are in all lowercase (from my experience).
There is also a coding style called hungarian, which I believe is used by microsoft. I personally believe that it is a waste of time, but it may prove useful. This is were variable names are given short prefixes such as i, or f to hint the variables type. For example: int iVarname, char* strVarname.

It is accepted that you end a struct/class name with _t, to differentiate it from a variable name. E.g.:

class cat_t {
  ...
};

cat_t myCat;

It is also generally accepted to add a affix to indicate pointers, such as pVariable or variable_p.

In all, there really isn't any single standard, but many. The choices you make about naming your variables doesn't matter, so long as it is understandable, and above all, consistent. Consistency, consistency, CONSISTENCY! (try typing that thrice!)

And if all else fails, google it.

Sorting table rows according to table header column using javascript or jquery

You might want to see this page:
http://blog.niklasottosson.com/?p=1914

I guess you can go something like this:

DEMO:http://jsfiddle.net/g9eL6768/2/

HTML:

 <table id="mytable"><thead>
  <tr>
     <th id="sl">S.L.</th>
     <th id="nm">name</th>
  </tr>
   ....

JS:

//  sortTable(f,n)
//  f : 1 ascending order, -1 descending order
//  n : n-th child(<td>) of <tr>
function sortTable(f,n){
    var rows = $('#mytable tbody  tr').get();

    rows.sort(function(a, b) {

        var A = getVal(a);
        var B = getVal(b);

        if(A < B) {
            return -1*f;
        }
        if(A > B) {
            return 1*f;
        }
        return 0;
    });

    function getVal(elm){
        var v = $(elm).children('td').eq(n).text().toUpperCase();
        if($.isNumeric(v)){
            v = parseInt(v,10);
        }
        return v;
    }

    $.each(rows, function(index, row) {
        $('#mytable').children('tbody').append(row);
    });
}
var f_sl = 1; // flag to toggle the sorting order
var f_nm = 1; // flag to toggle the sorting order
$("#sl").click(function(){
    f_sl *= -1; // toggle the sorting order
    var n = $(this).prevAll().length;
    sortTable(f_sl,n);
});
$("#nm").click(function(){
    f_nm *= -1; // toggle the sorting order
    var n = $(this).prevAll().length;
    sortTable(f_nm,n);
});

Hope this helps.

Safari 3rd party cookie iframe trick no longer working?

I decided to get rid of the $_SESSION variable all together & wrote a wrapper around memcache to mimic the session.

Check https://github.com/manpreetssethi/utils/blob/master/Session_manager.php

Use-case: The moment a user lands on the app, store the signed request using the Session_manager and since it's in the cache, you may access it on any page henceforth.

Note: This will not work when browsing privately in Safari since the session_id resets every time the page reloads. (Stupid Safari)

How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

Try this

myApp.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }
]);

Just setting useXDomain = true is not enough. AJAX request are also send with the X-Requested-With header, which indicate them as being AJAX. Removing the header is necessary, so the server is not rejecting the incoming request.

Joining Multiple Tables - Oracle

You are doing a cartesian join. This means that if you wouldn't have even have the single where clause, the number of results you get would be book_customer size times books size times book_order size times publisher size.

In order words, the result set gets blown up because you didn't add meaningful join clauses. Your correct query should look something like this:

SELECT bc.firstname, bc.lastname, b.title, TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order Date", p.publishername
FROM book_customer bc, books b, book_order bo, publisher p
WHERE bc.book_id = b.book_id
AND bo.book_id = b.book_id
(etc.)
AND publishername = 'PRINTING IS US';

Note: usually it is adviced to not use the implicit joins like in this query, but use the INNER JOIN syntax. I am assuming however, that this syntax is used in your study material so I've left it in.

How to check all checkboxes using jQuery?

$('#checkAll').on('change', function(){
    if($(this).attr('checked')){
        $('input[type=checkbox]').attr('checked',true);
    }
    else{
        $('input[type=checkbox]').removeAttr('checked');
    }
});

How can I change the Bootstrap default font family using font from Google?

I know this is a late answer but you could manually change the 7 font declarations in the latest version of Bootstrap:

html {
  font-family: sans-serif;
}

body {
  font-family: sans-serif;
}

pre, code, kbd, samp {
  font-family: monospace;
}

input, button, select, optgroup, textarea {
  font-family: inherit;
}

.tooltip {
  font-family: sans-serif;
}

.popover {
  font-family: sans-serif;
}

.text-monospace {
  font-family: monospace;
}

Good luck.

How to check if a string contains a specific text

If you need to know if a word exists in a string you can use this. As it is not clear from your question if you just want to know if the variable is a string or not. Where 'word' is the word you are searching in the string.

if (strpos($a,'word') !== false) {
echo 'true';
}

or use the is_string method. Whichs returns true or false on the given variable.

<?php
$a = '';
is_string($a);
?>

How to get data by SqlDataReader.GetValue by column name

Log.WriteLine("Value of CompanyName column:" + thisReader["CompanyName"]); 

JQuery datepicker language

Try Adding this

$('input[name="daterangepicker"]').daterangepicker({

   "locale": {
    "firstDay" :1 // 0 Tuesday - 6 - Monday between
         }});

It must be completed within the locale object of the defined daterangepicker. detailed information can be found here.

Resize iframe height according to content height in it

Try using scrolling=no attribute on the iframe tag. Mozilla also has an overflow-x and overflow-y CSS property you may look into.

In terms of the height, you could also try height=100% on the iframe tag.

How to store a list in a column of a database table

I'd just store it as CSV, if it's simple values then it should be all you need (XML is very verbose and serializing to/from it would probably be overkill but that would be an option as well).

Here's a good answer for how to pull out CSVs with LINQ.

Why the switch statement cannot be applied on strings?

To add a variation using the simplest container possible (no need for an ordered map)... I wouldn't bother with an enum--just put the container definition immediately before the switch so it'll be easy to see which number represents which case.

This does a hashed lookup in the unordered_map and uses the associated int to drive the switch statement. Should be quite fast. Note that at is used instead of [], as I've made that container const. Using [] can be dangerous--if the string isn't in the map, you'll create a new mapping and may end up with undefined results or a continuously growing map.

Note that the at() function will throw an exception if the string isn't in the map. So you may want to test first using count().

const static std::unordered_map<std::string,int> string_to_case{
   {"raj",1},
   {"ben",2}
};
switch(string_to_case.at("raj")) {
  case 1: // this is the "raj" case
       break;
  case 2: // this is the "ben" case
       break;


}

The version with a test for an undefined string follows:

const static std::unordered_map<std::string,int> string_to_case{
   {"raj",1},
   {"ben",2}
};
// in C++20, you can replace .count with .contains
switch(string_to_case.count("raj") ? string_to_case.at("raj") : 0) {
  case 1: // this is the "raj" case
       break;
  case 2: // this is the "ben" case
       break;
  case 0: //this is for the undefined case

}

Changing the page title with Jquery

There's no need to use jQuery to change the title. Try:

document.title = "blarg";

See this question for more details.

To dynamically change on button click:

$(selectorForMyButton).click(function(){
    document.title = "blarg";
});

To dynamically change in loop, try:

var counter = 0;

var titleTimerId = setInterval(function(){
    document.title = document.title + '>';
    counter++;
    if(counter == 5){
        clearInterval(titleTimerId);
    }
}, 100);

To string the two together so that it dynamically changes on button click, in a loop:

var counter = 0;

$(selectorForMyButton).click(function(){
  titleTimerId = setInterval(function(){
    document.title = document.title + '>';
    counter++;
    if(counter == 5){
        clearInterval(titleTimerId);
    }
  }, 100);
});

Format numbers to strings in Python

Starting in Python 2.6, there is an alternative: the str.format() method. Here are some examples using the existing string format operator (%):

>>> "Name: %s, age: %d" % ('John', 35) 
'Name: John, age: 35' 
>>> i = 45 
>>> 'dec: %d/oct: %#o/hex: %#X' % (i, i, i) 
'dec: 45/oct: 055/hex: 0X2D' 
>>> "MM/DD/YY = %02d/%02d/%02d" % (12, 7, 41) 
'MM/DD/YY = 12/07/41' 
>>> 'Total with tax: $%.2f' % (13.00 * 1.0825) 
'Total with tax: $14.07' 
>>> d = {'web': 'user', 'page': 42} 
>>> 'http://xxx.yyy.zzz/%(web)s/%(page)d.html' % d 
'http://xxx.yyy.zzz/user/42.html' 

Here are the equivalent snippets but using str.format():

>>> "Name: {0}, age: {1}".format('John', 35) 
'Name: John, age: 35' 
>>> i = 45 
>>> 'dec: {0}/oct: {0:#o}/hex: {0:#X}'.format(i) 
'dec: 45/oct: 0o55/hex: 0X2D' 
>>> "MM/DD/YY = {0:02d}/{1:02d}/{2:02d}".format(12, 7, 41) 
'MM/DD/YY = 12/07/41' 
>>> 'Total with tax: ${0:.2f}'.format(13.00 * 1.0825) 
'Total with tax: $14.07' 
>>> d = {'web': 'user', 'page': 42} 
>>> 'http://xxx.yyy.zzz/{web}/{page}.html'.format(**d) 
'http://xxx.yyy.zzz/user/42.html'

Like Python 2.6+, all Python 3 releases (so far) understand how to do both. I shamelessly ripped this stuff straight out of my hardcore Python intro book and the slides for the Intro+Intermediate Python courses I offer from time-to-time. :-)

Aug 2018 UPDATE: Of course, now that we have the f-string feature in 3.6, we need the equivalent examples of that, yes another alternative:

>>> name, age = 'John', 35
>>> f'Name: {name}, age: {age}'
'Name: John, age: 35'

>>> i = 45
>>> f'dec: {i}/oct: {i:#o}/hex: {i:#X}'
'dec: 45/oct: 0o55/hex: 0X2D'

>>> m, d, y = 12, 7, 41
>>> f"MM/DD/YY = {m:02d}/{d:02d}/{y:02d}"
'MM/DD/YY = 12/07/41'

>>> f'Total with tax: ${13.00 * 1.0825:.2f}'
'Total with tax: $14.07'

>>> d = {'web': 'user', 'page': 42}
>>> f"http://xxx.yyy.zzz/{d['web']}/{d['page']}.html"
'http://xxx.yyy.zzz/user/42.html'

Creating a BLOB from a Base64 string in JavaScript

See this example: https://jsfiddle.net/pqhdce2L/

_x000D_
_x000D_
function b64toBlob(b64Data, contentType, sliceSize) {_x000D_
  contentType = contentType || '';_x000D_
  sliceSize = sliceSize || 512;_x000D_
_x000D_
  var byteCharacters = atob(b64Data);_x000D_
  var byteArrays = [];_x000D_
_x000D_
  for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {_x000D_
    var slice = byteCharacters.slice(offset, offset + sliceSize);_x000D_
_x000D_
    var byteNumbers = new Array(slice.length);_x000D_
    for (var i = 0; i < slice.length; i++) {_x000D_
      byteNumbers[i] = slice.charCodeAt(i);_x000D_
    }_x000D_
_x000D_
    var byteArray = new Uint8Array(byteNumbers);_x000D_
_x000D_
    byteArrays.push(byteArray);_x000D_
  }_x000D_
    _x000D_
  var blob = new Blob(byteArrays, {type: contentType});_x000D_
  return blob;_x000D_
}_x000D_
_x000D_
_x000D_
var contentType = 'image/png';_x000D_
var b64Data = Your Base64 encode;_x000D_
_x000D_
var blob = b64toBlob(b64Data, contentType);_x000D_
var blobUrl = URL.createObjectURL(blob);_x000D_
_x000D_
var img = document.createElement('img');_x000D_
img.src = blobUrl;_x000D_
document.body.appendChild(img);
_x000D_
_x000D_
_x000D_

Printing a 2D array in C

Is this any help?

#include <stdio.h>

#define MAX 10

int main()
{
    char grid[MAX][MAX];
    int i,j,row,col;

    printf("Please enter your grid size: ");
    scanf("%d %d", &row, &col);


    for (i = 0; i < row; i++) {
        for (j = 0; j < col; j++) {
            grid[i][j] = '.';
            printf("%c ", grid[i][j]);
        }
        printf("\n");
    }

    return 0;
}

What is a file with extension .a?

.a files are created with the ar utility, and they are libraries. To use it with gcc, collect all .a files in a lib/ folder and then link with -L lib/ and -l<name of specific library>.

Collection of all .a files into lib/ is optional. Doing so makes for better looking directories with nice separation of code and libraries, IMHO.

CSS Circle with border

Here is a jsfiddle so you can see an example of this working.

HTML code:

<div class="circle"></div>

CSS code:

_x000D_
_x000D_
.circle {_x000D_
        /*This creates a 1px solid red border around your element(div) */_x000D_
        border:1px solid red;_x000D_
        background-color: #FFFFFF;_x000D_
        height: 100px;_x000D_
        /* border-radius 50% will make it fully rounded. */_x000D_
        border-radius: 50%;_x000D_
        -moz-border-radius:50%;_x000D_
        -webkit-border-radius: 50%;_x000D_
        width: 100px;_x000D_
    }
_x000D_
<div class='circle'></div>
_x000D_
_x000D_
_x000D_

Get a list of dates between two dates

Typically one would use an auxiliary numbers table you usually keep around for just this purpose with some variation on this:

SELECT *
FROM (
    SELECT DATEADD(d, number - 1, '2009-01-01') AS dt
    FROM Numbers
    WHERE number BETWEEN 1 AND DATEDIFF(d, '2009-01-01', '2009-01-13') + 1
) AS DateRange
LEFT JOIN YourStuff
    ON DateRange.dt = YourStuff.DateColumn

I've seen variations with table-valued functions, etc.

You can also keep a permanent list of dates. We have that in our data warehouse as well as a list of times of day.

List all column except for one in R

In addition to tcash21's numeric indexing if OP may have been looking for negative indexing by name. Here's a few ways I know, some are risky than others to use:

mtcars[, -which(names(mtcars) == "carb")]  #only works on a single column
mtcars[, names(mtcars) != "carb"]          #only works on a single column
mtcars[, !names(mtcars) %in% c("carb", "mpg")] 
mtcars[, -match(c("carb", "mpg"), names(mtcars))] 
mtcars2 <- mtcars; mtcars2$hp <- NULL         #lost column (risky)


library(gdata) 
remove.vars(mtcars2, names=c("mpg", "carb"), info=TRUE) 

Generally I use:

mtcars[, !names(mtcars) %in% c("carb", "mpg")] 

because I feel it's safe and efficient.

Spring cron expression for every after 30 minutes

<property name="cronExpression" value="0 0/30 * * * ?" />

How do I open a new fragment from another fragment?

@Override
public void onListItemClick(ListView l, View v, int pos, long id) {
    super.onListItemClick(l, v, pos, id);
    UserResult nextFrag= new UserResult();
    this.getFragmentManager().beginTransaction()
    .replace(R.id.content_frame, nextFrag, null)
    .addToBackStack(null)
    .commit();  
}

Unsafe JavaScript attempt to access frame with URL

I found that using the XFBML version of the Facebook like button instead of the HTML5 version fixed this problem. Add the below code where you want the button to appear:

<div id="fb-root"></div>
<script>(function (d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

<fb:like send="true" layout="button_count" width="50" show_faces="false" font="arial"></fb:like>

Then add this to your HTML tag:

 xmlns:fb="http://ogp.me/ns/fb#"

When should I use curly braces for ES6 import?

If you think of import as just syntax sugar for Node.js modules, objects, and destructuring, I find it's pretty intuitive.

// bar.js
module = {};

module.exports = {
  functionA: () => {},
  functionB: ()=> {}
};

 // Really all that is is this:
 var module = {
   exports: {
      functionA, functionB
   }
  };

// Then, over in foo.js

// The whole exported object:
var fump = require('./bar.js'); //= { functionA, functionB }
// Or
import fump from './bar' // The same thing - object functionA and functionB properties


// Just one property of the object
var fump = require('./bar.js').functionA;

// Same as this, right?
var fump = { functionA, functionB }.functionA;

// And if we use ES6 destructuring:
var { functionA } =  { functionA, functionB };
// We get same result

// So, in import syntax:
import { functionA } from './bar';

WebService Client Generation Error with JDK8

If you are using ant you can add a jvmarg to your java calls:

<jvmarg value="-Djavax.xml.accessExternalSchema=all" />

A Simple, 2d cross-platform graphics library for c or c++?

One neat engine I came across is Angel-Engine. Info from the project site:

  • Cross-Platform functionality (Windows and Mac)
  • Actors (game objects with color, shape, responses, attributes, etc.)
  • Texturing with Transparency
  • "Animations" (texture swapping at defined intervals)
  • Rigid-Body Physics
    • A clever programmer can do soft-body physics with it
  • Sound
  • Text Rendering with multiple fonts
  • Particle Systems
  • Some basic AI (state machine and pathfinding)
  • Config File Processing
  • Logging
  • Input from a mouse, keyboard, or Xbox 360 controller
    • Binding inputs from a config file
  • Python Scripting
    • In-Game Console

Some users (including me) have succesfully (without any major problems) compiled it under linux.

'App not Installed' Error on Android

I had the same type of error this was cauysed by this line in my android manifest XML file.

android:permission="android.permission.INSTALL_LOCATION_PROVIDER"

I removed the line and it solved my issue. Hope this helps

Disable XML validation in Eclipse

In JBoss Developer 4.0 and above (Eclipse-based), this is a tad easier. Just right-click on your file or folder that contains xml-based files, choose "Exclude Validation", then click "Yes" to confirm. Then right-click the same files/folder again and click on "Validate", which will remove the errors with a confirmation.

Invalid default value for 'create_date' timestamp field

Default values should start from the year 1000.

For example,

ALTER TABLE mytable last_active DATETIME DEFAULT '1000-01-01 00:00:00'

Hope this helps someone.

Safely remove migration In Laravel

I agree with the current answers, I just wanna add little more information.

A new feature has been added to Laravel 5.3 and above version that will allow you to back out a single migration:

php artisan migrate:rollback --step=1

after, Manually delete the migration file under database/migrations/my_migration_file_name.php

This is a great feature for when you run a migration

In this way, you can safely remove the migration in laravel only in 2 step

SQL Server: Maximum character length of object names

128 characters. This is the max length of the sysname datatype (nvarchar(128)).

kubectl apply vs kubectl create?

kubectl create can work with one object configuration file at a time. This is also known as imperative management

kubectl create -f filename|url

kubectl apply works with directories and its sub directories containing object configuration yaml files. This is also known as declarative management. Multiple object configuration files from directories can be picked up. kubectl apply -f directory/

Details :
https://kubernetes.io/docs/tasks/manage-kubernetes-objects/declarative-config/ https://kubernetes.io/docs/tasks/manage-kubernetes-objects/imperative-config/

ASP.Net 2012 Unobtrusive Validation with jQuery

Add a reference to Microsoft.JScript in your application in your web.config as below :

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <add assembly="Microsoft.JScript, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="none"/>
  </appSettings>
</configuration>

Cleanest way to build an SQL string in Java

I am wondering if you are after something like Squiggle. Also something very useful is jDBI. It won't help you with the queries though.

$(document).ready(function() is not working

see for your js path that may be the causing issue...because You only get this error if jQuery is not correctly loaded.

How to call jQuery function onclick?

try this:

$('form').submit(function(){
    // this function will be raised when submit button is clicked.
    // perform submit operations here
});

Error You must specify a region when running command aws ecs list-container-instances

"You must specify a region" is a not an ECS specific error, it can happen with any AWS API/CLI/SDK command.

For the CLI, either set the AWS_DEFAULT_REGION environment variable. e.g.

export AWS_DEFAULT_REGION=us-east-1

or add it into the command (you will need this every time you use a region-specific command)

AWS_DEFAULT_REGION=us-east-1 aws ecs list-container-instances --cluster default

or set it in the CLI configuration file: ~/.aws/config

[default]
region=us-east-1

or pass/override it with the CLI call:

aws ecs list-container-instances --cluster default --region us-east-1

Show SOME invisible/whitespace characters in Eclipse

I would prefer to keep the "Show Whitespace" button on the toolbar, so that in one click you can toggle it.

Go to Window -> Perspective -> Customize Perspective and enable to show the button on toolbar.

enter image description here

Translating touch events from Javascript to jQuery

jQuery 'fixes up' events to account for browser differences. When it does so, you can always access the 'native' event with event.originalEvent (see the Special Properties subheading on this page).

How to enable loglevel debug on Apache2 server

Do note that on newer Apache versions the RewriteLog and RewriteLogLevel have been removed, and in fact will now trigger an error when trying to start Apache (at least on my XAMPP installation with Apache 2.4.2):

AH00526: Syntax error on line xx of path/to/config/file.conf: Invalid command 'RewriteLog', perhaps misspelled or defined by a module not included in the server configuration`

Instead, you're now supposed to use the general LogLevel directive, with a level of trace1 up to trace8. 'debug' didn't display any rewrite messages in the log for me.

Example: LogLevel warn rewrite:trace3

For the official documentation, see here.

Of course this also means that now your rewrite logs will be written in the general error log file and you'll have to sort them out yourself.

Intellij Idea: Importing Gradle project - getting JAVA_HOME not defined yet

For MacOS this worked for me without the need to hardcode a particular Java version:

launchctl setenv JAVA_HOME "$(jenv javahome)"