Programs & Examples On #Database diagram

0

How to get Current Directory?

Code snippets from my CAE project with unicode development environment:

/// @brief Gets current module file path. 
std::string getModuleFilePath() {
    TCHAR buffer[MAX_PATH];
    GetModuleFileName( NULL, buffer, MAX_PATH );
    CT2CA pszPath(buffer);
    std::string path(pszPath);
    std::string::size_type pos = path.find_last_of("\\/");
    return path.substr( 0, pos);
}

Just use the templete CA2CAEX or CA2AEX which calls the internal API ::MultiByteToWideChar or ::WideCharToMultiByte?

Find all elements on a page whose element ID contains a certain text using jQuery

If you're finding by Contains then it'll be like this

    $("input[id*='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you're finding by Starts With then it'll be like this

    $("input[id^='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you're finding by Ends With then it'll be like this

     $("input[id$='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which id is not a given string

    $("input[id!='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which name contains a given word, delimited by spaces

     $("input[name~='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which id is equal to a given string or starting with that string followed by a hyphen

     $("input[id|='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

How to ignore PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException?

Set validateTLSCertificates property to false for your JSoup command.

Jsoup.connect("https://google.com/").validateTLSCertificates(false).get();

Auto expand a textarea using jQuery

I just built this function to expand textareas on pageload. Just change each to keyup and it will occur when the textarea is typed in.

// On page-load, auto-expand textareas to be tall enough to contain initial content
$('textarea').each(function(){
    var pad = parseInt($(this).css('padding-top'));
    if ($.browser.mozilla) 
        $(this).height(1);
    var contentHeight = this.scrollHeight;
    if (!$.browser.mozilla) 
        contentHeight -= pad * 2;
    if (contentHeight > $(this).height()) 
        $(this).height(contentHeight);
});

Tested in Chrome, IE9 and Firefox. Unfortunately Firefox has this bug which returns the incorrect value for scrollHeight, so the above code contains a (hacky) workaround for it.

PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)

As I know, PDO_MYSQLND replaced PDO_MYSQL in PHP 5.3. Confusing part is that name is still PDO_MYSQL. So now ND is default driver for MySQL+PDO.

Overall, to execute multiple queries at once you need:

  • PHP 5.3+
  • mysqlnd
  • Emulated prepared statements. Make sure PDO::ATTR_EMULATE_PREPARES is set to 1 (default). Alternatively you can avoid using prepared statements and use $pdo->exec directly.

Using exec

$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');

// works regardless of statements emulation
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 0);

$sql = "
DELETE FROM car; 
INSERT INTO car(name, type) VALUES ('car1', 'coupe'); 
INSERT INTO car(name, type) VALUES ('car2', 'coupe');
";

$db->exec($sql);

Using statements

$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');

// works not with the following set to 0. You can comment this line as 1 is default
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);

$sql = "
DELETE FROM car; 
INSERT INTO car(name, type) VALUES ('car1', 'coupe'); 
INSERT INTO car(name, type) VALUES ('car2', 'coupe');
";

$stmt = $db->prepare($sql);
$stmt->execute();

A note:

When using emulated prepared statements, make sure you have set proper encoding (that reflects actual data encoding) in DSN (available since 5.3.6). Otherwise there can be a slight possibility for SQL injection if some odd encoding is used.

How do I get the domain originating the request in express.js?

You have to retrieve it from the HOST header.

var host = req.get('host');

It is optional with HTTP 1.0, but required by 1.1. And, the app can always impose a requirement of its own.


If this is for supporting cross-origin requests, you would instead use the Origin header.

var origin = req.get('origin');

Note that some cross-origin requests require validation through a "preflight" request:

req.options('/route', function (req, res) {
    var origin = req.get('origin');
    // ...
});

If you're looking for the client's IP, you can retrieve that with:

var userIP = req.socket.remoteAddress;

Note that, if your server is behind a proxy, this will likely give you the proxy's IP. Whether you can get the user's IP depends on what info the proxy passes along. But, it'll typically be in the headers as well.

How to refresh activity after changing language (Locale) inside application

After changing language newly created activities display with changed new language, but current activity and previously created activities which are in pause state are not updated.How to update activities ?

Pre API 11 (Honeycomb), the simplest way to make the existing activities to be displayed in new language is to restart it. In this way you don't bother to reload each resources by yourself.

private void restartActivity() {
    Intent intent = getIntent();
    finish();
    startActivity(intent);
}

Register an OnSharedPreferenceChangeListener, in its onShredPreferenceChanged(), invoke restartActivity() if language preference was changed. In my example, only the PreferenceActivity is restarted, but you should be able to restart other activities on activity resume by setting a flag.

Update (thanks @stackunderflow): As of API 11 (Honeycomb) you should use recreate() instead of restartActivity().

public class PreferenceActivity extends android.preference.PreferenceActivity implements
        OnSharedPreferenceChangeListener {

    // ...

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (key.equals("pref_language")) {
            ((Application) getApplication()).setLocale();
            restartActivity();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
    }
}

I have a blog post on this topic with more detail, but it's in Chinese. The full source code is on github: PreferenceActivity.java

How to restore PostgreSQL dump file into Postgres databases?

The problem with your attempt at the psql command line is the direction of the slashes:

newTestDB-# /i E:\db-rbl-restore-20120511_Dump-20120514.sql   # incorrect
newTestDB-# \i E:/db-rbl-restore-20120511_Dump-20120514.sql   # correct

To be clear, psql commands start with a backslash, so you should have put \i instead. What happened as a result of your typo is that psql ignored everything until finding the first \, which happened to be followed by db, and \db happens to be the psql command for listing table spaces, hence why the output was a List of tablespaces. It was not a listing of "default tables of PostgreSQL" as you said.

Further, it seems that psql expects the filepath argument to delimit directories using the forward slash regardless of OS (thus on Windows this would be counter-intuitive).

It is worth noting that your attempt at "elevating permissions" had no relation to the outcome of the command you attempted to execute. Also, you did not say what caused the supposed "Permission Denied" error.

Finally, the extension on the dump file does not matter, in fact you don't even need an extension. Indeed, pgAdmin suggests a .backup extension when selecting a backup filename, but you can actually make it whatever you want, again, including having no extension at all. The problem is that pgAdmin seems to only allow a "Restore" of "Custom or tar" or "Directory" dumps (at least this is the case in the MAC OS X version of the app), so just use the psql \i command as shown above.

CodeIgniter: 404 Page Not Found on Live Server

I had the same problem. Changing controlers first letter to uppercase helped.

Access cell value of datatable

You can also try (first cell in 4th column):

dt.Rows[0][3]

np.mean() vs np.average() in Python NumPy?

In addition to the differences already noted, there's another extremely important difference that I just now discovered the hard way: unlike np.mean, np.average doesn't allow the dtype keyword, which is essential for getting correct results in some cases. I have a very large single-precision array that is accessed from an h5 file. If I take the mean along axes 0 and 1, I get wildly incorrect results unless I specify dtype='float64':

>T.shape
(4096, 4096, 720)
>T.dtype
dtype('<f4')

m1 = np.average(T, axis=(0,1))                #  garbage
m2 = np.mean(T, axis=(0,1))                   #  the same garbage
m3 = np.mean(T, axis=(0,1), dtype='float64')  # correct results

Unfortunately, unless you know what to look for, you can't necessarily tell your results are wrong. I will never use np.average again for this reason but will always use np.mean(.., dtype='float64') on any large array. If I want a weighted average, I'll compute it explicitly using the product of the weight vector and the target array and then either np.sum or np.mean, as appropriate (with appropriate precision as well).

Equal sized table cells to fill the entire width of the containing table

Using table-layout: fixed as a property for table and width: calc(100%/3); for td (assuming there are 3 td's). With these two properties set, the table cells will be equal in size.

Refer to the demo.

Cannot read property 'length' of null (javascript)

I tried this:

if(capital !== null){ 
//Capital has something 
}

How can I tail a log file in Python?

If you are on linux you implement a non-blocking implementation in python in the following way.

import subprocess
subprocess.call('xterm -title log -hold -e \"tail -f filename\"&', shell=True, executable='/bin/csh')
print "Done"

Duplicate line in Visual Studio Code

Windows:

Duplicate Line Down : Ctrl + Shift + D

Injecting Mockito mocks into a Spring bean

Today I found out that a spring context where I declared a before the Mockito beans, was failing to load. After moving the AFTER the mocks, the app context was loaded successfully. Take care :)

Ant if else condition?

Since ant 1.9.1 you can use a if:set condition : https://ant.apache.org/manual/ifunless.html

Proper way to restrict text input values (e.g. only numbers)

Tested Answer By me:

form.html

<input type="text" (keypress)="restrictNumeric($event)">

form.component.ts:

public restrictNumeric(e) {
  let input;
  if (e.metaKey || e.ctrlKey) {
    return true;
  }
  if (e.which === 32) {
   return false;
  }
  if (e.which === 0) {
   return true;
  }
  if (e.which < 33) {
    return true;
  }
  input = String.fromCharCode(e.which);
  return !!/[\d\s]/.test(input);
 }

How to pass variable from jade template file to a script file?

See this question: JADE + EXPRESS: Iterating over object in inline JS code (client-side)?

I'm having the same problem. Jade does not pass local variables in (or do any templating at all) to javascript scripts, it simply passes the entire block in as literal text. If you use the local variables 'address' and 'port' in your Jade file above the script tag they should show up.

Possible solutions are listed in the question I linked to above, but you can either: - pass every line in as unescaped text (!= at the beginning of every line), and simply put "-" before every line of javascript that uses a local variable, or: - Pass variables in through a dom element and access through JQuery (ugly)

Is there no better way? It seems the creators of Jade do not want multiline javascript support, as shown by this thread in GitHub: https://github.com/visionmedia/jade/pull/405

Div show/hide media query

I'm not sure, what you mean as the 'mobile width'. But in each case, the CSS @media can be used for hiding elements in the screen width basis. See some example:

<div id="my-content"></div>

...and:

@media screen and (min-width: 0px) and (max-width: 400px) {
  #my-content { display: block; }  /* show it on small screens */
}

@media screen and (min-width: 401px) and (max-width: 1024px) {
  #my-content { display: none; }   /* hide it elsewhere */
}

Some truly mobile detection is kind of hard programming and rather difficult. Eventually see the: http://detectmobilebrowsers.com/ or other similar sources.

SQL Logic Operator Precedence: And and Or

And has precedence over Or, so, even if a <=> a1 Or a2

Where a And b 

is not the same as

Where a1 Or a2 And b,

because that would be Executed as

Where a1 Or (a2 And b)

and what you want, to make them the same, is the following (using parentheses to override rules of precedence):

 Where (a1 Or a2) And b

Here's an example to illustrate:

Declare @x tinyInt = 1
Declare @y tinyInt = 0
Declare @z tinyInt = 0

Select Case When @x=1 OR @y=1 And @z=1 Then 'T' Else 'F' End -- outputs T
Select Case When (@x=1 OR @y=1) And @z=1 Then 'T' Else 'F' End -- outputs F

For those who like to consult references (in alphabetic order):

Node.js/Windows error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm'

Install a stable version instead of the latest one, I have downgrade my version to node-v0.10.29-x86.msi from 'node-v0.10.33-x86.msi' and it is working well for me!

http://blog.nodejs.org/2014/06/16/node-v0-10-29-stable/

Java generating Strings with placeholders

If you can tolerate a different kind of placeholder (i.e. %s in place of {}) you can use String.format method for that:

String s = "hello %s!";
s = String.format(s, "world" );
assertEquals(s, "hello world!"); // true

How to delete a cookie using jQuery?

Worked for me only when path was set, i.e.:

$.cookie('name', null, {path:'/'})

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

There's now a simpler way with .NET Standard or .NET Core:

var client = new HttpClient();
var response = await client.PostAsync(uri, myRequestObject, new JsonMediaTypeFormatter());

NOTE: In order to use the JsonMediaTypeFormatter class, you will need to install the Microsoft.AspNet.WebApi.Client NuGet package, which can be installed directly, or via another such as Microsoft.AspNetCore.App.

Using this signature of HttpClient.PostAsync, you can pass in any object and the JsonMediaTypeFormatter will automatically take care of serialization etc.

With the response, you can use HttpContent.ReadAsAsync<T> to deserialize the response content to the type that you are expecting:

var responseObject = await response.Content.ReadAsAsync<MyResponseType>();

How to Diff between local uncommitted changes and origin

I know it's not an answer to the exact question asked, but I found this question looking to diff a file in a branch and a local uncommitted file and I figured I would share

Syntax:

git diff <commit-ish>:./ -- <path>

Examples:

git diff origin/master:./ -- README.md
git diff HEAD^:./ -- README.md
git diff stash@{0}:./ -- README.md
git diff 1A2B3C4D:./ -- README.md

(Thanks Eric Boehs for a way to not have to type the filename twice)

Changing API level Android Studio

For me what worked was: (right click)project->android tools->clear lint markers. Although for some reason the Manifest reverted to the old (lower) minimum API level, but after I changed it back to the new (higher) API level there was no red error underline and the project now uses the new minimum API level.

Edit: Sorry, I see you were using Android Studio, not Eclipse. But I guess there is a similar 'clear lint markers' in Studio somewhere and it might solve the problem.

HttpServlet cannot be resolved to a type .... is this a bug in eclipse?

You have to set the runtime for your web project to the Tomcat installation you are using; you can do it in the "Targeted runtimes" section of the project configuration.

In this way you will allow Eclipse to add Tomcat's Java EE Web Profile jars to the build path.

Remember that the HttpServlet class isn't in a JRE, but at least in an Enterprise Web Profile (e.g. a servlet container runtime /lib folder).

Technically what is the main difference between Oracle JDK and OpenJDK?

OpenJDK is a reference model and open source, while Oracle JDK is an implementation of the OpenJDK and is not open source. Oracle JDK is more stable than OpenJDK.

OpenJDK is released under GPL v2 license whereas Oracle JDK is licensed under Oracle Binary Code License Agreement.

OpenJDK and Oracle JDK have almost the same code, but Oracle JDK has more classes and some bugs fixed.

So if you want to develop enterprise/commercial software I would suggest to go for Oracle JDK, as it is thoroughly tested and stable.

I have faced lot of problems with application crashes using OpenJDK, which are fixed just by switching to Oracle JDK

How do I prevent people from doing XSS in Spring MVC?

**To avoid XSS security threat in spring application**

solution to the XSS issue is to filter all the textfields in the form at the time of submitting the form.

    It needs XML entry in the web.xml file & two simple classes.

        java code :-
        The code for the  first class named CrossScriptingFilter.java is :

        package com.filter;

        import java.io.IOException;
        import javax.servlet.Filter;
        import javax.servlet.FilterChain;
        import javax.servlet.FilterConfig;
        import javax.servlet.ServletException;
        import javax.servlet.ServletRequest;
        import javax.servlet.ServletResponse;
        import javax.servlet.http.HttpServletRequest;
        import org.apache.log4j.Logger;

        public class CrossScriptingFilter implements Filter {
            private static Logger logger = Logger.getLogger(CrossScriptingFilter.class);
            private FilterConfig filterConfig;

            public void init(FilterConfig filterConfig) throws ServletException {
                this.filterConfig = filterConfig;
            }

            public void destroy() {
                this.filterConfig = null;
            }

            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
                logger.info("Inlter CrossScriptingFilter  ...............");
                chain.doFilter(new RequestWrapper((HttpServletRequest) request), response);
                logger.info("Outlter CrossScriptingFilter ...............");
            }

        }

The code second class named RequestWrapper.java is :

package com.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.log4j.Logger;

public final class RequestWrapper extends HttpServletRequestWrapper {
    private static Logger logger = Logger.getLogger(RequestWrapper.class);
    public RequestWrapper(HttpServletRequest servletRequest) {
        super(servletRequest);
    }

    public String[] getParameterValues(String parameter) {
        logger.info("InarameterValues .. parameter .......");
        String[] values = super.getParameterValues(parameter);
        if (values == null) {
            return null;
        }
        int count = values.length;
        String[] encodedValues = new String[count];
        for (int i = 0; i < count; i++) {
            encodedValues[i] = cleanXSS(values[i]);
        }
        return encodedValues;
    }

    public String getParameter(String parameter) {
        logger.info("Inarameter .. parameter .......");
        String value = super.getParameter(parameter);
        if (value == null) {
            return null;
        }
        logger.info("Inarameter RequestWrapper ........ value .......");
        return cleanXSS(value);
    }

    public String getHeader(String name) {
        logger.info("Ineader .. parameter .......");
        String value = super.getHeader(name);
        if (value == null)
            return null;
        logger.info("Ineader RequestWrapper ........... value ....");
        return cleanXSS(value);
    }

    private String cleanXSS(String value) {
        // You'll need to remove the spaces from the html entities below
        logger.info("InnXSS RequestWrapper ..............." + value);
        //value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
        //value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
        //value = value.replaceAll("'", "& #39;");
        value = value.replaceAll("eval\\((.*)\\)", "");
        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");

        value = value.replaceAll("(?i)<script.*?>.*?<script.*?>", "");
        value = value.replaceAll("(?i)<script.*?>.*?</script.*?>", "");
        value = value.replaceAll("(?i)<.*?javascript:.*?>.*?</.*?>", "");
        value = value.replaceAll("(?i)<.*?\\s+on.*?>.*?</.*?>", "");
        //value = value.replaceAll("<script>", "");
        //value = value.replaceAll("</script>", "");
        logger.info("OutnXSS RequestWrapper ........ value ......." + value);
        return value;
    }

The only thing remained is the XML entry in the web.xml file:

        <filter>
        <filter-name>XSS</filter-name>
        <display-name>XSS</display-name>
        <description></description>
        <filter-class>com.filter.CrossScriptingFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>XSS</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

The /* indicates that for every request made from browser, it will call CrossScriptingFilter class. Which will parse all the components/elements came from the request & will replace all the javascript tags put by hacker with empty string i.e

ImportError: No module named dateutil.parser

For Python 3 above, use:

sudo apt-get install python3-dateutil

DatabaseError: current transaction is aborted, commands ignored until end of transaction block?

I have met this issue , the error comes out since the error transactions hasn't been ended rightly, I found the postgresql_transactions of Transaction Control command here

Transaction Control

The following commands are used to control transactions

BEGIN TRANSACTION - To start a transaction.

COMMIT - To save the changes, alternatively you can use END TRANSACTION command.

ROLLBACK - To rollback the changes.

so i use the END TRANSACTION to end the error TRANSACTION, code like this:

    for key_of_attribute, command in sql_command.items():
        cursor = connection.cursor()
        g_logger.info("execute command :%s" % (command))
        try:
            cursor.execute(command)
            rows = cursor.fetchall()
            g_logger.info("the command:%s result is :%s" % (command, rows))
            result_list[key_of_attribute] = rows
            g_logger.info("result_list is :%s" % (result_list))
        except Exception as e:
            cursor.execute('END TRANSACTION;')
            g_logger.info("error command :%s and error is :%s" % (command, e))
    return result_list

How to switch to new window in Selenium for Python?

window_handles should give you the references to all open windows.

this is what the docu has to say about switching windows.

ImportError: Couldn't import Django

To create a virtual environment for your project, open a new command prompt, navigate to the folder where you want to create your project and then enter the following:

py -m venv project-name This will create a folder called ‘project-name’ if it does not already exist and setup the virtual environment. To activate the environment, run: project-name\Scripts\activate.bat**

The virtual environment will be activated and you’ll see “(project-name)” next to the command prompt to designate that. Each time you start a new command prompt, you’ll need to activate the environment again.

Install Django

Django can be installed easily using pip within your virtual environment.

In the command prompt, ensure your virtual environment is active, and execute the following command:

py -m pip install Django

Where does the .gitignore file belong?

As the other answers stated, you can place .gitignore within any directory in a Git repository. However, if you need to have a private version of .gitignore, you can add the rules to .git/info/exclude file.

Using cut command to remove multiple columns

The same could be done with Perl
Because it uses 0-based-indexing instead of 1-based-indexing, the field values are offset by 1

perl -F, -lane 'print join ",", @F[1..3,5..9,11..19]'    

is equivalent to:

cut -d, -f2-4,6-10,12-20

If the commas are not needed in the output:

perl -F, -lane 'print "@F[1..3,5..9,11..19]"'

Check if a value is in an array (C#)

You are just missing something in your method:

public void PrinterSetup(string printer)
{
   if (printer == "jupiter") 
   {
      Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC"");
   }
}

Just add string and you'll be fine.

Calculate execution time of a SQL query?

You can use

SET STATISTICS TIME { ON | OFF }

Displays the number of milliseconds required to parse, compile, and execute each statement

When SET STATISTICS TIME is ON, the time statistics for a statement are displayed. When OFF, the time statistics are not displayed

USE AdventureWorks2012;  
GO         
SET STATISTICS TIME ON;  
GO  
SELECT ProductID, StartDate, EndDate, StandardCost   
FROM Production.ProductCostHistory  
WHERE StandardCost < 500.00;  
GO  
SET STATISTICS TIME OFF;  
GO  

Google Maps how to Show city or an Area outline

From what I searched, at this moment there is no option from Google in the Maps API v3 and there is an issue on the Google Maps API going back to 2008. There are some older questions - Add "Search Area" outline onto google maps result , Google has started highlighting search areas in Pink color. Is this feature available in Google Maps API 3? and you might find some newer answers here with updated information, but this is not a feature.

What you can do is draw shapes on your map - but for this you need to have the coordinates of the borders of your region.

Now, in order to get the administrative area boundaries, you will have to do a little work: http://www.gadm.org/country (if you are lucky and there is enough level of detail available there).

On this website you can locally download a file (there are many formats available) with the .kmz extension. Unzip it and you will have a .kml file which contains most administrative areas (cities, villages).

  <?xml version="1.0" encoding="utf-8" ?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document id="root_doc">
<Schema name="x" id="x">
    <SimpleField name="ID_0" type="int"></SimpleField>
    <SimpleField name="ISO" type="string"></SimpleField>
    <SimpleField name="NAME_0" type="string"></SimpleField>
    <SimpleField name="ID_1" type="string"></SimpleField>
    <SimpleField name="NAME_1" type="string"></SimpleField>
    <SimpleField name="ID_2" type="string"></SimpleField>
    <SimpleField name="NAME_2" type="string"></SimpleField>
    <SimpleField name="TYPE_2" type="string"></SimpleField>
    <SimpleField name="ENGTYPE_2" type="string"></SimpleField>
    <SimpleField name="NL_NAME_2" type="string"></SimpleField>
    <SimpleField name="VARNAME_2" type="string"></SimpleField>
    <SimpleField name="Shape_Length" type="float"></SimpleField>
    <SimpleField name="Shape_Area" type="float"></SimpleField>
</Schema>
<Folder><name>x</name>
  <Placemark>
    <Style><LineStyle><color>ff0000ff</color></LineStyle><PolyStyle><fill>0</fill></PolyStyle></Style>
    <ExtendedData><SchemaData schemaUrl="#x">
        <SimpleData name="ID_0">186</SimpleData>
        <SimpleData name="ISO">ROU</SimpleData>
        <SimpleData name="NAME_0">Romania</SimpleData>
        <SimpleData name="ID_1">1</SimpleData>
        <SimpleData name="NAME_1">Alba</SimpleData>
        <SimpleData name="ID_2">1</SimpleData>
        <SimpleData name="NAME_2">Abrud</SimpleData>
        <SimpleData name="TYPE_2">Comune</SimpleData>
        <SimpleData name="ENGTYPE_2">Commune</SimpleData>
        <SimpleData name="VARNAME_2">Oras Abrud</SimpleData>
        <SimpleData name="Shape_Length">0.2792904164402</SimpleData>
        <SimpleData name="Shape_Area">0.00302673357146115</SimpleData>
    </SchemaData></ExtendedData>
      <MultiGeometry><Polygon><outerBoundaryIs><LinearRing><coordinates>23.117561340332031,46.269237518310547 23.108898162841797,46.265365600585937 23.107486724853629,46.264305114746207 23.104681015014762,46.260105133056641 23.101633071899471,46.250000000000114 23.100803375244254,46.249053955078239 23.097520828247184,46.246582031250114 23.0965576171875,46.245487213134822 23.095674514770508,46.244930267334098 23.092174530029354,46.243438720703182 23.088010787963924,46.240383148193473 23.083366394043082,46.238204956054801 23.075212478637809,46.234935760498047 23.071325302123967,46.239696502685547 23.070602416992131,46.241668701171875 23.069700241088924,46.242824554443416 23.068435668945369,46.243541717529354 23.066627502441406,46.244037628173771 23.064964294433651,46.246234893798885 23.062850952148437,46.247486114501953 23.0626220703125,46.248153686523438 23.062761306762752,46.250873565673942 23.061862945556697,46.255172729492301 23.061449050903434,46.256267547607422 23.05998420715332,46.258060455322322 23.057676315307674,46.259838104248161 23.055141448974666,46.262714385986442 23.053401947021484,46.264244079589901 23.049621582031193,46.266674041748161 23.043565750122013,46.268516540527457 23.041521072387695,46.269458770751953 23.034791946411076,46.270542144775334 23.027051925659293,46.27105712890625 23.025453567504826,46.271255493164063 23.022710800170898,46.272083282470703 23.020351409912053,46.271331787109432 23.018688201904297,46.270687103271598 23.015596389770508,46.270793914794922 23.014116287231502,46.271579742431697 23.009817123413143,46.275333404541016 23.006668090820426,46.277061462402401 23.004106521606445,46.279254913330135 23.001775741577205,46.282882690429688 23.005559921264648,46.283077239990348 23.009967803955135,46.28415679931652 23.014947891235465,46.286224365234489 23.019996643066463,46.28900146484375 23.024263381958121,46.292709350586051 23.027633666992301,46.295299530029411 23.028041839599609,46.295692443847656 23.032444000244197,46.294342041015625 23.03491401672369,46.293315887451229 23.044847488403434,46.290401458740234 23.047790527343807,46.28928375244152 23.053009033203239,46.288627624511719 23.057231903076229,46.288341522216797 23.064565658569393,46.287548065185547 23.070388793945426,46.286254882812614 23.075139999389592,46.284847259521428 23.075983047485465,46.284801483154411 23.085800170898494,46.28253173828125 23.098115921020451,46.280982971191406 23.099718093872127,46.280590057373104 23.105833053588981,46.278388977050838 23.112155914306641,46.274082183837947 23.116207122802791,46.270610809326172 23.117561340332031,46.269237518310547</coordinates></LinearRing></outerBoundaryIs></Polygon></MultiGeometry>
  </Placemark>
</Folder>
</Document></kml>

From this point on, when the user searches for a city/village, you simply retrieve the boundaries and draw around those coordinates on the map - https://developers.google.com/maps/documentation/javascript/overlays#Polygons

I hope this helps you! Good luck!

border on Google Map using the above coordinates UPDATE: I made the borders of this city using the coordinates above

                   var ctaLayer = new google.maps.KmlLayer({
                       url: 'https://www.dropbox.com/s/0grhlim3q4572jp/ROU_adm2%20-%20Copy.kml?dl=1'
  });
  ctaLayer.setMap(map);

(I put a small kml file on my Dropbox containing the borders of a single city)

Note that this uses the Google built in KML system, in which it their server gets the file, computes the view and spits it back to you - it has limited usage and I used it to show you how the borders look. In your application you should be able to parse the coordinates from the kml file, put them in an array (as the polygon documentation tells you - https://developers.google.com/maps/documentation/javascript/examples/polygon-arrays ) and display them.

Note that there will be differences between the borders that Google sets on http://www.google.com/maps and the borders that you will get with this data.

Good luck! enter image description here

UPDATE: http://pastebin.com/x2V1aarJ , http://pastebin.com/Gh55EDW5 These are the javascript files (they were minified, so I used an online tool to make them readable) from the website. If you are not fully satisfied with this my solution, feel free to study them.

Best of luck!

SQL error "ORA-01722: invalid number"

This happened to me too, but the problem was actually different: file encoding.

The file was correct, but the file encoding was wrong. It was generated by the export utility of SQL Server and I saved it as Unicode.

The file itself looked good in the text editor, but when I opened the *.bad file that the SQL*loader generated with the rejected lines, I saw it had bad characters between every original character. Then I though about the encoding.

I opened the original file with Notepad++ and converted it to ANSI, and everything loaded properly.

How to take keyboard input in JavaScript?

Since event.keyCode is deprecated, I found the event.key useful in javascript. Below is an example for getting the names of the keyboard keys pressed (using an input element). They are given as a KeyboardEvent key text property:

_x000D_
_x000D_
function setMyKeyDownListener() {_x000D_
    window.addEventListener(_x000D_
      "keydown",_x000D_
      function(event) {MyFunction(event.key)}_x000D_
    )_x000D_
}_x000D_
_x000D_
function MyFunction (the_Key) {_x000D_
    alert("Key pressed is: "+the_Key);_x000D_
}
_x000D_
html { font-size: 4vw; background-color: green; color: white; padding: 1em; }
_x000D_
<body onload="setMyKeyDownListener()">_x000D_
    <div>_x000D_
        <input id="MyInputId">_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Finding the id of a parent div using Jquery

$(this).parents('div').attr('id');

How do you increase the max number of concurrent connections in Apache?

Here's a detailed explanation about the calculation of MaxClients and MaxRequestsPerChild

http://web.archive.org/web/20160415001028/http://www.genericarticles.com/mediawiki/index.php?title=How_to_optimize_apache_web_server_for_maximum_concurrent_connections_or_increase_max_clients_in_apache

ServerLimit 16
StartServers 2
MaxClients 200
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25

First of all, whenever an apache is started, it will start 2 child processes which is determined by StartServers parameter. Then each process will start 25 threads determined by ThreadsPerChild parameter so this means 2 process can service only 50 concurrent connections/clients i.e. 25x2=50. Now if more concurrent users comes, then another child process will start, that can service another 25 users. But how many child processes can be started is controlled by ServerLimit parameter, this means that in the configuration above, I can have 16 child processes in total, with each child process can handle 25 thread, in total handling 16x25=400 concurrent users. But if number defined in MaxClients is less which is 200 here, then this means that after 8 child processes, no extra process will start since we have defined an upper cap of MaxClients. This also means that if I set MaxClients to 1000, after 16 child processes and 400 connections, no extra process will start and we cannot service more than 400 concurrent clients even if we have increase the MaxClient parameter. In this case, we need to also increase ServerLimit to 1000/25 i.e. MaxClients/ThreadsPerChild=40 So this is the optmized configuration to server 1000 clients

<IfModule mpm_worker_module>
    ServerLimit          40
    StartServers          2
    MaxClients          1000
    MinSpareThreads      25
    MaxSpareThreads      75 
    ThreadsPerChild      25
    MaxRequestsPerChild   0
</IfModule>

How to sort List of objects by some property

Guava's ComparisonChain:

Collections.sort(list, new Comparator<ActiveAlarm>(){
            @Override
            public int compare(ActiveAlarm a1, ActiveAlarm a2) {
                 return ComparisonChain.start()
                       .compare(a1.timestarted, a2.timestarted)
                       //...
                       .compare(a1.timeEnded, a1.timeEnded).result();
            }});

Preserve Line Breaks From TextArea When Writing To MySQL

Two solutions for this:

  1. PHP function nl2br():

    e.g.,

    echo nl2br("This\r\nis\n\ra\nstring\r");
    
    // will output
    This<br />
    is<br />
    a<br />
    string<br />
    
  2. Wrap the input in <pre></pre> tags.

    See: W3C Wiki - HTML/Elements/pre

Difference between Node object and Element object?

Element inherits from Node, in the same way that Dog inherits from Animal.

An Element object "is-a" Node object, in the same way that a Dog object "is-a" Animal object.

Node is for implementing a tree structure, so its methods are for firstChild, lastChild, childNodes, etc. It is more of a class for a generic tree structure.

And then, some Node objects are also Element objects. Element inherits from Node. Element objects actually represents the objects as specified in the HTML file by the tags such as <div id="content"></div>. The Element class define properties and methods such as attributes, id, innerHTML, clientWidth, blur(), and focus().

Some Node objects are text nodes and they are not Element objects. Each Node object has a nodeType property that indicates what type of node it is, for HTML documents:

1: Element node
3: Text node
8: Comment node
9: the top level node, which is document

We can see some examples in the console:

> document instanceof Node
  true

> document instanceof Element
  false

> document.firstChild
  <html>...</html>

> document.firstChild instanceof Node
  true

> document.firstChild instanceof Element
  true

> document.firstChild.firstChild.nextElementSibling
  <body>...</body>

> document.firstChild.firstChild.nextElementSibling === document.body
  true

> document.firstChild.firstChild.nextSibling
  #text

> document.firstChild.firstChild.nextSibling instanceof Node
  true

> document.firstChild.firstChild.nextSibling instanceof Element
  false

> Element.prototype.__proto__ === Node.prototype
  true

The last line above shows that Element inherits from Node. (that line won't work in IE due to __proto__. Will need to use Chrome, Firefox, or Safari).

By the way, the document object is the top of the node tree, and document is a Document object, and Document inherits from Node as well:

> Document.prototype.__proto__ === Node.prototype
  true

Here are some docs for the Node and Element classes:
https://developer.mozilla.org/en-US/docs/DOM/Node
https://developer.mozilla.org/en-US/docs/DOM/Element

Java - How to create a custom dialog box?

If you don't need much in the way of custom behavior, JOptionPane is a good time saver. It takes care of the placement and localization of OK / Cancel options, and is a quick-and-dirty way to show a custom dialog without needing to define your own classes. Most of the time the "message" parameter in JOptionPane is a String, but you can pass in a JComponent or array of JComponents as well.

Example:

JTextField firstName = new JTextField();
JTextField lastName = new JTextField();
JPasswordField password = new JPasswordField();
final JComponent[] inputs = new JComponent[] {
        new JLabel("First"),
        firstName,
        new JLabel("Last"),
        lastName,
        new JLabel("Password"),
        password
};
int result = JOptionPane.showConfirmDialog(null, inputs, "My custom dialog", JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
    System.out.println("You entered " +
            firstName.getText() + ", " +
            lastName.getText() + ", " +
            password.getText());
} else {
    System.out.println("User canceled / closed the dialog, result = " + result);
}

Multiple Indexes vs Multi-Column Indexes

Yes. I recommend you check out Kimberly Tripp's articles on indexing.

If an index is "covering", then there is no need to use anything but the index. In SQL Server 2005, you can also add additional columns to the index that are not part of the key which can eliminate trips to the rest of the row.

Having multiple indexes, each on a single column may mean that only one index gets used at all - you will have to refer to the execution plan to see what effects different indexing schemes offer.

You can also use the tuning wizard to help determine what indexes would make a given query or workload perform the best.

When should I use curly braces for ES6 import?

Usually when you export a function you need to use the {}.

If you have

export const x

you use

import {x} from ''

If you use

export default const x

you need to use

import x from ''

Here you can change X to whatever variable you want.

hadoop copy a local file system folder to HDFS

In Short

hdfs dfs -put <localsrc> <dest>

In detail with example:

Checking source and target before placing files into HDFS

[cloudera@quickstart ~]$ ll files/
total 132
-rwxrwxr-x 1 cloudera cloudera  5387 Nov 14 06:33 cloudera-manager
-rwxrwxr-x 1 cloudera cloudera  9964 Nov 14 06:33 cm_api.py
-rw-rw-r-- 1 cloudera cloudera   664 Nov 14 06:33 derby.log
-rw-rw-r-- 1 cloudera cloudera 53655 Nov 14 06:33 enterprise-deployment.json
-rw-rw-r-- 1 cloudera cloudera 50515 Nov 14 06:33 express-deployment.json

[cloudera@quickstart ~]$ hdfs dfs -ls
Found 1 items
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 00:45 .sparkStaging

Copy files HDFS using -put or -copyFromLocal command

[cloudera@quickstart ~]$ hdfs dfs -put files/ files

Verify the result in HDFS

[cloudera@quickstart ~]$ hdfs dfs -ls
Found 2 items
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 00:45 .sparkStaging
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 06:34 files

[cloudera@quickstart ~]$ hdfs dfs -ls files
Found 5 items
-rw-r--r--   1 cloudera cloudera       5387 2017-11-14 06:34 files/cloudera-manager
-rw-r--r--   1 cloudera cloudera       9964 2017-11-14 06:34 files/cm_api.py
-rw-r--r--   1 cloudera cloudera        664 2017-11-14 06:34 files/derby.log
-rw-r--r--   1 cloudera cloudera      53655 2017-11-14 06:34 files/enterprise-deployment.json
-rw-r--r--   1 cloudera cloudera      50515 2017-11-14 06:34 files/express-deployment.json

How can I change the version of npm using nvm?

nvm doesn't handle npm.

So if you want to install node 0.4.x (which many packages still depend on) and use NPM, you can still use npm 1.0.x.

Install node 0.6.x (which comes with npm 1.1.x) and install nvm with npm:

npm install nvm
. ~/nvm/nvm.sh

Install node 0.4.x with nvm:

nvm install v0.4.12
nvm use v0.4.12

Install npm using install.sh (note the -L param to follow any redirects):

curl -L https://npmjs.org/install.sh | sh

This will detect node 0.4.12 and install npm 1.0.106 in your ~/nvm/v0.4.12/lib/node_modules folder and create symlink for nvm

~/nvm/v0.4.12/bin/npm -> ../lib/node_modules/npm/bin/npm-cli.js

If you try to run npm, it will still give an error but if you do nvm use v0.4.12 again, it should now work.

What is the difference between bindParam and bindValue?

Here are some I can think about :

  • With bindParam, you can only pass variables ; not values
  • with bindValue, you can pass both (values, obviously, and variables)
  • bindParam works only with variables because it allows parameters to be given as input/output, by "reference" (and a value is not a valid "reference" in PHP) : it is useful with drivers that (quoting the manual) :

support the invocation of stored procedures that return data as output parameters, and some also as input/output parameters that both send in data and are updated to receive it.

With some DB engines, stored procedures can have parameters that can be used for both input (giving a value from PHP to the procedure) and ouput (returning a value from the stored proc to PHP) ; to bind those parameters, you've got to use bindParam, and not bindValue.

How do I download the Android SDK without downloading Android Studio?

For those using the latest distribution on windows, the following should be enough:

  1. Download the command line tools from here
  2. Extract it somewhere (e.g. C:\androidsdk)
  3. Add ANDROID_SDK_TOOLS as environment variable pointing to where you extracted it (C:\androidsdk)
  4. Create a folder named latest inside the cmdlime-tools you extracted. And move what's inside(bin,lib...) to the folder latest.
  5. cd cmdline-tools/latest/bin and execute the following:

sdkmanager.bat system-images;android-29;default;x86_64 platforms;android-29 build-tools;29.0.3 extras;google;m2repository extras;android;m2repository

  1. Agree to the terms and conditions and continue. voilà

Parsing JSON string in Java

Firstly there is an extra } after every array object.

Secondly "geodata" is a JSONArray. So instead of JSONObject geoObject = jObject.getJSONObject("geodata"); you have to get it as JSONArray geoObject = jObject.getJSONArray("geodata");

Once you have the JSONArray you can fetch each entry in the JSONArray using geoObject.get(<index>).

I am using org.codehaus.jettison.json.

MongoDB query with an 'or' condition

Query objects in Mongo by default AND expressions together. Mongo currently does not include an OR operator for such queries, however there are ways to express such queries.

Use "in" or "where".

Its gonna be something like this:

db.mycollection.find( { $where : function() { 
return ( this.startTime < Now() && this.expireTime > Now() || this.expireTime == null ); } } );

Create an Excel file using vbscripts

'Create Excel

Set objExcel = Wscript.CreateObject("Excel.Application")

objExcel.visible = True

Set objWb = objExcel.Workbooks.Add

objWb.Saveas("D:\Example.xlsx")

objExcel.Quit

In PHP, what is a closure and why does it use the "use" identifier?

Zupa did a great job explaining closures with 'use' and the difference between EarlyBinding and Referencing the variables that are 'used'.

So I made a code example with early binding of a variable (= copying):

<?php

$a = 1;
$b = 2;

$closureExampleEarlyBinding = function() use ($a, $b){
    $a++;
    $b++;
    echo "Inside \$closureExampleEarlyBinding() \$a = ".$a."<br />";
    echo "Inside \$closureExampleEarlyBinding() \$b = ".$b."<br />";    
};

echo "Before executing \$closureExampleEarlyBinding() \$a = ".$a."<br />";
echo "Before executing \$closureExampleEarlyBinding() \$b = ".$b."<br />";  

$closureExampleEarlyBinding();

echo "After executing \$closureExampleEarlyBinding() \$a = ".$a."<br />";
echo "After executing \$closureExampleEarlyBinding() \$b = ".$b."<br />";

/* this will output:
Before executing $closureExampleEarlyBinding() $a = 1
Before executing $closureExampleEarlyBinding() $b = 2
Inside $closureExampleEarlyBinding() $a = 2
Inside $closureExampleEarlyBinding() $b = 3
After executing $closureExampleEarlyBinding() $a = 1
After executing $closureExampleEarlyBinding() $b = 2
*/

?>

Example with referencing a variable (notice the '&' character before variable);

<?php

$a = 1;
$b = 2;

$closureExampleReferencing = function() use (&$a, &$b){
    $a++;
    $b++;
    echo "Inside \$closureExampleReferencing() \$a = ".$a."<br />";
    echo "Inside \$closureExampleReferencing() \$b = ".$b."<br />"; 
};

echo "Before executing \$closureExampleReferencing() \$a = ".$a."<br />";
echo "Before executing \$closureExampleReferencing() \$b = ".$b."<br />";   

$closureExampleReferencing();

echo "After executing \$closureExampleReferencing() \$a = ".$a."<br />";
echo "After executing \$closureExampleReferencing() \$b = ".$b."<br />";    

/* this will output:
Before executing $closureExampleReferencing() $a = 1
Before executing $closureExampleReferencing() $b = 2
Inside $closureExampleReferencing() $a = 2
Inside $closureExampleReferencing() $b = 3
After executing $closureExampleReferencing() $a = 2
After executing $closureExampleReferencing() $b = 3
*/

?>

jQuery load first 3 elements, click "load more" to display next 5 elements

WARNING: size() was deprecated in jQuery 1.8 and removed in jQuery 3.0, use .length instead

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
    });
});


New JS to show or hide load more and show less

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
         $('#showLess').show();
        if(x == size_li){
            $('#loadMore').hide();
        }
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
        $('#loadMore').show();
         $('#showLess').show();
        if(x == 3){
            $('#showLess').hide();
        }
    });
});

CSS

#showLess {
    color:red;
    cursor:pointer;
    display:none;
}

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/2/

Hadoop: «ERROR : JAVA_HOME is not set»

The solution that worked for me was setting my JAVA_HOME in /etc/environment

Though JAVA_HOME can be set inside the /etc/profile files, the preferred location for JAVA_HOME or any system variable is /etc/environment.

Open /etc/environment in any text editor like nano or vim and add the following line:

JAVA_HOME="/usr/lib/jvm/your_java_directory"

Load the variables:

source /etc/environment

Check if the variable loaded correctly:

echo $JAVA_HOME

Reading rather large json files in Python

The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.

The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.

The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.

Edit: Also worth a look - kashif's comment about json-streamer and Henrik Heino's comment about bigjson.

Android studio logcat nothing to show

For me, the issue was that I had two emulators with the same name (I created it, deleted it, and then created it again with the same name). There were two emulator entries in the logcat dropdown and it was connected to the wrong one. All I had to do was switch to the other one. I prevented the problem permanently by renaming the emulator.

enter image description here

How to get POST data in WebAPI?

None of the answers here worked for me. Using FormDataCollection in the post method seems like the right answer but something about my post request was causing webapi to choke. eventually I made it work by including no parameters in the method call and just manually parsing out the form parameters like this.

public HttpResponseMessage FileUpload() {
    System.Web.HttpRequest httpRequest = System.Web.HttpContext.Current.Request;
    System.Collections.Specialized.NameValueCollection formData = httpRequest.Form;
    int ID = Convert.ToInt32(formData["ID"]);
    etc

How to get a MemoryStream from a Stream in .NET?

How do I copy the contents of one stream to another?

see that. accept a stream and copy to memory. you should not use .Length for just Stream because it is not necessarily implemented in every concrete Stream.

How to sort with a lambda?

Can the problem be with the "a.mProperty > b.mProperty" line? I've gotten the following code to work:

#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
#include <sstream>

struct Foo
{
    Foo() : _i(0) {};

    int _i;

    friend std::ostream& operator<<(std::ostream& os, const Foo& f)
    {
        os << f._i;
        return os;
    };
};

typedef std::vector<Foo> VectorT;

std::string toString(const VectorT& v)
{
    std::stringstream ss;
    std::copy(v.begin(), v.end(), std::ostream_iterator<Foo>(ss, ", "));
    return ss.str();
};

int main()
{

    VectorT v(10);
    std::for_each(v.begin(), v.end(),
            [](Foo& f)
            {
                f._i = rand() % 100;
            });

    std::cout << "before sort: " << toString(v) << "\n";

    sort(v.begin(), v.end(),
            [](const Foo& a, const Foo& b)
            {
                return a._i > b._i;
            });

    std::cout << "after sort:  " << toString(v) << "\n";
    return 1;
};

The output is:

before sort: 83, 86, 77, 15, 93, 35, 86, 92, 49, 21,
after sort:  93, 92, 86, 86, 83, 77, 49, 35, 21, 15,

What are App Domains in Facebook Apps?

To add to the answers above, the App Domain is required for security reasons. For example, your app has been sending the browser to "www.example.com/PAGE_NAME_HERE", but suddenly a third party application (or something else) sends the user to "www.supposedlymaliciouswebsite.com/PAGE_HERE", then a 191 error is thrown saying that this wasn't part of the app domains you listed in your Facebook application settings.

how to extract only the year from the date in sql server 2008?

DATEPART(yyyy, date_column) could be used to extract year. In general, DATEPART function is used to extract specific portions of a date value.

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

Javascript "Not a Constructor" Exception while creating objects

In my case I was using the prototype name as the object name. For e.g.

function proto1()
{}

var proto1 = new proto1();

It was a silly mistake but might be of help to someone like me ;)

How do I temporarily disable triggers in PostgreSQL?

You can also disable triggers in pgAdmin (III):

  1. Find your table
  2. Expand the +
  3. Find your trigger in Triggers
  4. Right-click, uncheck "Trigger Enabled?"

Boto3 to download all files from a S3 Bucket

I have the same needs and created the following function that download recursively the files.

The directories are created locally only if they contain files.

import boto3
import os

def download_dir(client, resource, dist, local='/tmp', bucket='your_bucket'):
    paginator = client.get_paginator('list_objects')
    for result in paginator.paginate(Bucket=bucket, Delimiter='/', Prefix=dist):
        if result.get('CommonPrefixes') is not None:
            for subdir in result.get('CommonPrefixes'):
                download_dir(client, resource, subdir.get('Prefix'), local, bucket)
        for file in result.get('Contents', []):
            dest_pathname = os.path.join(local, file.get('Key'))
            if not os.path.exists(os.path.dirname(dest_pathname)):
                os.makedirs(os.path.dirname(dest_pathname))
            resource.meta.client.download_file(bucket, file.get('Key'), dest_pathname)

The function is called that way:

def _start():
    client = boto3.client('s3')
    resource = boto3.resource('s3')
    download_dir(client, resource, 'clientconf/', '/tmp', bucket='my-bucket')

Clang vs GCC - which produces faster binaries?

A peculiar difference I have noted on gcc 5.2.1 and clang 3.6.2 is that if you have a critical loop like:

for (;;) {
    if (!visited) {
        ....
    }
    node++;
    if (!*node) break;
  }

Then gcc will, when compiling with -O3 or -O2, speculatively unroll the loop eight times. Clang will not unroll it at all. Through trial and error I found that in my specific case with my program data, the right amount of unrolling is five so gcc overshot and clang undershot. However, overshooting was more detrimental to performance, so gcc performed much worse here.

I have no idea if the unrolling difference is a general trend or just something that was specific to my scenario.

A while back I wrote a few garbage collectors to teach myself more about performance optimization in C. And the results I got is in my mind enough to slightly favor clang. Especially since garbage collection is mostly about pointer chasing and copying memory.

The results are (numbers in seconds):

+---------------------+-----+-----+
|Type                 |GCC  |Clang|
+---------------------+-----+-----+
|Copying GC           |22.46|22.55|
|Copying GC, optimized|22.01|20.22|
|Mark & Sweep         | 8.72| 8.38|
|Ref Counting/Cycles  |15.14|14.49|
|Ref Counting/Plain   | 9.94| 9.32|
+---------------------+-----+-----+

This is all pure C code, and I make no claim about either compiler's performance when compiling C++ code.

On Ubuntu 15.10, x86.64, and an AMD Phenom(tm) II X6 1090T processor.

Passing variables in remote ssh command

As answered previously, you do not need to set the environment variable on the remote host. Instead, you can simply do the meta-expansion on the local host, and pass the value to the remote host.

ssh [email protected] '~/tools/run_pvt.pl $BUILD_NUMBER'

If you really want to set the environment variable on the remote host and use it, you can use the env program

ssh [email protected] "env BUILD_NUMBER=$BUILD_NUMBER ~/tools/run_pvt.pl \$BUILD_NUMBER"

In this case this is a bit of an overkill, and note

  • env BUILD_NUMBER=$BUILD_NUMBER does the meta expansion on the local host
  • the remote BUILD_NUMBER environment variable will be used by
    the remote shell

What is the difference between a cer, pvk, and pfx file?

Windows uses .cer extension for an X.509 certificate. These can be in "binary" (ASN.1 DER), or it can be encoded with Base-64 and have a header and footer applied (PEM); Windows will recognize either. To verify the integrity of a certificate, you have to check its signature using the issuer's public key... which is, in turn, another certificate.

Windows uses .pfx for a PKCS #12 file. This file can contain a variety of cryptographic information, including certificates, certificate chains, root authority certificates, and private keys. Its contents can be cryptographically protected (with passwords) to keep private keys private and preserve the integrity of root certificates.

Windows uses .pvk for a private key file. I'm not sure what standard (if any) Windows follows for these. Hopefully they are PKCS #8 encoded keys. Emmanuel Bourg reports that these are a proprietary format. Some documentation is available.

You should never disclose your private key. These are contained in .pfx and .pvk files.

Generally, you only exchange your certificate (.cer) and the certificates of any intermediate issuers (i.e., the certificates of all of your CAs, except the root CA) with other parties.

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

Is it possible to force Excel recognize UTF-8 CSV files automatically?

Had the same problems with PHP-generated CSV files. Excel ignored the BOM when the Separator was defined via "sep=,\n" at the beginning of the content (but of course after the BOM).

So adding a BOM ("\xEF\xBB\xBF") at the beginning of the content and setting the semicolon as separator via fputcsv($fh, $data_array, ";"); does the trick.

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

The standard states that prompting can be controlled by canceling the beforeunload event or setting the return value to a non-null value. It also states that authors should use Event.preventDefault() instead of returnValue, and the message shown to the user is not customizable.

As of 69.0.3497.92, Chrome has not met the standard. However, there is a bug report filed, and a review is in progress. Chrome requires returnValue to be set by reference to the event object, not the value returned by the handler.

It is the author's responsibility to track whether changes have been made; it can be done with a variable or by ensuring the event is only handled when necessary.

_x000D_
_x000D_
window.addEventListener('beforeunload', function (e) {_x000D_
    // Cancel the event as stated by the standard._x000D_
    e.preventDefault();_x000D_
    // Chrome requires returnValue to be set._x000D_
    e.returnValue = '';_x000D_
});_x000D_
    _x000D_
window.location = 'about:blank';
_x000D_
_x000D_
_x000D_

Add/Delete table rows dynamically using JavaScript

Javascript dynamically adding table data.

SCRIPT

function addRow(tableID) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    var colCount = table.rows[0].cells.length;    
    var validate_Noof_columns = (colCount - 1); // •No Of Columns to be Validated on Text.
    for(var j = 0; j < colCount; j++) { 
        var text = window.document.getElementById('input'+j).value;

        if (j == validate_Noof_columns) {
            row = table.insertRow(2); // •location of new row.
            for(var i = 0; i < colCount; i++) {       
            var text = window.document.getElementById('input'+i).value;
            var newcell = row.insertCell(i);
                if(i == (colCount - 1)) {  // Replace last column with delete button
    newcell.innerHTML = "<INPUT type='button' value='X' onclick='removeRow(this)'/>"; break;
                } else  {
                    newcell.innerHTML = text;
                    window.document.getElementById('input'+i).value = '';
                }
            }   
        }else if (text != 'undefined' && text.trim() == ''){ 
            alert('input'+j+' is EMPTY');break;
        }  
    }   
}
function removeRow(onclickTAG) {
    // Iterate till we find TR tag. 
    while ( (onclickTAG = onclickTAG.parentElement)  && onclickTAG.tagName != 'TR' );
            onclickTAG.parentElement.removeChild(onclickTAG);      
}

HTMl

<div align='center'>
<TABLE id='dataTable' border='1' >
<TBODY>
    <TR><th align='center'><b>First Name:</b></th>
        <th align='center' colspan='2'><b>Last  Name:</b></th>
        <th></th>
    </TR>    
    <TR><TD ><INPUT id='input0' type="text"/></TD>              
        <TD ><INPUT id='input1' type='text'/></TD>
        <TD>
<INPUT type='button' id='input2' value='+' onclick="addRow('dataTable')" />
        </TD>
    </TR>
</TBODY> 
</TABLE>
</div>

Example : jsfiddle

How to make a list of n numbers in Python and randomly select any number?

You can create the enumeration of the elements by something like this:

mylist = list(xrange(10))

Then you can use the random.choice function to select your items:

import random
...
random.choice(mylist)

As Asim Ihsan correctly stated, my answer did not address the full problem of the OP. To remove the values from the list, simply list.remove() can be called:

import random
...
value = random.choice(mylist)
mylist.remove(value)

As takataka pointed out, the xrange builtin function was renamed to range in Python 3.

Change background color of edittext in android

one line of lazy code:

mEditText.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP);

Cloud Firestore collection count

I agree with @Matthew, it will cost a lot if you perform such query.

[ADVICE FOR DEVELOPERS BEFORE STARTING THEIR PROJECTS]

Since we have foreseen this situation at the beginning, we can actually make a collection namely counters with a document to store all the counters in a field with type number.

For example:

For each CRUD operation on the collection, update the counter document:

  1. When you create a new collection/subcollection: (+1 in the counter) [1 write operation]
  2. When you delete a collection/subcollection: (-1 in the counter) [1 write operation]
  3. When you update an existing collection/subcollection, do nothing on the counter document: (0)
  4. When you read an existing collection/subcollection, do nothing on the counter document: (0)

Next time, when you want to get the number of collection, you just need to query/point to the document field. [1 read operation]

In addition, you can store the collections name in an array, but this will be tricky, the condition of array in firebase is shown as below:

// we send this
['a', 'b', 'c', 'd', 'e']
// Firebase stores this
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}

// since the keys are numeric and sequential,
// if we query the data, we get this
['a', 'b', 'c', 'd', 'e']

// however, if we then delete a, b, and d,
// they are no longer mostly sequential, so
// we do not get back an array
{2: 'c', 4: 'e'}

So, if you are not going to delete the collection , you can actually use array to store list of collections name instead of querying all the collection every time.

Hope it helps!

Getting Textbox value in Javascript

Since you have master page and your control is in content place holder, Your control id will be generated different in client side. you need to do like...

var TestVar = document.getElementById('<%= txt_model_code.ClientID %>').value;

Javascript runs on client side and to get value you have to provide client id of your control

Eclipse - Failed to create the java virtual machine

I had the same problem, I've fixed it very simple by updating my JDK version. If you don't have JDK installed or not updated, please Go here and install/update it. Mostly your problem will be fixed.

jQuery .load() call doesn't execute JavaScript in loaded HTML file

If you want to load both the HTML and scripts, here's a more automated way to do so utilizing both $(selector).load() and jQuery.getScript(). This specific example loads the HTML content of the element with ID "toLoad" from content.html, inserts the HTML into the element with ID "content", and then loads and runs all scripts within the element with the "toLoad" ID.

$("#content").load("content.html #toLoad", function(data) {
    var scripts = $(data).find("script");

    if (scripts.length) {
        $(scripts).each(function() {
            if ($(this).attr("src")) {
                $.getScript($(this).attr("src"));
            }
            else {
                eval($(this).html());
            }
        });
    }

});

This code finds all of the script elements in the content that is being loaded, and loops through each of these elements. If the element has a src attribute, meaning it is a script from an external file, we use the jQuery.getScript method of fetching and running the script. If the element does not have a src attribute, meaning it is an inline script, we simply use eval to run the code. If it finds no script elements, it solely inserts the HTML into the target element and does not attempt to load any scripts.

I've tested this method in Chrome and it works. Remember to be cautious when using eval, as it can run potentially unsafe scripts and is generally considered harmful. You might want to avoid using inline scripts when using this method in order to avoid having to use eval.

AES Encryption for an NSString on the iPhone

Since you haven't posted any code, it's difficult to know exactly which problems you're encountering. However, the blog post you link to does seem to work pretty decently... aside from the extra comma in each call to CCCrypt() which caused compile errors.

A later comment on that post includes this adapted code, which works for me, and seems a bit more straightforward. If you include their code for the NSData category, you can write something like this: (Note: The printf() calls are only for demonstrating the state of the data at various points — in a real application, it wouldn't make sense to print such values.)

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSString *key = @"my password";
    NSString *secret = @"text to encrypt";

    NSData *plain = [secret dataUsingEncoding:NSUTF8StringEncoding];
    NSData *cipher = [plain AES256EncryptWithKey:key];
    printf("%s\n", [[cipher description] UTF8String]);

    plain = [cipher AES256DecryptWithKey:key];
    printf("%s\n", [[plain description] UTF8String]);
    printf("%s\n", [[[NSString alloc] initWithData:plain encoding:NSUTF8StringEncoding] UTF8String]);

    [pool drain];
    return 0;
}

Given this code, and the fact that encrypted data will not always translate nicely into an NSString, it may be more convenient to write two methods that wrap the functionality you need, in forward and reverse...

- (NSData*) encryptString:(NSString*)plaintext withKey:(NSString*)key {
    return [[plaintext dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:key];
}

- (NSString*) decryptData:(NSData*)ciphertext withKey:(NSString*)key {
    return [[[NSString alloc] initWithData:[ciphertext AES256DecryptWithKey:key]
                                  encoding:NSUTF8StringEncoding] autorelease];
}

This definitely works on Snow Leopard, and @Boz reports that CommonCrypto is part of the Core OS on the iPhone. Both 10.4 and 10.5 have /usr/include/CommonCrypto, although 10.5 has a man page for CCCryptor.3cc and 10.4 doesn't, so YMMV.


EDIT: See this follow-up question on using Base64 encoding for representing encrypted data bytes as a string (if desired) using safe, lossless conversions.

Calculating width from percent to pixel then minus by pixel in LESS CSS

I think width: -moz-calc(25% - 1em); is what you are looking for. And you may want to give this Link a look for any further assistance

How to check for a Null value in VB.NET

editTransactionRow.pay_id is Null so in fact you are doing: null.ToString() and it cannot be executed. You need to check editTransactionRow.pay_id and not editTransactionRow.pay_id.ToString();

You code should be (IF pay_id is a string):

If String.IsNullOrEmpty(editTransactionRow.pay_id) = False Then
    stTransactionPaymentID = editTransactionRow.pay_id 'Check for null value
End If

If pay_id is an Integer than you can just check if it's null normally without String... Edit to show you if it's not a String:

If editTransactionRow.pay_id IsNot Nothing Then
    stTransactionPaymentID = editTransactionRow.pay_id 'Check for null value
End If

If it's from a database you can use IsDBNull but if not, do not use it.

Clean out Eclipse workspace metadata

In some cases, I could prevent Eclipse from crashing during startup by deleting a .snap file in your workspace meta-data (.metadata/.plugins/org.eclipse.core.resources/.snap).

See also https://bugs.eclipse.org/bugs/show_bug.cgi?id=149121 (the bug has been closed, but happened to me recently)

Read remote file with node.js (http.get)

I'd use request for this:

request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

Or if you don't need to save to a file first, and you just need to read the CSV into memory, you can do the following:

var request = require('request');
request.get('http://www.whatever.com/my.csv', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var csv = body;
        // Continue with your processing here.
    }
});

etc.

How do I get the current date and time in PHP?

echo date("d-m-Y H:i:sa");

This code will get the date and time of the server that the code runs on.

Parse String to Date with Different Format in Java

tl;dr

LocalDate.parse( 
    "19/05/2009" , 
    DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) 
)

Details

The other Answers with java.util.Date, java.sql.Date, and SimpleDateFormat are now outdated.

LocalDate

The modern way to do date-time is work with the java.time classes, specifically LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.

DateTimeFormatter

To parse, or generate, a String representing a date-time value, use the DateTimeFormatter class.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( "19/05/2009" , f );

Do not conflate a date-time object with a String representing its value. A date-time object has no format, while a String does. A date-time object, such as LocalDate, can generate a String to represent its internal value, but the date-time object and the String are separate distinct objects.

You can specify any custom format to generate a String. Or let java.time do the work of automatically localizing.

DateTimeFormatter f = 
    DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL )
                     .withLocale( Locale.CANADA_FRENCH ) ;
String output = ld.format( f );

Dump to console.

System.out.println( "ld: " + ld + " | output: " + output );

ld: 2009-05-19 | output: mardi 19 mai 2009

See in action in IdeOne.com.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

"Debug certificate expired" error in Eclipse Android plugins

After you install the Android SDK in Eclipse, it generates a debug signing certificate for you in a keystore called debug.keystore. The Eclipse plug-in uses this certificate to sign each application build that is generated.

Now, the problem with this debug certificate is that it is only valid for a year, or 365 days. If your Eclipse IDE uses an expired debug certificate, you will not be able to create and/or deploy an Android app.

To fix this problem all you need to do is delete the debug.keystore file.

  1. Go to Preferences
  2. Android
  3. Build
  4. Default debug keystore

There you should see the folder where the file is located. Simply delete that file and you are good to go.

For more info. you can visit

http://developer.android.com/tools/publishing/app-signing.html

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

Pls, check if DataGridComboBoxColumn xaml below would work for you:

<DataGridComboBoxColumn 
    SelectedValueBinding="{Binding CompanyID}" 
    DisplayMemberPath="Name" 
    SelectedValuePath="ID">

    <DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="ItemsSource" Value="{Binding Path=DataContext.CompanyItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
        </Style>
    </DataGridComboBoxColumn.ElementStyle>
    <DataGridComboBoxColumn.EditingElementStyle>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="ItemsSource" Value="{Binding Path=DataContext.CompanyItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
        </Style>
    </DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>

Here you can find another solution for the problem you're facing: Using combo boxes with the WPF DataGrid

How to use subList()

To get the last element, simply use the size of the list as the second parameter. So for example, if you have 35 files, and you want the last five, you would do:

dataList.subList(30, 35);

A guaranteed safe way to do this is:

dataList.subList(Math.max(0, first), Math.min(dataList.size(), last) );

How to make a simple image upload using Javascript/HTML

Here's a simple example with no jQuery. Use URL.createObjectURL, which

creates a DOMString containing a URL representing the object given in the parameter

Then, you can simply set the src of the image to that url:

_x000D_
_x000D_
window.addEventListener('load', function() {
  document.querySelector('input[type="file"]').addEventListener('change', function() {
      if (this.files && this.files[0]) {
          var img = document.querySelector('img');
          img.onload = () => {
              URL.revokeObjectURL(img.src);  // no longer needed, free memory
          }

          img.src = URL.createObjectURL(this.files[0]); // set src to blob url
      }
  });
});
_x000D_
<input type='file' />
<br><img id="myImg" src="#">
_x000D_
_x000D_
_x000D_

How to format date and time in Android?

Shortest way:

// 2019-03-29 16:11
String.format("%1$tY-%<tm-%<td %<tR", Calendar.getInstance())

%tR is short for %tH:%tM, < means to reuse last parameter(1$).

It is equivalent to String.format("%1$tY-%1$tm-%1$td %1$tH:%1$tM", Calendar.getInstance())

https://developer.android.com/reference/java/util/Formatter.html

Add CSS to iFrame

Based on solution You've already found How to apply CSS to iframe?:

var cssLink = document.createElement("link") 
cssLink.href = "file://path/to/style.css"; 
cssLink .rel = "stylesheet"; 
cssLink .type = "text/css"; 
frames['iframe'].document.body.appendChild(cssLink);

or more jqueryish (from Append a stylesheet to an iframe with jQuery):

var $head = $("iframe").contents().find("head");                
$head.append($("<link/>", 
    { rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));

as for security issues: Disabling same-origin policy in Safari

Resource files not found from JUnit test cases

Main classes should be under src/main/java
and
test classes should be under src/test/java

If all in the correct places and still main classes are not accessible then
Right click project => Maven => Update Project
Hope so this will resolve the issue

Adding a module (Specifically pymorph) to Spyder (Python IDE)

I faced the same problem when trying to add the seaborn module in Spyder. I installed seaborn into my anaconda directory in ubuntu 14.04. The seaborn module would load if I added the entire anaconda/lib/python2.7/site-packages/ directory which contained the 'seaborn' and seaborn-0.5.1-py2.7.egg-info folders. The problem was this anaconda site-packages folder also contained many other modules which Spyder did not like.

My solution: I created a new directory in my personal Home folder that I named 'spyderlibs' where I placed seaborn and seaborn-0.5.1-py2.7.egg-info folders. Adding my new spyderlib directory in Spyder's PYTHONPATH manager worked!

D3 transform scale and translate

The transforms are SVG transforms (for details, have a look at the standard; here are some examples). Basically, scale and translate apply the respective transformations to the coordinate system, which should work as expected in most cases. You can apply more than one transform however (e.g. first scale and then translate) and then the result might not be what you expect.

When working with the transforms, keep in mind that they transform the coordinate system. In principle, what you say is true -- if you apply a scale > 1 to an object, it will look bigger and a translate will move it to a different position relative to the other objects.

VBA macro that search for file in multiple subfolders

Just for fun, here's a sample with a recursive function which (I hope) should be a bit simpler to understand and to use with your code:

Function Recurse(sPath As String) As String

    Dim FSO As New FileSystemObject
    Dim myFolder As Folder
    Dim mySubFolder As Folder

    Set myFolder = FSO.GetFolder(sPath)
    For Each mySubFolder In myFolder.SubFolders
        Call TestSub(mySubFolder.Path)
        Recurse = Recurse(mySubFolder.Path)
    Next

End Function

Sub TestR()

    Call Recurse("D:\Projets\")

End Sub

Sub TestSub(ByVal s As String)

    Debug.Print s

End Sub

Edit: Here's how you can implement this code in your workbook to achieve your objective.

Sub TestSub(ByVal s As String)

    Dim FSO As New FileSystemObject
    Dim myFolder As Folder
    Dim myFile As File

    Set myFolder = FSO.GetFolder(s)
    For Each myFile In myFolder.Files
        If myFile.Name = Range("E1").Value Then
            Debug.Print myFile.Name 'Or do whatever you want with the file
        End If
    Next

End Sub

Here, I just debug the name of the found file, the rest is up to you. ;)

Of course, some would say it's a bit clumsy to call twice the FileSystemObject so you could simply write your code like this (depends on wether you want to compartmentalize or not):

Function Recurse(sPath As String) As String

    Dim FSO As New FileSystemObject
    Dim myFolder As Folder
    Dim mySubFolder As Folder
    Dim myFile As File

    Set myFolder = FSO.GetFolder(sPath)

    For Each mySubFolder In myFolder.SubFolders
        For Each myFile In mySubFolder.Files
            If myFile.Name = Range("E1").Value Then
                Debug.Print myFile.Name & " in " & myFile.Path 'Or do whatever you want with the file
                Exit For
            End If
        Next
        Recurse = Recurse(mySubFolder.Path)
    Next

End Function

Sub TestR()

    Call Recurse("D:\Projets\")

End Sub

How to detect iPhone 5 (widescreen devices)?

I've taken the liberty to put the macro by Macmade into a C function, and name it properly because it detects widescreen availability and NOT necessarily the iPhone 5.

The macro also doesn't detect running on an iPhone 5 in case where the project doesn't include the [email protected]. Without the new Default image, the iPhone 5 will report a regular 480x320 screen size (in points). So the check isn't just for widescreen availability but for widescreen mode being enabled as well.

BOOL isWidescreenEnabled()
{
    return (BOOL)(fabs((double)[UIScreen mainScreen].bounds.size.height - 
                                               (double)568) < DBL_EPSILON);
}

Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0?

I have several projects in a solution. For some of the projects, I previously added the references manually. When I used NuGet to update the WebAPI package, those references were not updated automatically.

I found out that I can either manually update those reference so they point to the v5 DLL inside the Packages folder of my solution or do the following.

  1. Go to the "Manage NuGet Packages"
  2. Select the Installed Package "Microsoft ASP.NET Web API 2.1"
  3. Click Manage and check the projects that I manually added before.

How can I loop through a List<T> and grab each item?

foreach:

foreach (var money in myMoney) {
    Console.WriteLine("Amount is {0} and type is {1}", money.amount, money.type);
}

MSDN Link

Alternatively, because it is a List<T>.. which implements an indexer method [], you can use a normal for loop as well.. although its less readble (IMO):

for (var i = 0; i < myMoney.Count; i++) {
    Console.WriteLine("Amount is {0} and type is {1}", myMoney[i].amount, myMoney[i].type);
}

Git: Find the most recent common ancestor of two branches

You are looking for git merge-base. Usage:

$ git merge-base branch2 branch3
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

JSON.Parse,'Uncaught SyntaxError: Unexpected token o

Your last example is invalid JSON. Single quotes are not allowed in JSON except inside strings. In the second example, the single quotes are not in the string, but serve to show the start and end.

See http://www.json.org/ for the specifications.

Should add: Why do you think this: "like I seem to need to in my real code"? Then maybe we can help you come up with the solution.

mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in

That query is failing and returning false.

Put this after mysqli_query() to see what's going on.

if (!$check1_res) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

For more information:

http://www.php.net/manual/en/mysqli.error.php

Issue with parsing the content from json file with Jackson & message- JsonMappingException -Cannot deserialize as out of START_ARRAY token

As said, JsonMappingException: out of START_ARRAY token exception is thrown by Jackson object mapper as it's expecting an Object {} whereas it found an Array [{}] in response.

A simpler solution could be replacing the method getLocations with:

public static List<Location> getLocations(InputStream inputStream) {
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        TypeReference<List<Location>> typeReference = new TypeReference<>() {};
        return objectMapper.readValue(inputStream, typeReference);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

On the other hand, if you don't have a pojo like Location, you could use:

TypeReference<List<Map<String, Object>>> typeReference = new TypeReference<>() {};
return objectMapper.readValue(inputStream, typeReference);

Getting Image from API in Angular 4/5+?

angular 5 :

 getImage(id: string): Observable<Blob> {
    return this.httpClient.get('http://myip/image/'+id, {responseType: "blob"});
}

Replace all elements of Python NumPy Array that are greater than some value

You can consider using numpy.putmask:

np.putmask(arr, arr>=T, 255.0)

Here is a performance comparison with the Numpy's builtin indexing:

In [1]: import numpy as np
In [2]: A = np.random.rand(500, 500)

In [3]: timeit np.putmask(A, A>0.5, 5)
1000 loops, best of 3: 1.34 ms per loop

In [4]: timeit A[A > 0.5] = 5
1000 loops, best of 3: 1.82 ms per loop

Get domain name

If you want specific users to have access to all or part of the WMI object space, you need to permission them as shown here. Note that you have to be running on as an admin to perform this setting.

Changing java platform on which netbeans runs

on Fedora it is currently impossible to set a new jdk-HOME to some sdk. They designed it such that it will always break. Try --jdkhome [whatever] but in all likelihood it will break and show some cryptic nonsensical error message as usual.

Default Xmxsize in Java 8 (max heap size)

As of 8, May, 2019:

JVM heap size depends on system configuration, meaning:

a) client jvm vs server jvm

b) 32bit vs 64bit.

Links:

1) updation from J2SE5.0: https://docs.oracle.com/javase/6/docs/technotes/guides/vm/gc-ergonomics.html
2) brief answer: https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/ergonomics.html
3) detailed answer: https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/parallel.html#default_heap_size
4) client vs server: https://www.javacodegeeks.com/2011/07/jvm-options-client-vs-server.html

Summary: (Its tough to understand from the above links. So summarizing them here)

1) Default maximum heap size for Client jvm is 256mb (there is an exception, read from links above).

2) Default maximum heap size for Server jvm of 32bit is 1gb and of 64 bit is 32gb (again there are exceptions here too. Kindly read that from the links).

So default maximum jvm heap size is: 256mb or 1gb or 32gb depending on VM, above.

Are HTTPS headers encrypted?

The headers are entirely encrypted. The only information going over the network 'in the clear' is related to the SSL setup and D/H key exchange. This exchange is carefully designed not to yield any useful information to eavesdroppers, and once it has taken place, all data is encrypted.

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

How to calculate the sentence similarity using word2vec model of gensim with python

you can use Word Mover's Distance algorithm. here is an easy description about WMD.

#load word2vec model, here GoogleNews is used
model = gensim.models.KeyedVectors.load_word2vec_format('../GoogleNews-vectors-negative300.bin', binary=True)
#two sample sentences 
s1 = 'the first sentence'
s2 = 'the second text'

#calculate distance between two sentences using WMD algorithm
distance = model.wmdistance(s1, s2)

print ('distance = %.3f' % distance)

P.s.: if you face an error about import pyemd library, you can install it using following command:

pip install pyemd

How to pass credentials to httpwebrequest for accessing SharePoint Library

If you need to run request as the current user from desktop application use CredentialCache.DefaultCredentials (see on MSDN).

Your code looks fine if you need to run a request from server side code or under a different user.

Please note that you should be careful when storing passwords - consider using the SecureString version of the constructor.

Sorting string array in C#

Actually I don't see any nulls:

given:

static void Main()
        {
            string[] testArray = new string[]
            {
                "aa",
                "ab",
                "ac",
                "ad",
                "ab",
                "af"
            };

            Array.Sort(testArray, StringComparer.InvariantCulture);

            Array.ForEach(testArray, x => Console.WriteLine(x));
        }

I obtained:

enter image description here

The correct way to read a data file into an array

open AAAA,"/filepath/filename.txt";
my @array = <AAAA>; # read the file into an array of lines
close AAAA;

regular expression for finding 'href' value of a <a> link

Try this :

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var res = Find(html);
        }

        public static List<LinkItem> Find(string file)
        {
            List<LinkItem> list = new List<LinkItem>();

            // 1.
            // Find all matches in file.
            MatchCollection m1 = Regex.Matches(file, @"(<a.*?>.*?</a>)",
                RegexOptions.Singleline);

            // 2.
            // Loop over each match.
            foreach (Match m in m1)
            {
                string value = m.Groups[1].Value;
                LinkItem i = new LinkItem();

                // 3.
                // Get href attribute.
                Match m2 = Regex.Match(value, @"href=\""(.*?)\""",
                RegexOptions.Singleline);
                if (m2.Success)
                {
                    i.Href = m2.Groups[1].Value;
                }

                // 4.
                // Remove inner tags from text.
                string t = Regex.Replace(value, @"\s*<.*?>\s*", "",
                RegexOptions.Singleline);
                i.Text = t;

                list.Add(i);
            }
            return list;
        }

        public struct LinkItem
        {
            public string Href;
            public string Text;

            public override string ToString()
            {
                return Href + "\n\t" + Text;
            }
        }

    }  

Input:

  string html = "<a href=\"www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a> 2.<a href=\"http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a> "; 

Result:

[0] = {www.aaa.xx/xx.zz?id=xxxx&name=xxxx}
[1] = {http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx}

C# Scraping HTML Links

Scraping HTML extracts important page elements. It has many legal uses for webmasters and ASP.NET developers. With the Regex type and WebClient, we implement screen scraping for HTML.

Edited

Another easy way:you can use a web browser control for getting href from tag a,like this:(see my example)

 public Form1()
        {
            InitializeComponent();
            webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            webBrowser1.DocumentText = "<a href=\"www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"https://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"www.aaa.xx/xx.zz/xxx\" ....></a>";
        }

        void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            List<string> href = new List<string>();
            foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("a"))
            {
                href.Add(el.GetAttribute("href"));
            }
        }

How to create a new column in a select query

SELECT field1, 
       field2,
       'example' AS newfield
FROM TABLE1

This will add a column called "newfield" to the output, and its value will always be "example".

What is the order of precedence for CSS?

Here's a compilation of CSS styling order in a diagram, on which CSS rules has higher priority and take precedence over the rest: CSS styling order

Disclaimer: My team and I worked this piece out together with a blog post (https://vecta.io/blog/definitive-guide-to-css-styling-order) which I think will come in handy to all front-end developers.

Get div's offsetTop positions in React

  import ReactDOM from 'react-dom';
  //...
  componentDidMount() {
    var n = ReactDOM.findDOMNode(this);
    console.log(n.offsetTop);
  }

You can just grab the offsetTop from the Node.

Automatically create an Enum based on values in a database lookup table?

Just showing the answer of Pandincus with "of the shelf" code and some explanation: You need two solutions for this example ( I know it could be done via one also ; ), let the advanced students present it ...

So here is the DDL SQL for the table :

USE [ocms_dev]
    GO

CREATE TABLE [dbo].[Role](
    [RoleId] [int] IDENTITY(1,1) NOT NULL,
    [RoleName] [varchar](50) NULL
) ON [PRIMARY]

So here is the console program producing the dll:

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
using System.Data.Common;
using System.Data;
using System.Data.SqlClient;

namespace DynamicEnums
{
    class EnumCreator
    {
        // after running for first time rename this method to Main1
        static void Main ()
        {
            string strAssemblyName = "MyEnums";
            bool flagFileExists = System.IO.File.Exists (
                   AppDomain.CurrentDomain.SetupInformation.ApplicationBase + 
                   strAssemblyName + ".dll"
            );

            // Get the current application domain for the current thread
            AppDomain currentDomain = AppDomain.CurrentDomain;

            // Create a dynamic assembly in the current application domain,
            // and allow it to be executed and saved to disk.
            AssemblyName name = new AssemblyName ( strAssemblyName );
            AssemblyBuilder assemblyBuilder = 
                    currentDomain.DefineDynamicAssembly ( name,
                            AssemblyBuilderAccess.RunAndSave );

            // Define a dynamic module in "MyEnums" assembly.
            // For a single-module assembly, the module has the same name as
            // the assembly.
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule (
                    name.Name, name.Name + ".dll" );

            // Define a public enumeration with the name "MyEnum" and
            // an underlying type of Integer.
            EnumBuilder myEnum = moduleBuilder.DefineEnum (
                    "EnumeratedTypes.MyEnum",
                    TypeAttributes.Public,
                    typeof ( int )
            );

            #region GetTheDataFromTheDatabase
            DataTable tableData = new DataTable ( "enumSourceDataTable" );

            string connectionString = "Integrated Security=SSPI;Persist " +
                    "Security Info=False;Initial Catalog=ocms_dev;Data " +
                    "Source=ysg";

            using (SqlConnection connection = 
                    new SqlConnection ( connectionString ))
            {

                SqlCommand command = connection.CreateCommand ();
                command.CommandText = string.Format ( "SELECT [RoleId], " + 
                        "[RoleName] FROM [ocms_dev].[dbo].[Role]" );

                Console.WriteLine ( "command.CommandText is " + 
                        command.CommandText );

                connection.Open ();
                tableData.Load ( command.ExecuteReader ( 
                        CommandBehavior.CloseConnection
                ) );
            } //eof using

            foreach (DataRow dr in tableData.Rows)
            {
                myEnum.DefineLiteral ( dr[1].ToString (),
                        Convert.ToInt32 ( dr[0].ToString () ) );
            }
            #endregion GetTheDataFromTheDatabase

            // Create the enum
            myEnum.CreateType ();

            // Finally, save the assembly
            assemblyBuilder.Save ( name.Name + ".dll" );
        } //eof Main 
    } //eof Program
} //eof namespace 

Here is the Console programming printing the output ( remember that it has to reference the dll ). Let the advance students present the solution for combining everything in one solution with dynamic loading and checking if there is already build dll.

// add the reference to the newly generated dll
use MyEnums ; 

class Program
{
    static void Main ()
    {
        Array values = Enum.GetValues ( typeof ( EnumeratedTypes.MyEnum ) );

        foreach (EnumeratedTypes.MyEnum val in values)
        {
            Console.WriteLine ( String.Format ( "{0}: {1}",
                    Enum.GetName ( typeof ( EnumeratedTypes.MyEnum ), val ),
                    val ) );
        }

        Console.WriteLine ( "Hit enter to exit " );
        Console.ReadLine ();
    } //eof Main 
} //eof Program

jQuery $(this) keyword

Have a look at this code:

HTML:

<div class="multiple-elements" data-bgcol="red"></div>
<div class="multiple-elements" data-bgcol="blue"></div>

JS:

$('.multiple-elements').each(
    function(index, element) {
        $(this).css('background-color', $(this).data('bgcol')); // Get value of HTML attribute data-bgcol="" and set it as CSS color
    }
);

this refers to the current element that the DOM engine is sort of working on, or referring to.

Another example:

<a href="#" onclick="$(this).css('display', 'none')">Hide me!</a>

Hope you understand now. The this keyword occurs while dealing with object oriented systems, or as we have in this case, element oriented systems :)

What's the difference between using CGFloat and float?

As others have said, CGFloat is a float on 32-bit systems and a double on 64-bit systems. However, the decision to do that was inherited from OS X, where it was made based on the performance characteristics of early PowerPC CPUs. In other words, you should not think that float is for 32-bit CPUs and double is for 64-bit CPUs. (I believe, Apple's ARM processors were able to process doubles long before they went 64-bit.) The main performance hit of using doubles is that they use twice the memory and therefore might be slower if you are doing a lot of floating point operations.

Insert string at specified position

str_replace($sub_str, $insert_str.$sub_str, $org_str);

java.lang.OutOfMemoryError: GC overhead limit exceeded

Use alternative HashMap implementation (Trove). Standard Java HashMap has >12x memory overhead. One can read details here.

Rollback to last git commit

If you want to just uncommit the last commit use this:

git reset HEAD~

work like charm for me.

How to create dictionary and add key–value pairs dynamically?

I ran into this problem.. but within a for loop. The top solution did not work (when using variables (and not strings) for the parameters of the push function), and the others did not account for key values based on variables. I was surprised this approach (which is common in php) worked..

  // example dict/json                  
  var iterateDict = {'record_identifier': {'content':'Some content','title':'Title of my Record'},
    'record_identifier_2': {'content':'Some  different content','title':'Title of my another Record'} };

  var array = [];

  // key to reduce the 'record' to
  var reduceKey = 'title';

  for(key in iterateDict)
   // ultra-safe variable checking...
   if(iterateDict[key] !== undefined && iterateDict[key][reduceKey] !== undefined)
    // build element to new array key
     array[key]=iterateDict[key][reduceKey];

How to manually install an artifact in Maven 2?

All the posted answers rightfully discuss this from a strictly maven perspective. My issues was in doing this install for maven using Netbeans as my primary IDE. I found the below article helpful.

Credit to the following netbeans forum article: http://forums.netbeans.org/topic22907.html

  1. In Maven project open "Add dependency" dialog
  2. Make up some groupId, artifactId and version and fill them, OK.
  3. Dependency will be added to the pom.xml and will appear under "Libraries" node of maven project
  4. Right-click Lib node and "manually install artifact", fill the path to the jar. Jar should be installed to local Maven repo with coordinates entered in step 2)

How can I use a batch file to write to a text file?

@echo off Title Writing using Batch Files color 0a

echo Example Text > Filename.txt echo Additional Text >> Filename.txt

@ECHO OFF
Title Writing Using Batch Files
color 0a

echo Example Text > Filename.txt
echo Additional Text >> Filename.txt

Angular 2 ngfor first, last, index loop

Check out this plunkr.

When you're binding to variables, you need to use the brackets. Also, you use the hashtag when you want to get references to elements in your html, not for declaring variables inside of templates like that.

<md-button-toggle *ngFor="let indicador of indicadores; let first = first;" [value]="indicador.id" [checked]="first"> 
...

Edit: Thanks to Christopher Moore: Angular exposes the following local variables:

  • index
  • first
  • last
  • even
  • odd

Importing CommonCrypto in a Swift framework

In case you have the below issue :

ld: library not found for -lapple_crypto clang: error: linker command failed with exit code 1 (use -v to see invocation)

In Xcode 10, Swift 4.0. CommonCrypto is a part of the framework.

Add

 import CommonCrypto

Remove

  • CommonCrpto lib file from link binary with libraries from Build phases
  • import CommonCrypto from Bridging header

This worked for me!

File to import not found or unreadable: compass

In short, if you've installed the gem the run:

compass compile

in your rails root dir

How to rename a file using svn?

Using TortoiseSVN worked easily on Windows for me.

http://tortoisesvn.net/

Right click file -> TortoiseSVN menu -> Repo-browser -> right click file in repository -> rename -> press Enter -> click Ok

Using SVN 1.8.8 TortoiseSVN version 1.8.5

Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

/*Maximum value that can be entered is 2,147,483,647
 * Program to convert entered number into string
 * */
import java.util.Scanner;

public class NumberToWords 
{

public static void main(String[] args) 
{
    double num;//for taking input number
    Scanner obj=new Scanner(System.in);
    do
    {
        System.out.println("\n\nEnter the Number (Maximum value that can be entered is 2,147,483,647)");
        num=obj.nextDouble();
        if(num<=2147483647)//checking if entered number exceeds maximum integer value
        {
            int number=(int)num;//type casting double number to integer number
            splitNumber(number);//calling splitNumber-it will split complete number in pairs of 3 digits
        }
        else
            System.out.println("Enter smaller value");//asking user to enter a smaller value compared to 2,147,483,647
    }while(num>2147483647);
}
//function to split complete number into pair of 3 digits each
public static void splitNumber(int number)
{   //splitNumber array-contains the numbers in pair of 3 digits
    int splitNumber[]=new int[4],temp=number,i=0,index;
    //splitting number into pair of 3
    if(temp==0)
        System.out.println("zero");
    while(temp!=0)
    {
        splitNumber[i++]=temp%1000;
        temp/=1000;
    }
    //passing each pair of 3 digits to another function
    for(int j=i-1;j>-1;j--)
    {   //toWords function will split pair of 3 digits to separate digits
        if(splitNumber[j]!=0)
            {toWords(splitNumber[j]);
        if(j==3)//if the number contained more than 9 digits
            System.out.print("billion,");
        else if(j==2)//if the number contained more than 6 digits & less than 10 digits
            System.out.print("million,");
        else if(j==1)
            System.out.print("thousand,");//if the number contained more than 3 digits & less than 7 digits
            }
            }       
}
//function that splits number into individual digits
public static void toWords(int number)
    //splitSmallNumber array contains individual digits of number passed to this function
{   int splitSmallNumber[]=new int[3],i=0,j;
    int temp=number;//making temporary copy of the number
    //logic to split number into its constituent digits

    while(temp!=0)
    {
        splitSmallNumber[i++]=temp%10;
        temp/=10;
    }
    //printing words for each digit
    for(j=i-1;j>-1;j--)
      //{   if the digit is greater than zero
        if(splitSmallNumber[j]>=0)
            //if the digit is at 3rd place or if digit is at (1st place with digit at 2nd place not equal to zero)
        {   if(j==2||(j==0 && (splitSmallNumber[1]!=1)))
            {
                switch(splitSmallNumber[j])
                {

                    case 1:System.out.print("one ");break;
                    case 2:System.out.print("two ");break;
                    case 3:System.out.print("three ");break;
                    case 4:System.out.print("four ");break;
                    case 5:System.out.print("five ");break;
                    case 6:System.out.print("six ");break;
                    case 7:System.out.print("seven ");break;
                    case 8:System.out.print("eight ");break;
                    case 9:System.out.print("nine ");break;

            }

        }
        //if digit is at 2nd place
        if(j==1)
        {       //if digit at 2nd place is 0 or 1
                if(((splitSmallNumber[j]==0)||(splitSmallNumber[j]==1))&& splitSmallNumber[2]!=0 )
                System.out.print("hundred ");
            switch(splitSmallNumber[1])
            {   case 1://if digit at 2nd place is 1 example-213
                        switch(splitSmallNumber[0])
                        {
                        case 1:System.out.print("eleven ");break;
                        case 2:System.out.print("twelve ");break;
                        case 3:System.out.print("thirteen ");break;
                        case 4:System.out.print("fourteen ");break;
                        case 5:System.out.print("fifteen ");break;
                        case 6:System.out.print("sixteen ");break;
                        case 7:System.out.print("seventeen ");break;
                        case 8:System.out.print("eighteen ");break;
                        case 9:System.out.print("nineteen ");break;
                        case 0:System.out.print("ten ");break;
                        }break;
                        //if digit at 2nd place is not 1
                    case 2:System.out.print("twenty ");break;
                    case 3:System.out.print("thirty ");break;
                    case 4:System.out.print("forty ");break;
                    case 5:System.out.print("fifty ");break;
                    case 6:System.out.print("sixty ");break;
                    case 7:System.out.print("seventy ");break;
                    case 8:System.out.print("eighty ");break;
                    case 9:System.out.print("ninety ");break;
                    //case 0:   System.out.println("hundred ");break;

            }                           
        }           
    }
  }

}

Is it possible to set the stacking order of pseudo-elements below their parent element?

I fixed it very simple:

.parent {
  position: relative;
  z-index: 1;
}

.child {
  position: absolute;
  z-index: -1;
}

What this does is stack the parent at z-index: 1, which gives the child room to 'end up' at z-index: 0 since other dom elements 'exist' on z-index: 0. If we don't give the parent an z-index of 1 the child will end up below the other dom elements and thus will not be visible.

This also works for pseudo elements like :after

Get textarea text with javascript or Jquery

As @Darin Dimitrov said, if it is not an iframe on the same domain it is not posible, if it is, check that $("#frame1").contents() returns all it should, and then check if the textbox is found:

$("#frame1").contents().find("#area1").length should be 1.

Edit

If when your textarea is "empty" an empty string is returned and when it has some text entered that text is returned, then it is working perfect!! When the textarea is empty, an empty string is returned!

Edit 2 Ok. Here there is one way, it is not very pretty but it works:

Outside the iframe you will access the textarea like this:

window.textAreaInIframe

And inside the iframe (which I assume has jQuery) in the document ready put this code:

$("#area1").change(function() {
    window.parent.textAreaInIframe = $(this).val();
}).trigger("change");

Differences between Emacs and Vim

A jaundiced point of view:

vi (not vim) is a professional necessity. You always have some form of vi easily available, no matter what the environment. You can be in vi when in emacs, you can be in vi to build bash commands in unix-land.

Even Microsquish has to support vi (although they do a good job of hiding it) because of gov't and corporate compliance with published standards.

In my opinion, if you are in a hands-on job in a busy environment--not a hothouse flower confined to one fancy rig in a development environment, or in academia--knowing a lot about a fancy editor is a job handicap. Don't learn all the fancy tricks in vim or emacs, and don't develop a bunch of macros to make the editing environment bend to your will. It's an enormous time sink that gets in your way when you attend to different machines that you probably can't justify in a factory environment.

Read Bill Joy's paper--it is a very competent, perhaps even beautiful, engineering exercise in editing plain text very, very fast. Parito's rule applies here: 80% of the fruit is in 20% of the baskets. Editing plain text very very fast is the crux of editing competence--all else is optional--and sometimes hurtful.

Using Cygwin to Compile a C program; Execution error

Windows path C:\src under cygwin becomes /cygdrive/c/src

Group by & count function in sqlalchemy

You can also count on multiple groups and their intersection:

self.session.query(func.count(Table.column1),Table.column1, Table.column2).group_by(Table.column1, Table.column2).all()

The query above will return counts for all possible combinations of values from both columns.

Long vs Integer, long vs int, what to use and when?

Long is the Object form of long, and Integer is the object form of int.

The long uses 64 bits. The int uses 32 bits, and so can only hold numbers up to ±2 billion (-231 to +231-1).

You should use long and int, except where you need to make use of methods inherited from Object, such as hashcode. Java.util.collections methods usually use the boxed (Object-wrapped) versions, because they need to work for any Object, and a primitive type, like int or long, is not an Object.

Another difference is that long and int are pass-by-value, whereas Long and Integer are pass-by-reference value, like all non-primitive Java types. So if it were possible to modify a Long or Integer (it's not, they're immutable without using JNI code), there would be another reason to use one over the other.

A final difference is that a Long or Integer could be null.

Git Commit Messages: 50/72 Formatting

Is the maximum recommended title length really 50?

I have believed this for years, but as I just noticed the documentation of "git commit" actually states

$ git help commit | grep -C 1 50
      Though not required, it’s a good idea to begin the commit message with
      a single short (less than 50 character) line summarizing the change,
      followed by a blank line and then a more thorough description. The text

$  git version
git version 2.11.0

One could argue that "less then 50" can only mean "no longer than 49".

How to cherry-pick multiple commits

To cherry pick from a commit id up to the tip of the branch, you can use:

git cherry-pick commit_id^..branch_name

IE6/IE7 css border on select element

i was having this same issue with ie, then i inserted this meta tag and it allowed me to edit the borders in ie

<meta http-equiv="X-UA-Compatible" content="IE=100" >

How to insert element as a first child?

parentNode.insertBefore(newChild, refChild)

Inserts the node newChild as a child of parentNode before the existing child node refChild. (Returns newChild.)

If refChild is null, newChild is added at the end of the list of children. Equivalently, and more readably, use parentNode.appendChild(newChild).

What is the difference between Jupyter Notebook and JupyterLab?

This answer shows the python perspective. Jupyter supports various languages besides python.

Both Jupyter Notebook and Jupyterlab are browser compatible interactive python (i.e. python ".ipynb" files) environments, where you can divide the various portions of the code into various individually executable cells for the sake of better readability. Both of these are popular in Data Science/Scientific Computing domain.

I'd suggest you to go with Jupyterlab for the advantages over Jupyter notebooks:

  1. In Jupyterlab, you can create ".py" files, ".ipynb" files, open terminal etc. Jupyter Notebook allows ".ipynb" files while providing you the choice to choose "python 2" or "python 3".
  2. Jupyterlab can open multiple ".ipynb" files inside a single browser tab. Whereas, Jupyter Notebook will create new tab to open new ".ipynb" files every time. Hovering between various tabs of browser is tedious, thus Jupyterlab is more helpful here.

I'd recommend using PIP to install Jupyterlab.

If you can't open a ".ipynb" file using Jupyterlab on Windows system, here are the steps:

  1. Go to the file --> Right click --> Open With --> Choose another app --> More Apps --> Look for another apps on this PC --> Click.
  2. This will open a file explorer window. Now go inside your Python installation folder. You should see Scripts folder. Go inside it.
  3. Once you find jupyter-lab.exe, select that and now it will open the .ipynb files by default on your PC.

How to get GET (query string) variables in Express.js on Node.js?

If you ever need to send GET request to an IP as well as a Domain (Other answers did not mention you can specify a port variable), you can make use of this function:

function getCode(host, port, path, queryString) {
    console.log("(" + host + ":" + port + path + ")" + "Running httpHelper.getCode()")

    // Construct url and query string
    const requestUrl = url.parse(url.format({
        protocol: 'http',
        hostname: host,
        pathname: path,
        port: port,
        query: queryString
    }));

    console.log("(" + host + path + ")" + "Sending GET request")
    // Send request
    console.log(url.format(requestUrl))
    http.get(url.format(requestUrl), (resp) => {
        let data = '';

        // A chunk of data has been received.
        resp.on('data', (chunk) => {
            console.log("GET chunk: " + chunk);
            data += chunk;
        });

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            console.log("GET end of response: " + data);
        });

    }).on("error", (err) => {
        console.log("GET Error: " + err);
    });
}

Don't miss requiring modules at the top of your file:

http = require("http");
url = require('url')

Also bare in mind that you may use https module for communicating over secured domains and ssl. so these two lines would change:

https = require("https");
...
https.get(url.format(requestUrl), (resp) => { ......

How to get primary key of table?

For a PHP approach, you can use mysql_field_flags

$q = mysql_query('select * from table limit 1');

for($i = 0; $i < mysql_num_fields(); $i++)
    if(strpos(mysql_field_tags($q, $i), 'primary_key') !== false)
        echo mysql_field_name($q, $i)." is a primary key\n";

How to receive JSON as an MVC 5 action method parameter

There are a couple issues here. First, you need to make sure to bind your JSON object back to the model in the controller. This is done by changing

data: JSON.stringify(usersRoles),

to

data: { model: JSON.stringify(usersRoles) },

Secondly, you aren't binding types correctly with your jquery call. If you remove

contentType: "application/json; charset=utf-8",

it will inherently bind back to a string.

All together, use the first ActionResult method and the following jquery ajax call:

    jQuery.ajax({
        type: "POST",
        url: "@Url.Action("AddUser")",
        dataType: "json",
        data: { model: JSON.stringify(usersRoles) },
        success: function (data) { alert(data); },
        failure: function (errMsg) {
        alert(errMsg);
        }
   });

How to use Typescript with native ES6 Promises

I had to downgrade @types/core-js to 9.36 to get it to work with "target": "es5" set in my tsconfig.

"@types/core-js": "0.9.36",

How to get the Facebook user id using the access token

Check out this answer, which describes, how to get ID response. First, you need to create method get data:

const https = require('https');
getFbData = (accessToken, apiPath, callback) => {
    const options = {
        host: 'graph.facebook.com',
        port: 443,
        path: `${apiPath}access_token=${accessToken}`, // apiPath example: '/me/friends'
        method: 'GET'
    };

    let buffer = ''; // this buffer will be populated with the chunks of the data received from facebook
    const request = https.get(options, (result) => {
        result.setEncoding('utf8');
        result.on('data', (chunk) => {
            buffer += chunk;
        });

        result.on('end', () => {
            callback(buffer);
        });
    });

    request.on('error', (e) => {
        console.log(`error from facebook.getFbData: ${e.message}`)
    });

    request.end();
}

Then simply use your method whenever you want, like this:

getFbData(access_token, '/me?fields=id&', (result) => {
      console.log(result);
});

How to get the row number from a datatable?

ArrayList check = new ArrayList();            

for (int i = 0; i < oDS.Tables[0].Rows.Count; i++)
{
    int iValue = Convert.ToInt32(oDS.Tables[0].Rows[i][3].ToString());
    check.Add(iValue);

}

How to zip a file using cmd line?

ZIP FILE via Cross-platform Java without manifest and META-INF folder:

jar -cMf {yourfile.zip} {yourfolder}

How and where are Annotations used in Java?

JPA (from Java EE 5) is an excellent example of the (over)use of annotations. Java EE 6 will also introduce annotations in lot of new areas, such as RESTful webservices and new annotations for under each the good old Servlet API.

Here are several resources:

It is not only the configuration specifics which are to / can be taken over by annotations, but they can also be used to control the behaviour. You see this good back in the Java EE 6's JAX-RS examples.

Detect Close windows event by jQuery

You can use:

$(window).unload(function() {
    //do something
}

Unload() is deprecated in jQuery version 1.8, so if you use jQuery > 1.8 you can use even beforeunload instead.

The beforeunload event fires whenever the user leaves your page for any reason.

$(window).on("beforeunload", function() { 
    return confirm("Do you really want to close?"); 
})

Source Browser window close event

How to change the button color when it is active using bootstrap?

HTML--

<div class="col-sm-12" id="my_styles">
   <button type="submit" class="btn btn-warning" id="1">Button1</button>
   <button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>

css--

.active{
         background:red;
    }
 button.btn:active{
     background:red;
 }

jQuery--

jQuery("#my_styles .btn").click(function(){
    jQuery("#my_styles .btn").removeClass('active');
    jQuery(this).toggleClass('active'); 

});

view the live demo on jsfiddle

Check if a Postgres JSON array contains a string

You could use @> operator to do this something like

SELECT info->>'name'
FROM rabbits
WHERE info->'food' @> '"carrots"';

How to edit a text file in my terminal

Open the file again using vi. and then press " i " or press insert key ,

For save and quit

  Enter Esc    

and write the following command

  :wq

without save and quit

  :q!

Import Excel Data into PostgreSQL 9.3

For python you could use openpyxl for all 2010 and newer file formats (xlsx).

Al Sweigart has a full tutorial from automate the boring parts on working with excel spreadsheets its very indepth and the whole book and accompanying Udemy course are great resources.

From his example

>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> wb.get_sheet_names()
['Sheet1', 'Sheet2', 'Sheet3']
>>> sheet = wb.get_sheet_by_name('Sheet3')
>>> sheet
<Worksheet "Sheet3">

Understandably once you have this access you can now use psycopg to parse the data to postgres as you normally would do.

This is a link to a list of python resources at python-excel also xlwings provides a large array of features for using python in place of vba in excel.

How to switch from POST to GET in PHP CURL

CURL request by default is GET, you don't have to set any options to make a GET CURL request.

Sorting using Comparator- Descending order (User defined classes)

package com.test;

import java.util.Arrays;

public class Person implements Comparable {

private int age;

private Person(int age) {
    super();
    this.age = age;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

@Override
public int compareTo(Object o) {
    Person other = (Person)o;
    if (this == other)
        return 0;
    if (this.age < other.age) return 1;
    else if (this.age == other.age) return 0;
    else return -1;

}

public static void main(String[] args) {

    Person[] arr = new Person[4];
    arr[0] = new Person(50);
    arr[1] = new Person(20);
    arr[2] = new Person(10);
    arr[3] = new Person(90);

    Arrays.sort(arr);

    for (int i=0; i < arr.length; i++ ) {
        System.out.println(arr[i].age);
    }
}

}

Here is one way of doing it.

Python Write bytes to file

If you want to write bytes then you should open the file in binary mode.

f = open('/tmp/output', 'wb')

mysql select from n last rows

Last 5 rows retrieve in mysql

This query working perfectly

SELECT * FROM (SELECT * FROM recharge ORDER BY sno DESC LIMIT 5)sub ORDER BY sno ASC

or

select sno from(select sno from recharge order by sno desc limit 5) as t where t.sno order by t.sno asc

SVG rounded corner

I'd also consider using a plain old <rect> which provides the rx and ry attributes

MDN SVG docs <- note the second drawn rect element

Calendar Recurring/Repeating Events - Best Storage Method

I would follow this guide: https://github.com/bmoeskau/Extensible/blob/master/recurrence-overview.md

Also make sure you use the iCal format so not to reinvent the wheel and remember Rule #0: Do NOT store individual recurring event instances as rows in your database!

Reflection - get attribute name and value on property

Here are some static methods you can use to get the MaxLength, or any other attribute.

using System;
using System.Linq;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using System.Linq.Expressions;

public static class AttributeHelpers {

public static Int32 GetMaxLength<T>(Expression<Func<T,string>> propertyExpression) {
    return GetPropertyAttributeValue<T,string,MaxLengthAttribute,Int32>(propertyExpression,attr => attr.Length);
}

//Optional Extension method
public static Int32 GetMaxLength<T>(this T instance,Expression<Func<T,string>> propertyExpression) {
    return GetMaxLength<T>(propertyExpression);
}


//Required generic method to get any property attribute from any class
public static TValue GetPropertyAttributeValue<T, TOut, TAttribute, TValue>(Expression<Func<T,TOut>> propertyExpression,Func<TAttribute,TValue> valueSelector) where TAttribute : Attribute {
    var expression = (MemberExpression)propertyExpression.Body;
    var propertyInfo = (PropertyInfo)expression.Member;
    var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute),true).FirstOrDefault() as TAttribute;

    if (attr==null) {
        throw new MissingMemberException(typeof(T).Name+"."+propertyInfo.Name,typeof(TAttribute).Name);
    }

    return valueSelector(attr);
}

}

Using the static method...

var length = AttributeHelpers.GetMaxLength<Player>(x => x.PlayerName);

Or using the optional extension method on an instance...

var player = new Player();
var length = player.GetMaxLength(x => x.PlayerName);

Or using the full static method for any other attribute (StringLength for example)...

var length = AttributeHelpers.GetPropertyAttributeValue<Player,string,StringLengthAttribute,Int32>(prop => prop.PlayerName,attr => attr.MaximumLength);

Inspired by the Mikael Engver's answer.

Create ul and li elements in javascript.

Use the CSS property list-style-position to position the bullet:

list-style-position:inside /* or outside */;

converting numbers in to words C#

public static string NumberToWords(int number)
{
    if (number == 0)
        return "zero";

    if (number < 0)
        return "minus " + NumberToWords(Math.Abs(number));

    string words = "";

    if ((number / 1000000) > 0)
    {
        words += NumberToWords(number / 1000000) + " million ";
        number %= 1000000;
    }

    if ((number / 1000) > 0)
    {
        words += NumberToWords(number / 1000) + " thousand ";
        number %= 1000;
    }

    if ((number / 100) > 0)
    {
        words += NumberToWords(number / 100) + " hundred ";
        number %= 100;
    }

    if (number > 0)
    {
        if (words != "")
            words += "and ";

        var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
        var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };

        if (number < 20)
            words += unitsMap[number];
        else
        {
            words += tensMap[number / 10];
            if ((number % 10) > 0)
                words += "-" + unitsMap[number % 10];
        }
    }

    return words;
}

How to check internet access on Android? InetAddress never times out

Very important to check if we have connectivity with isAvailable() and if is possible to establish a connection with isConnected()

private static ConnectivityManager manager;

public static boolean isOnline(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
}

and you can derterminate the type of network active WiFi :

public static boolean isConnectedWifi(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
}

or mobile Móvil :

public static boolean isConnectedMobile(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
}

don´t forget the permissions:

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

MySQL Stored procedure variables from SELECT statements

I am facing a strange behavior.

SELECT INTO and SET Both works for some variables and not for others. Event syntaxes are the same

SET @Invoice_UserId :=  (SELECT UserId FROM invoice WHERE InvoiceId = @Invoice_Id  LIMIT 1); -- Working
                SET @myamount := (SELECT amount FROM invoice WHERE InvoiceId = @Invoice_Id LIMIT 1); - Not working
SELECT  Amount INTO @myamount FROM invoice WHERE InvoiceId = 29  LIMIT 1; - Not working

If I run these queries directly then works, but not working in stored procedure.

How to initialize a vector in C++

You can also do like this:

template <typename T>
class make_vector {
public:
  typedef make_vector<T> my_type;
  my_type& operator<< (const T& val) {
    data_.push_back(val);
    return *this;
  }
  operator std::vector<T>() const {
    return data_;
  }
private:
  std::vector<T> data_;
};

And use it like this:

std::vector<int> v = make_vector<int>() << 1 << 2 << 3;

Fatal error: [] operator not supported for strings

Solved!

$a['index'] = [];
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';

Swift Alamofire: How to get the HTTP response status code

For Swift 3.x / Swift 4.0 / Swift 5.0 users with Alamofire >= 4.0 / Alamofire >= 5.0


response.response?.statusCode

More verbose example:

Alamofire.request(urlString)
        .responseString { response in
            print("Success: \(response.result.isSuccess)")
            print("Response String: \(response.result.value)")

            var statusCode = response.response?.statusCode
            if let error = response.result.error as? AFError {  
                statusCode = error._code // statusCode private                 
                switch error {
                case .invalidURL(let url):
                    print("Invalid URL: \(url) - \(error.localizedDescription)")
                case .parameterEncodingFailed(let reason):
                    print("Parameter encoding failed: \(error.localizedDescription)")
                    print("Failure Reason: \(reason)")
                case .multipartEncodingFailed(let reason):
                    print("Multipart encoding failed: \(error.localizedDescription)")
                    print("Failure Reason: \(reason)")
                case .responseValidationFailed(let reason):
                    print("Response validation failed: \(error.localizedDescription)")
                    print("Failure Reason: \(reason)")

                    switch reason {
                    case .dataFileNil, .dataFileReadFailed:
                        print("Downloaded file could not be read")
                    case .missingContentType(let acceptableContentTypes):
                        print("Content Type Missing: \(acceptableContentTypes)")
                    case .unacceptableContentType(let acceptableContentTypes, let responseContentType):
                        print("Response content type: \(responseContentType) was unacceptable: \(acceptableContentTypes)")
                    case .unacceptableStatusCode(let code):
                        print("Response status code was unacceptable: \(code)")
                        statusCode = code
                    }
                case .responseSerializationFailed(let reason):
                    print("Response serialization failed: \(error.localizedDescription)")
                    print("Failure Reason: \(reason)")
                    // statusCode = 3840 ???? maybe..
                default:break
                }

                print("Underlying error: \(error.underlyingError)")
            } else if let error = response.result.error as? URLError {
                print("URLError occurred: \(error)")
            } else {
                print("Unknown error: \(response.result.error)")
            }

            print(statusCode) // the status code
    } 

(Alamofire 4 contains a completely new error system, look here for details)

For Swift 2.x users with Alamofire >= 3.0

Alamofire.request(.GET, urlString)
      .responseString { response in
             print("Success: \(response.result.isSuccess)")
             print("Response String: \(response.result.value)")
             if let alamoError = response.result.error {
               let alamoCode = alamoError.code
               let statusCode = (response.response?.statusCode)!
             } else { //no errors
               let statusCode = (response.response?.statusCode)! //example : 200
             }
}

What are the most-used vim commands/keypresses?

Have you run through Vim's built-in tutorial? If not, drop to the command-line and type vimtutor. It's a great way to learn the initial commands.

Vim has an incredible amount of flexibility and power and, if you're like most vim users, you'll learn a lot of new commands and forget old ones, then relearn them. The built-in help is good and worthy of periodic browsing to learn new stuff.

There are several good FAQs and cheatsheets for vim on the internet. I'd recommend searching for vim + faq and vim + cheatsheet. Cheat-Sheets.org#vim is a good source, as is Vim Tips wiki.

How do I create a comma delimited string from an ArrayList?

The solutions so far are all quite complicated. The idiomatic solution should doubtless be:

String.Join(",", x.Cast(Of String)().ToArray())

There's no need for fancy acrobatics in new framework versions. Supposing a not-so-modern version, the following would be easiest:

Console.WriteLine(String.Join(",", CType(x.ToArray(GetType(String)), String())))

mspmsp's second solution is a nice approach as well but it's not working because it misses the AddressOf keyword. Also, Convert.ToString is rather inefficient (lots of unnecessary internal evaluations) and the Convert class is generally not very cleanly designed. I tend to avoid it, especially since it's completely redundant.

MySQL error 2006: mysql server has gone away

If you are using the 64Bit WAMPSERVER, please search for multiple occurrences of max_allowed_packet because WAMP uses the value set under [wampmysqld64] and not the value set under [mysqldump], which for me was the issue, I was updating the wrong one. Set this to something like max_allowed_packet = 64M.

Hopefully this helps other Wampserver-users out there.

How do I check out a remote Git branch?

Use fetch to pull all your remote

   git fetch --all

To list remote branches:

   git branch -r

For list all your branches

   git branch -l
   >>outpots like-
     * develop
       test
       master

To checkout/change a branch

   git checkout master

How to display a readable array - Laravel

For everyone still searching for a nice way to achieve this, the recommended way is the dump() function from symfony/var-dumper.

It is added to documentation since version 5.2: https://laravel.com/docs/5.2/helpers#method-dd

Reason to Pass a Pointer by Reference in C++?

David's answer is correct, but if it's still a little abstract, here are two examples:

  1. You might want to zero all freed pointers to catch memory problems earlier. C-style you'd do:

    void freeAndZero(void** ptr)
    {
        free(*ptr);
        *ptr = 0;
    }
    
    void* ptr = malloc(...);
    
    ...
    
    freeAndZero(&ptr);
    

    In C++ to do the same, you might do:

    template<class T> void freeAndZero(T* &ptr)
    {
        delete ptr;
        ptr = 0;
    }
    
    int* ptr = new int;
    
    ...
    
    freeAndZero(ptr);
    
  2. When dealing with linked-lists - often simply represented as pointers to a next node:

    struct Node
    {
        value_t value;
        Node* next;
    };
    

    In this case, when you insert to the empty list you necessarily must change the incoming pointer because the result is not the NULL pointer anymore. This is a case where you modify an external pointer from a function, so it would have a reference to pointer in its signature:

    void insert(Node* &list)
    {
        ...
        if(!list) list = new Node(...);
        ...
    }
    

There's an example in this question.

double free or corruption (!prev) error in c program

Change this line

double *ptr = malloc(sizeof(double *) * TIME);

to

double *ptr = malloc(sizeof(double) * TIME);

Suppress warning messages using mysql from within Terminal, but password written in bash script

For PowerShell (pwsh, not bash), this was quite a rube-goldberg solution... My first attempt was to wrap the calls to mysql in a try/catch function, but due to some strange behavior in PowerShell error handling, this wasn't viable.

The solution was to override the $ErrorActionPreference just long enough to combine and capture STDERR and STDOUT and parse for the word ERROR and re-throw as needed. The reason we couldn't catch and release on "^mysql.*Warning.*password" is because PowerShell handles and raises the error as one stream, so you must capture it all in order to filter and re-throw. :/

Function CallMySQL() {
    # Cache the error action preference
    $_temp = $ErrorActionPreference
    $ErrorActionPreference = "Continue"

    # Capture all output from mysql
    $output = (&mysql --user=foo --password=bar 2>&1)

    # Restore the error action preference
    $ErrorActionPreference = $_temp

    if ($output -match "ERROR") {
        throw $output
    } elseif($output) {
        "   Swallowing $output"
    } else {
        "   No output"
    }
}

Note: PowerShell is available for Unix, so this solution is cross-platform. It can be adapted to bash with some minor syntax modifications.

Warning: There are dozens of edge-cases where this won't work such as non-english error messages or statements that return the word ERROR anywhere in the output, but it was enough to swallow the warning for a basic call to mysql without bombing out the entire script. Hopefully others find this useful.

It would be nice if mysql simply added an option to suppress this warning.

Is header('Content-Type:text/plain'); necessary at all?

no its not like that,here is Example for the support of my answer ---->the clear difference is visible ,when you go for HTTP Compression,which allows you to compress the data while travelling from Server to Client and the Type of this data automatically becomes as "gzip" which Tells browser that bowser got a zipped data and it has to upzip it,this is a example where Type really matters at Bowser.

How to access local files of the filesystem in the Android emulator?

In addition to the accepted answer, if you are using Android Studio you can

  1. invoke Android Device Monitor,
  2. select the device in the Devices tab on the left,
  3. select File Explorer tab on the right,
  4. navigate to the file you want, and
  5. click the Pull a file from the device button to save it to your local file system

Taken from Working with an emulator or device's file system

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

Help -> check for updates upon Eclipse update solved the issue

How to create empty constructor for data class in Kotlin Android

From the documentation

NOTE: On the JVM, if all of the parameters of the primary constructor have default values, the compiler will generate an additional parameterless constructor which will use the default values. This makes it easier to use Kotlin with libraries such as Jackson or JPA that create class instances through parameterless constructors.

How can I use getSystemService in a non-activity class (LocationManager)?

For some non-activity classes, like Worker, you're already given a Context object in the public constructor.

Worker(Context context, WorkerParameters workerParams)

You can just use that, e.g., save it to a private Context variable in the class (say, mContext), and then, for example

mContext.getSystenService(Context.ACTIVITY_SERVICE)

TypeScript - Append HTML to container element in Angular 2

There is a better solution to this answer that is more Angular based.

  1. Save your string in a variable in the .ts file

    MyStrings = ["one","two","three"]

  2. In the html file use *ngFor.

    <div class="one" *ngFor="let string of MyStrings; let i = index"> <div class="two">{{string}}</div> </div>

  3. if you want to dynamically insert the div element, just push more strings into the MyStrings array

    myFunction(nextString){ this.MyString.push(nextString) }

this way every time you click the button containing the myFunction(nextString) you effectively add another class="two" div which acts the same way as inserting it into the DOM with pure javascript.

How to compile a static library in Linux?

Here a full makefile example:

makefile

TARGET = prog

$(TARGET): main.o lib.a
    gcc $^ -o $@

main.o: main.c
    gcc -c $< -o $@

lib.a: lib1.o lib2.o
    ar rcs $@ $^

lib1.o: lib1.c lib1.h
    gcc -c -o $@ $<

lib2.o: lib2.c lib2.h
    gcc -c -o $@ $<

clean:
    rm -f *.o *.a $(TARGET)

explaining the makefile:

  • target: prerequisites - the rule head
  • $@ - means the target
  • $^ - means all prerequisites
  • $< - means just the first prerequisite
  • ar - a Linux tool to create, modify, and extract from archives see the man pages for further information. The options in this case mean:
    • r - replace files existing inside the archive
    • c - create a archive if not already existent
    • s - create an object-file index into the archive

To conclude: The static library under Linux is nothing more than a archive of object files.

main.c using the lib

#include <stdio.h>

#include "lib.h"

int main ( void )
{
    fun1(10);
    fun2(10);
    return 0;
}

lib.h the libs main header

#ifndef LIB_H_INCLUDED
#define LIB_H_INCLUDED

#include "lib1.h"
#include "lib2.h"

#endif

lib1.c first lib source

#include "lib1.h"

#include <stdio.h>

void fun1 ( int x )
{
    printf("%i\n",x);
}

lib1.h the corresponding header

#ifndef LIB1_H_INCLUDED
#define LIB1_H_INCLUDED

#ifdef __cplusplus
   extern “C” {
#endif

void fun1 ( int x );

#ifdef __cplusplus
   }
#endif

#endif /* LIB1_H_INCLUDED */

lib2.c second lib source

#include "lib2.h"

#include <stdio.h>

void fun2 ( int x )
{
    printf("%i\n",2*x);
}

lib2.h the corresponding header

#ifndef LIB2_H_INCLUDED
#define LIB2_H_INCLUDED

#ifdef __cplusplus
   extern “C” {
#endif

void fun2 ( int x );

#ifdef __cplusplus
   }
#endif

#endif /* LIB2_H_INCLUDED */

IndexError: list index out of range and python

Yes. The sequence doesn't have the 54th item.

What does hash do in python?

You can use the Dictionary data type in python. It's very very similar to the hash—and it also supports nesting, similar to the to nested hash.

Example:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School" # Add new entry

print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

For more information, please reference this tutorial on the dictionary data type.

understanding private setters

A private setter is useful if you have a read only property and don't want to explicitly declare the backing variable.

So:

public int MyProperty
{
    get; private set;
}

is the same as:

private int myProperty;
public int MyProperty
{
    get { return myProperty; }
}

For non auto implemented properties it gives you a consistent way of setting the property from within your class so that if you need validation etc. you only have it one place.

To answer your final question the MSDN has this to say on private setters:

However, for small classes or structs that just encapsulate a set of values (data) and have little or no behaviors, it is recommended to make the objects immutable by declaring the set accessor as private.

From the MSDN page on Auto Implemented properties

Show which git tag you are on?

Show all tags on current HEAD (or commit)

git tag --points-at HEAD