Programs & Examples On #Sites

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.

How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?

i got the same problem and i notice that my security config has diferent TAGS like the @Xenolion answer says

<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
    </domain-config>
</network-security-config>

so i change the TAGS "domain-config" for "base-config" and works, like this:

<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
    </base-config>
</network-security-config>

cmake error 'the source does not appear to contain CMakeLists.txt'

You should do mkdir build and cd build while inside opencv folder, not the opencv-contrib folder. The CMakeLists.txt is there.

TypeError: Object of type 'bytes' is not JSON serializable

I was dealing with this issue today, and I knew that I had something encoded as a bytes object that I was trying to serialize as json with json.dump(my_json_object, write_to_file.json). my_json_object in this case was a very large json object that I had created, so I had several dicts, lists, and strings to look at to find what was still in bytes format.

The way I ended up solving it: the write_to_file.json will have everything up to the bytes object that is causing the issue.

In my particular case this was a line obtained through

for line in text:
    json_object['line'] = line.strip()

I solved by first finding this error with the help of the write_to_file.json, then by correcting it to:

for line in text:
    json_object['line'] = line.strip().decode()

How to enable CORS in ASP.net Core WebAPI

In my case only get request works well according to MindingData's answer. For other types of request you need to write:

app.UseCors(corsPolicyBuilder =>
   corsPolicyBuilder.WithOrigins("http://localhost:3000")
  .AllowAnyMethod()
  .AllowAnyHeader()
);

Don't forget to add .AllowAnyHeader()

Python Selenium Chrome Webdriver

You need to specify the path where your chromedriver is located.

  1. Download chromedriver for your desired platform from here.

  2. Place chromedriver on your system path, or where your code is.

  3. If not using a system path, link your chromedriver.exe (For non-Windows users, it's just called chromedriver):

    browser = webdriver.Chrome(executable_path=r"C:\path\to\chromedriver.exe")
    

    (Set executable_path to the location where your chromedriver is located.)

    If you've placed chromedriver on your System Path, you can shortcut by just doing the following:

    browser = webdriver.Chrome()

  4. If you're running on a Unix-based operating system, you may need to update the permissions of chromedriver after downloading it in order to make it executable:

    chmod +x chromedriver

  5. That's all. If you're still experiencing issues, more info can be found on this other StackOverflow article: Can't use chrome driver for Selenium

Program to find largest and second largest number in array

The question is ambiguous: if the array may contain duplicate values, are you supposed to find the 2 largest distinct values or the two largest possibly identical values?

Your code seems to indicate you want the first approach, but you have a problem if the largest value is a[0]. You should use an extra boolean to keep track of whether you have found a different value yet.

You should also test the return value of the different scanf() calls and return 0 from main().

Here is a modified version:

#include <stdio.h>

int main(void) {
    int a[10], n, i;
    int largest1, largest2, has_largest2;

    printf("enter number of elements you want in array: ");
    if (scanf("%d", &n) != 1)
        return 1;
    if (n < 2) {
        printf("need at least 2 elements\n");
        return 1;
    }
    printf("enter elements: ");
    for (i = 0; i < n; i++) {
        if (scanf("%d", &a[i]) != 1) {
            printf("input error\n");
            return 1;
        }
    }
    largest1 = a[0];
    for (i = 1; i < n; i++) {
        if (a[i] > largest1) {
            largest1 = a[i];
        }
    }
    has_largest2 = largest2 = 0;
    for (i = 0; i < n; i++) {
        if (a[i] < largest1) {
            if (!has_largest2) {
                has_largest2 = 1;
                largest2 = a[i];
            } else
            if (a[i] > largest2) {
                largest2 = a[i];
            }
        }
    }
    if (has_largest2) {
        printf("First and second largest number is %d and %d\n",
               largest1, largest2);
    } else {
        printf("All values are identical to %d\n", largest1);
    }
    return 0;
}

nginx: [emerg] "server" directive is not allowed here

The path to the nginx.conf file which is the primary Configuration file for Nginx - which is also the file which shall INCLUDE the Path for other Nginx Config files as and when required is /etc/nginx/nginx.conf.

You may access and edit this file by typing this at the terminal

cd /etc/nginx

/etc/nginx$ sudo nano nginx.conf

Further in this file you may Include other files - which can have a SERVER directive as an independent SERVER BLOCK - which need not be within the HTTP or HTTPS blocks, as is clarified in the accepted answer above.

I repeat - if you need a SERVER BLOCK to be defined within the PRIMARY Config file itself than that SERVER BLOCK will have to be defined within an enclosing HTTP or HTTPS block in the /etc/nginx/nginx.conf file which is the primary Configuration file for Nginx.

Also note -its OK if you define , a SERVER BLOCK directly not enclosing it within a HTTP or HTTPS block , in a file located at path /etc/nginx/conf.d . Also to make this work you will need to include the path of this file in the PRIMARY Config file as seen below :-

http{
    include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}

Further to this you may comment out from the PRIMARY Config file , the line

http{
    #include /etc/nginx/sites-available/some_file.conf; # Comment Out 
    include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}

and need not keep any Config Files in /etc/nginx/sites-available/ and also no need to SYMBOLIC Link them to /etc/nginx/sites-enabled/ , kindly note this works for me - in case anyone think it doesnt for them or this kind of config is illegal etc etc , pls do leave a comment so that i may correct myself - thanks .

EDIT :- According to the latest version of the Official Nginx CookBook , we need not create any Configs within - /etc/nginx/sites-enabled/ , this was the older practice and is DEPRECIATED now .

Thus No need for the INCLUDE DIRECTIVE include /etc/nginx/sites-available/some_file.conf; .

Quote from Nginx CookBook page - 5 .

"In some package repositories, this folder is named sites-enabled, and configuration files are linked from a folder named site-available; this convention is depre- cated."

How to turn on/off MySQL strict mode in localhost (xampp)?

First, check whether the strict mode is enabled or not in mysql using:

     SHOW VARIABLES LIKE 'sql_mode';

If you want to disable it:

     SET sql_mode = '';

or any other mode can be set except the following. To enable strict mode:

     SET sql_mode = 'STRICT_TRANS_TABLES';

You can check the result from the first mysql query.

selenium - chromedriver executable needs to be in PATH

An answer from 2020. The following code solves this. A lot of people new to selenium seem to have to get past this step. Install the chromedriver and put it inside a folder on your desktop. Also make sure to put the selenium python project in the same folder as where the chrome driver is located.

Change USER_NAME and FOLDER in accordance to your computer.

For Windows

driver = webdriver.Chrome(r"C:\Users\USER_NAME\Desktop\FOLDER\chromedriver")

For Linux/Mac

driver = webdriver.Chrome("/home/USER_NAME/FOLDER/chromedriver")

docker cannot start on windows

I had the same issue lately. Problem was Security Software(Trendmicro) was blocking docker to create Hyperv network interface. You should also check firewall, AV software not blocking installation or configuration.

Disable nginx cache for JavaScript files

What you are looking for is a simple directive like:

location ~* \.(?:manifest|appcache|html?|xml|json)$ {
    expires -1;
}

The above will not cache the extensions within the (). You can configure different directives for different file types.

How to Inspect Element using Safari Browser

In your Safari menu bar click Safari > Preferences & then select the Advanced tab.

Select: "Show Develop menu in menu bar"

Now you can click Develop in your menu bar and choose Show Web Inspector

You can also right-click and press "Inspect element".

Why does this "Slow network detected..." log appear in Chrome?

Right mouse ?lick on Chrome Dev. Then select filter. And select source of messages.

'tsc command not found' in compiling typescript

After finding all solutions for this small issue for macOS only.
Finally, I got my TSC works on my MacBook pro.

This might be the best solution I found out.

For all macOS users, instead of installing TypeScript using NPM, you can install TypeScript using homebrew.

brew install typescript

Please see attached screencap for reference. enter image description here

How to add a custom CA Root certificate to the CA Store used by pip in Windows?

Alternative solution on Windows is to install python-certifi-win32 that will allow Python to use Windows Certificate Store.

pip install python-certifi-win32

Googlemaps API Key for Localhost

You can follow this way. It works at least for me :

in Credential page :

  1. Select option with IP address ( option no. 3 ).

  2. Put your IP address from your provider. If you don't it, search your IP address by using this link : https://www.google.com/search?q=my+ip

  3. Save it.

  4. Change your google map link as follow between the scrip tag :

    https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzxxxxxxxx"

  5. Wait for about 5 minutes or more to let your API key to propagate.

Now your google map should works.

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

Let me solve it for ya.

  • Get into the sql.
  • Enter the following thing.
SET GLOBAL validate_password.length = 4;
SET GLOBAL validate_password.mixed_case_count = 0;
SET GLOBAL validate_password.number_count = 0;
SET GLOBAL validate_password.policy = LOW;
SET GLOBAL validate_password.special_char_count = 0;
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'test';

Only for testing purposes.

React eslint error missing in props validation

the problem is in flow annotation in handleClick, i removed this and works fine thanks @alik

Automatically accept all SDK licences

I run

#react-native run-android 

from terminal and met that problem. For manually, go to Android Studio -> Android SDK -> SDK Platform Click Show Packages Detail and check :

+ Google APIs
+ Android SDK Platform 23
+ Intel x86 Atom_64 System Image
+ Google APIs Intel x86 Atom_64 System Image

When install packages, check accept license => can solve the problem.

Node Sass couldn't find a binding for your current environment

I had to first choose the new default node version nvm use *** or nvm install *** and then remove all in node_modules in the project and npm i again.

FCM getting MismatchSenderId

I had big trouble figuring out why I was getting a "MismatchSenderId" status. I added the gms dependency in the root build.gradle but my error was actually not applying the gms plugin in the app build.gradle.

If you have don't have this line in the app build.gradle, this could be the reason why the notification are not working: apply plugin: 'com.google.gms.google-services'

Docker-Compose with multiple services

The thing is that you are using the option -t when running your container.

Could you check if enabling the tty option (see reference) in your docker-compose.yml file the container keeps running?

version: '2'
services:
  ubuntu:
        build: .
        container_name: ubuntu
        volumes:
            - ~/sph/laravel52:/www/laravel
        ports:
          - "80:80"
        tty: true

Re-render React component when prop changes

componentWillReceiveProps(nextProps) { // your code here}

I think that is the event you need. componentWillReceiveProps triggers whenever your component receive something through props. From there you can have your checking then do whatever you want to do.

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

There was conflict in java version. Resolved after using 1.8 for maven.

How do I use a regex in a shell script?

I think this is what you want:

REGEX_DATE='^\d{2}[/-]\d{2}[/-]\d{4}$'

echo "$1" | grep -P -q $REGEX_DATE
echo $?

I've used the -P switch to get perl regex.

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

The SSL errors are often thrown by network management software such as Cyberroam.

To answer your question,

you will have to enter badidea into Chrome every time you visit a website.

You might at times have to enter it more than once, as the site may try to pull in various resources before load, hence causing multiple SSL errors

How to open google chrome from terminal?

In Terminal, type open -a Google\ Chrome

This will open Google Chrome application without any need to manipulate directories!

Babel command not found

Actually, if you want to use cmd commands,you have two ways. First, install it at gloabl environment. The other way is npm link. so, try the first way: npm install -g babel-cli.

DataTables: Cannot read property 'length' of undefined

It's even simpler: just use dataSrc:'' option in the ajax defintion so dataTable knows to expect an array instead of an object:

    $('#pos-table2').DataTable({
                  processing: true,
                  serverSide: true,
                  ajax:{url:"pos.json",dataSrc:""}
            }
    );

See ajax options

Can a website detect when you are using Selenium with chromedriver?

The bot detection I've seen seems more sophisticated or at least different than what I've read through in the answers below.

EXPERIMENT 1:

  1. I open a browser and web page with Selenium from a Python console.
  2. The mouse is already at a specific location where I know a link will appear once the page loads. I never move the mouse.
  3. I press the left mouse button once (this is necessary to take focus from the console where Python is running to the browser).
  4. I press the left mouse button again (remember, cursor is above a given link).
  5. The link opens normally, as it should.

EXPERIMENT 2:

  1. As before, I open a browser and the web page with Selenium from a Python console.

  2. This time around, instead of clicking with the mouse, I use Selenium (in the Python console) to click the same element with a random offset.

  3. The link doesn't open, but I am taken to a sign up page.

IMPLICATIONS:

  • opening a web browser via Selenium doesn't preclude me from appearing human
  • moving the mouse like a human is not necessary to be classified as human
  • clicking something via Selenium with an offset still raises the alarm

Seems mysterious, but I guess they can just determine whether an action originates from Selenium or not, while they don't care whether the browser itself was opened via Selenium or not. Or can they determine if the window has focus? Would be interesting to hear if anyone has any insights.

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

In 4.0 version of the .Net framework the ServicePointManager.SecurityProtocol only offered two options to set:

  • Ssl3: Secure Socket Layer (SSL) 3.0 security protocol.
  • Tls: Transport Layer Security (TLS) 1.0 security protocol

In the next release of the framework the SecurityProtocolType enumerator got extended with the newer Tls protocols, so if your application can use th 4.5 version you can also use:

  • Tls11: Specifies the Transport Layer Security (TLS) 1.1 security protocol
  • Tls12: Specifies the Transport Layer Security (TLS) 1.2 security protocol.

So if you are on .Net 4.5 change your line

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

to

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

so that the ServicePointManager will create streams that support Tls12 connections.

Do notice that the enumeration values can be used as flags so you can combine multiple protocols with a logical OR

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | 
                                       SecurityProtocolType.Tls11 |
                                       SecurityProtocolType.Tls12;

Note
Try to keep the number of protocols you support as low as possible and up-to-date with today security standards. Ssll3 is no longer deemed secure and the usage of Tls1.0 SecurityProtocolType.Tls is in decline.

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

I've solved by going to Project Properties -> Debug, after enable SSL and use the address in your browser

enter image description here

Why should Java 8's Optional not be used in arguments

There are almost no good reasons for not using Optional as parameters. The arguments against this rely on arguments from authority (see Brian Goetz - his argument is we can't enforce non null optionals) or that the Optional arguments may be null (essentially the same argument). Of course, any reference in Java can be null, we need to encourage rules being enforced by the compiler, not programmers memory (which is problematic and does not scale).

Functional programming languages encourage Optional parameters. One of the best ways of using this is to have multiple optional parameters and using liftM2 to use a function assuming the parameters are not empty and returning an optional (see http://www.functionaljava.org/javadoc/4.4/functionaljava/fj/data/Option.html#liftM2-fj.F-). Java 8 has unfortunately implemented a very limited library supporting optional.

As Java programmers we should only be using null to interact with legacy libraries.

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!

CORS header 'Access-Control-Allow-Origin' missing

You have to modify your server side code, as given below

public class CorsResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext,   ContainerResponseContext responseContext)
    throws IOException {
        responseContext.getHeaders().add("Access-Control-Allow-Origin","*");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");

  }
}

javascript change background color on click

You can set the background color of an object using CSS.

You can also use JavaScript to attach click handlers to objects and they can change the style of an object using element.style.property = 'value';. In the example below I've attached it in the HTML to a button but the handler could equally have been added to the body element or defined entirely in JavaScript.

_x000D_
_x000D_
body {_x000D_
  background-color: blue;_x000D_
}
_x000D_
<button onclick="document.body.style.backgroundColor = 'green';">Green</button>
_x000D_
_x000D_
_x000D_

nginx- duplicate default server error

Execute this at the terminal to see conflicting configurations listening to the same port:

grep -R default_server /etc/nginx

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.

A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, avg(a) OVER (ORDER BY t ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM data
ORDER BY t

... which yields:

t  a  avg
----------
1  1  3.00
2  5  3.00
3  3  4.33
4  5  4.00
5  4  6.67
6 11  7.50

As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding) and the subsequent row (1 following).

When you write ROWS UNBOUNDED PRECEDING, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, sum(a) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data
ORDER BY t

yielding...

t  a  sum
---------
1  1    1
2  5    6
3  3    9
4  5   14
5  4   18
6 11   29

Here's another very good explanations of SQL window functions.

How to bundle vendor scripts separately and require them as needed with Webpack?

I am not sure if I fully understand your problem but since I had similar issue recently I will try to help you out.

Vendor bundle.

You should use CommonsChunkPlugin for that. in the configuration you specify the name of the chunk (e.g. vendor), and file name that will be generated (vendor.js).

new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js", Infinity),

Now important part, you have to now specify what does it mean vendor library and you do that in an entry section. One one more item to entry list with the same name as the name of the newly declared chunk (i.e. 'vendor' in this case). The value of that entry should be the list of all the modules that you want to move to vendor bundle. in your case it should look something like:

entry: {
    app: 'entry.js',
    vendor: ['jquery', 'jquery.plugin1']
}

JQuery as global

Had the same problem and solved it with ProvidePlugin. here you are not defining global object but kind of shurtcuts to modules. i.e. you can configure it like that:

new webpack.ProvidePlugin({
    $: "jquery"
})

And now you can just use $ anywhere in your code - webpack will automatically convert that to

require('jquery')

I hope it helped. you can also look at my webpack configuration file that is here

I love webpack, but I agree that the documentation is not the nicest one in the world... but hey.. people were saying same thing about Angular documentation in the begining :)


Edit:

To have entrypoint-specific vendor chunks just use CommonsChunkPlugins multiple times:

new webpack.optimize.CommonsChunkPlugin("vendor-page1", "vendor-page1.js", Infinity),
new webpack.optimize.CommonsChunkPlugin("vendor-page2", "vendor-page2.js", Infinity),

and then declare different extenral libraries for different files:

entry: {
    page1: ['entry.js'],
    page2: ['entry2.js'],
    "vendor-page1": [
        'lodash'
    ],
    "vendor-page2": [
        'jquery'
    ]
},

If some libraries are overlapping (and for most of them) between entry points then you can extract them to common file using same plugin just with different configuration. See this example.

cURL error 60: SSL certificate: unable to get local issuer certificate

I spent too much time to figure out this problem for me.

I had PHP version 5.5 and I needed to upgrade to 5.6.

In versions < 5.6 Guzzle will use it's own cacert.pem file, but in higher versions of PHP it will use system's cacert.pem file.

I also downloaded file from here https://curl.haxx.se/docs/caextract.html and set it in php.ini.

Answer found in Guzzles StreamHandler.php file https://github.com/guzzle/guzzle/blob/0773d442aa96baf19d7195f14ba6e9c2da11f8ed/src/Handler/StreamHandler.php#L437

        // PHP 5.6 or greater will find the system cert by default. When
        // < 5.6, use the Guzzle bundled cacert.

The service cannot accept control messages at this time

In my case, the VS debugger was attached to the w3wp process. After detaching the debugger, I was able to restart the Application Pool

Responsive width Facebook Page Plugin

It seems that Facebook Page Plugin doesn't change at all in past  5-7 years :) It wasn't responsive from the begining and still not now, even new param Adapt to plugin container width doesn't work or I don't understand how it works.

I'm searching for the most posible simple way to do PLUGIN SIZE 100% WIDTH, and it seems it is not posible. Nonsense at it's best. How designers solve this problem?

I found the best decision for this time 2017 Oct:

.fb-page, .fb-page iframe[style], .fb-page span {
    width: 100% !important;
}
.fb-comments, .fb-comments iframe[style], .fb-comments span {
   width: 100% !important;
}

This lets do not broke screen size width for responsive screens, but still looks ugly, because cuted in some time and doesn't stretch... Facebook doesn't care about plugins design at all. That's the truth.

Unable to establish SSL connection upon wget on Ubuntu 14.04 LTS

Although this is almost certainly not the OPs issue, you can also get Unable to establish SSL connection from wget if you're behind a proxy and don't have HTTP_PROXY and HTTPS_PROXY environment variables set correctly. Make sure to set HTTP_PROXY and HTTPS_PROXY to point to your proxy.

This is a common situation if you work for a large corporation.

Force hide address bar in Chrome on Android

Check this has everything you need

http://www.html5rocks.com/en/mobile/fullscreen/

The Chrome team has recently implemented a feature that tells the browser to launch the page fullscreen when the user has added it to the home screen. It is similar to the iOS Safari model.

<meta name="mobile-web-app-capable" content="yes">

Google Chrome forcing download of "f.txt" file

FYI, after reading this thread, I took a look at my installed programs and found that somehow, shortly after upgrading to Windows 10 (possibly/probably? unrelated), an ASK search app was installed as well as a Chrome extension (Windows was kind enough to remind to check that). Since removing, I have not have the f.txt issue.

Open web in new tab Selenium + Python

You can achieve the opening/closing of a tab by the combination of keys COMMAND + T or COMMAND + W (OSX). On other OSs you can use CONTROL + T / CONTROL + W.

In selenium you can emulate such behavior. You will need to create one webdriver and as many tabs as the tests you need.

Here it is the code.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.google.com/")

#open tab
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't') 
# You can use (Keys.CONTROL + 't') on other OSs

# Load a page 
driver.get('http://stackoverflow.com/')
# Make the tests...

# close the tab
# (Keys.CONTROL + 'w') on other OSs.
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 'w') 


driver.close()

'cannot find or open the pdb file' Visual Studio C++ 2013

It worked for me. Go to Tools-> Options -> Debugger -> Native and check the Load DLL exports. Hope this helps

laravel the requested url was not found on this server

This looks like you have to enable .htaccess by adding this to your vhost:

<Directory /var/www/html/public/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

If that doesn't work, make sure you have mod_rewrite enabled.

Don't forget to restart apache after making the changes! (service apache2 restart)

How to configure Docker port mapping to use Nginx as an upstream proxy?

Using docker links, you can link the upstream container to the nginx container. An added feature is that docker manages the host file, which means you'll be able to refer to the linked container using a name rather than the potentially random ip.

IE11 Document mode defaults to IE7. How to reset?

Thanks to all the investigations of Lance, I could find a solution to my problem. It possibly had to do with my ISP.

To summarize:

  • Internet sites were displayed in the Intranet zone
  • Because of that the document mode was defaulted to 5 or 7 instead of Edge

I unchecked the "Automatically detect settings" in the Local Area Network Settings (found in "Internet Options" > Connections > LAN Settings.

Now the sites are correctly marked as Internet sites (instead of Intranet sites).

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

I'm going to assume your host is using C-Panel - and that it's probably HostGator or GoDaddy. In both cases they use C-Panel (in fact, a lot of hosts do) to make the Server administration as easy as possible on you, the end user. Even if you are hosting through someone else - see if you can log in to some kind of admin panel and find an .htaccess file that you can edit. (Note: The period before just means that it's a "hidden" file/directory).

Once you find the htaccess file add the following line:

  1. Header set Access-Control-Allow-Origin "*" Just to see if it works. Warning: Do not use this line on a production server

It should work. If not, call your host and ask them why the line isn't working - they'll probably be able to help you quickly from there.

  1. Once you do have the above working change the * to the address of the requesting domain http://cyclistinsuranceaustralia.com.au/. You may find an issue with canonical addressing (including the www) and if so you may need to configure your host for a redirect. That's a different and smaller bridge to cross though. You'll at least be in the right place.

phpmyadmin "Not Found" after install on Apache, Ubuntu

Run the following command in terminal:

sudo ln -s /usr/share/phpmyadmin /var/www/html/

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

Per the developers, this error is not an actual failure, but rather "misleading error reports". This bug is fixed in version 40, which is available on the canary and dev channels as of 25 Oct.

Patch

Chrome disable SSL checking for sites?

To disable the errors windows related with certificates you can start Chrome from console and use this option: --ignore-certificate-errors.

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --ignore-certificate-errors

You should use it for testing purposes. A more complete list of options is here: http://peter.sh/experiments/chromium-command-line-switches/

Why does git say "Pull is not possible because you have unmerged files"?

If you dont want any of your local branch changes i think this is the best approach

git clean -df
git reset --hard
git checkout REMOTE_BRANCH_NAME
git pull origin REMOTE_BRANCH_NAME

Difference between Amazon EC2 and AWS Elastic Beanstalk

First off, EC2 and Elastic Compute Cloud are the same thing.

Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.

EC2

EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n number of instances.

Elastic Beanstalk

Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.

Running Wordpress

For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.

What to pick?

In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.

Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/

Java ElasticSearch None of the configured nodes are available

For completion's sake, here's the snippet that creates the transport client using proper static method provided by InetSocketTransportAddress:

    Client esClient = TransportClient.builder()
        .settings(settings)
        .build()
        .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("143.79.236.xxx"), 9300));

Django: OperationalError No Such Table

I'm using Django 1.9, SQLite3 and DjangoCMS 3.2 and had the same issue. I solved it by running python manage.py makemigrations. This was followed by a prompt stating that the database contained non-null value types but did not have a default value set. It gave me two options: 1) select a one off value now or 2) exit and change the default setting in models.py. I selected the first option and gave the default value of 1. Repeated this four or five times until the prompt said it was finished. I then ran python manage.py migrate. Now it works just fine. Remember, by running python manage.py makemigrations first, a revised copy of the database is created (mine was 0004) and you can always revert back to a previous database state.

Java 8: Difference between two LocalDateTime in multiple units

Joda-Time

Since many of the answers required API 26 support and my min API was 23, I solved it by below code :

import org.joda.time.Days

LocalDate startDate = Something
LocalDate endDate = Something
// The difference would be exclusive of both dates, 
// so in most of use cases we may need to increment it by 1
Days.daysBetween(startDate, endDate).days

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

You need to add this to /etc/nginx/sites-enabled/default to execute php files on Nginx Server:

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html;
    index index.php index.html index.htm;

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

This is an old problem with some good information. But what I just found is that using a FQDN turns off the Compat mode in IE 9 - 11. Example. I have the compat problem with
http://lrmstst01:8080/JavaWeb/login.do
but the problems go away with
http://lrmstst01.mydomain.int:8080/JavaWeb/login.do
NB: The .int is part of our internal domain

How to enable CORS on Firefox?

This Firefox add-on may work for you:

https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/

It can toggle CORS on and off for development purposes.

Datatables: Cannot read property 'mData' of undefined

I am getting a similar error. The problem is that the header line is not correct. When I did the following header line, the problem I was having was resolved.

<table id="example" class="table table-striped table-bordered" style="width:100%">
        <thead>
    <tr>
                <th colspan="6">Common Title</th>
            </tr>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Tiger Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>61</td>
                <td>2011/04/25</td>
                <td>$320,800</td>
            </tr>
</tbody>
</table>

How to create an alert message in jsp page after submit process is complete

You can also create a new jsp file sayng that form is submited and in your main action file just write its file name

Eg. Your form is submited is in a file succes.jsp Then your action file will have

Request.sendRedirect("success.jsp")

sql try/catch rollback/commit - preventing erroneous commit after rollback

In your first example, you are correct. The batch will hit the commit transaction, regardless of whether the try block fires.

In your second example, I agree with other commenters. Using the success flag is unnecessary.

I consider the following approach to be, essentially, a light weight best practice approach.

If you want to see how it handles an exception, change the value on the second insert from 255 to 256.

CREATE TABLE #TEMP ( ID TINYINT NOT NULL );
INSERT  INTO #TEMP( ID ) VALUES  ( 1 )

BEGIN TRY
    BEGIN TRANSACTION

    INSERT  INTO #TEMP( ID ) VALUES  ( 2 )
    INSERT  INTO #TEMP( ID ) VALUES  ( 255 )

    COMMIT TRANSACTION
END TRY
BEGIN CATCH
    DECLARE 
        @ErrorMessage NVARCHAR(4000),
        @ErrorSeverity INT,
        @ErrorState INT;
    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();
    RAISERROR (
        @ErrorMessage,
        @ErrorSeverity,
        @ErrorState    
        );
    ROLLBACK TRANSACTION
END CATCH

SET NOCOUNT ON

SELECT ID
FROM #TEMP

DROP TABLE #TEMP

How do I solve this "Cannot read property 'appendChild' of null" error?

The element hasn't been appended yet, therefore it is equal to null. The Id will never = 0. When you call getElementById(id), it is null since it is not a part of the dom yet unless your static id is already on the DOM. Do a call through the console to see what it returns.

How to hide form code from view code/inspect element browser?

_x000D_
_x000D_
<script>_x000D_
document.onkeydown = function(e) {_x000D_
if(event.keyCode == 123) {_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.keyCode == 'E'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.shiftKey && e.keyCode == 'I'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.shiftKey && e.keyCode == 'J'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.keyCode == 'U'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.keyCode == 'S'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.keyCode == 'H'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.keyCode == 'A'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.keyCode == 'E'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_

Try this code

Using Laravel Homestead: 'no input file specified'

This issue occurred for me after editing the Homestead.yaml. I resolved this issue by

homestead destroy
homestead up

Where are Magento's log files located?

To create your custom log file, try this code

Mage::log('your debug message', null, 'yourlog_filename.log');

Refer this Answer

iFrame Height Auto (CSS)

I had this same issue but found the following that works great:

The key to creating a responsive YouTube embed is with padding and a container element, which allows you to give it a fixed aspect ratio. You can also use this technique with most other iframe-based embeds, such as slideshows.

Here is what a typical YouTube embed code looks like, with fixed width and height:

 <iframe width="560" height="315" src="//www.youtube.com/embed/yCOY82UdFrw" 
 frameborder="0" allowfullscreen></iframe>

It would be nice if we could just give it a 100% width, but it won't work as the height remains fixed. What you need to do is wrap it in a container like so (note the class names and removal of the width and height):

 <div class="container">
 <iframe src="//www.youtube.com/embed/yCOY82UdFrw" 
 frameborder="0" allowfullscreen class="video"></iframe>
 </div>

And use the following CSS:

 .container {
    position: relative;
     width: 100%;
     height: 0;
     padding-bottom: 56.25%;
 }
 .video {
     position: absolute;
     top: 0;
     left: 0;
     width: 100%;
     height: 100%;
 }

Here is the page I found the solution on:

https://www.h3xed.com/web-development/how-to-make-a-responsive-100-width-youtube-iframe-embed

Depending on your aspect ratio, you will probably need to adjust the padding-bottom: 56.25%; to get the height right.

How to enable local network users to access my WAMP sites?

Put your wamp server onlineenter image description here

and then go to control panel > system and security > windows firewall and turn windows firewall off

now you can access your wamp server from another computer over local network by the network IP of computer which have wamp server installed like http://192.168.2.34/mysite

How to use Elasticsearch with MongoDB?

I found mongo-connector useful. It is form Mongo Labs (MongoDB Inc.) and can be used now with Elasticsearch 2.x

Elastic 2.x doc manager: https://github.com/mongodb-labs/elastic2-doc-manager

mongo-connector creates a pipeline from a MongoDB cluster to one or more target systems, such as Solr, Elasticsearch, or another MongoDB cluster. It synchronizes data in MongoDB to the target then tails the MongoDB oplog, keeping up with operations in MongoDB in real-time. It has been tested with Python 2.6, 2.7, and 3.3+. Detailed documentation is available on the wiki.

https://github.com/mongodb-labs/mongo-connector https://github.com/mongodb-labs/mongo-connector/wiki/Usage%20with%20ElasticSearch

Add an index (numeric ID) column to large data frame

Using alternative dplyr package:

library("dplyr") # or library("tidyverse")

df <- df %>% mutate(id = row_number())

twitter bootstrap 3.0 typeahead ajax example

I'm using this https://github.com/biggora/bootstrap-ajax-typeahead

The result of code using Codeigniter/PHP

<pre>

$("#produto").typeahead({
        onSelect: function(item) {
            console.log(item);
            getProductInfs(item);
        },
        ajax: {
            url: path + 'produto/getProdName/',
            timeout: 500,
            displayField: "concat",
            valueField: "idproduto",
            triggerLength: 1,
            method: "post",
            dataType: "JSON",
            preDispatch: function (query) {
                showLoadingMask(true);
                return {
                    search: query
                }
            },
            preProcess: function (data) {

                if (data.success === false) {
                    return false;
                }else{
                    return data;    
                }                
            }               
        }
    });
</pre>   

How to see the proxy settings on windows?

You can use a tool called: NETSH

To view your system proxy information via command line:

netsh.exe winhttp show proxy

Another way to view it is to open IE, then click on the "gear" icon, then Internet options -> Connections tab -> click on LAN settings

"configuration file /etc/nginx/nginx.conf test failed": How do I know why this happened?

sudo nginx -t should test all files and return errors and warnings locations

Download TS files from video stream

You can use Xtreme Download Manager(XDM) software for this. This software can download from any site in this format. Even this software can change the ts file format. You only need to change the format when downloading.

like:https://www.videohelp.com/software/Xtreme-Download-Manager-

How to access site through IP address when website is on a shared host?

You can access you website using your IP address and your cPanel username with ~ symbols. For Example: http://serverip/~cpusername like as https://xxx.xxx.xx.xx/~mohidul

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

Timeout for python requests.get entire response

Set the timeout parameter:

r = requests.get(w, verify=False, timeout=10) # 10 seconds

As long as you don't set stream=True on that request, this will cause the call to requests.get() to timeout if the connection takes more than ten seconds, or if the server doesn't send data for more than ten seconds.

what does -zxvf mean in tar -zxvf <filename>?

Instead of wading through the description of all the options, you can jump to 3.4.3 Short Options Cross Reference under the info tar command.

x means --extract. v means --verbose. f means --file. z means --gzip. You can combine one-letter arguments together, and f takes an argument, the filename. There is something you have to watch out for:

Short options' letters may be clumped together, but you are not required to do this (as compared to old options; see below). When short options are clumped as a set, use one (single) dash for them all, e.g., ''tar' -cvf'. Only the last option in such a set is allowed to have an argument(1).


This old way of writing 'tar' options can surprise even experienced users. For example, the two commands:

 tar cfz archive.tar.gz file
 tar -cfz archive.tar.gz file

are quite different. The first example uses 'archive.tar.gz' as the value for option 'f' and recognizes the option 'z'. The second example, however, uses 'z' as the value for option 'f' -- probably not what was intended.

Single Page Application: advantages and disadvantages

Try not to consider using a SPA without first defining how you will address security and API stability on the server side. Then you will see some of the true advantages to using a SPA. Specifically, if you use a RESTful server that implements OAUTH 2.0 for security, you will achieve two fundamental separation of concerns that can lower your development and maintenance costs.

  1. This will move the session (and it's security) onto the SPA and relieve your server from all of that overhead.
  2. Your API's become both stable and easily extensible.

Hinted to earlier, but not made explicit; If your goal is to deploy Android & Apple applications, writing a JavaScript SPA that is wrapped by a native call to host the screen in a browser (Android or Apple) eliminates the need to maintain both an Apple code base and an Android code base.

NGINX - No input file specified. - php Fast/CGI

If someone is still having trouble with it ... I solved it by correcting it this way:

Inside the site conf file (example: /etc/nginx/conf.d/SITEEXAMPLE.conf) I have the following line:

fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/html$fastcgi_script_name;

The error occurs because my site is NOT in the "/usr/share/nginx/html" folder but in the folder: /var/www/html/SITE/

So, change that part, leaving the code as below. Note: For those who use the site standard in /var/www/html/YOUR_SITE/

fastcgi_param  SCRIPT_FILENAME  /var/www/html/YOUR_SITE/$fastcgi_script_name;

Difference between Relative path and absolute path in javascript

Completely relative:

<img src="kitten.png"/>

this is a relative path indeed.

Absolute in all respects:

<img src="http://www.foo.com/images/kitten.png"/>

this is a URL, and it can be seen in some way as an absolute path, but it's not representative for this matter.

The difference between relative and absolute paths is that when using relative paths you take as reference the current working directory while with absolute paths you refer to a certain, well known directory. Relative paths are useful when you make some program that has to use resources from certain folders that can be opened using the working directory as a starting point.

Example of relative paths:

  • image.png, which is the equivalent to .\image.png (in Windows) or ./image.png (anywhere else). The . explicitly specifies that you're expressing a path relative to the current working directory, but this is implied whenever the path doesn't begin at a root directory (designated with a slash), so you don't have to use it necessarily (except in certain contexts where a default directory (or a list of directories to search) will be applied unless you explicitly specify some directory).

  • ..\images\image2.jpg This way you can access resources from directories one step up the folders tree.  The ..\ means you've exited the current folder, entering the directory that contains both the working and images folders.  Again, use \ in Windows and / anywhere else.

Example of absolute paths:

  • D:\documents\something.doc
  • E:\music\good_music.mp3

and so on.

convert base64 to image in javascript/jquery

One quick and easy way:

function paintSvgToCanvas(uSvg, uCanvas) {

    var pbx = document.createElement('img');

    pbx.style.width  = uSvg.style.width;
    pbx.style.height = uSvg.style.height;

    pbx.src = 'data:image/svg+xml;base64,' + window.btoa(uSvg.outerHTML);
    uCanvas.getContext('2d').drawImage(pbx, 0, 0);

}

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

For many it's a permission issue, but for me it turns out the error was brought about by a mistake in the form I was trying to submit. To be specific i had accidentally put ">" sign after the value of "action". So I would suggest you take a second look at your code

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

Update (2016-11-01)

I was using AmplifyJS mentioned below to work around this issue. However, for Safari in Private browsing, it was falling back to a memory-based storage. In my case, it was not appropriate because it means the storage is cleared on refresh, even if the user is still in private browsing.

Also, I have noticed a number of users who are always browsing in Private mode on iOS Safari. For that reason, a better fallback for Safari is to use cookies (if available). By default, cookies are still accessible even in private browsing. Of course, they are cleared when exiting the private browsing, but they are not cleared on refresh.

I found the local-storage-fallback library. From the documentation:

Purpose

With browser settings like "Private Browsing" it has become a problem to rely on a working window.localStorage, even in newer browsers. Even though it may exist, it will throw exceptions when trying to use setItem or getItem. This module will run appropriate checks to see what browser storage mechanism might be available, and then expose it. It uses the same API as localStorage so it should work as a drop-in replacement in most cases.

Beware of the gotchas:

  • CookieStorage has storage limits. Be careful here.
  • MemoryStorage will not persist between page loads. This is more or less a stop-gap to prevent page crashes, but may be sufficient for websites that don't do full page loads.

TL;DR:

Use local-storage-fallback (unified API with .getItem(prop) and .setItem(prop, val)):

Check and use appropriate storage adapter for browser (localStorage, sessionStorage, cookies, memory)

Original answer

To add upon previous answers, one possible workaround would be to change the storage method. There are a few librairies such as AmplifyJS and PersistJS which can help. Both libs allow persistent client-side storage through several backends.

For AmplifyJS

localStorage

  • IE 8+
  • Firefox 3.5+
  • Safari 4+
  • Chrome
  • Opera 10.5+
  • iPhone 2+
  • Android 2+

sessionStorage

  • IE 8+
  • Firefox 2+
  • Safari 4+
  • Chrome
  • Opera 10.5+
  • iPhone 2+
  • Android 2+

globalStorage

  • Firefox 2+

userData

  • IE 5 - 7
  • userData exists in newer versions of IE as well, but due to quirks in IE 9's implementation, we don't register userData if localStorage is supported.

memory

  • An in-memory store is provided as a fallback if none of the other storage types are available.

For PersistentJS

  • flash: Flash 8 persistent storage.
  • gears: Google Gears-based persistent storage.
  • localstorage: HTML5 draft storage.
  • globalstorage: HTML5 draft storage (old spec).
  • ie: Internet Explorer userdata behaviors.
  • cookie: Cookie-based persistent storage.

They offer an abstraction layer so you don't have to worry about choosing the storage type. Keep in mind there might be some limitations (such as size limits) depending on the storage type though. Right now, I am using AmplifyJS, but I still have to do some more testing on iOS 7/Safari/etc. to see if it actually solves the problem.

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

I got this error:

System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions

when the port was used by another program.

Laravel blank white screen

Running this command solved it for me:

php artisan view:clear

I guess a blank error page was some how cached. Had to clear the caches.

Cloudfront custom-origin distribution returns 502 "ERROR The request could not be satisfied." for some URLs

For my particular case it was due to the fact that the Origin ALB behind my CloudFront Behavior had a DEFAULT ACM certificate which was pointing to a different domain name.

To fix this I had to:

  1. Go to the ALB
  2. Under the Listeners tab, selected my Listener and then Edit
  3. Under the Default SSL Certificate, choose the correct Origin Certificate.

How to call a PHP file from HTML or Javascript


How to make a button call PHP?

I don't care if the page reloads or displays the results immediately;

Good!

Note: If you don't want to refresh the page see "Ok... but how do I Use Ajax anyway?" below.

I just want to have a button on my website make a PHP file run.

That can be done with a form with a single button:

<form action="">
  <input type="submit" value="my button"/>
</form>

That's it.

Pretty much. Also note that there are cases where ajax is really the way to go.

That depends on what you want. In general terms you only need ajax when you want to avoid realoading the page. Still you have said that you don't care about that.


Why I cannot call PHP directly from JavaScript?

If I can write the code inside HTML just fine, why can't I just reference the file for it in there or make a simple call for it in Javascript?

Because the PHP code is not in the HTML just fine. That's an illusion created by the way most server side scripting languages works (including PHP, JSP, and ASP). That code only exists on the server, and it is no reachable form the client (the browser) without a remote call of some sort.

You can see evidence of this if you ask your browser to show the source code of the page. There you will not see the PHP code, that is because the PHP code is not send to the client, therefore it cannot be executed from the client. That's why you need to do a remote call to be able to have the client trigger the execution of PHP code.

If you don't use a form (as shown above) you can do that remote call from JavaScript with a little thing called Ajax. You may also want to consider if what you want to do in PHP can be done directly in JavaScript.


How to call another PHP file?

Use a form to do the call. You can have it to direct the user to a particlar file:

<form action="myphpfile.php">
  <input type="submit" value="click on me!">
</form>

The user will end up in the page myphpfile.php. To make it work for the current page, set action to an empty string (which is what I did in the example I gave you early).

I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.

You want to make an operation on the server, you should make your form have the fields you need (even if type="hidden" and use POST):

<form action="" method="POST">
  <input type="text" value="default value, you can edit it" name="myfield">
  <input type="submit" value = "post">
</form>

What do I need to know about it to call a PHP file that will create a text file on a button press?

see: How to write into a file in PHP.


How do you recieve the data from the POST in the server?

I'm glad you ask... Since you are a newb begginer, I'll give you a little template you can follow:

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        //Ok we got a POST, probably from a FORM, read from $_POST.
        var_dump($_PSOT); //Use this to see what info we got!
    }
    else
    {
       //You could assume you got a GET
       var_dump($_GET); //Use this to see what info we got!
    }
 ?>
 <!DOCTYPE html>
 <html lang="en">
   <head>
     <meta char-set="utf-8">
     <title>Page title</title>
   </head>
   <body>
     <form action="" method="POST">
       <input type="text" value="default value, you can edit it" name="myfield">
       <input type="submit" value = "post">
     </form>
   </body>
 </html>

Note: you can remove var_dump, it is just for debugging purposes.


How do I...

I know the next stage, you will be asking how to:

  1. how to pass variables form a PHP file to another?
  2. how to remember the user / make a login?
  3. how to avoid that anoying message the appears when you reload the page?

There is a single answer for that: Sessions.

I'll give a more extensive template for Post-Redirect-Get

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        var_dump($_PSOT);
        //Do stuff...
        //Write results to session
        session_start();
        $_SESSION['stuff'] = $something;
        //You can store stuff such as the user ID, so you can remeember him.
        //redirect:
        header('Location: ', true, 303);
        //The redirection will cause the browser to request with GET
        //The results of the operation are in the session variable
        //It has empty location because we are redirecting to the same page
        //Otherwise use `header('Location: anotherpage.php', true, 303);`
        exit();
    }
    else
    {
        //You could assume you got a GET
        var_dump($_GET); //Use this to see what info we got!
        //Get stuff from session
        session_start();
        if (array_key_exists('stuff', $_SESSION))
        {
           $something = $_SESSION['stuff'];
           //we got stuff
           //later use present the results of the operation to the user.
        }
        //clear stuff from session:
        unset($_SESSION['stuff']);
        //set headers
        header('Content-Type: text/html; charset=utf-8');
        //This header is telling the browser what are we sending.
        //And it says we are sending HTML in UTF-8 encoding
    }
 ?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta char-set="utf-8">
    <title>Page title</title>
  </head>
  <body>
    <?php if (isset($something)){ echo '<span>'.$something.'</span>'}?>;
    <form action="" method="POST">
      <input type="text" value="default value, you can edit it" name="myfield">
      <input type="submit" value = "post">
    </form>
  </body>
</html>

Please look at php.net for any function call you don't recognize. Also - if you don't have already - get a good tutorial on HTML5.

Also, use UTF-8 because UTF-8!


Notes:

I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately.

If are you using a CMS (Codepress, Joomla, Drupal... etc)? That make put some contraints on how you got to do things.

Also, if you are using a framework, you should look at their documentation or ask at their forum/mailing list/discussion page/contact or try to ask the authors.


Ok... but how do I Use Ajax anyway?

Well... Ajax is made easy by some JavaScript libraries. Since you are a begginer, I'll recomend jQuery.

So, let's send something to the server via Ajax with jQuery, I'll use $.post instead of $.ajax for this example.

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        var_dump($_PSOT);
        header('Location: ', true, 303);
        exit();
    }
    else
    {
        var_dump($_GET);
        header('Content-Type: text/html; charset=utf-8');
    }
 ?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta char-set="utf-8">
    <title>Page title</title>
    <script>
        function ajaxmagic()
        {
            $.post(                             //call the server
                "test.php",                     //At this url
                {
                    field: "value",
                    name: "John"
                }                               //And send this data to it
            ).done(                             //And when it's done
                function(data)
                {
                    $('#fromAjax').html(data);  //Update here with the response
                }
            );
        }
    </script>
  </head>
  <body>
    <input type="button" value = "use ajax", onclick="ajaxmagic()">
    <span id="fromAjax"></span>
  </body>
</html>

The above code will send a POST request to the page test.php.

Note: You can mix sessions with ajax and stuff if you want.


How do I...

  1. How do I connect to the database?
  2. How do I prevent SQL injection?
  3. Why shouldn't I use Mysql_* functions?

... for these or any other, please make another questions. That's too much for this one.

Site does not exist error for a2ensite

You probably updated your Ubuntu installation and one of the updates included the upgrade of Apache to version 2.4.x

In Apache 2.4.x the vhost configuration files, located in the /etc/apache2/sites-available directory, must have the .conf extension.

Using terminal (mv command), rename all your existing configuration files and add the .conf extension to all of them.

mv /etc/apache2/sites-available/cmsplus.dev /etc/apache2/sites-available/cmsplus.dev.conf

If you get a "Permission denied" error, then add "sudo " in front of your terminal commands.

You do not need to make any other changes to the configuration files.

Enable the vhost(s):

a2ensite cmsplus.dev.conf

And then reload Apache:

service apache2 reload

Your sites should be up and running now.


UPDATE: As mentioned here, a Linux distribution that you installed changed the configuration to Include *.conf only. Therefore it has nothing to do with Apache 2.2 or 2.4

How to get first item from a java.util.Set?

Or, using Java8:

Object firstElement = set.stream().findFirst().get();

And then you can do stuff with it straight away:

set.stream().findFirst().ifPresent(<doStuffHere>);

Or, if you want to provide an alternative in case the element is missing (my example returns new default string):

set.stream().findFirst().orElse("Empty string");

You can even throw an exception if the first element is missing:

set.stream().findFirst().orElseThrow(() -> new MyElementMissingException("Ah, blip, nothing here!"));

Kudos to Alex Vulaj for prompting me to provide more examples beyond the initial grabbing of the first element.

Reverse HashMap keys and values in Java

Apache commons collections library provides a utility method for inversing the map. You can use this if you are sure that the values of myHashMap are unique

org.apache.commons.collections.MapUtils.invertMap(java.util.Map map)

Sample code

HashMap<String, Character> reversedHashMap = MapUtils.invertMap(myHashMap) 

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

Since your server already includes the sites-enabled folder ( notice the include /etc/nginx/sites-enabled/* line ), then you better use that.

  1. Create a file inside /etc/nginx/sites-available and call it whatever you want, I'll call it django since it's a djanog server

    sudo touch /etc/nginx/sites-available/django
    
  2. Then create a symlink that points to it

    sudo ln -s /etc/nginx/sites-available/django /etc/nginx/sites-enabled
    
  3. Then edit that file with whatever file editor you use, vim or nano or whatever and create the server inside it

    server {
        # hostname or ip or multiple separated by spaces
        server_name localhost example.com 192.168.1.1; #change to your setting
        location / {
            root /home/techcee/scrapbook/local/lib/python2.7/site-packages/django/__init__.pyc/;
        }
    }
    
  4. Restart or reload nginx settings

    sudo service nginx reload
    

Note I believe that your configuration like this probably won't work yet because you need to pass it to a fastcgi server or something, but at least this is how you could create a valid server

How to create a simple http proxy in node.js?

Here's a more optimized version of Mike's answer above that gets the websites Content-Type properly, supports POST and GET request, and uses your browsers User-Agent so websites can identify your proxy as a browser. You can just simply set the URL by changing url = and it will automatically set HTTP and HTTPS stuff without manually doing it.

var express = require('express')
var app = express()
var https = require('https');
var http = require('http');
const { response } = require('express');


app.use('/', function(clientRequest, clientResponse) {
    var url;
    url = 'https://www.google.com'
    var parsedHost = url.split('/').splice(2).splice(0, 1).join('/')
    var parsedPort;
    var parsedSSL;
    if (url.startsWith('https://')) {
        parsedPort = 443
        parsedSSL = https
    } else if (url.startsWith('http://')) {
        parsedPort = 80
        parsedSSL = http
    }
    var options = { 
      hostname: parsedHost,
      port: parsedPort,
      path: clientRequest.url,
      method: clientRequest.method,
      headers: {
        'User-Agent': clientRequest.headers['user-agent']
      }
    };  
  
    var serverRequest = parsedSSL.request(options, function(serverResponse) { 
      var body = '';   
      if (String(serverResponse.headers['content-type']).indexOf('text/html') !== -1) {
        serverResponse.on('data', function(chunk) {
          body += chunk;
        }); 
  
        serverResponse.on('end', function() {
          // Make changes to HTML files when they're done being read.
          body = body.replace(`example`, `Cat!` );
  
          clientResponse.writeHead(serverResponse.statusCode, serverResponse.headers);
          clientResponse.end(body);
        }); 
      }   
      else {
        serverResponse.pipe(clientResponse, {
          end: true
        }); 
        clientResponse.contentType(serverResponse.headers['content-type'])
      }   
    }); 
  
    serverRequest.end();
  });    


  app.listen(3000)
  console.log('Running on 0.0.0.0:3000')

enter image description here

enter image description here

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

I was missing several DLLs. Even if I manually copied them to the directory the next time I published they would disappear. Each one was already set to Copy Locally in VS. The fix for me was to set each one to Copy Locally false, save, build then set each one to copy locally true. This time when I published all of the DLLs published correctly. Strange

What are the differences between git remote prune, git prune, git fetch --prune, etc

git remote prune and git fetch --prune do the same thing: deleting the refs to the branches that don't exist on the remote, as you said. The second command connects to the remote and fetches its current branches before pruning.

However it doesn't touch the local branches you have checked out, that you can simply delete with

git branch -d  random_branch_I_want_deleted

Replace -d by -D if the branch is not merged elsewhere

git prune does something different, it purges unreachable objects, those commits that aren't reachable in any branch or tag, and thus not needed anymore.

Match linebreaks - \n or \r\n?

In Python:

# as Peter van der Wal's answer
re.split(r'\r\n|\r|\n', text, flags=re.M) 

or more rigorous:

# https://docs.python.org/3/library/stdtypes.html#str.splitlines
str.splitlines()

Print page numbers on pages when printing html

Can you try this, you can use content: counter(page);

     @page {
       @bottom-left {
            content: counter(page) "/" counter(pages);
        }
     }

Ref: http://www.w3.org/TR/CSS21/generate.html#counters

http://www.princexml.com/doc/9.0/page-numbers/

auto refresh for every 5 mins

Refresh document every 300 seconds using HTML Meta tag add this inside the head tag of the page

 <meta http-equiv="refresh" content="300">

Using Script:

            setInterval(function() {
                  window.location.reload();
                }, 300000); 

How to create a sticky footer that plays well with Bootstrap 3

What worked for me was adding the position relative to the html tag.

html {
  min-height:100%;
  position:relative;
}
body {
  margin-bottom:60px;
}
footer {
  position:absolute;
  bottom:0;
  height:60px;
}

nodeJs callbacks simple example

A callback function is simply a function you pass into another function so that function can call it at a later time. This is commonly seen in asynchronous APIs; the API call returns immediately because it is asynchronous, so you pass a function into it that the API can call when it's done performing its asynchronous task.

The simplest example I can think of in JavaScript is the setTimeout() function. It's a global function that accepts two arguments. The first argument is the callback function and the second argument is a delay in milliseconds. The function is designed to wait the appropriate amount of time, then invoke your callback function.

setTimeout(function () {
  console.log("10 seconds later...");
}, 10000);

You may have seen the above code before but just didn't realize the function you were passing in was called a callback function. We could rewrite the code above to make it more obvious.

var callback = function () {
  console.log("10 seconds later...");
};
setTimeout(callback, 10000);

Callbacks are used all over the place in Node because Node is built from the ground up to be asynchronous in everything that it does. Even when talking to the file system. That's why a ton of the internal Node APIs accept callback functions as arguments rather than returning data you can assign to a variable. Instead it will invoke your callback function, passing the data you wanted as an argument. For example, you could use Node's fs library to read a file. The fs module exposes two unique API functions: readFile and readFileSync.

The readFile function is asynchronous while readFileSync is obviously not. You can see that they intend you to use the async calls whenever possible since they called them readFile and readFileSync instead of readFile and readFileAsync. Here is an example of using both functions.

Synchronous:

var data = fs.readFileSync('test.txt');
console.log(data);

The code above blocks thread execution until all the contents of test.txt are read into memory and stored in the variable data. In node this is typically considered bad practice. There are times though when it's useful, such as when writing a quick little script to do something simple but tedious and you don't care much about saving every nanosecond of time that you can.

Asynchronous (with callback):

var callback = function (err, data) {
  if (err) return console.error(err);
  console.log(data);
};
fs.readFile('test.txt', callback);

First we create a callback function that accepts two arguments err and data. One problem with asynchronous functions is that it becomes more difficult to trap errors so a lot of callback-style APIs pass errors as the first argument to the callback function. It is best practice to check if err has a value before you do anything else. If so, stop execution of the callback and log the error.

Synchronous calls have an advantage when there are thrown exceptions because you can simply catch them with a try/catch block.

try {
  var data = fs.readFileSync('test.txt');
  console.log(data);
} catch (err) {
  console.error(err);
}

In asynchronous functions it doesn't work that way. The API call returns immediately so there is nothing to catch with the try/catch. Proper asynchronous APIs that use callbacks will always catch their own errors and then pass those errors into the callback where you can handle it as you see fit.

In addition to callbacks though, there is another popular style of API that is commonly used called the promise. If you'd like to read about them then you can read the entire blog post I wrote based on this answer here.

How to append a jQuery variable value inside the .html tag

HTML :

<div id="myDiv">
    <form id="myForm">
    </form> 
</div>

jQuery :

var chbx='<input type="checkbox" id="Mumbai" name="Mumbai" value="Mumbai" />Mumbai<br /> <input type="checkbox" id=" Delhi" name=" Delhi" value=" Delhi" /> Delhi<br/><input type="checkbox" id=" Bangalore" name=" Bangalore" value=" Bangalore"/>Bangalore<br />';

$("#myDiv form#myForm").html(chbx);

//to insert dynamically created form 
$("#myDiv").html("<form id='dynamicForm'>" +chbx + "'</form>");

Demo

Select multiple images from android gallery

Define these variables in the class:

int PICK_IMAGE_MULTIPLE = 1; 
String imageEncoded;    
List<String> imagesEncodedList;

Let's Assume that onClick on a button it should open gallery to select images

 Intent intent = new Intent();
 intent.setType("image/*");
 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
 intent.setAction(Intent.ACTION_GET_CONTENT);
 startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE_MULTIPLE);

Then you should override onActivityResult Method

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    try {
        // When an Image is picked
        if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK
                    && null != data) {
            // Get the Image from data

            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            imagesEncodedList = new ArrayList<String>();
            if(data.getData()!=null){

                Uri mImageUri=data.getData();

                // Get the cursor
                Cursor cursor = getContentResolver().query(mImageUri,
                            filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imageEncoded  = cursor.getString(columnIndex);
                cursor.close();

            } else {
                if (data.getClipData() != null) {
                    ClipData mClipData = data.getClipData();
                    ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
                    for (int i = 0; i < mClipData.getItemCount(); i++) {

                        ClipData.Item item = mClipData.getItemAt(i);
                        Uri uri = item.getUri();
                        mArrayUri.add(uri);
                        // Get the cursor
                        Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
                        // Move to first row
                        cursor.moveToFirst();

                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        imageEncoded  = cursor.getString(columnIndex);
                        imagesEncodedList.add(imageEncoded);
                        cursor.close();

                    }
                    Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());
                }
            }
        } else {
            Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                    .show();
    }

    super.onActivityResult(requestCode, resultCode, data);
}

NOTE THAT: the gallery doesn't give you the ability to select multi-images so we here open all images studio that you can select multi-images from them. and don't forget to add the permissions to your manifest

VERY IMPORTANT: getData(); to get one single image and I've stored it here in imageEncoded String if the user select multi-images then they should be stored in the list

So you have to check which is null to use the other

Wish you have a nice try and to others

How do we change the URL of a working GitLab install?

You did everything correctly!

You might also change the email configuration, depending on if the email server is also the same server. The email configuration is in gitlab.yml for the mails sent by GitLab and also the admin-email.

Django: TemplateSyntaxError: Could not parse the remainder

also happens when you use jinja templates (which have different syntax for calling object methods) and you forget to set it in settings.py

How to put a text beside the image?

If you or some other fox who need to have link with Icon Image and text as link text beside the image see bellow code:

CSS

.linkWithImageIcon{

    Display:inline-block;
}
.MyLink{
  Background:#FF3300;
  width:200px;
  height:70px;
  vertical-align:top;
  display:inline-block; font-weight:bold;
} 

.MyLinkText{
  /*---The margin depends on how the image size is ---*/
  display:inline-block; margin-top:5px;
}

HTML

<a href="#" class="MyLink"><img src="./yourImageIcon.png" /><span class="MyLinkText">SIGN IN</span></a>

enter image description here

if you see the image the white portion is image icon and other is style this way you can create different buttons with any type of Icons you want to design

Nginx 403 error: directory index of [folder] is forbidden

In my case I didn't run this command

sudo apt-get install php7.4-fpm

How to check if an email address is real or valid using PHP

You can't verify (with enough accuracy to rely on) if an email actually exists using just a single PHP method. You can send an email to that account, but even that alone won't verify the account exists (see below). You can, at least, verify it's at least formatted like one

if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
    //Email is valid
}

You can add another check if you want. Parse the domain out and then run checkdnsrr

if(checkdnsrr($domain)) {
     // Domain at least has an MX record, necessary to receive email
}

Many people get to this point and are still unconvinced there's not some hidden method out there. Here are some notes for you to consider if you're bound and determined to validate email:

  1. Spammers also know the "connection trick" (where you start to send an email and rely on the server to bounce back at that point). One of the other answers links to this library which has this caveat

    Some mail servers will silently reject the test message, to prevent spammers from checking against their users' emails and filter the valid emails, so this function might not work properly with all mail servers.

    In other words, if there's an invalid address you might not get an invalid address response. In fact, virtually all mail servers come with an option to accept all incoming mail (here's how to do it with Postfix). The answer linking to the validation library neglects to mention that caveat.

  2. Spam blacklists. They blacklist by IP address and if your server is constantly doing verification connections you run the risk of winding up on Spamhaus or another block list. If you get blacklisted, what good does it do you to validate the email address?

  3. If it's really that important to verify an email address, the accepted way is to force the user to respond to an email. Send them a full email with a link they have to click to be verified. It's not spammy, and you're guaranteed that any responses have a valid address.

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

I ran into the same problem after restructuring the settings as per the instructions from Daniel Greenfield's book Two scoops of Django.

I resolved the issue by setting

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings.local")

in manage.py and wsgi.py.

Update:

In the above solution, local is the file name (settings/local.py) inside my settings folder, which holds the settings for my local environment.

Another way to resolve this issue is to keep all your common settings inside settings/base.py and then create 3 separate settings files for your production, staging and dev environments.

Your settings folder will look like:

settings/
    __init__.py
    base.py
    local.py
    prod.py
    stage.py

and keep the following code in your settings/__init__.py

from .base import *

env_name = os.getenv('ENV_NAME', 'local')

if env_name == 'prod':
    from .prod import *
elif env_name == 'stage':
    from .stage import *
else:
    from .local import *

HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory

keep this into your web config file then rename the add value="yourwebformname.aspx"

<system.webServer>
    <defaultDocument>
       <files>
          <add value="insertion.aspx" />
       </files>
    </defaultDocument>
    <directoryBrowse enabled="false" />
</system.webServer>

else

<system.webServer>
    <directoryBrowse enabled="true" />
</system.webServer>

Crontab Day of the Week syntax

You can also use day names like Mon for Monday, Tue for Tuesday, etc. It's more human friendly.

NodeJS/express: Cache and 304 status code

  • Operating system: Windows
  • Browser: Chrome

I used Ctrl + F5 keyboard combination. By doing so, instead of reading from cache, I wanted to get a new response. The solution is to do hard refresh the page.

On MDN Web Docs:

"The HTTP 304 Not Modified client redirection response code indicates that there is no need to retransmit the requested resources. It is an implicit redirection to a cached resource."

NGINX: upstream timed out (110: Connection timed out) while reading response header from upstream

I had the same problem and resulted that was an "every day" error in the rails controller. I don't know why, but on production, puma runs the error again and again causing the message:

upstream timed out (110: Connection timed out) while reading response header from upstream

Probably because Nginx tries to get the data from puma again and again.The funny thing is that the error caused the timeout message even if I'm calling a different action in the controller, so, a single typo blocks all the app.

Check your log/puma.stderr.log file to see if that is the situation.

Tar a directory, but don't store full absolute paths in the archive

tar -cjf site1.tar.bz2 -C /var/www/site1 .

In the above example, tar will change to directory /var/www/site1 before doing its thing because the option -C /var/www/site1 was given.

From man tar:

OTHER OPTIONS

  -C, --directory DIR
       change to directory DIR

Combining (concatenating) date and time into a datetime

Solution (1): datetime arithmetic

Given @myDate, which can be anything that can be cast as a DATE, and @myTime, which can be anything that can be cast as a TIME, starting SQL Server 2014+ this works fine and does not involve string manipulation:

CAST(CAST(@myDate as DATE) AS DATETIME) + CAST(CAST(@myTime as TIME) as DATETIME)

You can verify with:

SELECT  GETDATE(), 
        CAST(CAST(GETDATE() as DATE) AS DATETIME) + CAST(CAST(GETDATE() as TIME) as DATETIME)

Solution (2): string manipulation

SELECT  GETDATE(), 
        CONVERT(DATETIME, CONVERT(CHAR(8), GETDATE(), 112) + ' ' + CONVERT(CHAR(8), GETDATE(), 108))

However, solution (1) is not only 2-3x faster than solution (2), it also preserves the microsecond part.

See SQL Fiddle for the solution (1) using date arithmetic vs solution (2) involving string manipulation

How do I restart nginx only after the configuration test was successful on Ubuntu?

At least on Debian the nginx startup script has a reload function which does:

reload)
  log_daemon_msg "Reloading $DESC configuration" "$NAME"
  test_nginx_config
  start-stop-daemon --stop --signal HUP --quiet --pidfile $PID \
   --oknodo --exec $DAEMON
  log_end_msg $?
  ;;

Seems like all you'd need to do is call service nginx reload instead of restart since it calls test_nginx_config.

Why isn't .ico file defined when setting window's icon?

No way what is suggested here works - the error "bitmap xxx not defined" is ever present. And yes, I set the correct path to it.

What it did work is this:

imgicon = PhotoImage(file=os.path.join(sp,'myicon.gif'))
root.tk.call('wm', 'iconphoto', root._w, imgicon)  

where sp is the script path, and root the Tk root window.

It's hard to understand how it does work (I shamelessly copied it from fedoraforums) but it works

org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

If you want to re-filter the json data you can use following method. Given example is getting all document data from couchdb.

{
    Gson gson = new Gson();
    String resultJson = restTemplate.getForObject(url+"_all_docs?include_docs=true", String.class);
    JSONObject object =  (JSONObject) new JSONParser().parse(resultJson);
    JSONArray rowdata = (JSONArray) object.get("rows");   
    List<Object>list=new ArrayList<Object>();   
    for(int i=0;i<rowdata.size();i++) {
        JSONObject index = (JSONObject) rowdata.get(i);
        JSONObject data = (JSONObject) index.get("doc");
        list.add(data);      
    }
    // convert your list to json
    String devicelist = gson.toJson(list);
    return devicelist;
}

What is the difference between DBMS and RDBMS?

There are other database systems, such as document stores, key value stores, columnar stores, object oriented databases. These are databases too but they are not based on relations (relational theory) ie they are not relational database systems.

So there are lot of differences. Database management system is the name for all databases.

How to find files recursively by file type and copy them to a directory while in ssh?

Try this:

find . -name "*.pdf" -type f -exec cp {} ./pdfsfolder \;

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

My site configuration file is example.conf in sites-available folder So you can create a symbolic link as

ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/

Get operating system info

Based on the answer by Fred-II I wanted to share my take on the getOS function, it avoids globals, merges both lists and detects the architecture (x32/x64)

/**
 * @param $user_agent null
 * @return string
 */
function getOS($user_agent = null)
{
    if(!isset($user_agent) && isset($_SERVER['HTTP_USER_AGENT'])) {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
    }

    // https://stackoverflow.com/questions/18070154/get-operating-system-info-with-php
    $os_array = [
        'windows nt 10'                              =>  'Windows 10',
        'windows nt 6.3'                             =>  'Windows 8.1',
        'windows nt 6.2'                             =>  'Windows 8',
        'windows nt 6.1|windows nt 7.0'              =>  'Windows 7',
        'windows nt 6.0'                             =>  'Windows Vista',
        'windows nt 5.2'                             =>  'Windows Server 2003/XP x64',
        'windows nt 5.1'                             =>  'Windows XP',
        'windows xp'                                 =>  'Windows XP',
        'windows nt 5.0|windows nt5.1|windows 2000'  =>  'Windows 2000',
        'windows me'                                 =>  'Windows ME',
        'windows nt 4.0|winnt4.0'                    =>  'Windows NT',
        'windows ce'                                 =>  'Windows CE',
        'windows 98|win98'                           =>  'Windows 98',
        'windows 95|win95'                           =>  'Windows 95',
        'win16'                                      =>  'Windows 3.11',
        'mac os x 10.1[^0-9]'                        =>  'Mac OS X Puma',
        'macintosh|mac os x'                         =>  'Mac OS X',
        'mac_powerpc'                                =>  'Mac OS 9',
        'linux'                                      =>  'Linux',
        'ubuntu'                                     =>  'Linux - Ubuntu',
        'iphone'                                     =>  'iPhone',
        'ipod'                                       =>  'iPod',
        'ipad'                                       =>  'iPad',
        'android'                                    =>  'Android',
        'blackberry'                                 =>  'BlackBerry',
        'webos'                                      =>  'Mobile',

        '(media center pc).([0-9]{1,2}\.[0-9]{1,2})'=>'Windows Media Center',
        '(win)([0-9]{1,2}\.[0-9x]{1,2})'=>'Windows',
        '(win)([0-9]{2})'=>'Windows',
        '(windows)([0-9x]{2})'=>'Windows',

        // Doesn't seem like these are necessary...not totally sure though..
        //'(winnt)([0-9]{1,2}\.[0-9]{1,2}){0,1}'=>'Windows NT',
        //'(windows nt)(([0-9]{1,2}\.[0-9]{1,2}){0,1})'=>'Windows NT', // fix by bg

        'Win 9x 4.90'=>'Windows ME',
        '(windows)([0-9]{1,2}\.[0-9]{1,2})'=>'Windows',
        'win32'=>'Windows',
        '(java)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2})'=>'Java',
        '(Solaris)([0-9]{1,2}\.[0-9x]{1,2}){0,1}'=>'Solaris',
        'dos x86'=>'DOS',
        'Mac OS X'=>'Mac OS X',
        'Mac_PowerPC'=>'Macintosh PowerPC',
        '(mac|Macintosh)'=>'Mac OS',
        '(sunos)([0-9]{1,2}\.[0-9]{1,2}){0,1}'=>'SunOS',
        '(beos)([0-9]{1,2}\.[0-9]{1,2}){0,1}'=>'BeOS',
        '(risc os)([0-9]{1,2}\.[0-9]{1,2})'=>'RISC OS',
        'unix'=>'Unix',
        'os/2'=>'OS/2',
        'freebsd'=>'FreeBSD',
        'openbsd'=>'OpenBSD',
        'netbsd'=>'NetBSD',
        'irix'=>'IRIX',
        'plan9'=>'Plan9',
        'osf'=>'OSF',
        'aix'=>'AIX',
        'GNU Hurd'=>'GNU Hurd',
        '(fedora)'=>'Linux - Fedora',
        '(kubuntu)'=>'Linux - Kubuntu',
        '(ubuntu)'=>'Linux - Ubuntu',
        '(debian)'=>'Linux - Debian',
        '(CentOS)'=>'Linux - CentOS',
        '(Mandriva).([0-9]{1,3}(\.[0-9]{1,3})?(\.[0-9]{1,3})?)'=>'Linux - Mandriva',
        '(SUSE).([0-9]{1,3}(\.[0-9]{1,3})?(\.[0-9]{1,3})?)'=>'Linux - SUSE',
        '(Dropline)'=>'Linux - Slackware (Dropline GNOME)',
        '(ASPLinux)'=>'Linux - ASPLinux',
        '(Red Hat)'=>'Linux - Red Hat',
        // Loads of Linux machines will be detected as unix.
        // Actually, all of the linux machines I've checked have the 'X11' in the User Agent.
        //'X11'=>'Unix',
        '(linux)'=>'Linux',
        '(amigaos)([0-9]{1,2}\.[0-9]{1,2})'=>'AmigaOS',
        'amiga-aweb'=>'AmigaOS',
        'amiga'=>'Amiga',
        'AvantGo'=>'PalmOS',
        //'(Linux)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}(rel\.[0-9]{1,2}){0,1}-([0-9]{1,2}) i([0-9]{1})86){1}'=>'Linux',
        //'(Linux)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}(rel\.[0-9]{1,2}){0,1} i([0-9]{1}86)){1}'=>'Linux',
        //'(Linux)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}(rel\.[0-9]{1,2}){0,1})'=>'Linux',
        '[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}'=>'Linux',
        '(webtv)/([0-9]{1,2}\.[0-9]{1,2})'=>'WebTV',
        'Dreamcast'=>'Dreamcast OS',
        'GetRight'=>'Windows',
        'go!zilla'=>'Windows',
        'gozilla'=>'Windows',
        'gulliver'=>'Windows',
        'ia archiver'=>'Windows',
        'NetPositive'=>'Windows',
        'mass downloader'=>'Windows',
        'microsoft'=>'Windows',
        'offline explorer'=>'Windows',
        'teleport'=>'Windows',
        'web downloader'=>'Windows',
        'webcapture'=>'Windows',
        'webcollage'=>'Windows',
        'webcopier'=>'Windows',
        'webstripper'=>'Windows',
        'webzip'=>'Windows',
        'wget'=>'Windows',
        'Java'=>'Unknown',
        'flashget'=>'Windows',

        // delete next line if the script show not the right OS
        //'(PHP)/([0-9]{1,2}.[0-9]{1,2})'=>'PHP',
        'MS FrontPage'=>'Windows',
        '(msproxy)/([0-9]{1,2}.[0-9]{1,2})'=>'Windows',
        '(msie)([0-9]{1,2}.[0-9]{1,2})'=>'Windows',
        'libwww-perl'=>'Unix',
        'UP.Browser'=>'Windows CE',
        'NetAnts'=>'Windows',
    ];

    // https://github.com/ahmad-sa3d/php-useragent/blob/master/core/user_agent.php
    $arch_regex = '/\b(x86_64|x86-64|Win64|WOW64|x64|ia64|amd64|ppc64|sparc64|IRIX64)\b/ix';
    $arch = preg_match($arch_regex, $user_agent) ? '64' : '32';

    foreach ($os_array as $regex => $value) {
        if (preg_match('{\b('.$regex.')\b}i', $user_agent)) {
            return $value.' x'.$arch;
        }
    }

    return 'Unknown';
}

Fix CSS hover on iPhone/iPad/iPod

Add a tabIndex attribute to the body:

<body tabIndex=0 >

This is the only solution that also works when Javascript is disabled.

Add ontouchmove to the html element:

<html lang=en ontouchmove >

For examples and remarks see this blogpost:

Confirmed on iOS 13.

These solutions have the advantage that the hovered state disappears when you click somewhere else. Also no extra code needed in the source.

How to stop creating .DS_Store on Mac?

Its is possible by using mach_inject. Take a look at Death to .DS_Store

I found that overriding HFSPlusPropertyStore::FlushChanges() with a function that simply did nothing, successfully prevented the creation of .DS_Store files on both Snow Leopard and Lion.

DeathToDSStore source code

NOTE: On 10.11 you can not inject code into system apps.

Set port for php artisan.php serve

when we use the

php artisan serve 

it will start with the default HTTP-server port mostly it will be 8000 when we want to run the more site in the localhost we have to change the port. Just add the --port argument:

php artisan serve --port=8081

enter image description here

Add column to SQL query results

Manually add it when you build the query:

SELECT 'Site1' AS SiteName, t1.column, t1.column2
FROM t1

UNION ALL
SELECT 'Site2' AS SiteName, t2.column, t2.column2
FROM t2

UNION ALL
...

EXAMPLE:

DECLARE @t1 TABLE (column1 int, column2 nvarchar(1))
DECLARE @t2 TABLE (column1 int, column2 nvarchar(1))

INSERT INTO @t1
SELECT 1, 'a'
UNION SELECT 2, 'b'

INSERT INTO @t2
SELECT 3, 'c'
UNION SELECT 4, 'd'


SELECT 'Site1' AS SiteName, t1.column1, t1.column2
FROM @t1 t1

UNION ALL
SELECT 'Site2' AS SiteName, t2.column1, t2.column2
FROM @t2 t2

RESULT:

SiteName  column1  column2
Site1       1      a
Site1       2      b
Site2       3      c
Site2       4      d

Nginx not running with no error message

One case you check that nginx hold on 80 number port in system by default , check if you have any server like as apache or anything exist on system that block 80 number port thats the problem occurred.

1 .You change port number on nginx by this way,

sudo vim /etc/nginx/sites-available/default

Change 80 to 81 or anything,

  1. Check everything is ok by ,

sudo nginx -t

  1. Restart server

sudo service nginx start

  1. Check the status of nginx:

sudo service nginx status

Hope that will work

What is the exact meaning of Git Bash?

At its core, Git is a set of command line utility programs that are designed to execute on a Unix style command-line environment. Modern operating systems like Linux and macOS both include built-in Unix command line terminals. This makes Linux and macOS complementary operating systems when working with Git. Microsoft Windows instead uses Windows command prompt, a non-Unix terminal environment.

What is Git Bash?

Git Bash is an application for Microsoft Windows environments which provides an emulation layer for a Git command line experience. Bash is an acronym for Bourne Again Shell. A shell is a terminal application used to interface with an operating system through written commands. Bash is a popular default shell on Linux and macOS. Git Bash is a package that installs Bash, some common bash utilities, and Git on a Windows operating system.

source : https://www.atlassian.com/git/tutorials/git-bash

phpinfo() is not working on my CentOS server

It may not work for you if you use localhost/info.php.

You may be able to found the clue from the error. Find the port number in the error message. To me it was 80. I changed address as http://localhost:80/info.php, and then it worked to me.

Custom alert and confirm box in jquery

Check the jsfiddle http://jsfiddle.net/CdwB9/3/ and click on delete

function yesnodialog(button1, button2, element){
  var btns = {};
  btns[button1] = function(){ 
      element.parents('li').hide();
      $(this).dialog("close");
  };
  btns[button2] = function(){ 
      // Do nothing
      $(this).dialog("close");
  };
  $("<div></div>").dialog({
    autoOpen: true,
    title: 'Condition',
    modal:true,
    buttons:btns
  });
}
$('.delete').click(function(){
    yesnodialog('Yes', 'No', $(this));
})

This should help you

SQL Server Creating a temp table for this query

If you want to just create a temp table inside the query that will allow you to do something with the results that you deposit into it you can do something like the following:

DECLARE @T1 TABLE (
Item 1 VARCHAR(200)
, Item 2 VARCHAR(200)
, ...
, Item n VARCHAR(500)
)

On the top of your query and then do an

INSERT INTO @T1
SELECT
FROM
(...)

PHP Fatal error: Uncaught exception 'Exception'

This is expected behavior for an uncaught exception with display_errors off.

Your options here are to turn on display_errors via php or in the ini file or catch and output the exception.

 ini_set("display_errors", 1);

or

 try{
     // code that may throw an exception
 } catch(Exception $e){
     echo $e->getMessage();
 }

If you are throwing exceptions, the intention is that somewhere further down the line something will catch and deal with it. If not it is a server error (500).

Another option for you would be to use set_exception_handler to set a default error handler for your script.

 function default_exception_handler(Exception $e){
          // show something to the user letting them know we fell down
          echo "<h2>Something Bad Happened</h2>";
          echo "<p>We fill find the person responsible and have them shot</p>";
          // do some logging for the exception and call the kill_programmer function.
 }
 set_exception_handler("default_exception_handler");

Eliminating duplicate values based on only one column of the table

From your example it seems reasonable to assume that the siteIP column is determined by the siteName column (that is, each site has only one siteIP). If this is indeed the case, then there is a simple solution using group by:

select
  sites.siteName,
  sites.siteIP,
  max(history.date)
from sites
inner join history on
  sites.siteName=history.siteName
group by
  sites.siteName,
  sites.siteIP
order by
  sites.siteName;

However, if my assumption is not correct (that is, it is possible for a site to have multiple siteIP), then it is not clear from you question which siteIP you want the query to return in the second column. If just any siteIP, then the following query will do:

select
  sites.siteName,
  min(sites.siteIP),
  max(history.date)
from sites
inner join history on
  sites.siteName=history.siteName
group by
  sites.siteName
order by
  sites.siteName;

nginx missing sites-available directory

I tried sudo apt install nginx-full. You will get all the required packages.

AngularJS: How to clear query parameters in the URL?

You can delete a specific query parameter by using:

delete $location.$$search.nameOfParameter;

Or you can clear all the query params by setting search to an empty object:

$location.$$search = {};

What is log4j's default log file dumping path

You have copy this sample code from Here,right?
now, as you can see there property file they have define, have you done same thing? if not then add below code in your project with property file for log4j

So the content of log4j.properties file would be as follows:

# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n

make changes as per your requirement like log path

How to check for palindrome using Python logic

There is also a functional way:

def is_palindrome(word):
  if len(word) == 1: return True
  if word[0] != word[-1]: return False
  return is_palindrome(word[1:-1])

How to write and read java serialized objects into a file

I think you have to write each object to an own File or you have to split the one when reading it. You may also try to serialize your list and retrieve that when deserializing.

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

Had the same problem, I just coerced the id into a string.

My schema:

const product = new mongooseClient.Schema({
    retailerID: { type: mongoose.SchemaTypes.ObjectId, required: true, index: true }
});

And then, when inserting:

retailerID: `${retailer._id}`

Two divs side by side - Fluid display

_x000D_
_x000D_
<div style="height:50rem; width:100%; margin: auto;">
  <div style="height:50rem; width:20%; margin-left:4%; margin-right:0%; float:left; background-color: black;"></div>
  <div style="height:50rem; width:20%; margin-left:4%; margin-right:0%; float:left;  background-color: black;"></div>
  <div style="height:50rem; width:20%; margin-left:4%; margin-right:0%; float:left;  background-color: black;"></div>
  <div style="height:50rem; width:20%; margin-left:4%; margin-right:0%; float:left;  background-color: black;"></div>
</div>
_x000D_
_x000D_
_x000D_

margin-right isn't needed though.

Sites not accepting wget user agent header

It seems Yahoo server does some heuristic based on User-Agent in a case Accept header is set to */*.

Accept: text/html

did the trick for me.

e.g.

wget  --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0"  http://yahoo.com

Note: if you don't declare Accept header then wget automatically adds Accept:*/* which means give me anything you have.

download and install visual studio 2008

Try this one: http://www.asp.net/downloads/essential This has web developer and VS2008 express

Windows 7, 64 bit, DLL problems

I suggest also checking how much memory is currently being used.

It turns out that the inability to find these DLL files was the first symptom exhibited when trying to run a program (either run or debug) in Visual Studio.

After over a half hour with much head scratching, searching the web, running Process Monitor, and Task Manager, and depends, a completely different program that had been running since the beginning of time reported that "memory is low; try stopping some programs" or some such. After killing Firefox, Thunderbird, Process Monitor, and depends, everything worked again.

Excel VBA Code: Compile Error in x64 Version ('PtrSafe' attribute required)

I'm quite sure you won't get this 32Bit DLL working in Office 64Bit. The DLL needs to be updated by the author to be compatible with 64Bit versions of Office.

The code changes you have found and supplied in the question are used to convert calls to APIs that have already been rewritten for Office 64Bit. (Most Windows APIs have been updated.)

From: http://technet.microsoft.com/en-us/library/ee681792.aspx:

"ActiveX controls and add-in (COM) DLLs (dynamic link libraries) that were written for 32-bit Office will not work in a 64-bit process."

Edit: Further to your comment, I've tried the 64Bit DLL version on Win 8 64Bit with Office 2010 64Bit. Since you are using User Defined Functions called from the Excel worksheet you are not able to see the error thrown by Excel and just end up with the #VALUE returned.

If we create a custom procedure within VBA and try one of the DLL functions we see the exact error thrown. I tried a simple function of swe_day_of_week which just has a time as an input and I get the error Run-time error '48' File not found: swedll32.dll.

Now I have the 64Bit DLL you supplied in the correct locations so it should be found which suggests it has dependencies which cannot be located as per https://stackoverflow.com/a/8607250/1733206

I've got all the .NET frameworks installed which would be my first guess, so without further information from the author it might be difficult to find the problem.

Edit2: And after a bit more investigating it appears the 64Bit version you have supplied is actually a 32Bit version. Hence the error message on the 64Bit Office. You can check this by trying to access the '64Bit' version in Office 32Bit.

How do I change the background of a Frame in Tkinter?

The root of the problem is that you are unknowingly using the Frame class from the ttk package rather than from the tkinter package. The one from ttk does not support the background option.

This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.

I recommend doing imports like this:

import tkinter as tk
import ttk

Then you prefix the widgets with either tk or ttk :

f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)

It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.

Win32Exception (0x80004005): The wait operation timed out

I had the same issue, and by Running "exec sp_updatestats" the issue solved and works now

Most efficient way to find mode in numpy array

A neat solution that only uses numpy (not scipy nor the Counter class):

A = np.array([[1,3,4,2,2,7], [5,2,2,1,4,1], [3,3,2,2,1,1]])

np.apply_along_axis(lambda x: np.bincount(x).argmax(), axis=0, arr=A)

array([1, 3, 2, 2, 1, 1])

Django DoesNotExist

The solution that i believe is best and optimized is:

try:
   #your code
except "ModelName".DoesNotExist:
   #your code

Adding a stylesheet to asp.net (using Visual Studio 2010)

Add your style here:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="BSC.SiteMaster" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
    <title></title>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Styles/NewStyle.css" rel="stylesheet" type="text/css" />

    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
</head>

Then in the page:

<asp:Table CssClass=NewStyleExampleClass runat="server" >

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

Replace the earlier function with the provided one. The simplest solution is:

def __unicode__(self):

    return unicode(self.nom_du_site)

Get HTML inside iframe using jQuery

Try this code:

$('#iframe').contents().find("html").html();

This will return all the html in your iframe. Instead of .find("html") you can use any selector you want eg: .find('body'),.find('div#mydiv').

Forbidden You don't have permission to access /wp-login.php on this server

Make sure the following lines are not in your wp.config

define( 'FORCE_SSL_LOGIN', true );
define( 'FORCE_SSL_ADMIN', true );
define( 'DISALLOW_FILE_EDIT', true );

I got locked out after deactivating iThemes security plugin

Insertion Sort vs. Selection Sort

The logic for both algorithms is quite similar. They both have a partially sorted sub-array in the beginning of the array. The only difference is how they search for the next element to be put in the sorted array.

  • Insertion sort: inserts the next element at the correct position;

  • Selection sort: selects the smallest element and exchange it with the current item;

Also, Insertion Sort is stable, as opposed to Selection Sort.

I implemented both in python, and it's worth noting how similar they are:

def insertion(data):
    data_size = len(data)
    current = 1
    while current < data_size:
        for i in range(current):
            if data[current] < data[i]:
                temp = data[i]
                data[i] = data[current]
                data[current] = temp

        current += 1

    return data

With a small change it is possible to make the Selection Sort algorithm.

def selection(data):
    data_size = len(data)
    current = 0
    while current < data_size:
        for i in range(current, data_size):
            if data[i] < data[current]:
                temp = data[i]
                data[i] = data[current]
                data[current] = temp

        current += 1

    return data

Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?

It was particular for me. I am sending a header named 'SESSIONHASH'. No problem for Chrome and Opera, but Firefox also wants this header in the list "Access-Control-Allow-Headers". Otherwise, Firefox will throw the CORS error.

Apache - MySQL Service detected with wrong path. / Ports already in use

To delete existing service is not good solution for me, because on port 3306 run MySQL, which need other service. But it is possible to run two MySQL services at one time (one with other name and port). I found the solution here: http://emjaywebdesigns.com/xampp-and-multiple-instances-of-mysql-on-windows/

Here is my modified setting: Edit your “my.ini” file in c:\xampp\mysql\bin\ Change all default 3306 port entries to a new value 3308

edit your “php.ini” in c:\xampp\php and replace 3306 by 3308

Create the service entry - in Windows command line type

sc.exe create "mysqlweb" binPath= "C:\xampp\mysql\bin\mysqld.exe --defaults-file=c:\xampp\mysql\bin\my.ini mysqlweb"

Open Windows Services and set Startup Type: Automatic, Start the service

Responsive font size in CSS

There are the following ways by which you can achieve this:

  1. Use rem for e.g. 2.3 rem
  2. Use em for e.g. 2.3em
  3. Use % for e.g. 2.3% Moreover, you can use : vh, vw, vmax and vmin.

These units will autoresize depending upon the width and height of the screen.

IIS: Display all sites and bindings in PowerShell

function Get-ADDWebBindings {
param([string]$Name="*",[switch]$http,[switch]$https)
    try {
    if (-not (Get-Module WebAdministration)) { Import-Module WebAdministration }
    Get-WebBinding | ForEach-Object { $_.ItemXPath -replace '(?:.*?)name=''([^'']*)(?:.*)', '$1' } | Sort | Get-Unique | Where-Object {$_ -like $Name} | ForEach-Object {
        $n=$_
        Get-WebBinding | Where-Object { ($_.ItemXPath -replace '(?:.*?)name=''([^'']*)(?:.*)', '$1') -like $n } | ForEach-Object {
            if ($http -or $https) {
                if ( ($http -and ($_.protocol -like "http")) -or ($https -and ($_.protocol -like "https")) ) {
                    New-Object psobject -Property @{Name = $n;Protocol=$_.protocol;Binding = $_.bindinginformation}
                }
            } else {
                New-Object psobject -Property @{Name = $n;Protocol=$_.protocol;Binding = $_.bindinginformation}
            }
        }
    }
    }
    catch {
       $false
    }
}

iPhone/iPad browser simulator?

I have been using Mobilizer, which is an awesome free app

Currently it has default simulation for Iphone4, Iphone5, Samsung Galaxt S3, Nokia Lumia, Palm Pre, Blackberry Storm and HTC Evo. Simple straightforward and effective.

Include CSS and Javascript in my django template

First, create staticfiles folder. Inside that folder create css, js, and img folder.

settings.py

import os

PROJECT_DIR = os.path.dirname(__file__)

DATABASES = {
    'default': {
         'ENGINE': 'django.db.backends.sqlite3', 
         'NAME': os.path.join(PROJECT_DIR, 'myweblabdev.sqlite'),                        
         'USER': '',
         'PASSWORD': '',
         'HOST': '',                      
         'PORT': '',                     
    }
}

MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')

MEDIA_URL = '/media/'

STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(PROJECT_DIR, 'staticfiles'),
)

main urls.py

from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from myweblab import settings

admin.autodiscover()

urlpatterns = patterns('',
    .......
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += staticfiles_urlpatterns()

template

{% load static %}

<link rel="stylesheet" href="{% static 'css/style.css' %}">

How to add a href link in PHP?

Looks like you missed a few closing tags and you nshould have "http://" on the front of an external URL. Also, you should move your styles to external style sheets instead of using inline styles.

.box{
  float:right;
}
.box a img{
  vertical-align: middle;
  border: 0px;
}

<div class="box">
    <a href="<?php echo "http://www.someotherwebsite.com"; ?>">
        <img src="<?php echo url::file_loc('img'); ?>media/img/twitter.png" alt="Image Decription">
    </a>
</div>

As noted in other comments, it may be easier to use straight HTML, depending on your exact setup.

<div class="box">
    <a href="http://www.someotherwebsite.com">
        <img src="file_location/media/img/twitter.png" alt="Image Decription">
    </a>
</div>

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

The most likely reason why the Java Runtime Environment JRE or Java Development Kit JDK is that it's owned by Oracle not Google and they would need a redistribution agreement which if you know there is some history between the two companies.

Lucky for us that Sun Microsystems before it was bought by Oracle open sourced Java and MySQL a win for us little guys.... Thank you Sun!

Google should probably have a caveat saying you may also need JRE OR JDK

node-request - Getting error "SSL23_GET_SERVER_HELLO:unknown protocol"

So in Short,

vi ~/.proxy_info

export http_proxy=<username>:<password>@<proxy>:8080
export https_proxy=<username>:<password>@<proxy>:8080

source ~/.proxy_info

Hope this helps someone in hurry :)

An error has occured. Please see log file - eclipse juno

For me it was down to a locking/permissions bug on

(path to Eclipse IDE)\configuration\org.eclipse.osgi.manager.fileTableLock

See here

Spring Tool Suite 4 (64 bit for Windows Server 2016)

Version: 4.2.2.RELEASE Build Id: 201905232009

based on Eclipse

Version: 2.2.500.v20190307-0500 Build id: I20190307-0500

wouldn't launch and a pop up dialog appeared saying:

launch error has occurred see log file null

(This became apparent from the latest text log file in the folder (path to Eclipse IDE)\configuration)

!ENTRY org.eclipse.osgi 4 0 
2019-06-19 18:41:10.408
!MESSAGE Error reading configuration: C:\opt\sts-4.2.2.RELEASE\configuration\org.eclipse.osgi\.manager\.fileTableLock (Access is denied)
!STACK 0
java.io.FileNotFoundException: C:\opt\sts-4.2.2.RELEASE\configuration\org.eclipse.osgi\.manager\.fileTableLock (Access is denied)
...

I had to go and tweak the permissions via File Explorer (Full access).

It appeared as if the IDE was doing nothing for a while.

The splash screen for Spring Tool Suite (based on Eclipse) eventually disappeared and the IDE started up again.

Now everything is back working correctly again.

Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.."

I think that you can bind the load event of the iframe, the event fires when the iframe content is fully loaded.

At the same time you can start a setTimeout, if the iFrame is loaded clear the timeout alternatively let the timeout fire.

Code:

var iframeError;

function change() {
    var url = $("#addr").val();
    $("#browse").attr("src", url);
    iframeError = setTimeout(error, 5000);
}

function load(e) {
    alert(e);
}

function error() {
    alert('error');
}

$(document).ready(function () {
    $('#browse').on('load', (function () {
        load('ok');
        clearTimeout(iframeError);
    }));

});

Demo: http://jsfiddle.net/IrvinDominin/QXc6P/

Second problem

It is because you miss the parens in the inline function call; try change this:

<iframe id="browse" style="width:100%;height:100%" onload="load" onerror="error"></iframe>

into this:

<iframe id="browse" style="width:100%;height:100%" onload="load('Done func');" onerror="error('failed function');"></iframe>

Demo: http://jsfiddle.net/IrvinDominin/ALBXR/4/

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

Try this, instead of selecting your websete's Application Pool to DefaultAppPool, select ASP.NET v4.0

Select your website in IIS => Basic Settings => Application Pool => Select ASP.NET v4.0

and you will be good to go. Hope it helps :)

What's the best way to cancel event propagation between nested ng-click calls?

<div ng-click="methodName(event)"></div>

IN controller use

$scope.methodName = function(event) { 
    event.stopPropagation();
}

Setting DEBUG = False causes 500 Error

Complementing the main answer
It is annoying to change the ALLOWED_HOSTS and DEBUG global constants in settings.py when switching between development and production. I am using this code to set these setting automatically:

import socket

if socket.gethostname() == "server_name":
    DEBUG = False
    ALLOWED_HOSTS = [".your_domain_name.com",]
    ...
else:
    DEBUG = True
    ALLOWED_HOSTS = ["localhost", "127.0.0.1",]
    ...

If you use macOS you could write a more generic code:

if socket.gethostname().endswith(".local"): # True in your local computer
    DEBUG = True
    ALLOWED_HOSTS = ["localhost", "127.0.0.1",]
else:
    ...

Server is already running in Rails

On Windows Rails 5.2, delete this file

c:/Sites/<your_folder>/tmp/pids/server.pid

and run

rails s

again.

Object not found! The requested URL was not found on this server. localhost

One thing I found out is that your folder holding your php/html files cannot be named the same name as the folder in your HTDOCS carrying your project.

How prevent CPU usage 100% because of worker process in iis

If it is not necessary turn off 'Enable 32-bit Applications' from your respective application pool of your website.

This worked for me on my local machine

Are there any style options for the HTML5 Date picker?

You can use the following CSS to style the input element.

_x000D_
_x000D_
input[type="date"] {_x000D_
  background-color: red;_x000D_
  outline: none;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-clear-button {_x000D_
  font-size: 18px;_x000D_
  height: 30px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-inner-spin-button {_x000D_
  height: 28px;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-calendar-picker-indicator {_x000D_
  font-size: 15px;_x000D_
}
_x000D_
<input type="date" value="From" name="from" placeholder="From" required="" />
_x000D_
_x000D_
_x000D_

IIS_IUSRS and IUSR permissions in IIS8

@EvilDr You can create an IUSR_[identifier] account within your AD environment and let the particular application pool run under that IUSR_[identifier] account:

"Application pool" > "Advanced Settings" > "Identity" > "Custom account"

Set your website to "Applicaton user (pass-through authentication)" and not "Specific user", in the Advanced Settings.

Now give that IUSR_[identifier] the appropriate NTFS permissions on files and folders, for example: modify on companydata.

Table scroll with HTML and CSS

_x000D_
_x000D_
  .outer {_x000D_
    overflow-y: auto;_x000D_
    height: 300px;_x000D_
  }_x000D_
_x000D_
  .outer {_x000D_
    width: 100%;_x000D_
    -layout: fixed;_x000D_
  }_x000D_
_x000D_
  .outer th {_x000D_
    text-align: left;_x000D_
    top: 0;_x000D_
    position: sticky;_x000D_
    background-color: white;_x000D_
  }
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="UTF-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
    <meta http-equiv="X-UA-Compatible" content="ie=edge">_x000D_
    <title>MYCRUD</title>_x000D_
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">_x000D_
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container-fluid col-md-11">_x000D_
  <div class="row">_x000D_
_x000D_
    <div class="col-lg-12">_x000D_
_x000D_
   _x000D_
        <div class="card-body">_x000D_
          <div class="outer">_x000D_
_x000D_
            <table class="table table-hover bg-light">_x000D_
              <thead>_x000D_
                <tr>_x000D_
                  <th scope="col">ID</th>_x000D_
                  <th scope="col">Marca</th>_x000D_
                  <th scope="col">Editar</th>_x000D_
                  <th scope="col">Eliminar</th>_x000D_
                </tr>_x000D_
              </thead>_x000D_
              <tbody>_x000D_
_x000D_
                _x000D_
                  <tr>_x000D_
                    <td>4</td>_x000D_
                    <td>Toyota</td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                                  <tr>_x000D_
                    <td>3</td>_x000D_
                    <td>Honda </td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                                  <tr>_x000D_
                    <td>5</td>_x000D_
                    <td>Myo</td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                                  <tr>_x000D_
                    <td>6</td>_x000D_
                    <td>Acer</td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                                  <tr>_x000D_
                    <td>7</td>_x000D_
                    <td>HP</td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                                  <tr>_x000D_
                    <td>8</td>_x000D_
                    <td>DELL</td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                                  <tr>_x000D_
                    <td>9</td>_x000D_
                    <td>LOGITECH</td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                              </tbody>_x000D_
            </table>_x000D_
          </div>_x000D_
_x000D_
        </div>_x000D_
_x000D_
     _x000D_
_x000D_
_x000D_
_x000D_
_x000D_
    </div>_x000D_
_x000D_
  </div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

how do I give a div a responsive height

I don't think this is the BEST solution, but it does appear to work. Instead of using the background color, I'm going to just embed an image of the background, position it relatively and then wrap the text in a child element and position it absolute - in the centre.

WebSockets protocol vs HTTP

You seem to assume that WebSocket is a replacement for HTTP. It is not. It's an extension.

The main use-case of WebSockets are Javascript applications which run in the web browser and receive real-time data from a server. Games are a good example.

Before WebSockets, the only method for Javascript applications to interact with a server was through XmlHttpRequest. But these have a major disadvantage: The server can't send data unless the client has explicitly requested it.

But the new WebSocket feature allows the server to send data whenever it wants. This allows to implement browser-based games with a much lower latency and without having to use ugly hacks like AJAX long-polling or browser plugins.

So why not use normal HTTP with streamed requests and responses

In a comment to another answer you suggested to just stream the client request and response body asynchronously.

In fact, WebSockets are basically that. An attempt to open a WebSocket connection from the client looks like a HTTP request at first, but a special directive in the header (Upgrade: websocket) tells the server to start communicating in this asynchronous mode. First drafts of the WebSocket protocol weren't much more than that and some handshaking to ensure that the server actually understands that the client wants to communicate asynchronously. But then it was realized that proxy servers would be confused by that, because they are used to the usual request/response model of HTTP. A potential attack scenario against proxy servers was discovered. To prevent this it was necessary to make WebSocket traffic look unlike any normal HTTP traffic. That's why the masking keys were introduced in the final version of the protocol.

Opening Chrome From Command Line

Answering this for Ubuntu users for reference.

Run command google-chrome --app-url "http://localhost/"

Replace your desired URL in the parameter.

You can get more options like incognito mode etc. Run google-chrome --help to see the options.

IFrame: This content cannot be displayed in a frame

Use target="_top" attribute in anchor tag that will really work.

Relative imports for the billionth time

Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

Wrote a little python package to PyPi that might help viewers of this question. The package acts as workaround if one wishes to be able to run python files containing imports containing upper level packages from within a package / project without being directly in the importing file's directory. https://pypi.org/project/import-anywhere/

How to remove a web site from google analytics

You can also do in this way : select your profile then go to admin => in admin second column "Property" select the site you want to remove => go to third column "view settings" clic => on the right bottom you ll see delete the view => confirm and it s done , have a nice day all

Python calling method in class

Let's say you have a shiny Foo class. Well you have 3 options:

1) You want to use the method (or attribute) of a class inside the definition of that class:

class Foo(object):
    attribute1 = 1                   # class attribute (those don't use 'self' in declaration)
    def __init__(self):
        self.attribute2 = 2          # instance attribute (those are accessible via first
                                     # parameter of the method, usually called 'self'
                                     # which will contain nothing but the instance itself)
    def set_attribute3(self, value): 
        self.attribute3 = value

    def sum_1and2(self):
        return self.attribute1 + self.attribute2

2) You want to use the method (or attribute) of a class outside the definition of that class

def get_legendary_attribute1():
    return Foo.attribute1

def get_legendary_attribute2():
    return Foo.attribute2

def get_legendary_attribute1_from(cls):
    return cls.attribute1

get_legendary_attribute1()           # >>> 1
get_legendary_attribute2()           # >>> AttributeError: type object 'Foo' has no attribute 'attribute2'
get_legendary_attribute1_from(Foo)   # >>> 1

3) You want to use the method (or attribute) of an instantiated class:

f = Foo()
f.attribute1                         # >>> 1
f.attribute2                         # >>> 2
f.attribute3                         # >>> AttributeError: 'Foo' object has no attribute 'attribute3'
f.set_attribute3(3)
f.attribute3                         # >>> 3

Composer Warning: openssl extension is missing. How to enable in WAMP

I had the same problem even though openssl was enabled. The issue was that the Composer installer was looking at this config file:

C:\wamp\bin\php\php5.4.3\php.ini

But the config file that's loaded is actually here:

C:\wamp\bin\apache\apache2.2.22\bin\php.ini

So I just had to uncomment it in the first php.ini file and that did the trick. This is how WAMP was installed on my machine by default. I didn't go changing anything, so this will probably happen to others as well. This is basically the same as Augie Gardner's answer above, but I just wanted to point out that you might have two php.ini files.

HTML favicon won't show on google chrome

This trick works: add this script in header or masterPage for Example

    var link = document.createElement('link');
    link.type = 'image/x-icon';
    link.rel = 'shortcut icon';
    link.href = '/favicon.png';

and will be cached. It's not optimal, but it works.

The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'Negotiate,NTLM'

You can eliminate the client from the problem by using wftech, this is an old tool but I have found it useful in diagnosing authentication issues. wfetch allows you to specify NTLM, Negotiate and kerberos, this may well help you better understand your problem. As you are trying to call a service and wfetch knows nothing about WCF, I would suggest applying your endpoint binding (PROVIDERSSoapBinding) to the serviceMetadata then you can do an HTTP GET of the WSDL for the service with the same security settings.

Another option, which may be available to you is to force the server to use NTLM, you can do this by either editing the metabase (IIS 6) and removing the Negotiate setting, more details at http://support.microsoft.com/kb/215383.

If you are using IIS 7.x then the approach is slightly different, details of how to configure the authentication providers are here http://www.iis.net/configreference/system.webserver/security/authentication/windowsauthentication.

I notice that you have blocked out the server address with xxx.xx.xx.xxx, so I'm guessing that this is an IP address rather than a server name, this may cause issues with authentication, so if possible try targeting the machine name.

Sorry that I haven't given you the answer but rather pointers for getting closer to the issue, but I hope it helps.

I'll finish by saying that I have experienced this same issue and my only recourse was to use Kerberos rather than NTLM, don't forget you'll need to register an SPN for the service if you do go down this route.

htaccess Access-Control-Allow-Origin

Try this in the .htaccess of the external root folder :

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

And if it only concerns .js scripts you should wrap the above code inside this:

<FilesMatch "\.(js)$">
...
</FilesMatch>

Fixing slow initial load for IIS

Writing a ping service/script to hit your idle website is rather a best way to go because you will have a complete control. Other options that you have mentioned would be available if you have leased a dedicated hosting box.

In a shared hosting space, warmup scripts are the best first level defense (self help is the best help). Here is an article which shares an idea on how to do it from your own web application.

Leave menu bar fixed on top when scrolled

You can also use css rules:

position: fixed ; and top: 0px ;

on your menu tag.

Principal Component Analysis (PCA) in Python

You can find a PCA function in the matplotlib module:

import numpy as np
from matplotlib.mlab import PCA

data = np.array(np.random.randint(10,size=(10,3)))
results = PCA(data)

results will store the various parameters of the PCA. It is from the mlab part of matplotlib, which is the compatibility layer with the MATLAB syntax

EDIT: on the blog nextgenetics I found a wonderful demonstration of how to perform and display a PCA with the matplotlib mlab module, have fun and check that blog!

Decoding UTF-8 strings in Python

It's an encoding error - so if it's a unicode string, this ought to fix it:

text.encode("windows-1252").decode("utf-8")

If it's a plain string, you'll need an extra step:

text.decode("utf-8").encode("windows-1252").decode("utf-8")

Both of these will give you a unicode string.

By the way - to discover how a piece of text like this has been mangled due to encoding issues, you can use chardet:

>>> import chardet
>>> chardet.detect(u"And the Hip’s coming, too")
{'confidence': 0.5, 'encoding': 'windows-1252'}

Change header text of columns in a GridView

I Think this Works:

 testGV.HeaderRow.Cells[0].Text="Date"

Error - Unable to access the IIS metabase

  1. Create a shortcut to the "devenv.exe"
  2. select the "Run as administrator" option for the shortcut
  3. doble click on the short cut and reopen your project

How to extract a single value from JSON response?

Only suggestion is to access your resp_dict via .get() for a more graceful approach that will degrade well if the data isn't as expected.

resp_dict = json.loads(resp_str)
resp_dict.get('name') # will return None if 'name' doesn't exist

You could also add some logic to test for the key if you want as well.

if 'name' in resp_dict:
    resp_dict['name']
else:
    # do something else here.

Creating a search form in PHP to search a database?

Are you sure, that specified database and table exists? Did you try to look at your database using any database client? For example command-line MySQL client bundled with MySQL server. Or if you a developer newbie, there are dozens of a GUI and web interface clients (HeidiSQL, MySQL Workbench, phpMyAdmin and many more). So first check, if your table creation script was successful and had created what it have to.

BTW why do you have a script for creating the database structure? It's usualy a nonrecurring operation, so write the script to do this is unneeded. It's useful only in case of need of repeatedly creating and manipulating the database structure on the fly.

Exit/save edit to sudoers file? Putty SSH

Be careful to type exactly :wq as Wouter Verleur said at step 7. After type enter, you will save the changes and exit the visudo editor to bash.

Nginx not picking up site in sites-enabled?

Include sites-available/default in sites-enabled/default. It requires only one line.

In sites-enabled/default (new config version?):

It seems that the include path is relative to the file that included it

include sites-available/default;

See the include documentation.


I believe that certain versions of nginx allows including/linking to other files purely by having a single line with the relative path to the included file. (At least that's what it looked like in some "inherited" config files I've been using, until a new nginx version broke them.)

In sites-enabled/default (old config version?):

It seems that the include path is relative to the current file

../sites-available/default

Error TF30063: You are not authorized to access ... \DefaultCollection

Just restarting the visual Studio would do the job. As I did this and it worked like a charm

Executing a shell script from a PHP script

I was struggling with this exact issue for three days. I had set permissions on the script to 755. I had been calling my script as follows.

<?php
   $outcome = shell_exec('/tmp/clearUp.sh');
   echo $outcome;
?>

My script was as follows.

#!bin/bash
find . -maxdepth 1 -name "search*.csv" -mmin +0 -exec rm {} \;

I was getting no output or feedback. The change I made to get the script to run was to add a cd to tmp inside the script:

#!bin/bash
cd /tmp;
find . -maxdepth 1 -name "search*.csv" -mmin +0 -exec rm {} \;

This was more by luck than judgement but it is now working perfectly. I hope this helps.

How to trigger an event after using event.preventDefault()

The accepted solution wont work in case you are working with an anchor tag. In this case you wont be able to click the link again after calling e.preventDefault(). Thats because the click event generated by jQuery is just layer on top of native browser events. So triggering a 'click' event on an anchor tag wont follow the link. Instead you could use a library like jquery-simulate that will allow you to launch native browser events.

More details about this can be found in this link

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

Today not working adjustResize on full screen issue is actual for android sdk.

From answers i found:
the solution - but solution has this showing on picture issue :

Than i found the solution and remove the one unnecessary action:

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

So, see my fixed solution code on Kotlin:

class AndroidBug5497Workaround constructor(val activity: Activity) {

    private val content = activity.findViewById<View>(android.R.id.content) as FrameLayout

    private val mChildOfContent = content.getChildAt(0)
    private var usableHeightPrevious: Int = 0
    private val contentContainer = activity.findViewById(android.R.id.content) as ViewGroup
    private val rootView = contentContainer.getChildAt(0)
    private val rootViewLayout = rootView.layoutParams as FrameLayout.LayoutParams

    private val listener = {
        possiblyResizeChildOfContent()
    }

    fun addListener() {
        mChildOfContent.apply {
            viewTreeObserver.addOnGlobalLayoutListener(listener)

        }
    }

    fun removeListener() {
        mChildOfContent.apply {
            viewTreeObserver.removeOnGlobalLayoutListener(listener)
        }
    }

    private fun possiblyResizeChildOfContent() {
        val contentAreaOfWindowBounds = Rect()
        mChildOfContent.getWindowVisibleDisplayFrame(contentAreaOfWindowBounds)
        val usableHeightNow = contentAreaOfWindowBounds.height()

        if (usableHeightNow != usableHeightPrevious) {
            rootViewLayout.height = usableHeightNow
            rootView.layout(contentAreaOfWindowBounds.left,
                    contentAreaOfWindowBounds.top, contentAreaOfWindowBounds.right, contentAreaOfWindowBounds.bottom);
            mChildOfContent.requestLayout()
            usableHeightPrevious = usableHeightNow
        }
    }
}

My bug fixing implement code:

 class LeaveDetailActivity : BaseActivity(){

    private val keyBoardBugWorkaround by lazy {
        AndroidBug5497Workaround(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

    }

    override fun onResume() {
        keyBoardBugWorkaround.addListener()
        super.onResume()
    }

    override fun onPause() {
        keyBoardBugWorkaround.removeListener()
        super.onPause()
    }
}

How to cancel an $http request in AngularJS?

Cancelation of requests issued with $http is not supported with the current version of AngularJS. There is a pull request opened to add this capability but this PR wasn't reviewed yet so it is not clear if its going to make it into AngularJS core.

How to run Nginx within a Docker container without halting?

It is also good idea to use supervisord or runit[1] for service management.

[1] https://github.com/phusion/baseimage-docker

Detect the Internet connection is offline?

IE 8 will support the window.navigator.onLine property.

But of course that doesn't help with other browsers or operating systems. I predict other browser vendors will decide to provide that property as well given the importance of knowing online/offline status in Ajax applications.

Until that happens, either XHR or an Image() or <img> request can provide something close to the functionality you want.

Update (2014/11/16)

Major browsers now support this property, but your results will vary.

Quote from Mozilla Documentation:

In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking.

In Firefox and Internet Explorer, switching the browser to offline mode sends a false value. All other conditions return a true value.

How to add key,value pair to dictionary?

May be some time this also will be helpful

import collections
#Write you select statement here and other things to fetch the data.
 if rows:
            JArray = []
            for row in rows:

                JArray2 = collections.OrderedDict()
                JArray2["id"]= str(row['id'])
                JArray2["Name"]= row['catagoryname']
                JArray.append(JArray2)

            return json.dumps(JArray)

Example Output:

[
    {
        "id": 14
        "Name": "someName1"
    },
    {
        "id": 15
        "Name": "someName2"
    }
]

Initialize Array of Objects using NSArray

This way you can Create NSArray, NSMutableArray.

NSArray keys =[NSArray arrayWithObjects:@"key1",@"key2",@"key3",nil];

NSArray objects =[NSArray arrayWithObjects:@"value1",@"value2",@"value3",nil];

How to switch to another domain and get-aduser

I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server argument.

$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite

Get-ADUser -Server $dc.HostName[0] `
    -Filter { EmailAddress -Like "*Smith_Karla*" } `
    -Properties EmailAddress

How to change or add theme to Android Studio?

On Windows: File-> Settings-> Appearance&Behavior-> Appearance: Change "Theme field".

Retrieve all values from HashMap keys in an ArrayList Java

Java 8 solution for produce string like "key1: value1,key2: value2"

private static String hashMapToString(HashMap<String, String> hashMap) {

    return hashMap.keySet().stream()
            .map((key) -> key + ": " + hashMap.get(key))
            .collect(Collectors.joining(","));

}

and produce a list simple collect as list

private static List<String> hashMapToList(HashMap<String, String> hashMap) {

    return hashMap.keySet().stream()
            .map((key) -> key + ": " + hashMap.get(key))
            .collect(Collectors.toList());

}

JSON - Iterate through JSONArray

JsonArray jsonArray;
Iterator<JsonElement> it = jsonArray.iterator();
while(it.hasNext()){
    System.out.println(it.next());
}

Convert normal Java Array or ArrayList to Json Array in android

you need external library

 json-lib-2.2.2-jdk15.jar

List mybeanList = new ArrayList();
mybeanList.add("S");
mybeanList.add("b");

JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);

Google Gson is the best library http://code.google.com/p/google-gson/

How to find difference between two columns data?

select previous, Present, previous-Present as Difference from tablename

or

select previous, Present, previous-Present as Difference from #TEMP1

RecyclerView: Inconsistency detected. Invalid item position

I have same issue .It was occur when I was scrolling fast and calling API and updating data.After trying all things to prevent crash , I found solution.

mRecyclerView.stopScroll();

It will work.

Add ripple effect to my button with button background color?

Now we need to create a drawable resource file and name it ripple_effect as shown below

ripple_effect.xml

<?xml version="1.0" encoding="utf-8"?>

<ripple

    xmlns:android="http://schemas.android.com/apk/res/android"

    android:color="@color/colorRipple">     <!-- ripple color -->

    <!-- for Button -->

    <item>

        <shape android:shape="rectangle">

            <corners android:radius="3dp" />

            <solid android:color="@color/colorPrimary"/>

        </shape>

    </item>

</ripple>

Source Full: https://code-android-example.blogspot.com/2020/11/ripple-effect-in-android-for-button.html

Unable to load script from assets index.android.bundle on windows

Ubuntu

first time, I created new app with react-native init project-name. I got the same error. so i do the following steps to resolve this in my case.

  1. Firstly run sudo chown user-name-of-pc /dev/kvm in my case.
  2. While debugging from your Android phone, select Use USB to Transfer photos (PTP).

  3. Create Folder assets in project-name/android/app/src/main

  4. make sure index.js be avaiable into your project root directory and then run below command from console after cd project-name directory.

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

or for index.android.js then

react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

  1. run command ./studio.sh in android-studio/bin directory. It will opens up Android Studio.

  2. run command react-native run-android.

enter image description here

Count textarea characters

_x000D_
_x000D_
var maxchar = 10;_x000D_
$('#message').after('<span id="count" class="counter"></span>');_x000D_
$('#count').html(maxchar+' of '+maxchar);_x000D_
$('#message').attr('maxlength', maxchar);_x000D_
$('#message').parent().addClass('wrap-text');_x000D_
$('#message').on("keydown", function(e){_x000D_
 var len =  $('#message').val().length;_x000D_
 if (len >= maxchar && e.keyCode != 8)_x000D_
     e.preventDefault();_x000D_
 else if(len <= maxchar && e.keyCode == 8){_x000D_
  if(len <= maxchar && len != 0)_x000D_
      $('#count').html(maxchar+' of '+(maxchar - len +1));_x000D_
     else if(len == 0)_x000D_
      $('#count').html(maxchar+' of '+(maxchar - len));_x000D_
 }else_x000D_
   $('#count').html(maxchar+' of '+(maxchar - len-1)); _x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea id="message" name="text"></textarea>
_x000D_
_x000D_
_x000D_

How to Join to first row

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

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

accepting HTTPS connections with self-signed certificates

The top answer didn´t work for me. After some investigation I found the required information on "Android Developer": https://developer.android.com/training/articles/security-ssl.html#SelfSigned

Creating an empty implementation of X509TrustManager did the trick:

private static class MyTrustManager implements X509TrustManager
{

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType)
         throws CertificateException
    {
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType)
        throws CertificateException
    {
    }

    @Override
    public X509Certificate[] getAcceptedIssuers()
    {
        return null;
    }

}

...

HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
try
{
    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance("TLS");
    TrustManager[] tmlist = {new MyTrustManager()};
    context.init(null, tmlist, null);
    conn.setSSLSocketFactory(context.getSocketFactory());
}
catch (NoSuchAlgorithmException e)
{
    throw new IOException(e);
} catch (KeyManagementException e)
{
    throw new IOException(e);
}
conn.setRequestMethod("GET");
int rcode = conn.getResponseCode();

Please be aware that this empty implementation of TustManager is just an example and using it in a productive environment would cause a severe security threat!

How to perform a for loop on each character in a string in Bash?

The C style loop in @chepner's answer is in the shell function update_terminal_cwd, and the grep -o . solution is clever, but I was surprised not to see a solution using seq. Here's mine:

read word
for i in $(seq 1 ${#word}); do
  echo "${word:i-1:1}"
done

is there something like isset of php in javascript/jQuery?

The problem is that passing an undefined variable to a function causes an error.

This means you have to run typeof before passing it as an argument.

The cleanest way I found to do this is like so:

function isset(v){
    if(v === 'undefined'){
        return false;
    }
    return true;
}

Usage:

if(isset(typeof(varname))){
  alert('is set');
} else {
  alert('not set');
}

Now the code is much more compact and readable.

This will still give an error if you try to call a variable from a non instantiated variable like:

isset(typeof(undefVar.subkey))

thus before trying to run this you need to make sure the object is defined:

undefVar = isset(typeof(undefVar))?undefVar:{};

How to use numpy.genfromtxt when first column is string and the remaining columns are numbers?

data=np.genfromtxt(csv_file, delimiter=',', dtype='unicode')

It works fine for me.

Getting an option text/value with JavaScript

var option_user_selection = document.getElementById("maincourse").options[document.getElementById("maincourse").selectedIndex ].text

ArrayList initialization equivalent to array initialization

How about this one.

ArrayList<String> names = new ArrayList<String>();
Collections.addAll(names, "Ryan", "Julie", "Bob");

parent & child with position fixed, parent overflow:hidden bug

As an alternative to using clip you could also use {border-radius: 0.0001px} on a parent element. It works not only with absolute/fixed positioned elements.

Vertical divider doesn't work in Bootstrap 3

I find using the pipe character with some top and bottom padding works well. Using a div with a border will require more CSS to vertically align it and get the horizontal spacing even with the other elements.

CSS

.divider-vertical {
    padding-top: 14px;
    padding-bottom: 14px;
}

HTML

<ul class="nav navbar-nav">
    <li class="active"><a href="#">Home</a></li>
    <li class="divider-vertical">&#124;</li>
    <li><a href="#">Faq</a></li>
    <li class="divider-vertical">&#124;</li>
    <li><a href="#">News</a></li>
    <li class="divider-vertical">&#124;</li>
    <li><a href="#">Contact</a></li>
</ul>

Change the On/Off text of a toggle button Android

Yes you can change the on / off button

    android:textOn="Light ON"
    android:textOff="Light OFF"

Refer for more

http://androidcoding.in/2016/09/11/android-tutorial-toggle-button

Append a Lists Contents to another List C#

GlobalStrings.AddRange(localStrings);

Note: You cannot declare the list object using the interface (IList).
Documentation: List<T>.AddRange(IEnumerable<T>).

Read from a gzip file in python

Try gzipping some data through the gzip libary like this...

import gzip
content = "Lots of content here"
f = gzip.open('Onlyfinnaly.log.gz', 'wb')
f.write(content)
f.close()

... then run your code as posted ...

import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content

This method worked for me as for some reason the gzip library fails to read some files.

makefile:4: *** missing separator. Stop

Its pretty old question but still I would like say about one more option using vi/vim editor to visualize the tabs. If you have vi/vim installed then open a Makefile (e.g. vim Makefile) and enter :set list. This will show number of tabs inserted as below,

 %-linux: force$
^I@if [ "$(GCC_VERSION)" = "2.96" ] ; then \$
^I^Iecho ===== Generating build tree for legacy $@ architecture =====; \$
^I^I$(CONFIGURE) $(CWD) $@ legacy; \$
^Ielse \$
^I^Iecho ===== Generating build tree for $@ architecture =====; \$
^I^I$(CONFIGURE) $(CWD) $@; \$
^Ifi$
^Icd build-$@;make$

Cannot use special principal dbo: Error 15405

This answer doesn't help for SQL databases where SharePoint is connected. db_securityadmin is required for the configuration databases. In order to add db_securityadmin, you will need to change the owner of the database to an administrative account. You can use that account just for dbo roles.

Printing with sed or awk a line following a matching pattern

Actually sed -n '/pattern/{n;p}' filename will fail if the pattern match continuous lines:

$ seq 15 |sed -n '/1/{n;p}'
2
11
13
15

The expected answers should be:

2
11
12
13
14
15

My solution is:

$ sed -n -r 'x;/_/{x;p;x};x;/pattern/!s/.*//;/pattern/s/.*/_/;h' filename

For example:

$ seq 15 |sed -n -r 'x;/_/{x;p;x};x;/1/!s/.*//;/1/s/.*/_/;h'
2
11
12
13
14
15

Explains:

  1. x;: at the beginning of each line from input, use x command to exchange the contents in pattern space & hold space.
  2. /_/{x;p;x};: if pattern space, which is the hold space actually, contains _ (this is just a indicator indicating if last line matched the pattern or not), then use x to exchange the actual content of current line to pattern space, use p to print current line, and x to recover this operation.
  3. x: recover the contents in pattern space and hold space.
  4. /pattern/!s/.*//: if current line does NOT match pattern, which means we should NOT print the NEXT following line, then use s/.*// command to delete all contents in pattern space.
  5. /pattern/s/.*/_/: if current line matches pattern, which means we should print the NEXT following line, then we need to set a indicator to tell sed to print NEXT line, so use s/.*/_/ to substitute all contents in pattern space to a _(the second command will use it to judge if last line matched the pattern or not).
  6. h: overwrite the hold space with the contents in pattern space; then, the content in hold space is ^_$ which means current line matches the pattern, or ^$, which means current line does NOT match the pattern.
  7. the fifth step and sixth step can NOT exchange, because after s/.*/_/, the pattern space can NOT match /pattern/, so the s/.*// MUST be executed!

Declare global variables in Visual Studio 2010 and VB.NET

Pretty much the same way that you always have, with "Modules" instead of classes and just use "Public" instead of the old "Global" keyword:

Public Module Module1
    Public Foo As Integer
End Module

Adding class to element using Angular JS

AngularJS has some methods called JQlite so we can use it. see link

Select the element in DOM is

angular.element( document.querySelector( '#div1' ) );

add the class like .addClass('alpha');

So finally

var myEl = angular.element( document.querySelector( '#div1' ) );
myEl.addClass('alpha');

How can I change the value of the elements in a vector?

Well, you could always run a transform over the vector:

std::transform(v.begin(), v.end(), v.begin(), [mean](int i) -> int { return i - mean; });

You could always also devise an iterator adapter that returns the result of an operation applied to the dereference of its component iterator when it's dereferenced. Then you could just copy the vector to the output stream:

std::copy(adapter(v.begin(), [mean](int i) -> { return i - mean; }), v.end(), std::ostream_iterator<int>(cout, "\n"));

Or, you could use a for loop...but that's kind of boring.

ssh script returns 255 error

This error will also occur when using pdsh to hosts which are not contained in your "known_hosts" file.

I was able to correct this by SSH'ing into each host manually and accepting the question "Do you want to add this to known hosts".

How to present popover properly in iOS 8

In iOS9 UIPopoverController is depreciated. So can use the below code for Objective-C version above iOS9.x,

- (IBAction)onclickPopover:(id)sender {
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
UIViewController *viewController = [sb instantiateViewControllerWithIdentifier:@"popover"];

viewController.modalPresentationStyle = UIModalPresentationPopover;
viewController.popoverPresentationController.sourceView = self.popOverBtn;
viewController.popoverPresentationController.sourceRect = self.popOverBtn.bounds;
viewController.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionAny;
[self presentViewController:viewController animated:YES completion:nil]; }

PHP Check for NULL

I think you want to use

mysql_fetch_assoc($query)

rather than

mysql_fetch_row($query)

The latter returns an normal array index by integers, whereas the former returns an associative array, index by the field names.

Div with horizontal scrolling only

I couldn't get the selected answer to work but after a bit of research, I found that the horizontal scrolling div must have white-space: nowrap in the css.

Here's complete working code:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Something</title>
    <style type="text/css">
        #scrolly{
            width: 1000px;
            height: 190px;
            overflow: auto;
            overflow-y: hidden;
            margin: 0 auto;
            white-space: nowrap
        }

        img{
            width: 300px;
            height: 150px;
            margin: 20px 10px;
            display: inline;
        }
    </style>
</head>
<body>
    <div id='scrolly'>
        <img src='img/car.jpg'></img>
        <img src='img/car.jpg'></img>
        <img src='img/car.jpg'></img>
        <img src='img/car.jpg'></img>
        <img src='img/car.jpg'></img>
        <img src='img/car.jpg'></img>
    </div>
</body>
</html>

C# Example of AES256 encryption using System.Security.Cryptography.Aes

Once I'd discovered all the information of how my client was handling the encryption/decryption at their end it was straight forward using the AesManaged example suggested by dtb.

The finally implemented code started like this:

    try
    {
        // Create a new instance of the AesManaged class.  This generates a new key and initialization vector (IV).
        AesManaged myAes = new AesManaged();

        // Override the cipher mode, key and IV
        myAes.Mode = CipherMode.ECB;
        myAes.IV = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // CRB mode uses an empty IV
        myAes.Key = CipherKey;  // Byte array representing the key
        myAes.Padding = PaddingMode.None;

        // Create a encryption object to perform the stream transform.
        ICryptoTransform encryptor = myAes.CreateEncryptor();

        // TODO: perform the encryption / decryption as required...

    }
    catch (Exception ex)
    {
        // TODO: Log the error 
        throw ex;
    }

How do you wait for input on the same Console.WriteLine() line?

As Matt has said, use Console.Write. I would also recommend explicitly flushing the output, however - I believe WriteLine does this automatically, but I'd seen oddities when just using Console.Write and then waiting. So Matt's code becomes:

Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();

What is the difference between explicit and implicit cursors in Oracle?

In PL/SQL, A cursor is a pointer to this context area. It contains all the information needed for processing the statement.

Implicit Cursors: Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the information in it.

Explicit Cursors: Explicit cursors are programmer-defined cursors for gaining more control over the context area. An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns more than one row.

The syntax for creating an explicit cursor is:

CURSOR cursor_name IS select_statement; 

What is the difference between hg forget and hg remove?

A file can be tracked or not, you use hg add to track a file and hg remove or hg forget to un-track it. Using hg remove without flags will both delete the file and un-track it, hg forget will simply un-track it without deleting it.

Delete last N characters from field in a SQL Server database

UPDATE mytable SET column=LEFT(column, LEN(column)-5)

Removes the last 5 characters from the column (every row in mytable)

Return array in a function

and what about:

int (*func())
{
    int *f = new int[10] {1,2,3};

    return f;
}

int fa[10] = { 0 };
auto func2() -> int (*) [10]
{
    return &fa;
}

SQL permissions for roles

USE DataBaseName; GO --------- CREATE ROLE --------- CREATE ROLE Doctors ; GO  ---- Assign Role To users -------  CREATE USER [Username] FOR LOGIN [Domain\Username] EXEC sp_addrolemember N'Doctors', N'Username'  ----- GRANT Permission to Users Assinged with this Role----- GRANT ALL ON Table1, Table2, Table3 TO Doctors; GO 

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

What about this?

java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf("2007-09-23 10:10:10.0");

Run a shell script with an html button

PHP is likely the easiest.

Just make a file script.php that contains <?php shell_exec("yourscript.sh"); ?> and send anybody who clicks the button to that destination. You can return the user to the original page with header:

<?php
shell_exec("yourscript.sh");
header('Location: http://www.website.com/page?success=true');
?>

Reference: http://php.net/manual/en/function.shell-exec.php

Switch role after connecting to database

--create a user that you want to use the database as:

create role neil;

--create the user for the web server to connect as:

create role webgui noinherit login password 's3cr3t';

--let webgui set role to neil:

grant neil to webgui; --this looks backwards but is correct.

webgui is now in the neil group, so webgui can call set role neil . However, webgui did not inherit neil's permissions.

Later, login as webgui:

psql -d some_database -U webgui
(enter s3cr3t as password)

set role neil;

webgui does not need superuser permission for this.

You want to set role at the beginning of a database session and reset it at the end of the session. In a web app, this corresponds to getting a connection from your database connection pool and releasing it, respectively. Here's an example using Tomcat's connection pool and Spring Security:

public class SetRoleJdbcInterceptor extends JdbcInterceptor {

    @Override
    public void reset(ConnectionPool connectionPool, PooledConnection pooledConnection) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if(authentication != null) {
            try {

                /* 
                  use OWASP's ESAPI to encode the username to avoid SQL Injection. Can't use parameters with SET ROLE. Need to write PG codec.

                  Or use a whitelist-map approach
                */
                String username = ESAPI.encoder().encodeForSQL(MY_CODEC, authentication.getName());

                Statement statement = pooledConnection.getConnection().createStatement();
                statement.execute("set role \"" + username + "\"");
                statement.close();
            } catch(SQLException exp){
                throw new RuntimeException(exp);
            }
        }
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        if("close".equals(method.getName())){
            Statement statement = ((Connection)proxy).createStatement();
            statement.execute("reset role");
            statement.close();
        }

        return super.invoke(proxy, method, args);
    }
}

Can I set the cookies to be used by a WKWebView?

If anyone is using Alamofire, then this is better solution.

  let cookies = Alamofire.SessionManager.default.session.configuration.httpCookieStorage?.cookies(for: URL(string: BASE_URL)!)
  for (cookie) in cookies ?? [] {
      webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie)
  }

How can I use grep to find a word inside a folder?

GREP: Global Regular Expression Print/Parser/Processor/Program.
You can use this to search the current directory.
You can specify -R for "recursive", which means the program searches in all subfolders, and their subfolders, and their subfolder's subfolders, etc.

grep -R "your word" .

-n will print the line number, where it matched in the file.
-i will search case-insensitive (capital/non-capital letters).

grep -inR "your regex pattern" .

Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

Starting from Framework v4.5 you can use Activator.CreateInstanceFrom() to easily instantiate classes within assemblies. The following example shows how to use it and how to call a method passing parameters and getting return value.

    // Assuming moduleFileName contains full or valid relative path to assembly    
    var moduleInstance = Activator.CreateInstanceFrom(moduleFileName, "MyNamespace.MyClass");
    MethodInfo mi = moduleInstance.Unwrap().GetType().GetMethod("MyMethod");
    // Assuming the method returns a boolean and accepts a single string parameter
    bool rc = Convert.ToBoolean(mi.Invoke(moduleInstance.Unwrap(), new object[] { "MyParamValue" } ));

How to search a string in multiple files and return the names of files in Powershell?

This should give the location of the files that contain your pattern:

Get-ChildItem -Recurse | Select-String "dummy" -List | Select Path

git stash and git pull

When you have changes on your working copy, from command line do:

git stash 

This will stash your changes and clear your status report

git pull

This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge

git stash pop

This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.

if you need to see what is in your stash

git stash list

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

You must use newCachedThreadPool only when you have short-lived asynchronous tasks as stated in Javadoc, if you submit tasks which takes longer time to process, you will end up creating too many threads. You may hit 100% CPU if you submit long running tasks at faster rate to newCachedThreadPool (http://rashcoder.com/be-careful-while-using-executors-newcachedthreadpool/).

iOS9 getting error “an SSL error has occurred and a secure connection to the server cannot be made”

I get the same error when I specify my HTTPS URL as : https://www.mywebsite.com . However it works fine when I specify it without the three W's as : https://mywebsite.com .

Render HTML string as real HTML in a React component

dangerouslySetInnerHTML

dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous. For example:

function createMarkup() {
  return {__html: 'First &middot; Second'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

How to read from input until newline is found using scanf()?

use getchar and a while that look like this

while(x = getchar())
{   
    if(x == '\n'||x == '\0')
       do what you need when space or return is detected
    else
        mystring.append(x)
}

Sorry if I wrote a pseudo-code but I don't work with C language from a while.

Find duplicate lines in a file and count how many time each line was duplicated?

Assuming there is one number per line:

sort <file> | uniq -c

You can use the more verbose --count flag too with the GNU version, e.g., on Linux:

sort <file> | uniq --count

Any way to make a WPF textblock selectable?

Create ControlTemplate for the TextBlock and put a TextBox inside with readonly property set. Or just use TextBox and make it readonly, then you can change the TextBox.Style to make it looks like TextBlock.

generate model using user:references vs user_id:integer

Both will generate the same columns when you run the migration. In rails console, you can see that this is the case:

:001 > Micropost
=> Micropost(id: integer, user_id: integer, created_at: datetime, updated_at: datetime)

The second command adds a belongs_to :user relationship in your Micropost model whereas the first does not. When this relationship is specified, ActiveRecord will assume that the foreign key is kept in the user_id column and it will use a model named User to instantiate the specific user.

The second command also adds an index on the new user_id column.

Get a list of dates between two dates using a function

WITH TEMP (DIA, SIGUIENTE_DIA ) AS
           (SELECT 
               1, 
               CAST(@FECHAINI AS DATE)
            FROM 
               DUAL
           UNION ALL
            SELECT 
               DIA, 
               DATEADD(DAY, DIA, SIGUIENTE_DIA)
            FROM 
               TEMP
            WHERE
               DIA < DATEDIFF(DAY,  @FECHAINI, @FECHAFIN)   
               AND DATEADD(DAY, 1, SIGUIENTE_DIA) <=  CAST(@FECHAFIN AS DATE)
           )
           SELECT 
              SIGUIENTE_DIA AS CALENDARIO 
           FROM
              TEMP
           ORDER BY   
              SIGUIENTE_DIA

The detail is on the table DUAL but if your exchange this table for a dummy table this works.

Doctrine 2 ArrayCollection filter method

The Boris Guéry answer's at this post, may help you: Doctrine 2, query inside entities

$idsToFilter = array(1,2,3,4);

$member->getComments()->filter(
    function($entry) use ($idsToFilter) {
       return in_array($entry->getId(), $idsToFilter);
    }
); 

How to add images to README.md on GitHub?

  • You can create a New Issue
  • upload(drag & drop) images to it
  • Copy the images URL and paste it into your README.md file.

here is a detailed youTube video explained this in detail:

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

How do I start a process from C#?

Just as Matt says, use Process.Start.

You can pass a URL, or a document. They will be started by the registered application.

Example:

Process.Start("Test.Txt");

This will start Notepad.exe with Text.Txt loaded.

Delete empty lines using sed

With help from the accepted answer here and the accepted answer above, I have used:

$ sed 's/^ *//; s/ *$//; /^$/d; /^\s*$/d' file.txt > output.txt

`s/^ *//`  => left trim
`s/ *$//`  => right trim
`/^$/d`    => remove empty line
`/^\s*$/d` => delete lines which may contain white space

This covers all the bases and works perfectly for my needs. Kudos to the original posters @Kent and @kev

Change the row color in DataGridView based on the quantity of a cell value

I fixed my error. just removed "Value" from this line:

If drv.Item("Quantity").Value < 5  Then

So it will look like

If drv.Item("Quantity") < 5 Then

Using Excel VBA to export data to MS Access table

@Ahmed

Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".

Sub test()
    dbWb = Application.ActiveWorkbook.FullName
    dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2"  'Data2 is a named range


sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh

Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command

dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon

dbCommand.CommandText = sCommand
dbCommand.Execute

dbCon.Close


End Sub

How to adjust gutter in Bootstrap 3 grid system?

To define a 3 column grid you could use the customizer or download the source set your less variables and recompile.

To learn more about the grid and the columns / gutter widths, please also read:

In you case with a container of 960px consider the medium grid (see also: http://getbootstrap.com/css/#grid). This grid will have a max container width of 970px. When setting @grid-columns:3; and setting @grid-gutter-width:15px; in variables.less you will get:

15px | 1st column (298.33) | 15px | 2nd column (298.33) |15px | 3th column (298.33) | 15px

HTTP Basic: Access denied fatal: Authentication failed

Open CMD (Run as administrator) type command:

git config --system --unset credential.helper

then enter new password for Git remote server.

How to convert string to char array in C++?

Simplest way I can think of doing it is:

string temp = "cat";
char tab2[1024];
strcpy(tab2, temp.c_str());

For safety, you might prefer:

string temp = "cat";
char tab2[1024];
strncpy(tab2, temp.c_str(), sizeof(tab2));
tab2[sizeof(tab2) - 1] = 0;

or could be in this fashion:

string temp = "cat";
char * tab2 = new char [temp.length()+1];
strcpy (tab2, temp.c_str());

Convert pem key to ssh-rsa format

ssh-keygen -f private.pem -y > public.pub

VMWare Player vs VMWare Workstation

VMWare Player can be seen as a free, closed-source competitor to Virtualbox.

Initially VMWare Player (up to version 2.5) was intended to operate on fixed virtual operating systems (e.g. play back pre-created virtual disks).

Many advanced features such as vsphere are probably not required by most users, and VMWare Player will provide the same core technologies and 3D acceleration as the ESX Workstation solution.

From my experience VMWare Player 5 is faster than Virtualbox 4.2 RC3 and has better SMP performance. Both are great however, each with its own unique advantages. Both are somewhat lacking in 2D rendering performance.

See the official FAQ, and a feature comparison table.

What are the differences between using the terminal on a mac vs linux?

@Michael Durrant's answer ably covers the shell itself, but the shell environment also includes the various commands you use in the shell and these are going to be similar -- but not identical -- between OS X and linux. In general, both will have the same core commands and features (especially those defined in the Posix standard), but a lot of extensions will be different.

For example, linux systems generally have a useradd command to create new users, but OS X doesn't. On OS X, you generally use the GUI to create users; if you need to create them from the command line, you use dscl (which linux doesn't have) to edit the user database (see here). (Update: starting in macOS High Sierra v10.13, you can use sysadminctl -addUser instead.)

Also, some commands they have in common will have different features and options. For example, linuxes generally include GNU sed, which uses the -r option to invoke extended regular expressions; on OS X, you'd use the -E option to get the same effect. Similarly, in linux you might use ls --color=auto to get colorized output; on macOS, the closest equivalent is ls -G.

EDIT: Another difference is that many linux commands allow options to be specified after their arguments (e.g. ls file1 file2 -l), while most OS X commands require options to come strictly first (ls -l file1 file2).

Finally, since the OS itself is different, some commands wind up behaving differently between the OSes. For example, on linux you'd probably use ifconfig to change your network configuration. On OS X, ifconfig will work (probably with slightly different syntax), but your changes are likely to be overwritten randomly by the system configuration daemon; instead you should edit the network preferences with networksetup, and then let the config daemon apply them to the live network state.

python 3.x ImportError: No module named 'cStringIO'

I had the same issue because my file was called email.py. I renamed the file and the issue disappeared.

Masking password input from the console : Java

Console console = System.console();
String username = console.readLine("Username: ");
char[] password = console.readPassword("Password: ");

Displaying output of a remote command with Ansible

If you pass the -v flag to the ansible-playbook command, then ansible will show the output on your terminal.

For your use case, you may want to try using the fetch module to copy the public key from the server to your local machine. That way, it will only show a "changed" status when the file changes.

Search a text file and print related lines in Python?

Note the potential for an out-of-range index with "i+3". You could do something like:

with open("file.txt", "r") as f:
    searchlines = f.readlines()
j=len(searchlines)-1
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        k=min(i+3,j)
        for l in searchlines[i:k]: print l,
        print

Edit: maybe not necessary. I just tested some examples. x[y] will give errors if y is out of range, but x[y:z] doesn't seem to give errors for out of range values of y and z.

ssh connection refused on Raspberry Pi

Apparently, the SSH server on Raspbian is now disabled by default. If there is no server listening for connections, it will not accept them. You can manually enable the SSH server according to this raspberrypi.org tutorial :

As of the November 2016 release, Raspbian has the SSH server disabled by default.

There are now multiple ways to enable it. Choose one:

From the desktop

  1. Launch Raspberry Pi Configuration from the Preferences menu
  2. Navigate to the Interfaces tab
  3. Select Enabled next to SSH
  4. Click OK

From the terminal with raspi-config

  1. Enter sudo raspi-config in a terminal window
  2. Select Interfacing Options
  3. Navigate to and select SSH
  4. Choose Yes
  5. Select Ok
  6. Choose Finish

Start the SSH service with systemctl

sudo systemctl enable ssh
sudo systemctl start ssh

On a headless Raspberry Pi

For headless setup, SSH can be enabled by placing a file named ssh, without any extension, onto the boot partition of the SD card. When the Pi boots, it looks for the ssh file. If it is found, SSH is enabled, and the file is deleted. The content of the file does not matter: it could contain text, or nothing at all.

Find which rows have different values for a given column in Teradata SQL

Personally, I would print them to a file using Perl or Python in the format

<COL_NAME>:  <COL_VAL>

for each row so that the file has as many lines as there are columns. Then I'd do a diff between the two files, assuming you are on Unix or compare them using some equivalent utilty on another OS. If you have multiple recordsets (i.e. more than one row), I would prepend to each file row and then the file would have NUM_DB_ROWS * NUM_COLS lines

Redirect from asp.net web api post action

Here is another way you can get to the root of your website without hard coding the url:

var response = Request.CreateResponse(HttpStatusCode.Moved);
string fullyQualifiedUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);
response.Headers.Location = new Uri(fullyQualifiedUrl);

Note: Will only work if both your MVC website and WebApi are on the same URL

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

AngularJS: Insert HTML from a string

Have a look at the example in this link :

http://docs.angularjs.org/api/ngSanitize.$sanitize

Basically, angular has a directive to insert html into pages. In your case you can insert the html using the ng-bind-html directive like so :

If you already have done all this :

// My magic HTML string function.
function htmlString (str) {
    return "<h1>" + str + "</h1>";
}

function Ctrl ($scope) {
  var str = "HELLO!";
  $scope.htmlString = htmlString(str);
}
Ctrl.$inject = ["$scope"];

Then in your html within the scope of that controller, you could

<div ng-bind-html="htmlString"></div>

Nested iframes, AKA Iframe Inception

I think the best way to reach your div:

var your_element=$('iframe#uploads').children('iframe').children('div#element');

It should work well.

When do I need to use Begin / End Blocks and the Go keyword in SQL Server?

GO isn't a keyword in SQL Server; it's a batch separator. GO ends a batch of statements. This is especially useful when you are using something like SQLCMD. Imagine you are entering in SQL statements on the command line. You don't necessarily want the thing to execute every time you end a statement, so SQL Server does nothing until you enter "GO".

Likewise, before your batch starts, you often need to have some objects visible. For example, let's say you are creating a database and then querying it. You can't write:

CREATE DATABASE foo;
USE foo;
CREATE TABLE bar;

because foo does not exist for the batch which does the CREATE TABLE. You'd need to do this:

CREATE DATABASE foo;
GO
USE foo;
CREATE TABLE bar;

How to use Spring Boot with MySQL database and JPA?

You can move Application.java to a folder under the java.

Android Studio - How to Change Android SDK Path

Here's how you can change the android sdk path in Android studio:

  1. Open your required android project in Android studio
  2. Click on the main project folder and press F4
  3. Now click on "SDKs" under Platform Settings (Left hand side of the dialog box)
  4. You should now see a plus sign on the top, click it and choose "Android SDK"
  5. Now you would be asked to choose the required SDK folder
  6. Select the required build target(if necessary) and click "ok"
  7. Now you should see the new entry in the list of SDKs
  8. Click "Modules" under Project Settings
  9. Select your project folder and in the Dropdown for "Module SDK", select the new SDK entry and click "apply"
  10. Now click "OK" and your done.

Note: If changes do not take effect, restarting android studio should fix the problem.

Last Run Date on a Stored Procedure in SQL Server

The below code should do the trick (>= 2008)

SELECT o.name, 
       ps.last_execution_time 
FROM   sys.dm_exec_procedure_stats ps 
INNER JOIN 
       sys.objects o 
       ON ps.object_id = o.object_id 
WHERE  DB_NAME(ps.database_id) = '' 
ORDER  BY 
       ps.last_execution_time DESC  

Edit 1 : Please take note of Jeff Modens advice below. If you find a procedure here, you can be sure that it is accurate. If you do not then you just don't know - you cannot conclude it is not running.

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

I see this isn't answered yet, this is an exact quote from here:

WSHttpBinding will try and perform an internal negotiate at the SSP layer. In order for this to be successful, you will need to allow anonymous in IIS for the VDir. WCF will then by default perfrom an SPNEGO for window credentials. Allowing anonymous at IIS layer is not allowing anyone in, it is deferring to the WCF stack.

I found this via: http://fczaja.blogspot.com/2009/10/http-request-is-unauthorized-with.html

After googling: http://www.google.tt/#hl=en&source=hp&q=+The+HTTP+request+is+unauthorized+with+client+authentication+scheme+%27Anonymous

How can I disable all views inside the layout?

Let's change tütü's code

private void disableEnableControls(boolean enable, ViewGroup vg){
for (int i = 0; i < vg.getChildCount(); i++){
   View child = vg.getChildAt(i);
   if (child instanceof ViewGroup){ 
      disableEnableControls(enable, (ViewGroup)child);
   } else {
     child.setEnabled(enable);
   }
 }
}

I think, there is no point in just making viewgroup disable. If you want to do it, there is another way I have used for exactly the same purpose. Create view as a sibling of your groupview :

<View
    android:visibility="gone"
    android:id="@+id/reservation_second_screen"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="bottom"
    android:background="#66ffffff"
    android:clickable="false" />

and at run-time, make it visible. Note: your groupview's parent layout should be either relative or frame layout. Hope this will help.

How to program a fractal?

The mandelbrot set is generated by repeatedly evaluating a function until it overflows (some defined limit), then checking how long it took you to overflow.

Pseudocode:

MAX_COUNT = 64 // if we haven't escaped to infinity after 64 iterations, 
               // then we're inside the mandelbrot set!!!

foreach (x-pixel)
  foreach (y-pixel)
    calculate x,y as mathematical coordinates from your pixel coordinates
    value = (x, y)
    count = 0
    while value.absolutevalue < 1 billion and count < MAX_COUNT
        value = value * value + (x, y)
        count = count + 1

    // the following should really be one statement, but I split it for clarity
    if count == MAX_COUNT 
        pixel_at (x-pixel, y-pixel) = BLACK
    else 
        pixel_at (x-pixel, y-pixel) = colors[count] // some color map. 

Notes:

value is a complex number. a complex number (a+bi) is squared to give (aa-b*b+2*abi). You'll have to use a complex type, or include that calculation in your loop.

How to dynamically add elements to String array?

Arrays in Java have a defined size, you cannot change it later by adding or removing elements (you can read some basics here).

Instead, use a List:

ArrayList<String> mylist = new ArrayList<String>();
mylist.add(mystring); //this adds an element to the list.

Of course, if you know beforehand how many strings you are going to put in your array, you can create an array of that size and set the elements by using the correct position:

String[] myarray = new String[numberofstrings];
myarray[23] = string24; //this sets the 24'th (first index is 0) element to string24.

sklearn plot confusion matrix with labels

UPDATE:

In scikit-learn 0.22, there's a new feature to plot the confusion matrix directly.

See the documentation: sklearn.metrics.plot_confusion_matrix


OLD ANSWER:

I think it's worth mentioning the use of seaborn.heatmap here.

import seaborn as sns
import matplotlib.pyplot as plt     

ax= plt.subplot()
sns.heatmap(cm, annot=True, ax = ax); #annot=True to annotate cells

# labels, title and ticks
ax.set_xlabel('Predicted labels');ax.set_ylabel('True labels'); 
ax.set_title('Confusion Matrix'); 
ax.xaxis.set_ticklabels(['business', 'health']); ax.yaxis.set_ticklabels(['health', 'business']);

enter image description here

Adding files to a GitHub repository

The general idea is to add, commit and push your files to the GitHub repo.

First you need to clone your GitHub repo.
Then, you would git add all the files from your other folder: one trick is to specify an alternate working tree when git add'ing your files.

git --work-tree=yourSrcFolder add .

(done from the root directory of your cloned Git repo, then git commit -m "a msg", and git push origin master)

That way, you keep separate your initial source folder, from your Git working tree.


Note that since early December 2012, you can create new files directly from GitHub:

Create new File

ProTip™: You can pre-fill the filename field using just the URL.
Typing ?filename=yournewfile.txt at the end of the URL will pre-fill the filename field with the name yournewfile.txt.

d

Android: adb pull file on desktop

Judging by the desktop folder location you are using Windows. The command in Windows would be:

adb pull /sdcard/log.txt %USERPROFILE%\Desktop\

AngularJS - get element attributes values

<button class="myButton" data-id="345" ng-click="doStuff($element.target)">Button</button>

I added class to button to get by querySelector, then get data attribute

var myButton = angular.element( document.querySelector( '.myButton' ) );
console.log( myButton.data( 'id' ) );

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

The "SNAPSHOT" term means that the build is a snapshot of your code at a given time.

It usually means that this version is still under heavy development.

When the code is ready and it is time to release it, you will want to change the version listed in the POM. Then instead of having a "SNAPSHOT" you would use a label like "1.0".

For some help with versioning, check out the Semantic Versioning specification.

How to Install pip for python 3.7 on Ubuntu 18?

In general, don't do this:

pip install package

because, as you have correctly noticed, it's not clear what Python version you're installing package for.

Instead, if you want to install package for Python 3.7, do this:

python3.7 -m pip install package

Replace package with the name of whatever you're trying to install.

Took me a surprisingly long time to figure it out, too. The docs about it are here.

Your other option is to set up a virtual environment. Once your virtual environment is active, executable names like python and pip will point to the correct ones.

How to get an object's methods?

Remember that technically javascript objects don't have methods. They have properties, some of which may be function objects. That means that you can enumerate the methods in an object just like you can enumerate the properties. This (or something close to this) should work:

var bar
for (bar in foo)
{
    console.log("Foo has property " + bar);
}

There are complications to this because some properties of objects aren't enumerable so you won't be able to find every function on the object.

Possible to restore a backup of SQL Server 2014 on SQL Server 2012?

Sure it's possible... use Export Wizard in source option use SQL SERVER NATIVE CLIENT 11, later your source server ex.192.168.100.65\SQLEXPRESS next step select your new destination server ex.192.168.100.65\SQL2014

Just be sure to be using correct instance and connect each other

Just pay attention in Stored procs must be recompiled

Escape double quotes in Java

Use Java's replaceAll(String regex, String replacement)

For example, Use a substitution char for the quotes and then replace that char with \"

String newstring = String.replaceAll("%","\"");

or replace all instances of \" with \\\"

String newstring = String.replaceAll("\"","\\\"");

Environment variables for java installation

In Windows inorder to set

Step 1 : Right Click on MyComputer and click on properties .

Step 2 : Click on Advanced tab

alt text

Step 3: Click on Environment Variables

alt text

Step 4: Create a new class path for JAVA_HOME

alt text

Step 5: Enter the Variable name as JAVA_HOME and the value to your jdk bin path ie c:\Programfiles\Java\jdk-1.6\bin and

NOTE Make sure u start with .; in the Value so that it doesn't corrupt the other environment variables which is already set.

alt text

Step 6 : Follow the Above step and edit the Path in System Variables add the following ;c:\Programfiles\Java\jdk-1.6\bin in the value column.

Step 7 :Your are done setting up your environment variables for your Java , In order to test it go to command prompt and type

 java   

who will get a list of help doc

In order make sure whether compiler is setup Type in cmd

  javac

who will get a list related to javac

Hope this Helps !

Find a commit on GitHub given the commit hash

View single commit:
https://github.com/<user>/<project>/commit/<hash>

View log:
https://github.com/<user>/<project>/commits/<hash>

View full repo:
https://github.com/<user>/<project>/tree/<hash>

<hash> can be any length as long as it is unique.

Writing a VLOOKUP function in vba

Dim found As Integer
    found = 0

    Dim vTest As Variant

    vTest = Application.VLookup(TextBox1.Value, _
    Worksheets("Sheet3").Range("A2:A55"), 1, False)

If IsError(vTest) Then
    found = 0
    MsgBox ("Type Mismatch")
    TextBox1.SetFocus
    Cancel = True
    Exit Sub
Else

    TextBox2.Value = Application.VLookup(TextBox1.Value, _
    Worksheets("Sheet3").Range("A2:B55"), 2, False)
    found = 1
    End If

Android: how to hide ActionBar on certain activities

The ActionBar usually exists along Fragments so from the Activity you can hide it

getActionBar().hide();
getActionBar().show();

and from the Fragment you can do it

getActivity().getActionBar().hide();
getActivity().getActionBar().show();

YouTube API to fetch all videos on a channel

Here is a video from Google Developers showing how to list all videos in a channel in v3 of the YouTube API.

There are two steps:

  1. Query Channels to get the "uploads" Id. eg https://www.googleapis.com/youtube/v3/channels?id={channel Id}&key={API key}&part=contentDetails

  2. Use this "uploads" Id to query PlaylistItems to get the list of videos. eg https://www.googleapis.com/youtube/v3/playlistItems?playlistId={"uploads" Id}&key={API key}&part=snippet&maxResults=50

Include CSS and Javascript in my django template

Read this https://docs.djangoproject.com/en/dev/howto/static-files/:

For local development, if you are using runserver or adding staticfiles_urlpatterns to your URLconf, you’re done with the setup – your static files will automatically be served at the default (for newly created projects) STATIC_URL of /static/.

And try:

~/tmp$ django-admin.py startproject myprj
~/tmp$ cd myprj/
~/tmp/myprj$ chmod a+x manage.py
~/tmp/myprj$ ./manage.py startapp myapp

Then add 'myapp' to INSTALLED_APPS (myprj/settings.py).

~/tmp/myprj$ cd myapp/
~/tmp/myprj/myapp$ mkdir static
~/tmp/myprj/myapp$ echo 'alert("hello!");' > static/hello.js
~/tmp/myprj/myapp$ mkdir templates
~/tmp/myprj/myapp$ echo '<script src="{{ STATIC_URL }}hello.js"></script>' > templates/hello.html

Edit myprj/urls.py:

from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView

class HelloView(TemplateView):
    template_name = "hello.html"

urlpatterns = patterns('',
    url(r'^$', HelloView.as_view(), name='hello'),
)

And run it:

~/tmp/myprj/myapp$ cd ..
~/tmp/myprj$ ./manage.py runserver

It works!

How to call a parent class function from derived class function?

If your base class is called Base, and your function is called FooBar() you can call it directly using Base::FooBar()

void Base::FooBar()
{
   printf("in Base\n");
}

void ChildOfBase::FooBar()
{
  Base::FooBar();
}

Is there a good Valgrind substitute for Windows?

I've been loving Memory Validator, from a company called Software Verification.

Create a asmx web service in C# using visual studio 2013

  1. Create Empty ASP.NET Project enter image description here
  2. Add Web Service(asmx) to your project
    enter image description here

MSIE and addEventListener Problem in Javascript?

As of IE11, you need to use addEventListener. attachEvent is deprecated and throws an error.

How do I fix 'ImportError: cannot import name IncompleteRead'?

The problem is the Python module requests. It can be fixed by

$ sudo apt-get purge python-requests
[now requests and pip gets deinstalled]
$ sudo apt-get install python-requests python-pip

If you have this problem with Python 3, you have to write python3 instead of python.

How to capture Enter key press?

Small bit of generic jQuery for you..

$('div.search-box input[type=text]').on('keydown', function (e) {
    if (e.which == 13) {
        $(this).parent().find('input[type=submit]').trigger('click');
        return false;
     }
});

This works on the assumes that the textbox and submit button are wrapped on the same div. works a treat with multiple search boxes on a page

Line break (like <br>) using only css

It works like this:

h4 {
    display:inline;
}
h4:after {
    content:"\a";
    white-space: pre;
}

Example: http://jsfiddle.net/Bb2d7/

The trick comes from here: https://stackoverflow.com/a/66000/509752 (to have more explanation)

Remove Item in Dictionary based on Value

You can use the following as extension method

 public static void RemoveByValue<T,T1>(this Dictionary<T,T1> src , T1 Value)
    {
        foreach (var item in src.Where(kvp => kvp.Value.Equals( Value)).ToList())
        {
            src.Remove(item.Key);
        }
    }

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

Random String Generator Returning Same String

And here is another idea based on GUIDs. I've used it for the Visual Studio performance test to generate random string contaning only alphanumeric characters.

public string GenerateRandomString(int stringLength)
{
    Random rnd = new Random();
    Guid guid;
    String randomString = string.Empty;

    int numberOfGuidsRequired = (int)Math.Ceiling((double)stringLength / 32d);
    for (int i = 0; i < numberOfGuidsRequired; i++)
    {
        guid = Guid.NewGuid();
        randomString += guid.ToString().Replace("-", "");
    }

    return randomString.Substring(0, stringLength);
}

How to break/exit from a each() function in JQuery?

You can use return false;

+----------------------------------------+
| JavaScript              | PHP          |
+-------------------------+--------------+
|                         |              |
| return false;           | break;       |
|                         |              |
| return true; or return; | continue;    |
+-------------------------+--------------+

How to set portrait and landscape media queries in css?

It can also be as simple as this.

@media (orientation: landscape) {

}

Angular - "has no exported member 'Observable'"

I had a similar issue. Back-revving RXJS from 6.x to the latest 5.x release fixed it for Angular 5.2.x.

Open package.json.

Change "rxjs": "^6.0.0", to "rxjs": "^5.5.10",

run npm update

How do I save a String to a text file using Java?

Use this, it is very readable:

import java.nio.file.Files;
import java.nio.file.Paths;

Files.write(Paths.get(path), lines.getBytes(), StandardOpenOption.WRITE);

SQL Server query to find all current database names

SELECT name  
FROM sys.databases

You'll only see the databases you have permission to see.

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

^ outside of the character class ("[a-zA-Z]") notes that it is the "begins with" operator.
^ inside of the character negates the specified class.

So, "^[a-zA-Z]" translates to "begins with character from a-z or A-Z", and "[^a-zA-Z]" translates to "is not either a-z or A-Z"

Here's a quick reference: http://www.regular-expressions.info/reference.html

On localhost, how do I pick a free port number?

For the sake of snippet of what the guys have explained above:

import socket
from contextlib import closing

def find_free_port():
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
        s.bind(('', 0))
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        return s.getsockname()[1]

How to concatenate multiple column values into a single column in Panda dataframe

df['New_column_name'] = df['Column1'].map(str) + 'X' + df['Steps']

X= x is any delimiter (eg: space) by which you want to separate two merged column.

Trigger a keypress/keydown/keyup event in JS/jQuery?

For typescript cast to KeyboardEventInit and provide the correct keyCode integer

const event = new KeyboardEvent("keydown", {
          keyCode: 38,
        } as KeyboardEventInit);

How to check if a value is not null and not empty string in JS

When we code empty in essence could mean any one of the following given the circumstances;

  • 0 as in number value
  • 0.0 as in float value
  • '0' as in string value
  • '0.0' as in string value
  • null as in Null value, as per chance it could also capture undefined or it may not
  • undefined as in undefined value
  • false as in false truthy value, as per chance 0 also as truthy but what if we want to capture false as it is
  • '' empty sting value with no white space or tab
  • ' ' string with white space or tab only

In real life situation as OP stated we may wish to test them all or at times we may only wish to test for limited set of conditions.

Generally if(!a){return true;} serves its purpose most of the time however it will not cover wider set of conditions.

Another hack that has made its round is return (!value || value == undefined || value == "" || value.length == 0);

But what if we need control on whole process?

There is no simple whiplash solution in native core JavaScript it has to be adopted. Considering we drop support for legacy IE11 (to be honest even windows has so should we) below solution born out of frustration works in all modern browsers;

 function empty (a,b=[])
 {if(!Array.isArray(b)) return; 
 var conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
 if(conditions.includes(a)|| (typeof a === 'string' && conditions.includes(a.toString().trim())))
 {return true;};
 return false;};`

Logic behind the solution is function has two parameters a and b, a is value we need to check, b is a array with set conditions we need to exclude from predefined conditions as listed above. Default value of b is set to an empty array [].

First run of function is to check if b is an array or not, if not then early exit the function.

next step is to compute array difference from [null,'0','0.0',false,undefined,''] and from array b. if b is an empty array predefined conditions will stand else it will remove matching values.

conditions = [predefined set] - [to be excluded set] filter function does exactly that make use of it. Now that we have conditions in array set all we need to do is check if value is in conditions array. includes function does exactly that no need to write nasty loops of your own let JS engine do the heavy lifting.

Gotcha if we are to convert a into string for comparison then 0 and 0.0 would run fine however Null and Undefined would through error blocking whole script. We need edge case solution. Below simple || covers the edge case if first condition is not satisfied. Running another early check through include makes early exit if not met.

if(conditions.includes(a)||  (['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim())))

trim() function will cover for wider white spaces and tabs only value and will only come into play in edge case scenario.

Play ground

_x000D_
_x000D_
function empty (a,b=[]){
if(!Array.isArray(b)) return;
conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
if(conditions.includes(a)|| 
(['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim()))){
 return true;
} 
return false;
}

console.log('1 '+empty());
console.log('2 '+empty(''));
console.log('3 '+empty('      '));
console.log('4 '+empty(0));
console.log('5 '+empty('0'));
console.log('6 '+empty(0.0));
console.log('7 '+empty('0.0'));
console.log('8 '+empty(false));
console.log('9 '+empty(null));
console.log('10 '+empty(null,[null]));
console.log('11 dont check 0 as number '+empty(0,['0']));
console.log('12 dont check 0 as string '+empty('0',['0']));
console.log('13 as number for false as value'+empty(false,[false]));
_x000D_
_x000D_
_x000D_

Lets make it complex - what if our value to compare is array its self and can be as deeply nested it can be. what if we are to check if any value in array is empty, it can be an edge business case.

_x000D_
_x000D_
function empty (a,b=[]){
    if(!Array.isArray(b)) return;

    conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
    if(Array.isArray(a) && a.length > 0){
    for (i = 0; i < a.length; i++) { if (empty(a[i],b))return true;} 
    } 
    
    if(conditions.includes(a)|| 
    (['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim()))){
     return true;
    } 
    return false;
    }

console.log('checking for all values '+empty([1,[0]]));
console.log('excluding for 0 from condition '+empty([1,[0]], ['0']));
_x000D_
_x000D_
_x000D_

it simple and wider use case function that I have adopted in my framework;

  • Gives control over as to what exactly is the definition of empty in a given situation
  • Gives control over to redefine conditions of empty
  • Can compare for almost for every thing from string, number, float, truthy, null, undefined and deep arrays
  • Solution is drawn keeping in mind the resuability and flexibility. All other answers are suited in case if simple one or two cases are to be dealt with. However, there is always a case when definition of empty changes while coding above snippets make work flawlessly in that case.

How is attr_accessible used in Rails 4?

We can use

params.require(:person).permit(:name, :age)

where person is Model, you can pass this code on a method person_params & use in place of params[:person] in create method or else method

How to use BOOLEAN type in SELECT statement

Compile this in your database and start using boolean statements in your querys.

note: the function get's a varchar2 param, so be sure to wrap any "strings" in your statement. It will return 1 for true and 0 for false;

select bool('''abc''<''bfg''') from dual;

CREATE OR REPLACE function bool(p_str in varchar2) return varchar2 
 is
 begin

 execute immediate ' begin if '||P_str||' then
          :v_res :=  1;
       else
          :v_res :=  0;
       end if; end;' using out v_res;

       return v_res;

 exception 
  when others then 
    return '"'||p_str||'" is not a boolean expr.';
 end;
/

What is Common Gateway Interface (CGI)?

CGI essentially passes the request off to any interpreter that is configured with the web server - This could be Perl, Python, PHP, Ruby, C pretty much anything. Perl was the most common back in the day thats why you often see it in reference to CGI.

CGI is not dead. In fact most large hosting companies run PHP as CGI as opposed to mod_php because it offers user level config and some other things while it is slower than mod_php. Ruby and Python are also typically run as CGI. they key difference here is that a server module runs as part of the actual server software - where as with CGI its totally outside the server The server just uses the CGI module to determine how to pass and recieve data to the outside interpreter.

What is the iBeacon Bluetooth Profile

Just to reconcile the difference between sandeepmistry's answer and davidgyoung's answer:

02 01 1a 1a ff 4C 00

Is part of the advertising data format specification [1]

  02 # length of following AD structure
  01 # <<Flags>> AD Structure [2]
  1a # read as b00011010. 
     # In this case, LE General Discoverable,
     # and simultaneous BR/EDR but this may vary by device!

  1a # length of following AD structure
  FF # Manufacturer specific data [3]
4C00 # Apple Inc [4]
0215 # ?? some 2-byte header

Missing from the AD is a Service [5] definition. I think the iBeacon protocol itself has no relationship to the GATT and standard service discovery. If you download RedBearLab's iBeacon program, you'll see that they happen to use the GATT for configuring the advertisement parameters, but this seems to be specific to their implementation, and not part of the spec. The AirLocate program doesn't seem to use the GATT for configuration, for instance, according to LightBlue and or other similar programs I tried.

References:

  1. Core Bluetooth Spec v4, Vol 3, Part C, 11
  2. Vol 3, Part C, 18.1
  3. Vol 3, Part C, 18.11
  4. https://www.bluetooth.org/en-us/specification/assigned-numbers/company-identifiers
  5. Vol 3, Part C, 18.2

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

For Genymotion 2.12.2 you can find GApps added in all their virtual devices. Run any virtual device by Genymotion and then you can find on the top right corner which says Open GApps. Press it and it will automatically install GApps.

!(https://imgur.com/a/ju3EYE0)

Convert .pfx to .cer

the simple way I believe is to import it then export it, using the certificate manager in Windows Management Console.

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

Say you want to answer a request with a 204: No Content HTTP status. Firefox will complain with "no element found" in the console of the browser. This is a bug in Firefox that has been reported, but never fixed, for several years. By sending a "Content-type: text/plain" header, you can prevent this error in Firefox.

How to Get the Current URL Inside @if Statement (Blade) in Laravel 4?

You can also use Route::current()->getName() to check your route name.

Example: routes.php

Route::get('test', ['as'=>'testing', function() {
    return View::make('test');
}]);

View:

@if(Route::current()->getName() == 'testing')
    Hello This is testing
@endif

CS0234: Mvc does not exist in the System.Web namespace

add Microsoft.AspNet.Mvc nuget package.

JQuery: dynamic height() with window resize()

The cleanest solution - also purely CSS - would be using calc and vh.

The middle div's heigh will be calculated thusly:

#middle-div { 
height: calc(100vh - 46px); 
}

That is, 100% of the viewport height minus the 2*23px. This will ensure that the page loads properly and is dynamic(demo here).

Also remember to use box-sizing, so the paddings and borders don't make the divs outfill the viewport.

SSIS Connection not found in package

I'm a little late to the party, but I ran across this thread while experiencing the same errors and found a different resolution.

When creating an SSIS 2012 package, in the Solution Explorer window you will see the Connection Managers folder at the project level. This seems like the most logical place to create a connection, and should be used when creating a connection that can be used by any package in the project. It is included at the project level, and not the package level.

When running my dtsx package using dtexec, I received the same errors shown above. This is because the connection is not included in the package (just the project). My solution was to go into the package designer, and then in the Connection Manager window, right click the project level connection (which is shown using the "(project)" prefix) and choose "Convert to Package Connection". This will embed the connection in the actual dtsx package. This alleviated my problem.

How can I keep my branch up to date with master with git?

Assuming you're fine with taking all of the changes in master, what you want is:

git checkout <my branch>

to switch the working tree to your branch; then:

git merge master

to merge all the changes in master with yours.

rotate image with css

Perform rotation using transform: rotate(xdeg) and also apply overflow: hidden to the parent component to avoid overlapping effect

.div-parent {
   overflow: hidden
}

.div-child {
   transform: rotate(270deg);
}

How to update npm

upgrading to nodejs v0.12.7

 # Note the new setup script name for Node.js v0.12
 curl -sL https://deb.nodesource.com/setup_0.12 | sudo bash -

 # Then install with:
 sudo apt-get install -y nodejs

Source from nodesource.com

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

  1. Turn on usb debugging
  2. Turn on Install via USB :-> While turning on it asks for mi account sign in you can get instant otp vis sms service to sign in quickly.
  3. Turn off MIUI optimization.

How to clear https proxy setting of NPM?

I think it's not http-proxy but proxy:

npm config set proxy="http://yourproxyhere"

How do I check for equality using Spark Dataframe without SQL Query?

Let's create a sample dataset and do a deep dive into exactly why OP's code didn't work.

Here's our sample data:

val df = Seq(
  ("Rockets", 2, "TX"),
  ("Warriors", 6, "CA"),
  ("Spurs", 5, "TX"),
  ("Knicks", 2, "NY")
).toDF("team_name", "num_championships", "state")

We can pretty print our dataset with the show() method:

+---------+-----------------+-----+
|team_name|num_championships|state|
+---------+-----------------+-----+
|  Rockets|                2|   TX|
| Warriors|                6|   CA|
|    Spurs|                5|   TX|
|   Knicks|                2|   NY|
+---------+-----------------+-----+

Let's examine the results of df.select(df("state")==="TX").show():

+------------+
|(state = TX)|
+------------+
|        true|
|       false|
|        true|
|       false|
+------------+

It's easier to understand this result by simply appending a column - df.withColumn("is_state_tx", df("state")==="TX").show():

+---------+-----------------+-----+-----------+
|team_name|num_championships|state|is_state_tx|
+---------+-----------------+-----+-----------+
|  Rockets|                2|   TX|       true|
| Warriors|                6|   CA|      false|
|    Spurs|                5|   TX|       true|
|   Knicks|                2|   NY|      false|
+---------+-----------------+-----+-----------+

The other code OP tried (df.select(df("state")=="TX").show()) returns this error:

<console>:27: error: overloaded method value select with alternatives:
  [U1](c1: org.apache.spark.sql.TypedColumn[org.apache.spark.sql.Row,U1])org.apache.spark.sql.Dataset[U1] <and>
  (col: String,cols: String*)org.apache.spark.sql.DataFrame <and>
  (cols: org.apache.spark.sql.Column*)org.apache.spark.sql.DataFrame
 cannot be applied to (Boolean)
       df.select(df("state")=="TX").show()
          ^

The === operator is defined in the Column class. The Column class doesn't define a == operator and that's why this code is erroring out. Read this blog for more background information about the Spark Column class.

Here's the accepted answer that works:

df.filter(df("state")==="TX").show()

+---------+-----------------+-----+
|team_name|num_championships|state|
+---------+-----------------+-----+
|  Rockets|                2|   TX|
|    Spurs|                5|   TX|
+---------+-----------------+-----+

As other posters have mentioned, the === method takes an argument with an Any type, so this isn't the only solution that works. This works too for example:

df.filter(df("state") === lit("TX")).show

+---------+-----------------+-----+
|team_name|num_championships|state|
+---------+-----------------+-----+
|  Rockets|                2|   TX|
|    Spurs|                5|   TX|
+---------+-----------------+-----+

The Column equalTo method can also be used:

df.filter(df("state").equalTo("TX")).show()

+---------+-----------------+-----+
|team_name|num_championships|state|
+---------+-----------------+-----+
|  Rockets|                2|   TX|
|    Spurs|                5|   TX|
+---------+-----------------+-----+

It worthwhile studying this example in detail. Scala's syntax seems magical at times, especially when method are invoked without dot notation. It's hard for the untrained eye to see that === is a method defined in the Column class!

See this blog post if you'd like even more details on Spark Column equality.

\r\n, \r and \n what is the difference between them?

  • \r = CR (Carriage Return) → Used as a new line character in Mac OS before X
  • \n = LF (Line Feed) → Used as a new line character in Unix/Mac OS X
  • \r\n = CR + LF → Used as a new line character in Windows

Javascript regular expression password validation having special characters

it,s work perfect for me and i am sure will work for you guys checkout it easy and accurate

var regix = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=. 
            {8,})");

if(regix.test(password) == false ) {
     $('.messageBox').html(`<div class="messageStackError">
       password must be a minimum of 8 characters including number, Upper, Lower And 
       one special character
     </div>`);
}
else
{
        $('form').submit();
}

String escape into XML

Another take based on John Skeet's answer that doesn't return the tags:

void Main()
{
    XmlString("Brackets & stuff <> and \"quotes\"").Dump();
}

public string XmlString(string text)
{
    return new XElement("t", text).LastNode.ToString();
} 

This returns just the value passed in, in XML encoded format:

Brackets &amp; stuff &lt;&gt; and "quotes"

Convert NaN to 0 in javascript

Using a double-tilde (double bitwise NOT) - ~~ - does some interesting things in JavaScript. For instance you can use it instead of Math.floor or even as an alternative to parseInt("123", 10)! It's been discussed a lot over the web, so I won't go in why it works here, but if you're interested: What is the "double tilde" (~~) operator in JavaScript?

We can exploit this property of a double-tilde to convert NaN to a number, and happily that number is zero!

console.log(~~NaN); // 0

not finding android sdk (Unity)

1- Just open https://developer.android.com/studio/index.html

2- scroll down to the bottom of that page

3- download last version of tools for your OS (for example tools_r25.2.3-windows.zip)

4- Unzip it

5- Delete folder tools from previous Android Sdk folder

6- Copy new folder tools to Android SDK Folder like this image:

enter image description here

Could not locate Gemfile

Here is something you could try.

Add this to any config files you use to run your app.

ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' # Set up gems listed in the Gemfile.
Bundler.require(:default)

Rails and other Rack based apps use this scheme. It happens sometimes that you are trying to run things which are some directories deeper than your root where your Gemfile normally is located. Of course you solved this problem for now but occasionally we all get into trouble with this finding the Gemfile. I sometimes like when you can have all you gems in the .bundle directory also. It never hurts to keep this site address under your pillow. http://bundler.io/

Constructor overload in TypeScript

Note that you can also work around the lack of overloading at the implementation level through default parameters in TypeScript, e.g.:

interface IBox {    
    x : number;
    y : number;
    height : number;
    width : number;
}

class Box {
    public x: number;
    public y: number;
    public height: number;
    public width: number;

    constructor(obj : IBox = {x:0,y:0, height:0, width:0}) {    
        this.x = obj.x;
        this.y = obj.y;
        this.height = obj.height;
        this.width = obj.width;
    }   
}

Edit: As of Dec 5 '16, see Benson's answer for a more elaborate solution that allows more flexibility.

asp.net validation to make sure textbox has integer values

Use Int32.TryParse.

 int integer;
 Int32.TryParse(Textbox.Text, out integer)

It will return a bool so you can see if they entered a valid integer.

Purpose of a constructor in Java?

As mentioned in LotusUNSW answer Constructors are used to initialize the instances of a class.

Example:

Say you have an Animal class something like

class Animal{
   private String name;
   private String type;
}

Lets see what happens when you try to create an instance of Animal class, say a Dog named Puppy. Now you have have to initialize name = Puppy and type = Dog. So, how can you do that. A way of doing it is having a constructor like

    Animal(String nameProvided, String typeProvided){
         this.name = nameProvided;
         this.type = typeProvided;
     }

Now when you create an object of class Animal, something like Animal dog = new Animal("Puppy", "Dog"); your constructor is called and initializes name and type to the values you provided i.e. Puppy and Dog respectively.

Now you might ask what if I didn't provide an argument to my constructor something like

Animal xyz = new Animal();

This is a default Constructor which initializes the object with default values i.e. in our Animal class name and type values corresponding to xyz object would be name = null and type = null

How do I make a text go onto the next line if it overflows?

In order to use word-wrap: break-word, you need to set a width (in px). For example:

div {
    width: 250px;
    word-wrap: break-word;
}

word-wrap is a CSS3 property, but it should work in all browsers, including IE 5.5-9.

checking memory_limit in PHP

Checking on command line:

php -i | grep "memory_limit"

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

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

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

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

See also Issue1646728

Only variable references should be returned by reference - Codeigniter

Edit filename: core/Common.php, line number: 257

Before

return $_config[0] =& $config; 

After

$_config[0] =& $config;
return $_config[0]; 

Update

Added by NikiC

In PHP assignment expressions always return the assigned value. So $_config[0] =& $config returns $config - but not the variable itself, but a copy of its value. And returning a reference to a temporary value wouldn't be particularly useful (changing it wouldn't do anything).

Update

This fix has been merged into CI 2.2.1 (https://github.com/bcit-ci/CodeIgniter/commit/69b02d0f0bc46e914bed1604cfbd9bf74286b2e3). It's better to upgrade rather than modifying core framework files.

Javascript - How to show escape characters in a string?

You have to escape the backslash, so try this:

str = "Hello\\nWorld";

Here are more escaped characters in Javascript.

Execution order of events when pressing PrimeFaces p:commandButton

I just love getting information like BalusC gives here - and he is kind enough to help SO many people with such GOOD information that I regard his words as gospel, but I was not able to use that order of events to solve this same kind of timing issue in my project. Since BalusC put a great general reference here that I even bookmarked, I thought I would donate my solution for some advanced timing issues in the same place since it does solve the original poster's timing issues as well. I hope this code helps someone:

        <p:pickList id="formPickList" 
                    value="#{mediaDetail.availableMedia}" 
                    converter="MediaPicklistConverter" 
                    widgetVar="formsPicklistWidget" 
                    var="mediaFiles" 
                    itemLabel="#{mediaFiles.mediaTitle}" 
                    itemValue="#{mediaFiles}" >
            <f:facet name="sourceCaption">Available Media</f:facet>
            <f:facet name="targetCaption">Chosen Media</f:facet>
        </p:pickList>

        <p:commandButton id="viewStream_btn" 
                         value="Stream chosen media" 
                         icon="fa fa-download"
                         ajax="true"
                         action="#{mediaDetail.prepareStreams}"                                              
                         update=":streamDialogPanel"
                         oncomplete="PF('streamingDialog').show()"
                         styleClass="ui-priority-primary"
                         style="margin-top:5px" >
            <p:ajax process="formPickList"  />
        </p:commandButton>

The dialog is at the top of the XHTML outside this form and it has a form of its own embedded in the dialog along with a datatable which holds additional commands for streaming the media that all needed to be primed and ready to go when the dialog is presented. You can use this same technique to do things like download customized documents that need to be prepared before they are streamed to the user's computer via fileDownload buttons in the dialog box as well.

As I said, this is a more complicated example, but it hits all the high points of your problem and mine. When the command button is clicked, the result is to first insure the backing bean is updated with the results of the pickList, then tell the backing bean to prepare streams for the user based on their selections in the pick list, then update the controls in the dynamic dialog with an update, then show the dialog box ready for the user to start streaming their content.

The trick to it was to use BalusC's order of events for the main commandButton and then to add the <p:ajax process="formPickList" /> bit to ensure it was executed first - because nothing happens correctly unless the pickList updated the backing bean first (something that was not happening for me before I added it). So, yea, that commandButton rocks because you can affect previous, pending and current components as well as the backing beans - but the timing to interrelate all of them is not easy to get a handle on sometimes.

Happy coding!

How to check whether a int is not null or empty?

int variables can't be null

If a null is to be converted to int, then it is the converter which decides whether to set 0, throw exception, or set another value (like Integer.MIN_VALUE). Try to plug your own converter.

jinja2.exceptions.TemplateNotFound error

I think you shouldn't prepend themesDir. You only pass the filename of the template to flask, it will then look in a folder called templates relative to your python file.

How to instantiate a File object in JavaScript?

The idea ...To create a File object (api) in javaScript for images already present in the DOM :

<img src="../img/Products/fijRKjhudDjiokDhg1524164151.jpg">

var file = new File(['fijRKjhudDjiokDhg1524164151'],
                     '../img/Products/fijRKjhudDjiokDhg1524164151.jpg', 
                     {type:'image/jpg'});

// created object file
console.log(file);

Don't do that ! ... (but I did it anyway)

-> the console give a result similar as an Object File :

File(0) {name: "fijRKjokDhgfsKtG1527053050.jpg", lastModified: 1527053530715, lastModifiedDate: Wed May 23 2018 07:32:10 GMT+0200 (Paris, Madrid (heure d’été)), webkitRelativePath: "", size: 0, …}
lastModified:1527053530715
lastModifiedDate:Wed May 23 2018 07:32:10 GMT+0200 (Paris, Madrid (heure d’été)) {}
name:"fijRKjokDhgfsKtG1527053050.jpg"
size:0
type:"image/jpg"
webkitRelativePath:""__proto__:File

But the size of the object is wrong ...

Why i need to do that ?

For example to retransmit an image form already uploaded, during a product update, along with additional images added during the update

"Stack overflow in line 0" on Internet Explorer

I ran into this problem recently and wrote up a post about the particular case in our code that was causing this problem.

http://cappuccino.org/discuss/2010/03/01/internet-explorer-global-variables-and-stack-overflows/

The quick summary is: recursion that passes through the host global object is limited to a stack depth of 13. In other words, if the reference your function call is using (not necessarily the function itself) was defined with some form window.foo = function, then recursing through foo is limited to a depth of 13.

C/C++ switch case with string

You could use the string to index into a hash table of function pointers.

Edit: glib has a hash table implementation that supports strings as keys and arbitrary pointers as values: http://library.gnome.org/devel/glib/stable/glib-Hash-Tables.html

Get root password for Google Cloud Engine VM

I had the same problem. Even after updating the password using sudo passwd it was not working. I had to give "multiple" roles for my user through IAM & Admin Refer Screen Shot on IAM & Admin screen of google cloud

After that i restarted the VM. Then again changed the password and then it worked.

user1@sap-hanaexpress-public-1-vm:~> sudo passwd
New password: 
Retype new password: 
passwd: password updated successfully
user1@sap-hanaexpress-public-1-vm:~> su
Password: 
sap-hanaexpress-public-1-vm:/home/user1 # whoami
root
sap-hanaexpress-public-1-vm:/home/user1 #

Django 1.7 - makemigrations not detecting changes

Make sure your model is not abstract. I actually made that mistake and it took a while, so I thought I'd post it.

What is the difference between Python and IPython?

IPython is basically the "recommended" Python shell, which provides extra features. There is no language called IPython.

Creating default object from empty value in PHP?

I had similar problem and this seem to solve the problem. You just need to initialize the $res object to a class . Suppose here the class name is test.

class test
{
   //You can keep the class empty or declare your success variable here
}
$res = new test();
$res->success = false;

Is it not possible to stringify an Error using JSON.stringify?

JSON.stringify(err, Object.getOwnPropertyNames(err))

seems to work

[from a comment by /u/ub3rgeek on /r/javascript] and felixfbecker's comment below

Java default constructor

If a class doesn't have any constructor provided by programmer, then java compiler will add a default constructor with out parameters which will call super class constructor internally with super() call. This is called as default constructor.

In your case, there is no default constructor as you are adding them programmatically. If there are no constructors added by you, then compiler generated default constructor will look like this.

public Module()
{
   super();
}

Note: In side default constructor, it will add super() call also, to call super class constructor.

Purpose of adding default constructor:

Constructor's duty is to initialize instance variables, if there are no instance variables you could choose to remove constructor from your class. But when you are inheriting some class it is your class responsibility to call super class constructor to make sure that super class initializes all its instance variables properly.

That's why if there are no constructors, java compiler will add a default constructor and calls super class constructor.

Sql Server equivalent of a COUNTIF aggregate function

Adding on to Josh's answer,

SELECT COUNT(CASE WHEN myColumn=1 THEN AD_CurrentView.PrimaryKeyColumn ELSE NULL END)
FROM AD_CurrentView

Worked well for me (in SQL Server 2012) without changing the 'count' to a 'sum' and the same logic is portable to other 'conditional aggregates'. E.g., summing based on a condition:

SELECT SUM(CASE WHEN myColumn=1 THEN AD_CurrentView.NumberColumn ELSE 0 END)
FROM AD_CurrentView

How to multiply a BigDecimal by an integer in Java

You have a lot of type-mismatches in your code such as trying to put an int value where BigDecimal is required. The corrected version of your code:

public class Payment
{
    BigDecimal itemCost  = BigDecimal.ZERO;
    BigDecimal totalCost = BigDecimal.ZERO;

    public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
    {
        itemCost  = itemPrice.multiply(new BigDecimal(itemQuantity));
        totalCost = totalCost.add(itemCost);
        return totalCost;
    }
}

iPhone Safari Web App opens links in new window

You can simply remove this meta tag.

<meta name="apple-mobile-web-app-capable" content="yes">

Open another page in php

Use the following code:

if(processing == success) {
  header("Location:filename");
  exit();
}

And you are good to go.

Android: No Activity found to handle Intent error? How it will resolve

Intent intent=new Intent(String) is defined for parameter task, whereas you are passing parameter componentname into this, use instead:

Intent i = new Intent(Settings.this, com.scytec.datamobile.vd.gui.android.AppPreferenceActivity.class);
                    startActivity(i);

In this statement replace ActivityName by Name of Class of Activity, this code resides in.

TSQL Default Minimum DateTime

I think your only option here is a constant. With that said - don't use it - stick with nulls instead of bogus dates.

create table atable
(
  atableID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
  Modified datetime DEFAULT '1/1/1753'
)

Visual Studio opens the default browser instead of Internet Explorer

With VS 2017, debugging ASP.NET project with Chrome doesn't sign you in with your Google account.

To fix that go to Tools -> Options -> Debugging -> General and turn off the setting Enable JavaScript Debugging for ASP.NET (Chrome and IE).

https://msdnshared.blob.core.windows.net/media/2016/11/debugger-settings-1024x690.png

How can I prevent the textarea from stretching beyond his parent DIV element? (google-chrome issue only)

To disable resizing completely:

textarea {
    resize: none;
}

To allow only vertical resizing:

textarea {
    resize: vertical;
}

To allow only horizontal resizing:

textarea {
    resize: horizontal;
}

Or you can limit size:

textarea {
    max-width: 100px; 
    max-height: 100px;
}

To limit size to parents width and/or height:

textarea {
    max-width: 100%; 
    max-height: 100%;
}

Switch statement fall-through...should it be allowed?

Fall-through should be used only when it is used as a jump table into a block of code. If there is any part of the code with an unconditional break before more cases, all the case groups should end that way.

Anything else is "evil".

Attach event to dynamic elements in javascript

I have found the solution posted by jillykate works, but only if the target element is the most nested. If this is not the case, this can be rectified by iterating over the parents, i.e.

function on_window_click(event)
{
    let e = event.target;

    while (e !== null)
    {
        // --- Handle clicks here, e.g. ---
        if (e.getAttribute(`data-say_hello`))
        {
            console.log("Hello, world!");
        }

        e = e.parentElement;
    }
}

window.addEventListener("click", on_window_click);

Also note we can handle events by any attribute, or attach our listener at any level. The code above uses a custom attribute and window. I doubt there is any pragmatic difference between the various methods.

Loop through a date range with JavaScript

var start = new Date("2014-05-01"); //yyyy-mm-dd
var end = new Date("2014-05-05"); //yyyy-mm-dd

while(start <= end){

    var mm = ((start.getMonth()+1)>=10)?(start.getMonth()+1):'0'+(start.getMonth()+1);
    var dd = ((start.getDate())>=10)? (start.getDate()) : '0' + (start.getDate());
    var yyyy = start.getFullYear();
    var date = dd+"/"+mm+"/"+yyyy; //yyyy-mm-dd

    alert(date); 

    start = new Date(start.setDate(start.getDate() + 1)); //date increase by 1
}

Open PDF in new browser full window

To do it from a Base64 encoding you can use the following function:

function base64ToArrayBuffer(data) {
  const bString = window.atob(data);
  const bLength = bString.length;
  const bytes = new Uint8Array(bLength);
  for (let i = 0; i < bLength; i++) {
      bytes[i] = bString.charCodeAt(i);
  }
  return bytes;
}
function base64toPDF(base64EncodedData, fileName = 'file') {
  const bufferArray = base64ToArrayBuffer(base64EncodedData);
  const blobStore = new Blob([bufferArray], { type: 'application/pdf' });
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blobStore);
      return;
  }
  const data = window.URL.createObjectURL(blobStore);
  const link = document.createElement('a');
  document.body.appendChild(link);
  link.href = data;
  link.download = `${fileName}.pdf`;
  link.click();
  window.URL.revokeObjectURL(data);
  link.remove();
}

SQL Server: Get data for only the past year

I, like @D.E. White, came here for similar but different reasons than the original question. The original question asks for the last 365 days. @samjudson's answer provides that. @D.E. White's answer returns results for the prior calendar year.

My query is a bit different in that it works for the prior year up to and including the current date:

SELECT .... FROM .... WHERE year(date) > year(DATEADD(year, -2, GETDATE()))

For example, on Feb 17, 2017 this query returns results from 1/1/2016 to 2/17/2017

Benefits of inline functions in C++?

Inline function is the optimization technique used by the compilers. One can simply prepend inline keyword to function prototype to make a function inline. Inline function instruct compiler to insert complete body of the function wherever that function got used in code.

Advantages :-

  1. It does not require function calling overhead.

  2. It also save overhead of variables push/pop on the stack, while function calling.

  3. It also save overhead of return call from a function.

  4. It increases locality of reference by utilizing instruction cache.

  5. After in-lining compiler can also apply intra-procedural optimization if specified. This is the most important one, in this way compiler can now focus on dead code elimination, can give more stress on branch prediction, induction variable elimination etc..

To check more about it one can follow this link http://tajendrasengar.blogspot.com/2010/03/what-is-inline-function-in-cc.html

SQL Query to find the last day of the month

SQL Server 2012 introduces the eomonth function:

select eomonth('2013-05-31 00:00:00:000')
-->
2013-05-31

Enable PHP Apache2

You have two ways to enable it.

First, you can set the absolute path of the php module file in your httpd.conf file like this:

LoadModule php5_module /path/to/mods-available/libphp5.so

Second, you can link the module file to the mods-enabled directory:

ln -s /path/to/mods-available/libphp5.so /path/to/mods-enabled/libphp5.so

How can I do DNS lookups in Python, including referring to /etc/hosts?

The normal name resolution in Python works fine. Why do you need DNSpython for that. Just use socket's getaddrinfo which follows the rules configured for your operating system (on Debian, it follows /etc/nsswitch.conf:

>>> print socket.getaddrinfo('google.com', 80)
[(10, 1, 6, '', ('2a00:1450:8006::63', 80, 0, 0)), (10, 2, 17, '', ('2a00:1450:8006::63', 80, 0, 0)), (10, 3, 0, '', ('2a00:1450:8006::63', 80, 0, 0)), (10, 1, 6, '', ('2a00:1450:8006::68', 80, 0, 0)), (10, 2, 17, '', ('2a00:1450:8006::68', 80, 0, 0)), (10, 3, 0, '', ('2a00:1450:8006::68', 80, 0, 0)), (10, 1, 6, '', ('2a00:1450:8006::93', 80, 0, 0)), (10, 2, 17, '', ('2a00:1450:8006::93', 80, 0, 0)), (10, 3, 0, '', ('2a00:1450:8006::93', 80, 0, 0)), (2, 1, 6, '', ('209.85.229.104', 80)), (2, 2, 17, '', ('209.85.229.104', 80)), (2, 3, 0, '', ('209.85.229.104', 80)), (2, 1, 6, '', ('209.85.229.99', 80)), (2, 2, 17, '', ('209.85.229.99', 80)), (2, 3, 0, '', ('209.85.229.99', 80)), (2, 1, 6, '', ('209.85.229.147', 80)), (2, 2, 17, '', ('209.85.229.147', 80)), (2, 3, 0, '', ('209.85.229.147', 80))]

Git - remote: Repository not found

In my case none solution above worked.

I solved it by switching remote.origin.url from https to ssh:

verify git configuration:

git config --list

should be like:

...
remote.origin.url=https://github.com/ORG/repo-name.git
...

update remote.origin.url with ssh to be used:

git remote set-url origin [email protected]:ORG/repo-name.git

Is returning out of a switch statement considered a better practice than using break?

It depends, if your function only consists of the switch statement, then I think that its fine. However, if you want to perform any other operations within that function, its probably not a great idea. You also may have to consider your requirements right now versus in the future. If you want to change your function from option one to option two, more refactoring will be needed.

However, given that within if/else statements it is best practice to do the following:

var foo = "bar";

if(foo == "bar") {
    return 0;
}
else {
    return 100;
}

Based on this, the argument could be made that option one is better practice.

In short, there's no clear answer, so as long as your code adheres to a consistent, readable, maintainable standard - that is to say don't mix and match options one and two throughout your application, that is the best practice you should be following.

Get current URL with jQuery?

In jstl we can access current url path using pageContext.request.contextPath, If you want to do a ajax call,

  url = "${pageContext.request.contextPath}" + "/controller/path"

Ex: in the page http://stackoverflow.com/questions/406192 this will give http://stackoverflow.com/controller/path

Checking if a website is up via Python

Hi this class can do speed and up test for your web page with this class:

 from urllib.request import urlopen
 from socket import socket
 import time


 def tcp_test(server_info):
     cpos = server_info.find(':')
     try:
         sock = socket()
         sock.connect((server_info[:cpos], int(server_info[cpos+1:])))
         sock.close
         return True
     except Exception as e:
         return False


 def http_test(server_info):
     try:
         # TODO : we can use this data after to find sub urls up or down    results
         startTime = time.time()
         data = urlopen(server_info).read()
         endTime = time.time()
         speed = endTime - startTime
         return {'status' : 'up', 'speed' : str(speed)}
     except Exception as e:
         return {'status' : 'down', 'speed' : str(-1)}


 def server_test(test_type, server_info):
     if test_type.lower() == 'tcp':
         return tcp_test(server_info)
     elif test_type.lower() == 'http':
         return http_test(server_info)

How do I link to Google Maps with a particular longitude and latitude?

Using the query parameter won't work, Google will try to approximate the location.

The location I want : http://maps.google.com/maps?ll=43.7920533400153,6.37761393942265

The approximate location (west of the actual location) : http://maps.google.com/?q=43.7920533400153,6.37761393942265

How do I increase memory on Tomcat 7 when running as a Windows Service?

According to catalina.sh customizations should always go into your own setenv.sh (or setenv.bat respectively) eg:

CATALINA_OPTS='-Xms512m -Xmx1024m'

My guess is that setenv.bat will also be called when starting a service.I might be wrong, though, since I'm not a windows user.

How can I combine hashes in Perl?

Check out perlfaq4: How do I merge two hashes. There is a lot of good information already in the Perl documentation and you can have it right away rather than waiting for someone else to answer it. :)


Before you decide to merge two hashes, you have to decide what to do if both hashes contain keys that are the same and if you want to leave the original hashes as they were.

If you want to preserve the original hashes, copy one hash (%hash1) to a new hash (%new_hash), then add the keys from the other hash (%hash2 to the new hash. Checking that the key already exists in %new_hash gives you a chance to decide what to do with the duplicates:

my %new_hash = %hash1; # make a copy; leave %hash1 alone

foreach my $key2 ( keys %hash2 )
    {
    if( exists $new_hash{$key2} )
        {
        warn "Key [$key2] is in both hashes!";
        # handle the duplicate (perhaps only warning)
        ...
        next;
        }
    else
        {
        $new_hash{$key2} = $hash2{$key2};
        }
    }

If you don't want to create a new hash, you can still use this looping technique; just change the %new_hash to %hash1.

foreach my $key2 ( keys %hash2 )
    {
    if( exists $hash1{$key2} )
        {
        warn "Key [$key2] is in both hashes!";
        # handle the duplicate (perhaps only warning)
        ...
        next;
        }
    else
        {
        $hash1{$key2} = $hash2{$key2};
        }
    }

If you don't care that one hash overwrites keys and values from the other, you could just use a hash slice to add one hash to another. In this case, values from %hash2 replace values from %hash1 when they have keys in common:

@hash1{ keys %hash2 } = values %hash2;

how to get list of port which are in use on the server

TCPView is a Windows program that will show you detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. On Windows Server 2008, Vista, NT, 2000 and XP TCPView also reports the name of the process that owns the endpoint. TCPView provides a more informative and conveniently presented subset of the Netstat program that ships with Windows. The TCPView download includes Tcpvcon, a command-line version with the same functionality.

http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx