Programs & Examples On #Doctrine query

Doctrine Query Language (DQL) is one of the Doctrine 2 ORM key features, it is the option to write database queries in a proprietary object oriented SQL dialect.

Doctrine - How to print out the real sql, not just the prepared statement?

There is no other real query, this is how prepared statements work. The values are bound in the database server, not in the application layer.

See my answer to this question: In PHP with PDO, how to check the final SQL parametrized query?

(Repeated here for convenience:)

Using prepared statements with parametrised values is not simply another way to dynamically create a string of SQL. You create a prepared statement at the database, and then send the parameter values alone.

So what is probably sent to the database will be a PREPARE ..., then SET ... and finally EXECUTE ....

You won't be able to get some SQL string like SELECT * FROM ..., even if it would produce equivalent results, because no such query was ever actually sent to the database.

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

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

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

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

});

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

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

CSS to line break before/after a particular `inline-block` item

You are not interested in a lot of "solutions" to your problem. I do not think there really is a good way to do what you want to do. Anything you insert using :after and content has exactly the same syntactic and semantic validity it would have done if you had just written it in there yourself.

The tools CSS provide work. You should just float the lis and then clear: left when you want to start a new line, as you have mentioned:

See an example: http://jsfiddle.net/marcuswhybrow/YMN7U/5/

Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0

For some reason, even if changing the iOS Deployment Target to 8.0 or higher, the Xib files don't adopt that change and remain with the previous settings in the File inspector

File inspector in the Xib after changing the iOS Deployment target

Therefore, you should change it manually for each Xib Afther the manual change

Once done, the warning will disappear :-)

Opencv - Grayscale mode Vs gray color conversion

Note: This is not a duplicate, because the OP is aware that the image from cv2.imread is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)

To illustrate, I've opened up this same color JPEG image:

enter image description here

once using the conversion

img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

and another by loading it in gray scale mode

img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom

enter image description here

I've summed up the diff too to see

import numpy as np
np.sum(diff)
# I got 6143, on a 494 x 750 image

I tried all cv2.imread() modes

Among all the IMREAD_ modes for cv2.imread(), only IMREAD_COLOR and IMREAD_ANYCOLOR can be converted using COLOR_BGR2GRAY, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE

The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)

Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.

In brief, let's not mix the versions and types in the processing pipeline.

So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)

JavaScript backslash (\) in variables is causing an error

If you want to use special character in javascript variable value, Escape Character (\) is required.

Backslash in your example is special character, too.

So you should do something like this,

var ttt = "aa ///\\\\\\"; // --> ///\\\

or

var ttt = "aa ///\\"; // --> ///\

But Escape Character not require for user input.

When you press / in prompt box or input field then submit, that means single /.

Return array in a function

As above mentioned paths are correct. But i think if we just return a local array variable of a function sometimes it returns garbage values as its elements.

in-order to avoid that i had to create the array dynamically and proceed. Which is something like this.

int* func()
{
  int* Arr = new int[100];
  return Arr;
}

int main()
{
  int* ArrResult = func();
  cout << ArrResult[0] << " " << ArrResult[1] << endl;
  return 0;
} 




Convert int to char in java

First, convert the int (or another type) to String,

int a = 1;
String value = String.valueOf(a);

Then, convert that String to char.

char newValue = value.charAt(0);

You can avoid empty output in this way...

System.out.println(newValue);

SFTP file transfer using Java JSch

Usage:

sftp("file:/C:/home/file.txt", "ssh://user:pass@host/home");
sftp("ssh://user:pass@host/home/file.txt", "file:/C:/home");

Implementation

How to set fake GPS location on IOS real device

it seems with XCode 9.2 the way to import .gpx has changed, I tried the ways described here and did not do. The only way worked for me was to drag and drop the file .gpx to the project navigator window on the left. Then I can choose the country in the simulator item.

Hope this helps to someone.

Determine the process pid listening on a certain port

Short version which you can pass to kill command:

lsof -i:80 -t

Table row and column number in jQuery

You can use the Core/index function in a given context, for example you can check the index of the TD in it's parent TR to get the column number, and you can check the TR index on the Table, to get the row number:

$('td').click(function(){
  var col = $(this).parent().children().index($(this));
  var row = $(this).parent().parent().children().index($(this).parent());
  alert('Row: ' + row + ', Column: ' + col);
});

Check a running example here.

Any easy way to use icons from resources?

On Form_Load:

this.Icon = YourProjectNameSpace.Resources.YourResourceName.YouAppIconName;

How can I temporarily disable a foreign key constraint in MySQL?

To turn off the foreign key constraint globally:

SET GLOBAL FOREIGN_KEY_CHECKS = 0;

And for the active foreign key constraint:

SET GLOBAL FOREIGN_KEY_CHECKS = 1;

Couldn't load memtrack module Logcat Error

This error, as you can read on the question linked in comments above, results to be:

"[...] a problem with loading {some} hardware module. This could be something to do with GPU support, sdcard handling, basically anything."

The step 1 below should resolve this problem. Also as I can see, you have some strange package names inside your manifest:

  • package="com.example.hive" in <manifest> tag,
  • android:name="com.sit.gems.app.GemsApplication" for <application>
  • and android:name="com.sit.gems.activity" in <activity>

As you know, these things do not prevent your app to be displayed. But I think:

the Couldn't load memtrack module error could occur because of emulators configurations problems and, because your project contains many organization problems, it might help to give a fresh redesign.

For better using and with few things, this can be resolved by following these tips:


1. Try an other emulator...

And even a real device! The memtrack module error seems related to your emulator. So change it into Run configuration, don't forget to change the API too.


2. OpenGL error logs

For OpenGl errors, as called unimplemented OpenGL ES API, it's not an error but a statement! You should enable it in your manifest (you can read this answer if you're using GLSurfaceView inside HomeActivity.java, it might help you):

<uses-feature android:glEsVersion="0x00020000"></uses-feature>  
// or
<uses-feature android:glEsVersion="0x00010001" android:required="true" />

3. Use the same package

Don't declare different package names to all the tags in Manifest. You should have the same for Manifest, Activities, etc. Something like this looks right:

<!-- set the general package -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sit.gems.activity"
    android:versionCode="1"
    android:versionName="1.0" >

    <!-- don't set a package name in <application> -->
    <application ... >

        <!-- then, declare the activities -->
        <activity
            android:name="com.sit.gems.activity.SplashActivity" ... >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- same package here -->
        <activity
            android:name="com.sit.gems.activity.HomeActivity" ... >
        </activity>
    </application>
</manifest>  

4. Don't get lost with layouts:

You should set another layout for SplashScreenActivity.java because you're not using the TabHost for the splash screen and this is not a safe resource way. Declare a specific layout with something different, like the app name and the logo:

// inside SplashScreen class
setContentView(R.layout.splash_screen);

// layout splash_screen.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent" 
     android:gravity="center"
     android:text="@string/appname" />  

Avoid using a layout in activities which don't use it.


5. Splash Screen?

Finally, I don't understand clearly the purpose of your SplashScreenActivity. It sets a content view and directly finish. This is useless.

As its name is Splash Screen, I assume that you want to display a screen before launching your HomeActivity. Therefore, you should do this and don't use the TabHost layout ;):

// FragmentActivity is also useless here! You don't use a Fragment into it, so, use traditional Activity
public class SplashActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // set your splash_screen layout
        setContentView(R.layout.splash_screen);

        // create a new Thread
        new Thread(new Runnable() {
            public void run() {
                try {
                    // sleep during 800ms
                    Thread.sleep(800);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // start HomeActivity
                startActivity(new Intent(SplashActivity.this, HomeActivity.class));
                SplashActivity.this.finish();
            }
        }).start();
    }
}  

I hope this kind of tips help you to achieve what you want.
If it's not the case, let me know how can I help you.

webpack is not recognized as a internal or external command,operable program or batch file

The fix for me was locally installing webpack as devDependency. Although I have it as devDependencies it was not installed in node_modules folder. So I ran npm install --only=dev

Spring MVC 4: "application/json" Content Type is not being set correctly

Not exactly for this OP, but for those who encountered 404 and cannot set response content-type to "application/json" (any content-type). One possibility is a server actually responds 406 but explorer (e.g., chrome) prints it as 404.

If you do not customize message converter, spring would use AbstractMessageConverterMethodProcessor.java. It would run:

List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(request);
List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request, valueType, declaredType);

and if they do not have any overlapping (the same item), it would throw HttpMediaTypeNotAcceptableException and this finally causes 406. No matter if it is an ajax, or GET/POST, or form action, if the request uri ends with a .html or any suffix, the requestedMediaTypes would be "text/[that suffix]", and this conflicts with producibleMediaTypes, which is usually:

"application/json"  
"application/xml"   
"text/xml"          
"application/*+xml" 
"application/json"  
"application/*+json"
"application/json"  
"application/*+json"
"application/xml"   
"text/xml"          
"application/*+xml"
"application/xml"  
"text/xml"         
"application/*+xml"

What is HTTP "Host" header?

I would always recommend going to the authoritative source when trying to understand the meaning and purpose of HTTP headers.

The "Host" header field in a request provides the host and port
information from the target URI, enabling the origin server to
distinguish among resources while servicing requests for multiple
host names on a single IP address.

https://tools.ietf.org/html/rfc7230#section-5.4

Server did not recognize the value of HTTP Header SOAPAction

I had the same problem after changing the namespace from "tempuri" in my Web Service.

You have to update your Service Reference in the project that is consuming the above service, so it can get the latest SOAP definitions.

Or at least that worked for me. :)

How to write data to a JSON file using Javascript

JSON can be written into local storage using the JSON.stringify to serialize a JS object. You cannot write to a JSON file using only JS. Only cookies or local storage

    var obj = {"nissan": "sentra", "color": "green"};

localStorage.setItem('myStorage', JSON.stringify(obj));

And to retrieve the object later

var obj = JSON.parse(localStorage.getItem('myStorage'));

VS 2012: Scroll Solution Explorer to current file

I've found the Sync with Active Document button in the solution explorer to be the the most effective (this may be a vs2013 feature!)

enter image description here

WPF Add a Border to a TextBlock

No, you need to wrap your TextBlock in a Border. Example:

<Border BorderThickness="1" BorderBrush="Black">
    <TextBlock ... />
</Border>

Of course, you can set these properties (BorderThickness, BorderBrush) through styles as well:

<Style x:Key="notCalledBorder" TargetType="{x:Type Border}">
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="BorderBrush" Value="Black" />
</Style>

<Border Style="{StaticResource notCalledBorder}">
    <TextBlock ... />
</Border>

jquery find class and get the value

var myVar = $("#start").find('myClass').val();

needs to be

var myVar = $("#start").find('.myClass').val();

Remember the CSS selector rules require "." if selecting by class name. The absence of "." is interpreted to mean searching for <myclass></myclass>.

When to use Hadoop, HBase, Hive and Pig?

I worked on Lambda architecture processing Real time and Batch loads. Real time processing is needed where fast decisions need to be taken in case of Fire alarm send by sensor or fraud detection in case of banking transactions. Batch processing is needed to summarize data which can be feed into BI systems.

we used Hadoop ecosystem technologies for above applications.

Real Time Processing

Apache Storm: Stream Data processing, Rule application

HBase: Datastore for serving Realtime dashboard

Batch Processing Hadoop: Crunching huge chunk of data. 360 degrees overview or adding context to events. Interfaces or frameworks like Pig, MR, Spark, Hive, Shark help in computing. This layer needs scheduler for which Oozie is good option.

Event Handling layer

Apache Kafka was first layer to consume high velocity events from sensor. Kafka serves both Real Time and Batch analytics data flow through Linkedin connectors.

Primitive type 'short' - casting in Java

Given that the "why int by default" question hasn't been answered ...

First, "default" is not really the right term (although close enough). As noted by VonC, an expression composed of ints and longs will have a long result. And an operation consisting of ints/logs and doubles will have a double result. The compiler promotes the terms of an expression to whatever type provides a greater range and/or precision in the result (floating point types are presumed to have greater range and precision than integral, although you do lose precision converting large longs to double).

One caveat is that this promotion happens only for the terms that need it. So in the following example, the subexpression 5/4 uses only integral values and is performed using integer math, even though the overall expression involves a double. The result isn't what you might expect...

(5/4) * 1000.0

OK, so why are byte and short promoted to int? Without any references to back me up, it's due to practicality: there are a limited number of bytecodes.

"Bytecode," as its name implies, uses a single byte to specify an operation. For example iadd, which adds two ints. Currently, 205 opcodes are defined, and integer math takes 18 for each type (ie, 36 total between integer and long), not counting conversion operators.

If short, and byte each got their own set of opcodes, you'd be at 241, limiting the ability of the JVM to expand. As I said, no references to back me up on this, but I suspect that Gosling et al said "how often do people actually use shorts?" On the other hand, promoting byte to int leads to this not-so-wonderful effect (the expected answer is 96, the actual is -16):

byte x = (byte)0xC0;
System.out.println(x >> 2);

Javascript Thousand Separator / string format

I did not like any of the answers here, so I created a function that worked for me. Just want to share in case anyone else finds it useful.

function getFormattedCurrency(num) {
    num = num.toFixed(2)
    var cents = (num - Math.floor(num)).toFixed(2);
    return Math.floor(num).toLocaleString() + '.' + cents.split('.')[1];
}

Security of REST authentication schemes

Or you could use the known solution to this problem and use SSL. Self-signed certs are free and its a personal project right?

How to get a vCard (.vcf file) into Android contacts from website

I had problems with importing a VERSION:4.0 vcard file on Android 7 (LineageOS) with the standard Contacts app.

Since this is on the top search hits for "android vcard format not supported", I just wanted to note that I was able to import them with the Simple Contacts app (Play or F-Droid).

Move top 1000 lines from text file to a new file using Unix shell commands

This is a one-liner but uses four atomic commands:

head -1000 file.txt > newfile.txt; tail +1000 file.txt > file.txt.tmp; cp file.txt.tmp file.txt; rm file.txt.tmp

Java - remove last known item from ArrayList

clients.get will return a ClientThread and not a String, and it will bomb with an IndexOutOfBoundsException if it would compile as Java is zero based for indexing.

Similarly I think you should call remove on the clients list.

ClientThread hey = clients.get(clients.size()-1);
clients.remove(hey);
System.out.println(hey + " has logged out.");
System.out.println("CONNECTED PLAYERS: " + clients.size());

I would use the stack functions of a LinkedList in this case though.

ClientThread hey = clients.removeLast()

Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?

@Der Hochstapler thanks for the solution.
but in IONIC 4 some customization in project config.xml work for me

Add a line in Widget tag

<widget id="com.my.awesomeapp" version="1.0.0" 
xmlns="http://www.w3.org/ns/widgets"
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:cdv="http://cordova.apache.org/ns/1.0">

after this, in the Platform tag for android customize some lines check below
add usesCleartextTraffic=true after networkSecurityConfig and resource-file tags

 <platform name="android">
        <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
            <application android:networkSecurityConfig="@xml/network_security_config" />
        </edit-config>
        <resource-file src="resources/android/xml/network_security_config.xml" target="app/src/main/res/xml/network_security_config.xml" />
        <edit-config file="AndroidManifest.xml" mode="merge" target="/manifest/application">
            <application android:usesCleartextTraffic="true" />
        </edit-config>
    </platform>

SQL Server principal "dbo" does not exist,

Also had this error when accidentally fed a database connection string to the readonly mirror - not the primary database in a HA setup.

How to view the current heap size that an application is using?

Attach with jvisualvm from Sun Java 6 JDK. Startup flags are listed.

Error: No default engine was specified and no extension was provided

You can use express-error-handler to use static html pages for error handling and to avoid defining a view handler.

The error was probably caused by a 404, maybe a missing favicon (apparent if you had included the previous console message). The 'view handler' of 'html' doesn't seem to be valid in 4.x express.

Regardless of the cause, you can avoid defining a (valid) view handler as long as you modify additional elements of your configuration.

Your options are to fix this problem are:

  • Define a valid view handler as in other answers
  • Use send() instead of render to return the content directly

http://expressjs.com/en/api.html#res.render

Using render without a filepath automatically invokes a view handler as with the following two lines from your configuration:

res.render('404', { url: req.url });

and:

res.render('500);

Make sure you install express-error-handler with:

npm install --save express-error-handler

Then import it in your app.js

var ErrorHandler = require('express-error-handler');

Then change your error handling to use:

// define below all other routes
var errorHandler = ErrorHandler({
  static: {
    '404': 'error.html' // put this file in your Public folder
    '500': 'error.html' // ditto
});

// any unresolved requests will 404
app.use(function(req,res,next) {
  var err = new Error('Not Found');
  err.status(404);
  next(err);
}

app.use(errorHandler);

Visual Studio Expand/Collapse keyboard shortcuts

Visual Studio 2015:

Tools > Options > Settings > Environment > Keyboard

Defaults:

Edit.CollapsetoDefinitions: CTRL + M + O

Edit.CollapseCurrentRegion: CTRL + M +CTRL + S

Edit.ExpandAllOutlining: CTRL + M + CTRL + X

Edit.ExpandCurrentRegion: CTRL + M + CTRL + E

I like to set and use IntelliJ's shortcuts:

Edit.CollapsetoDefinitions: CTRL + SHIFT + NUM-

Edit.CollapseCurrentRegion: CTRL + NUM-

Edit.ExpandAllOutlining: CTRL + SHIFT + NUM+

Edit.ExpandCurrentRegion: CTRL + NUM+

EC2 instance types's exact network performance?

Bandwidth is tiered by instance size, here's a comprehensive answer:

For t2/m3/c3/c4/r3/i2/d2 instances:

  • t2.nano = ??? (Based on the scaling factors, I'd expect 20-30 MBit/s)
  • t2.micro = ~70 MBit/s (qiita says 63 MBit/s) - t1.micro gets about ~100 Mbit/s
  • t2.small = ~125 MBit/s (t2, qiita says 127 MBit/s, cloudharmony says 125 Mbit/s with spikes to 200+ Mbit/s)
  • *.medium = t2.medium gets 250-300 MBit/s, m3.medium ~400 MBit/s
  • *.large = ~450-600 MBit/s (the most variation, see below)
  • *.xlarge = 700-900 MBit/s
  • *.2xlarge = ~1 GBit/s +- 10%
  • *.4xlarge = ~2 GBit/s +- 10%
  • *.8xlarge and marked specialty = 10 Gbit, expect ~8.5 GBit/s, requires enhanced networking & VPC for full throughput

m1 small, medium, and large instances tend to perform higher than expected. c1.medium is another freak, at 800 MBit/s.

I gathered this by combing dozens of sources doing benchmarks (primarily using iPerf & TCP connections). Credit to CloudHarmony & flux7 in particular for many of the benchmarks (note that those two links go to google searches showing the numerous individual benchmarks).

Caveats & Notes:

The large instance size has the most variation reported:

  • m1.large is ~800 Mbit/s (!!!)
  • t2.large = ~500 MBit/s
  • c3.large = ~500-570 Mbit/s (different results from different sources)
  • c4.large = ~520 MBit/s (I've confirmed this independently, by the way)
  • m3.large is better at ~700 MBit/s
  • m4.large is ~445 Mbit/s
  • r3.large is ~390 Mbit/s

Burstable (T2) instances appear to exhibit burstable networking performance too:

  • The CloudHarmony iperf benchmarks show initial transfers start at 1 GBit/s and then gradually drop to the sustained levels above after a few minutes. PDF links to reports below:

  • t2.small (PDF)

  • t2.medium (PDF)
  • t2.large (PDF)

Note that these are within the same region - if you're transferring across regions, real performance may be much slower. Even for the larger instances, I'm seeing numbers of a few hundred MBit/s.

Alternative for frames in html5 using iframes

HTML 5 does support iframes. There were a few interesting attributes added like "sandbox" and "srcdoc".

http://www.w3schools.com/html5/tag_iframe.asp

or you can use

<object data="framed.html" type="text/html"><p>This is the fallback code!</p></object>

What is the equivalent to getch() & getche() in Linux?

#include <unistd.h>
#include <termios.h>

char getch(void)
{
    char buf = 0;
    struct termios old = {0};
    fflush(stdout);
    if(tcgetattr(0, &old) < 0)
        perror("tcsetattr()");
    old.c_lflag &= ~ICANON;
    old.c_lflag &= ~ECHO;
    old.c_cc[VMIN] = 1;
    old.c_cc[VTIME] = 0;
    if(tcsetattr(0, TCSANOW, &old) < 0)
        perror("tcsetattr ICANON");
    if(read(0, &buf, 1) < 0)
        perror("read()");
    old.c_lflag |= ICANON;
    old.c_lflag |= ECHO;
    if(tcsetattr(0, TCSADRAIN, &old) < 0)
        perror("tcsetattr ~ICANON");
    printf("%c\n", buf);
    return buf;
 }

Remove the last printf if you don't want the character to be displayed.

Place API key in Headers or URL

passing api key in parameters makes it difficult for clients to keep their APIkeys secret, they tend to leak keys on a regular basis. A better approach is to pass it in header of request url.you can set user-key header in your code . For testing your request Url you can use Postman app in google chrome by setting user-key header to your api-key.

Pandas DataFrame concat vs append

So what are you doing is with append and concat is almost equivalent. The difference is the empty DataFrame. For some reason this causes a big slowdown, not sure exactly why, will have to look at some point. Below is a recreation of basically what you did.

I almost always use concat (though in this case they are equivalent, except for the empty frame); if you don't use the empty frame they will be the same speed.

In [17]: df1 = pd.DataFrame(dict(A = range(10000)),index=pd.date_range('20130101',periods=10000,freq='s'))

In [18]: df1
Out[18]: 
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 10000 entries, 2013-01-01 00:00:00 to 2013-01-01 02:46:39
Freq: S
Data columns (total 1 columns):
A    10000  non-null values
dtypes: int64(1)

In [19]: df4 = pd.DataFrame()

The concat

In [20]: %timeit pd.concat([df1,df2,df3])
1000 loops, best of 3: 270 us per loop

This is equavalent of your append

In [21]: %timeit pd.concat([df4,df1,df2,df3])
10 loops, best of 

 3: 56.8 ms per loop

img src SVG changing the styles with CSS

You could set your SVG as a mask. That way setting a background-color would act as your fill color.

HTML

<div class="logo"></div>

CSS

.logo {
  background-color: red;
  -webkit-mask: url(logo.svg) no-repeat center;
  mask: url(logo.svg) no-repeat center;
}

JSFiddle: https://jsfiddle.net/KuhlTime/2j8exgcb/
MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/mask

Please check whether your browser supports this feature: https://caniuse.com/#search=mask

Placeholder in UITextView


Simulating Native Placeholders


A common gripe is that iOS doesn't provide a native placeholder feature for textviews. The UITextView extension below attempts to address that concern by offering the convenience one would expect from a native feature, requiring only one line of code to add a placeholder to a textview instance.

The downside of this solution is, because it daisy chains delegate calls, it is vulnerable to (unlikely) changes to the UITextViewDelegate protocol in an iOS update. Specifically, if iOS adds new protocol methods and you implement any of them in the delegate for a text view with a placeholder, those methods won't be called unless you've also updated the extension to forward those calls.

Alternatively, the Inline Placeholder answer is a rock-solid and about as simple as can be.


Usage examples:


   • If the text view gaining the placeholder doesn't use a UITextViewDelegate:

    /* Swift 3 */

    class NoteViewController : UIViewController {
        @IBOutlet weak var noteView: UITextView!
        override func viewDidLoad() {
            noteView.addPlaceholder("Enter some text...",  color: UIColor.lightGray)
        }
    }

                                            -- OR --

   • If the text view gaining the placeholder does use a UITextViewDelegate:

    /* Swift 3 */

    class NoteViewController : UIViewController, UITextViewDelegate {
        @IBOutlet weak var noteView: UITextView!
        override func viewDidLoad() {
            noteView.addPlaceholder("Phone #", color: UIColor.lightGray, delegate: self)
        }
    }

Implementation (UITextView extension):


/* Swift 3 */

extension UITextView: UITextViewDelegate
{

    func addPlaceholder(_ placeholderText : String, 
                      color : UIColor? = UIColor.lightGray,
                      delegate : UITextViewDelegate? = nil) {

        self.delegate = self             // Make receiving textview instance a delegate
        let placeholder = UITextView()   // Need delegate storage ULabel doesn't provide
        placeholder.isUserInteractionEnabled = false  //... so we *simulate* UILabel
        self.addSubview(placeholder)     // Add to text view instance's view tree               
        placeholder.sizeToFit()          // Constrain to fit inside parent text view
        placeholder.tintColor = UIColor.clear // Unused in textviews. Can host our 'tag'
        placeholder.frame.origin = CGPoint(x: 5, y: 0) // Don't cover I-beam cursor
        placeholder.delegate = delegate  // Use as cache for caller's delegate 
        placeholder.font = UIFont.italicSystemFont(ofSize: (self.font?.pointSize)!)
        placeholder.text = placeholderText
        placeholder.textColor = color
    }

      
    func findPlaceholder() -> UITextView? { // find placeholder by its tag 
        for subview in self.subviews {
            if let textview = subview as? UITextView {
                if textview.tintColor == UIColor.clear { // sneaky tagging scheme
                    return textview
                }
            }
        }
        return nil
    }
     
    /* 
     * Safely daisychain to caller delegate methods as appropriate...
     */

    public func textViewDidChange(_ textView: UITextView) { // ?  need this delegate method
        if let placeholder = findPlaceholder() {
            placeholder.isHidden = !self.text.isEmpty // ? ... to do this
            placeholder.delegate?.textViewDidChange?(textView)
        } 
    }

    /* 
     * Since we're becoming a delegate on behalf of this placeholder-enabled
     * text view instance, we must forward *all* that protocol's activity expected
     * by the instance, not just the particular optional protocol method we need to
     * intercept, above.
     */

    public func textViewDidEndEditing(_ textView: UITextView) {
        if let placeholder = findPlaceholder() {
            placeholder.delegate?.textViewDidEndEditing?(textView)
        } 
    }

    public func textViewDidBeginEditing(_ textView: UITextView) {
        if let placeholder = findPlaceholder() {
            placeholder.delegate?.textViewDidBeginEditing?(textView)
        } 
    }

    public  func textViewDidChangeSelection(_ textView: UITextView) {
        if let placeholder = findPlaceholder() {
            placeholder.delegate?.textViewDidChangeSelection?(textView)
        } 
    }

    public func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
        if let placeholder = findPlaceholder() {
            guard let retval = placeholder.delegate?.textViewShouldEndEditing?(textView) else {
                return true
            }
            return retval
        }
        return true
    }

    public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        if let placeholder = findPlaceholder() {
            guard let retval = placeholder.delegate?.textViewShouldBeginEditing?(textView) else {
                return true
            }
            return retval
        } 
        return true
    }

    public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if let placeholder = findPlaceholder() {
            guard let retval = placeholder.delegate?.textView?(textView, shouldChangeTextIn: range, replacementText: text) else {
                return true
            }
            return retval
        } 
        return true
    }

    public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        if let placeholder = findPlaceholder() {
                guard let retval = placeholder.delegate?.textView?(textView, shouldInteractWith: URL, in: characterRange, interaction:
                    interaction) else {
                        return true
            }
            return retval
        }
        return true
    }

    public func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        if let placeholder = findPlaceholder() {
            guard let retval = placeholder.delegate?.textView?(textView, shouldInteractWith: textAttachment, in: characterRange, interaction: interaction) else {
                return true
            }
            return retval
        }
        return true
    }
}

1. As an extension of an essential iOS class like UITextView, it's important to know that this code has no interaction with any textviews that don't activate a placeholder, e.g textview instances that haven't been initialized with a call addPlaceholder()

2. Placeholder-enabled text views transparently become a UITextViewDelegate to track character count, in order to control placeholder visibility. If a delegate is passed to addPlaceholder(), this code daisy-chains (i.e. forwards) delegate callbacks to that delegate.

3. The author is investigating ways to inspect the UITextViewDelegate protocol and proxy it automatically without having to hardcode each method. That would inoculate the code from method signature changes and new methods being added to the protocol.

Multiple WHERE clause in Linq

Also, you can use bool method(s)

Query :

DataTable tempData = (DataTable)grdUsageRecords.DataSource;
var query = from r in tempData.AsEnumerable()
            where isValid(Field<string>("UserName"))// && otherMethod() && otherMethod2()                           
            select r;   

        DataTable newDT = query.CopyToDataTable();

Method:

bool isValid(string userName)
{
    if(userName == "XXXX" || userName == "YYYY")
        return false;
    else return true;
}

What is the "realm" in basic authentication

A realm can be seen as an area (not a particular page, it could be a group of pages) for which the credentials are used; this is also the string that will be shown when the browser pops up the login window, e.g.

Please enter your username and password for <realm name>:

When the realm changes, the browser may show another popup window if it doesn't have credentials for that particular realm.

Issue with background color in JavaFX 8

panel.setStyle("-fx-background-color: #FFFFFF;");

AngularJS ui-router login authentication

I have another solution: that solution works perfectly when you have only content you want to show when you are logged in. Define a rule where you checking if you are logged in and its not path of whitelist routes.

$urlRouterProvider.rule(function ($injector, $location) {
   var UserService = $injector.get('UserService');
   var path = $location.path(), normalized = path.toLowerCase();

   if (!UserService.isLoggedIn() && path.indexOf('login') === -1) {
     $location.path('/login/signin');
   }
});

In my example i ask if i am not logged in and the current route i want to route is not part of `/login', because my whitelist routes are the following

/login/signup // registering new user
/login/signin // login to app

so i have instant access to this two routes and every other route will be checked if you are online.

Here is my whole routing file for the login module

export default (
  $stateProvider,
  $locationProvider,
  $urlRouterProvider
) => {

  $stateProvider.state('login', {
    parent: 'app',
    url: '/login',
    abstract: true,
    template: '<ui-view></ui-view>'
  })

  $stateProvider.state('signin', {
    parent: 'login',
    url: '/signin',
    template: '<login-signin-directive></login-signin-directive>'
  });

  $stateProvider.state('lock', {
    parent: 'login',
    url: '/lock',
    template: '<login-lock-directive></login-lock-directive>'
  });

  $stateProvider.state('signup', {
    parent: 'login',
    url: '/signup',
    template: '<login-signup-directive></login-signup-directive>'
  });

  $urlRouterProvider.rule(function ($injector, $location) {
    var UserService = $injector.get('UserService');
    var path = $location.path();

    if (!UserService.isLoggedIn() && path.indexOf('login') === -1) {
         $location.path('/login/signin');
    }
  });

  $urlRouterProvider.otherwise('/error/not-found');
}

() => { /* code */ } is ES6 syntax, use instead function() { /* code */ }

What does "where T : class, new()" mean?

That is a constraint on the generic parameter T. It must be a class (reference type) and must have a public parameter-less default constructor.

That means T can't be an int, float, double, DateTime or any other struct (value type).

It could be a string, or any other custom reference type, as long as it has a default or parameter-less constructor.

Grouping into interval of 5 minutes within a time range

This works with every interval.

PostgreSQL

SELECT
    TIMESTAMP WITH TIME ZONE 'epoch' +
    INTERVAL '1 second' * round(extract('epoch' from timestamp) / 300) * 300 as timestamp,
    name,
    count(b.name)
FROM time a, id 
WHERE …
GROUP BY 
round(extract('epoch' from timestamp) / 300), name


MySQL

SELECT
    timestamp,  -- not sure about that
    name,
    count(b.name)
FROM time a, id 
WHERE …
GROUP BY 
UNIX_TIMESTAMP(timestamp) DIV 300, name

Hide/Show Action Bar Option Menu Item for different fragments

Hello I got the best solution of this, suppose if u have to hide a particular item at on create Menu method and show that item in other fragment. I am taking an example of two menu item one is edit and other is delete. e.g menu xml is as given below:

sell_menu.xml

 <?xml version="1.0" encoding="utf-8"?>
 <menu xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/action_edit"
    android:icon="@drawable/ic_edit_white_shadow_24dp"
    app:showAsAction="always"
    android:title="Edit" />

<item
    android:id="@+id/action_delete"
    android:icon="@drawable/ic_delete_white_shadow_24dp"
    app:showAsAction="always"
    android:title="Delete" />

Now Override the two method in your activity & make a field variable mMenu as:

  private Menu mMenu;         //  field variable    


  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.sell_menu, menu);
    this.mMenu = menu;

    menu.findItem(R.id.action_delete).setVisible(false);
    return super.onCreateOptionsMenu(menu);
  }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.action_delete) {
       // do action
        return true;
    } else if (item.getItemId() == R.id.action_edit) {
      // do action
        return true;
    }

    return super.onOptionsItemSelected(item);
 }

Make two following method in your Activity & call them from fragment to hide and show your menu item. These method are as:

public void showDeleteImageOption(boolean status) {
    if (menu != null) {
        menu.findItem(R.id.action_delete).setVisible(status);
    }
}

public void showEditImageOption(boolean status) {
    if (menu != null) {
        menu.findItem(R.id.action_edit).setVisible(status);
    }
}

That's Solve from my side,I think this explanation will help you.

Javascript array sort and unique

Try using an external library like underscore

var f = _.compose(_.uniq, function(array) {
    return _.sortBy(array, _.identity);
});

var sortedUnique = f(array);

This relies on _.compose, _.uniq, _.sortBy, _.identity

See live example

What is it doing?

We want a function that takes an array and then returns a sorted array with the non-unique entries removed. This function needs to do two things, sorting and making the array unique.

This is a good job for composition, so we compose the unique & sort function together. _.uniq can just be applied on the array with one argument so it's just passed to _.compose

the _.sortBy function needs a sorting conditional functional. it expects a function that returns a value and the array will be sorted on that value. Since the value that we are ordering it by is the value in the array we can just pass the _.identity function.

We now have a composition of a function that (takes an array and returns a unique array) and a function that (takes an array and returns a sorted array, sorted by their values).

We simply apply the composition on the array and we have our uniquely sorted array.

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

private void OnDropDownClosed(object sender, EventArgs e)
{ 
     if (combobox.SelectedItem == null) return;
     // Do actions
}

How can I generate Unix timestamps?

In Linux or MacOS you can use:

date +%s

where

  • +%s, seconds since 1970-01-01 00:00:00 UTC. (GNU Coreutils 8.24 Date manual)

Example output now 1454000043.

Show a number to two decimal places

That's the same question I came across today and want to round a number and return float value up to a given decimal place and it must not be string (as returned from number_format) the answer is

echo sprintf('%.' . $decimalPlaces . 'f', round($number, $decimalPlaces));

How to get data from database in javascript based on the value passed to the function

Try the following:

<script> 
 //Functions to open database and to create, insert data into tables

 getSelectedRow = function(val)
    {
        db.transaction(function(transaction) {
              transaction.executeSql('SELECT * FROM Employ where number = ?;',[parseInt(val)], selectedRowValues, errorHandler);

        });
    };
    selectedRowValues = function(transaction,results)
    {
         for(var i = 0; i < results.rows.length; i++)
         {
             var row = results.rows.item(i);
             alert(row['number']);
             alert(row['name']);                 
         }
    };
</script>

You don't have access to javascript variable names in SQL, you must pass the values to the Database.

Can I pass a JavaScript variable to another browser window?

In your parent window:

var yourValue = 'something';
window.open('/childwindow.html?yourKey=' + yourValue);

Then in childwindow.html:

var query = location.search.substring(1);
var parameters = {};
var keyValues = query.split(/&/);
for (var keyValue in keyValues) {
    var keyValuePairs = keyValue.split(/=/);
    var key = keyValuePairs[0];
    var value = keyValuePairs[1];
    parameters[key] = value;
}

alert(parameters['yourKey']);

There is potentially a lot of error checking you should be doing in the parsing of your key/value pairs but I'm not including it here. Maybe someone can provide a more inclusive Javascript query string parsing routine in a later answer.

YouTube iframe API: how do I control an iframe player that's already in the HTML?

Fiddle Links: Source code - Preview - Small version
Update: This small function will only execute code in a single direction. If you want full support (eg event listeners / getters), have a look at Listening for Youtube Event in jQuery

As a result of a deep code analysis, I've created a function: function callPlayer requests a function call on any framed YouTube video. See the YouTube Api reference to get a full list of possible function calls. Read the comments at the source code for an explanation.

On 17 may 2012, the code size was doubled in order to take care of the player's ready state. If you need a compact function which does not deal with the player's ready state, see http://jsfiddle.net/8R5y6/.

/**
 * @author       Rob W <[email protected]>
 * @website      https://stackoverflow.com/a/7513356/938089
 * @version      20190409
 * @description  Executes function on a framed YouTube video (see website link)
 *               For a full list of possible functions, see:
 *               https://developers.google.com/youtube/js_api_reference
 * @param String frame_id The id of (the div containing) the frame
 * @param String func     Desired function to call, eg. "playVideo"
 *        (Function)      Function to call when the player is ready.
 * @param Array  args     (optional) List of arguments to pass to function func*/
function callPlayer(frame_id, func, args) {
    if (window.jQuery && frame_id instanceof jQuery) frame_id = frame_id.get(0).id;
    var iframe = document.getElementById(frame_id);
    if (iframe && iframe.tagName.toUpperCase() != 'IFRAME') {
        iframe = iframe.getElementsByTagName('iframe')[0];
    }

    // When the player is not ready yet, add the event to a queue
    // Each frame_id is associated with an own queue.
    // Each queue has three possible states:
    //  undefined = uninitialised / array = queue / .ready=true = ready
    if (!callPlayer.queue) callPlayer.queue = {};
    var queue = callPlayer.queue[frame_id],
        domReady = document.readyState == 'complete';

    if (domReady && !iframe) {
        // DOM is ready and iframe does not exist. Log a message
        window.console && console.log('callPlayer: Frame not found; id=' + frame_id);
        if (queue) clearInterval(queue.poller);
    } else if (func === 'listening') {
        // Sending the "listener" message to the frame, to request status updates
        if (iframe && iframe.contentWindow) {
            func = '{"event":"listening","id":' + JSON.stringify(''+frame_id) + '}';
            iframe.contentWindow.postMessage(func, '*');
        }
    } else if ((!queue || !queue.ready) && (
               !domReady ||
               iframe && !iframe.contentWindow ||
               typeof func === 'function')) {
        if (!queue) queue = callPlayer.queue[frame_id] = [];
        queue.push([func, args]);
        if (!('poller' in queue)) {
            // keep polling until the document and frame is ready
            queue.poller = setInterval(function() {
                callPlayer(frame_id, 'listening');
            }, 250);
            // Add a global "message" event listener, to catch status updates:
            messageEvent(1, function runOnceReady(e) {
                if (!iframe) {
                    iframe = document.getElementById(frame_id);
                    if (!iframe) return;
                    if (iframe.tagName.toUpperCase() != 'IFRAME') {
                        iframe = iframe.getElementsByTagName('iframe')[0];
                        if (!iframe) return;
                    }
                }
                if (e.source === iframe.contentWindow) {
                    // Assume that the player is ready if we receive a
                    // message from the iframe
                    clearInterval(queue.poller);
                    queue.ready = true;
                    messageEvent(0, runOnceReady);
                    // .. and release the queue:
                    while (tmp = queue.shift()) {
                        callPlayer(frame_id, tmp[0], tmp[1]);
                    }
                }
            }, false);
        }
    } else if (iframe && iframe.contentWindow) {
        // When a function is supplied, just call it (like "onYouTubePlayerReady")
        if (func.call) return func();
        // Frame exists, send message
        iframe.contentWindow.postMessage(JSON.stringify({
            "event": "command",
            "func": func,
            "args": args || [],
            "id": frame_id
        }), "*");
    }
    /* IE8 does not support addEventListener... */
    function messageEvent(add, listener) {
        var w3 = add ? window.addEventListener : window.removeEventListener;
        w3 ?
            w3('message', listener, !1)
        :
            (add ? window.attachEvent : window.detachEvent)('onmessage', listener);
    }
}

Usage:

callPlayer("whateverID", function() {
    // This function runs once the player is ready ("onYouTubePlayerReady")
    callPlayer("whateverID", "playVideo");
});
// When the player is not ready yet, the function will be queued.
// When the iframe cannot be found, a message is logged in the console.
callPlayer("whateverID", "playVideo");

Possible questions (& answers):

Q: It doesn't work!
A: "Doesn't work" is not a clear description. Do you get any error messages? Please show the relevant code.

Q: playVideo does not play the video.
A: Playback requires user interaction, and the presence of allow="autoplay" on the iframe. See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes and https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide

Q: I have embedded a YouTube video using <iframe src="http://www.youtube.com/embed/As2rZGPGKDY" />but the function doesn't execute any function!
A: You have to add ?enablejsapi=1 at the end of your URL: /embed/vid_id?enablejsapi=1.

Q: I get error message "An invalid or illegal string was specified". Why?
A: The API doesn't function properly at a local host (file://). Host your (test) page online, or use JSFiddle. Examples: See the links at the top of this answer.

Q: How did you know this?
A: I have spent some time to manually interpret the API's source. I concluded that I had to use the postMessage method. To know which arguments to pass, I created a Chrome extension which intercepts messages. The source code for the extension can be downloaded here.

Q: What browsers are supported?
A: Every browser which supports JSON and postMessage.

  • IE 8+
  • Firefox 3.6+ (actually 3.5, but document.readyState was implemented in 3.6)
  • Opera 10.50+
  • Safari 4+
  • Chrome 3+

Related answer / implementation: Fade-in a framed video using jQuery
Full API support: Listening for Youtube Event in jQuery
Official API: https://developers.google.com/youtube/iframe_api_reference

Revision history

  • 17 may 2012
    Implemented onYouTubePlayerReady: callPlayer('frame_id', function() { ... }).
    Functions are automatically queued when the player is not ready yet.
  • 24 july 2012
    Updated and successully tested in the supported browsers (look ahead).
  • 10 october 2013 When a function is passed as an argument, callPlayer forces a check of readiness. This is needed, because when callPlayer is called right after the insertion of the iframe while the document is ready, it can't know for sure that the iframe is fully ready. In Internet Explorer and Firefox, this scenario resulted in a too early invocation of postMessage, which was ignored.
  • 12 Dec 2013, recommended to add &origin=* in the URL.
  • 2 Mar 2014, retracted recommendation to remove &origin=* to the URL.
  • 9 april 2019, fix bug that resulted in infinite recursion when YouTube loads before the page was ready. Add note about autoplay.

How to call a function from another controller in angularjs?

If you would like to execute the parent controller's parentmethod function inside a child controller, call it:

$scope.$parent.parentmethod();

You can try it over here

What is best tool to compare two SQL Server databases (schema and data)?

I like Open DBDiff.

While not the most complete tool, it works great, it's free, and it's very easy to use.

How to delete files/subfolders in a specific directory at the command prompt in Windows

RD stands for REMOVE Directory.

/S : Delete all files and subfolders in addition to the folder itself. Use this to remove an entire folder tree.

/Q : Quiet - do not display YN confirmation

Example :

RD /S /Q C:/folder_path/here

Best XML Parser for PHP

the crxml parser is a real easy to parser.

This class has got a search function, which takes a node name with any namespace as an argument. It searches the xml for the node and prints out the access statement to access that node using this class. This class also makes xml generation very easy.

you can download this class at

http://freshmeat.net/projects/crxml

or from phpclasses.org

http://www.phpclasses.org/package/6769-PHP-Manipulate-XML-documents-as-array.html

setImmediate vs. nextTick

As an illustration

import fs from 'fs';
import http from 'http';

const options = {
  host: 'www.stackoverflow.com',
  port: 80,
  path: '/index.html'
};

describe('deferredExecution', () => {
  it('deferredExecution', (done) => {
    console.log('Start');
    setTimeout(() => console.log('TO1'), 0);
    setImmediate(() => console.log('IM1'));
    process.nextTick(() => console.log('NT1'));
    setImmediate(() => console.log('IM2'));
    process.nextTick(() => console.log('NT2'));
    http.get(options, () => console.log('IO1'));
    fs.readdir(process.cwd(), () => console.log('IO2'));
    setImmediate(() => console.log('IM3'));
    process.nextTick(() => console.log('NT3'));
    setImmediate(() => console.log('IM4'));
    fs.readdir(process.cwd(), () => console.log('IO3'));
    console.log('Done');
    setTimeout(done, 1500);
  });
});

will give the following output

Start
Done
NT1
NT2
NT3
TO1
IO2
IO3
IM1
IM2
IM3
IM4
IO1

I hope this can help to understand the difference.

Updated:

Callbacks deferred with process.nextTick() run before any other I/O event is fired, while with setImmediate(), the execution is queued behind any I/O event that is already in the queue.

Node.js Design Patterns, by Mario Casciaro (probably the best book about node.js/js)

highlight the navigation menu for the current page

I usually use a class to achieve this. It's very simple to implement to anything, navigation links, hyperlinks and etc.

In your CSS document insert:

.current,
nav li a:hover {
   /* styles go here */
   color: #e00122;
   background-color: #fffff;
}

This will make the hover state of the list items have red text and a white background. Attach that class of current to any link on the "current" page and it will display the same styles.

Im your HTML insert:

<nav>
   <ul>
      <li class="current"><a href="#">Nav Item 1</a></li>
      <li><a href="#">Nav Item 2</a></li>
      <li><a href="#">Nav Item 3</a></li>
   </ul>
</nav>

replace special characters in a string python

One way is to use re.sub, that's my preferred way.

import re
my_str = "hey th~!ere"
my_new_string = re.sub('[^a-zA-Z0-9 \n\.]', '', my_str)
print my_new_string

Output:

hey there

Another way is to use re.escape:

import string
import re

my_str = "hey th~!ere"

chars = re.escape(string.punctuation)
print re.sub(r'['+chars+']', '',my_str)

Output:

hey there

Just a small tip about parameters style in python by PEP-8 parameters should be remove_special_chars and not removeSpecialChars

Also if you want to keep the spaces just change [^a-zA-Z0-9 \n\.] to [^a-zA-Z0-9\n\.]

Redirect website after certain amount of time

You're probably looking for the meta refresh tag:

<html>
    <head>
        <meta http-equiv="refresh" content="3;url=http://www.somewhere.com/" />
    </head>
    <body>
        <h1>Redirecting in 3 seconds...</h1>
    </body>
</html>

Note that use of meta refresh is deprecated and frowned upon these days, but sometimes it's the only viable option (for example, if you're unable to do server-side generation of HTTP redirect headers and/or you need to support non-JavaScript clients etc).

Bash: Strip trailing linebreak from output

If your expected output is a single line, you can simply remove all newline characters from the output. It would not be uncommon to pipe to the tr utility, or to Perl if preferred:

wc -l < log.txt | tr -d '\n'

wc -l < log.txt | perl -pe 'chomp'

You can also use command substitution to remove the trailing newline:

echo -n "$(wc -l < log.txt)"

printf "%s" "$(wc -l < log.txt)"

If your expected output may contain multiple lines, you have another decision to make:

If you want to remove MULTIPLE newline characters from the end of the file, again use cmd substitution:

printf "%s" "$(< log.txt)"

If you want to strictly remove THE LAST newline character from a file, use Perl:

perl -pe 'chomp if eof' log.txt

Note that if you are certain you have a trailing newline character you want to remove, you can use head from GNU coreutils to select everything except the last byte. This should be quite quick:

head -c -1 log.txt

Also, for completeness, you can quickly check where your newline (or other special) characters are in your file using cat and the 'show-all' flag -A. The dollar sign character will indicate the end of each line:

cat -A log.txt

Guid is all 0's (zeros)?

Try this instead:

var responseObject = proxy.CallService(new RequestObject
{
    Data = "misc. data",
    Guid = new Guid.NewGuid()
});

This will generate a 'real' Guid value. When you new a reference type, it will give you the default value (which in this case, is all zeroes for a Guid).

When you create a new Guid, it will initialize it to all zeroes, which is the default value for Guid. It's basically the same as creating a "new" int (which is a value type but you can do this anyways):

Guid g1;                    // g1 is 00000000-0000-0000-0000-000000000000
Guid g2 = new Guid();       // g2 is 00000000-0000-0000-0000-000000000000
Guid g3 = default(Guid);    // g3 is 00000000-0000-0000-0000-000000000000
Guid g4 = Guid.NewGuid();   // g4 is not all zeroes

Compare this to doing the same thing with an int:

int i1;                     // i1 is 0
int i2 = new int();         // i2 is 0
int i3 = default(int);      // i3 is 0

Adding rows to tbody of a table using jQuery

Here is an appendTo version using the html dropdown you mentioned. It inserts another row on "change".

$('#dropdown').on( 'change', function(e) {
    $('#table').append('<tr><td>COL1</td><td>COL2</td></tr>');
});

With an example for you to play with. Best of luck!

http://jsfiddle.net/xtHaF/12/

Disable back button in react navigation

For latest version of React Navigation, even if you use null in some cases it may still show "back" written!

Go for this in your main app.js under your screen name or just go to your class file and add: -

static navigationOptions = {
   headerTitle:'Disable back Options',
   headerTitleStyle: {color:'white'},
   headerStyle: {backgroundColor:'black'},
   headerTintColor: 'red',
   headerForceInset: {vertical: 'never'},
   headerLeft: " "
}

include external .js file in node.js app

If you just want to test a library from the command line, you could do:

cat somelibrary.js mytestfile.js | node

Make a number a percentage

The best solution, where en is the English locale:

fraction.toLocaleString("en", {style: "percent"})

Bash script and /bin/bash^M: bad interpreter: No such file or directory

Your file has Windows line endings, which is confusing Linux.

Remove the spurious CR characters. You can do it with the following command:

 $ sed -i -e 's/\r$//' setup.sh

How to use Visual Studio C++ Compiler?

In Visual Studio, you can't just open a .cpp file and expect it to run. You must create a project first, or open the .cpp in some existing project.

In your case, there is no project, so there is no project to build.

Go to File --> New --> Project --> Visual C++ --> Win32 Console Application. You can uncheck "create a directory for solution". On the next page, be sure to check "Empty project".

Then, You can add .cpp files you created outside the Visual Studio by right clicking in the Solution explorer on folder icon "Source" and Add->Existing Item.

Obviously You can create new .cpp this way too (Add --> New). The .cpp file will be created in your project directory.

Then you can press ctrl+F5 to compile without debugging and can see output on console window.

Error in file(file, "rt") : cannot open the connection

I came across a solution based on a few answers popped in the thread. (windows 10)

setwd("D:/path to folder where the files are")
directory <- getwd()
myfile<- "a_file_in_the_folder.txt"
filepath=paste0(directory,"/",myfile[1],sep="")
table <- read.table(table, sep = "\t", header=T, row.names = 1, dec=",")

accessing a docker container from another container

Easiest way is to use --link, however the newer versions of docker are moving away from that and in fact that switch will be removed soon.

The link below offers a nice how too, on connecting two containers. You can skip the attach portion, since that is just a useful how to on adding items to images.

https://deis.com/blog/2016/connecting-docker-containers-1/

The part you are interested in is the communication between two containers. The easiest way, is to refer to the DB container by name from the webserver container.

Example:

you named the db container db1 and the webserver container web0. The containers should both be on the bridge network, which means the web container should be able to connect to the DB container by referring to it's name.

So if you have a web config file for your app, then for DB host you will use the name db1.

if you are using an older version of docker, then you should use --link.

Example:

Step 1: docker run --name db1 oracle/database:12.1.0.2-ee

then when you start the web app. use:

Step 2: docker run --name web0 --link db1 webapp/webapp:3.0

and the web app will be linked to the DB. However, as I said the --link switch will be removed soon.

I'd use docker compose instead, which will build a network for you. However; you will need to download docker compose for your system. https://docs.docker.com/compose/install/#prerequisites

an example setup is like this:

file name is base.yml

version: "2"
services:
  webserver:
    image: "moodlehq/moodle-php-apache:7.1
    depends_on:
      - db
    volumes:
      - "/var/www/html:/var/www/html"
      - "/home/some_user/web/apache2_faildumps.conf:/etc/apache2/conf-enabled/apache2_faildumps.conf"
    environment:
      MOODLE_DOCKER_DBTYPE: pgsql
      MOODLE_DOCKER_DBNAME: moodle
      MOODLE_DOCKER_DBUSER: moodle
      MOODLE_DOCKER_DBPASS: "m@0dl3ing"
      HTTP_PROXY: "${HTTP_PROXY}"
      HTTPS_PROXY: "${HTTPS_PROXY}"
      NO_PROXY: "${NO_PROXY}"
  db:
    image: postgres:9
    environment:
      POSTGRES_USER: moodle
      POSTGRES_PASSWORD: "m@0dl3ing"
      POSTGRES_DB: moodle
      HTTP_PROXY: "${HTTP_PROXY}"
      HTTPS_PROXY: "${HTTPS_PROXY}"
      NO_PROXY: "${NO_PROXY}"

this will name the network a generic name, I can't remember off the top of my head what that name is, unless you use the --name switch.

IE docker-compose --name setup1 up base.yml

NOTE: if you use the --name switch, you will need to use it when ever calling docker compose, so docker-compose --name setup1 down this is so you can have more then one instance of webserver and db, and in this case, so docker compose knows what instance you want to run commands against; and also so you can have more then one running at once. Great for CI/CD, if you are running test in parallel on the same server.

Docker compose also has the same commands as docker so docker-compose --name setup1 exec webserver do_some_command

best part is, if you want to change db's or something like that for unit test you can include an additional .yml file to the up command and it will overwrite any items with similar names, I think of it as a key=>value replacement.

Example:

db.yml

version: "2"
services:
  webserver:
    environment:
      MOODLE_DOCKER_DBTYPE: oci
      MOODLE_DOCKER_DBNAME: XE
  db:
    image: moodlehq/moodle-db-oracle

Then call docker-compose --name setup1 up base.yml db.yml

This will overwrite the db. with a different setup. When needing to connect to these services from each container, you use the name set under service, in this case, webserver and db.

I think this might actually be a more useful setup in your case. Since you can set all the variables you need in the yml files and just run the command for docker compose when you need them started. So a more start it and forget it setup.

NOTE: I did not use the --port command, since exposing the ports is not needed for container->container communication. It is needed only if you want the host to connect to the container, or application from outside of the host. If you expose the port, then the port is open to all communication that the host allows. So exposing web on port 80 is the same as starting a webserver on the physical host and will allow outside connections, if the host allows it. Also, if you are wanting to run more then one web app at once, for whatever reason, then exposing port 80 will prevent you from running additional webapps if you try exposing on that port as well. So, for CI/CD it is best to not expose ports at all, and if using docker compose with the --name switch, all containers will be on their own network so they wont collide. So you will pretty much have a container of containers.

UPDATE: After using features further and seeing how others have done it for CICD programs like Jenkins. Network is also a viable solution.

Example:

docker network create test_network

The above command will create a "test_network" which you can attach other containers too. Which is made easy with the --network switch operator.

Example:

docker run \
    --detach \
    --name db1 \
    --network test_network \
    -e MYSQL_ROOT_PASSWORD="${DBPASS}" \
    -e MYSQL_DATABASE="${DBNAME}" \
    -e MYSQL_USER="${DBUSER}" \
    -e MYSQL_PASSWORD="${DBPASS}" \
    --tmpfs /var/lib/mysql:rw \
    mysql:5

Of course, if you have proxy network settings you should still pass those into the containers using the "-e" or "--env-file" switch statements. So the container can communicate with the internet. Docker says the proxy settings should be absorbed by the container in the newer versions of docker; however, I still pass them in as an act of habit. This is the replacement for the "--link" switch which is going away. Once the containers are attached to the network you created you can still refer to those containers from other containers using the 'name' of the container. Per the example above that would be db1. You just have to make sure all containers are connected to the same network, and you are good to go.

For a detailed example of using network in a cicd pipeline, you can refer to this link: https://git.in.moodle.com/integration/nightlyscripts/blob/master/runner/master/run.sh

Which is the script that is ran in Jenkins for a huge integration tests for Moodle, but the idea/example can be used anywhere. I hope this helps others.

How can I open multiple files using "with open" in Python?

As of Python 2.7 (or 3.1 respectively) you can write

with open('a', 'w') as a, open('b', 'w') as b:
    do_something()

In earlier versions of Python, you can sometimes use contextlib.nested() to nest context managers. This won't work as expected for opening multiples files, though -- see the linked documentation for details.


In the rare case that you want to open a variable number of files all at the same time, you can use contextlib.ExitStack, starting from Python version 3.3:

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # Do something with "files"

Most of the time you have a variable set of files, you likely want to open them one after the other, though.

Getting CheckBoxList Item values

This will do the trick for you:

foreach (int indexChecked in checkedListBox1.CheckedIndices)
{
    string itemtxt = checkedListBox11.Items[indexChecked];
}

It will return whatever string value is in the checkedlistbox items.

How do I determine the dependencies of a .NET application?

Try compiling your .NET assembly with the option --staticlink:"Namespace.Assembly" . This forces the compiler to pull in all the dependencies at compile time. If it comes across a dependency that's not referenced it will give a warning or error message usually with the name of that assembly.

Namespace.Assembly is the assembly you suspect as having the dependency problem. Typically just statically linking this assembly will reference all dependencies transitively.

Adding asterisk to required fields in Bootstrap 3

This works for me:

CSS

.form-group.required.control-label:before{
   content: "*";
   color: red;
}

OR

.form-group.required.control-label:after{
   content: "*";
   color: red;
}

Basic HTML

<div class="form-group required control-label">
  <input class="form-control" />
</div>

Border color on default input style

You can use jquery for this by utilizing addClass() method

CSS

 .defaultInput
    {
     width: 100px;
     height:25px;
     padding: 5px;
    }

.error
{
 border:1px solid red;
}

<input type="text" class="defaultInput"/>

Jquery Code

$(document).ready({
  $('.defaultInput').focus(function(){
       $(this).addClass('error');
  });
});

Update: You can remove that error class using

$('.defaultInput').removeClass('error');

It won't remove that default style. It will remove .error class only

Replace Fragment inside a ViewPager

I also made a solution, which is working with Stacks. It's a more modular approach so u don't have to specify each Fragment and Detail Fragment in your FragmentPagerAdapter. It's build on top of the Example from ActionbarSherlock which derives if I'm right from the Google Demo App.

/**
 * This is a helper class that implements the management of tabs and all
 * details of connecting a ViewPager with associated TabHost.  It relies on a
 * trick.  Normally a tab host has a simple API for supplying a View or
 * Intent that each tab will show.  This is not sufficient for switching
 * between pages.  So instead we make the content part of the tab host
 * 0dp high (it is not shown) and the TabsAdapter supplies its own dummy
 * view to show as the tab content.  It listens to changes in tabs, and takes
 * care of switch to the correct paged in the ViewPager whenever the selected
 * tab changes.
 * 
 * Changed to support more Layers of fragments on each Tab.
 * by sebnapi (2012)
 * 
 */
public class TabsAdapter extends FragmentPagerAdapter
        implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
    private final Context mContext;
    private final TabHost mTabHost;
    private final ViewPager mViewPager;

    private ArrayList<String> mTabTags = new ArrayList<String>();
    private HashMap<String, Stack<TabInfo>> mTabStackMap = new HashMap<String, Stack<TabInfo>>();

    static final class TabInfo {
        public final String tag;
        public final Class<?> clss;
        public Bundle args;

        TabInfo(String _tag, Class<?> _class, Bundle _args) {
            tag = _tag;
            clss = _class;
            args = _args;
        }
    }

    static class DummyTabFactory implements TabHost.TabContentFactory {
        private final Context mContext;

        public DummyTabFactory(Context context) {
            mContext = context;
        }

        @Override
        public View createTabContent(String tag) {
            View v = new View(mContext);
            v.setMinimumWidth(0);
            v.setMinimumHeight(0);
            return v;
        }
    }

    public interface SaveStateBundle{
        public Bundle onRemoveFragment(Bundle outState);
    }

    public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) {
        super(activity.getSupportFragmentManager());
        mContext = activity;
        mTabHost = tabHost;
        mViewPager = pager;
        mTabHost.setOnTabChangedListener(this);
        mViewPager.setAdapter(this);
        mViewPager.setOnPageChangeListener(this);
    }

    /**
     * Add a Tab which will have Fragment Stack. Add Fragments on this Stack by using
     * addFragment(FragmentManager fm, String _tag, Class<?> _class, Bundle _args)
     * The Stack will hold always the default Fragment u add here.
     * 
     * DON'T ADD Tabs with same tag, it's not beeing checked and results in unexpected
     * beahvior.
     * 
     * @param tabSpec
     * @param clss
     * @param args
     */
    public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args){
        Stack<TabInfo> tabStack = new Stack<TabInfo>();

        tabSpec.setContent(new DummyTabFactory(mContext));
        mTabHost.addTab(tabSpec);
        String tag = tabSpec.getTag();
        TabInfo info = new TabInfo(tag, clss, args);

        mTabTags.add(tag);                  // to know the position of the tab tag 
        tabStack.add(info);
        mTabStackMap.put(tag, tabStack);
        notifyDataSetChanged();
    }

    /**
     * Will add the Fragment to Tab with the Tag _tag. Provide the Class of the Fragment
     * it will be instantiated by this object. Proivde _args for your Fragment.
     * 
     * @param fm
     * @param _tag
     * @param _class
     * @param _args
     */
    public void addFragment(FragmentManager fm, String _tag, Class<?> _class, Bundle _args){
        TabInfo info = new TabInfo(_tag, _class, _args);
        Stack<TabInfo> tabStack = mTabStackMap.get(_tag);   
        Fragment frag = fm.findFragmentByTag("android:switcher:" + mViewPager.getId() + ":" + mTabTags.indexOf(_tag));
        if(frag instanceof SaveStateBundle){
            Bundle b = new Bundle();
            ((SaveStateBundle) frag).onRemoveFragment(b);
            tabStack.peek().args = b;
        }
        tabStack.add(info);
        FragmentTransaction ft = fm.beginTransaction();
        ft.remove(frag).commit();
        notifyDataSetChanged();
    }

    /**
     * Will pop the Fragment added to the Tab with the Tag _tag
     * 
     * @param fm
     * @param _tag
     * @return
     */
    public boolean popFragment(FragmentManager fm, String _tag){
        Stack<TabInfo> tabStack = mTabStackMap.get(_tag);   
        if(tabStack.size()>1){
            tabStack.pop();
            Fragment frag = fm.findFragmentByTag("android:switcher:" + mViewPager.getId() + ":" + mTabTags.indexOf(_tag));
            FragmentTransaction ft = fm.beginTransaction();
            ft.remove(frag).commit();
            notifyDataSetChanged();
            return true;
        }
        return false;
    }

    public boolean back(FragmentManager fm) {
        int position = mViewPager.getCurrentItem();
        return popFragment(fm, mTabTags.get(position));
    }

    @Override
    public int getCount() {
        return mTabStackMap.size();
    }

    @Override
    public int getItemPosition(Object object) {
        ArrayList<Class<?>> positionNoneHack = new ArrayList<Class<?>>();
        for(Stack<TabInfo> tabStack: mTabStackMap.values()){
            positionNoneHack.add(tabStack.peek().clss);
        }   // if the object class lies on top of our stacks, we return default
        if(positionNoneHack.contains(object.getClass())){
            return POSITION_UNCHANGED;
        }
        return POSITION_NONE;
    }

    @Override
    public Fragment getItem(int position) {
        Stack<TabInfo> tabStack = mTabStackMap.get(mTabTags.get(position));
        TabInfo info = tabStack.peek();
        return Fragment.instantiate(mContext, info.clss.getName(), info.args);
    }

    @Override
    public void onTabChanged(String tabId) {
        int position = mTabHost.getCurrentTab();
        mViewPager.setCurrentItem(position);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        // Unfortunately when TabHost changes the current tab, it kindly
        // also takes care of putting focus on it when not in touch mode.
        // The jerk.
        // This hack tries to prevent this from pulling focus out of our
        // ViewPager.
        TabWidget widget = mTabHost.getTabWidget();
        int oldFocusability = widget.getDescendantFocusability();
        widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
        mTabHost.setCurrentTab(position);
        widget.setDescendantFocusability(oldFocusability);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

}

Add this for back button functionality in your MainActivity:

@Override
public void onBackPressed() {
  if (!mTabsAdapter.back(getSupportFragmentManager())) {
    super.onBackPressed();
  }
}

If u like to save the Fragment State when it get's removed. Let your Fragment implement the interface SaveStateBundle return in the function a bundle with your save state. Get the bundle after instantiation by this.getArguments().

You can instantiate a tab like this:

mTabsAdapter.addTab(mTabHost.newTabSpec("firstTabTag").setIndicator("First Tab Title"),
                FirstFragmentActivity.FirstFragmentFragment.class, null);

works similiar if u want to add a Fragment on top of a Tab Stack. Important: I think, it won't work if u want to have 2 instances of same class on top of two Tabs. I did this solution quick together, so I can only share it without providing any experience with it.

List of IP Space used by Facebook

# Bloqueio facebook
for ip in `whois -h whois.radb.net '!gAS32934' | grep /`
do
  iptables -A FORWARD -p all -d $ip -j REJECT
done

Application_Start not firing?

If you are using the System.Diagnostics.Debugger.Break(); workaround (which I think is just fine for temporary use) and it's "just not working" on your Windows 8 Machine. The reason is a bug in Visual Studio's "Just in time debugging".

The fix is as follows is to fix the key for the "Visual Studio Just-In-Time Debugger"

Open regedit and go to HKEY_CLASSES_ROOT\AppID{E62A7A31-6025-408E-87F6-81AEB0DC9347} for the ‘AppIDFlags’ registry value, set the flag to 0x8

More info here: http://connect.microsoft.com/VisualStudio/feedback/details/770786/just-in-time-debugging-operation-attempted-is-not-supported

How to switch back to 'master' with git?

For deleting the branch you have to stash the changes made on the branch or you need to commit the changes you made on the branch. Follow the below steps if you made any changes in the current branch.

  1. git stash or git commit -m "XXX"
  2. git checkout master
  3. git branch -D merchantApi

Note: Above steps will delete the branch locally.

How do I import an existing Java keystore (.jks) file into a Java installation?

You can bulk import all aliases from one keystore to another:

keytool -importkeystore -srckeystore source.jks -destkeystore dest.jks

Using "&times" word in html changes to ×

&times; stands for × in html. Use &amp;times to get &times

Regular expression to extract numbers from a string

^\s*(\w+)\s*\(\s*(\d+)\D+(\d+)\D+\)\s*$

should work. After the match, backreference 1 will contain the month, backreference 2 will contain the first number and backreference 3 the second number.

Explanation:

^     # start of string
\s*   # optional whitespace
(\w+) # one or more alphanumeric characters, capture the match
\s*   # optional whitespace
\(    # a (
\s*   # optional whitespace
(\d+) # a number, capture the match
\D+   # one or more non-digits
(\d+) # a number, capture the match
\D+   # one or more non-digits
\)    # a )
\s*   # optional whitespace
$     # end of string

How do you install GLUT and OpenGL in Visual Studio 2012?

  1. Download and install Visual C++ Express.

  2. Download and extract "freeglut 2.8.0 MSVC Package" from http://www.transmissionzero.co.uk/software/freeglut-devel/

  3. Installation for Windows 32 bit:

(a) Copy all files from include/GL folder and paste into C:\Program Files\Microsoft SDKs\Windows\v7.0A\Include\gl folder.

(b) Copy all files from lib folder and paste into C:\Program Files\Microsoft SDKs\Windows\v7.0A\Lib folder.

(c) Copy freeglut.dll and paste into C:\windows\system32 folder.

How to run an application as "run as administrator" from the command prompt?

It looks like psexec -h is the way to do this:

 -h         If the target system is Windows Vista or higher, has the process
            run with the account's elevated token, if available.

Which... doesn't seem to be listed in the online documentation in Sysinternals - PsExec.

But it works on my machine.

AppSettings get value from .config file

Give this a go:

string filePath = ConfigurationManager.AppSettings["ClientsFilePath"];

Simple Digit Recognition OCR in OpenCV-Python

OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.

Data Used


This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.

Below is the implementation.




import numpy as np
import cv2
   
      
# Read the image
image = cv2.imread('digits.png')
  
# gray scale conversion
gray_img = cv2.cvtColor(image,
                        cv2.COLOR_BGR2GRAY)
  
# We will divide the image
# into 5000 small dimensions 
# of size 20x20
divisions = list(np.hsplit(i,100) for i in np.vsplit(gray_img,50))
  
# Convert into Numpy array
# of size (50,100,20,20)
NP_array = np.array(divisions)
   
# Preparing train_data
# and test_data.
# Size will be (2500,20x20)
train_data = NP_array[:,:50].reshape(-1,400).astype(np.float32)
  
# Size will be (2500,20x20)
test_data = NP_array[:,50:100].reshape(-1,400).astype(np.float32)
  
# Create 10 different labels 
# for each type of digit
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = np.repeat(k,250)[:,np.newaxis]
   
# Initiate kNN classifier
knn = cv2.ml.KNearest_create()
  
# perform training of data
knn.train(train_data,
          cv2.ml.ROW_SAMPLE, 
          train_labels)
   
# obtain the output from the
# classifier by specifying the
# number of neighbors.
ret, output ,neighbours,
distance = knn.findNearest(test_data, k = 3)
   
# Check the performance and
# accuracy of the classifier.
# Compare the output with test_labels
# to find out how many are wrong.
matched = output==test_labels
correct_OP = np.count_nonzero(matched)
   
#Calculate the accuracy.
accuracy = (correct_OP*100.0)/(output.size)
   
# Display accuracy.
print(accuracy)


Output

91.64


Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).

1) My first question was about letter_recognition.data file that comes with OpenCV samples. I wanted to know what is inside that file.

It contains a letter, along with 16 features of that letter.

And this SOF helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers. (Although I didn't understand some of the features at the end)

2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.

So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)

I took the below image for my training data:

enter image description here

(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).

To prepare the data for training, I made a small code in OpenCV. It does the following things:

  1. It loads the image.
  2. Selects the digits (obviously by contour finding and applying constraints on area and height of letters to avoid false detections).
  3. Draws the bounding rectangle around one letter and wait for key press manually. This time we press the digit key ourselves corresponding to the letter in the box.
  4. Once the corresponding digit key is pressed, it resizes this box to 10x10 and saves all 100 pixel values in an array (here, samples) and corresponding manually entered digit in another array(here, responses).
  5. Then save both the arrays in separate .txt files.

At the end of the manual classification of digits, all the digits in the training data (train.png) are labeled manually by ourselves, image will look like below:

enter image description here

Below is the code I used for the above purpose (of course, not so clean):

import sys

import numpy as np
import cv2

im = cv2.imread('pitrain.png')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

#################      Now finding Contours         ###################

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

samples =  np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            cv2.imshow('norm',im)
            key = cv2.waitKey(0)

            if key == 27:  # (escape to quit)
                sys.exit()
            elif key in keys:
                responses.append(int(chr(key)))
                sample = roismall.reshape((1,100))
                samples = np.append(samples,sample,0)

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"

np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)

Now we enter in to training and testing part.

For the testing part, I used the below image, which has the same type of letters I used for the training phase.

enter image description here

For training we do as follows:

  1. Load the .txt files we already saved earlier
  2. create an instance of the classifier we are using (it is KNearest in this case)
  3. Then we use KNearest.train function to train the data

For testing purposes, we do as follows:

  1. We load the image used for testing
  2. process the image as earlier and extract each digit using contour methods
  3. Draw a bounding box for it, then resize it to 10x10, and store its pixel values in an array as done earlier.
  4. Then we use KNearest.find_nearest() function to find the nearest item to the one we gave. ( If lucky, it recognizes the correct digit.)

I included last two steps (training and testing) in single code below:

import cv2
import numpy as np

#######   training part    ############### 
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))

model = cv2.KNearest()
model.train(samples,responses)

############################# testing part  #########################

im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            roismall = roismall.reshape((1,100))
            roismall = np.float32(roismall)
            retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
            string = str(int((results[0][0])))
            cv2.putText(out,string,(x,y+h),0,1,(0,255,0))

cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)

And it worked, below is the result I got:

enter image description here


Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.

But anyway, this is a good start to go for beginners (I hope so).

Double.TryParse or Convert.ToDouble - which is faster and safer?

To start with, I'd use double.Parse rather than Convert.ToDouble in the first place.

As to whether you should use Parse or TryParse: can you proceed if there's bad input data, or is that a really exceptional condition? If it's exceptional, use Parse and let it blow up if the input is bad. If it's expected and can be cleanly handled, use TryParse.

How to disable Paste (Ctrl+V) with jQuery?

You can catch key event :

function checkEventObj ( _event_ ){
    // --- IE explorer
    if ( window.event )
        return window.event;
    // --- Netscape and other explorers
    else
        return _event_;
}

document.keydown = function(_event) {
    var e = checkEventObject(_event);

    if( e.ctrlKey && (e.keyCode == 86) )
        window.clipboardData.clearData();
}

Not tested but, could help.

Source from comentcamarche and Zakaria

Understanding esModuleInterop in tsconfig file

Problem statement

Problem occurs when we want to import CommonJS module into ES6 module codebase.

Before these flags we had to import CommonJS modules with star (* as something) import:

// node_modules/moment/index.js
exports = moment
// index.ts file in our app
import * as moment from 'moment'
moment(); // not compliant with es6 module spec

// transpiled js (simplified):
const moment = require("moment");
moment();

We can see that * was somehow equivalent to exports variable. It worked fine, but it wasn't compliant with es6 modules spec. In spec, the namespace record in star import (moment in our case) can be only a plain object, not callable (moment() is not allowed).

Solution

With flag esModuleInterop we can import CommonJS modules in compliance with es6 modules spec. Now our import code looks like this:

// index.ts file in our app
import moment from 'moment'
moment(); // compliant with es6 module spec

// transpiled js with esModuleInterop (simplified):
const moment = __importDefault(require('moment'));
moment.default();

It works and it's perfectly valid with es6 modules spec, because moment is not namespace from star import, it's default import.

But how does it work? As you can see, because we did a default import, we called the default property on a moment object. But we didn't declare a default property on the exports object in the moment library. The key is the __importDefault function. It assigns module (exports) to the default property for CommonJS modules:

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};

As you can see, we import es6 modules as they are, but CommonJS modules are wrapped into an object with the default key. This makes it possible to import defaults on CommonJS modules.

__importStar does the similar job - it returns untouched esModules, but translates CommonJS modules into modules with a default property:

// index.ts file in our app
import * as moment from 'moment'

// transpiled js with esModuleInterop (simplified):
const moment = __importStar(require("moment"));
// note that "moment" is now uncallable - ts will report error!
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};

Synthetic imports

And what about allowSyntheticDefaultImports - what is it for? Now the docs should be clear:

Allow default imports from modules with no default export. This does not affect code emit, just typechecking.

In moment typings we don't have specified default export, and we shouldn't have, because it's available only with flag esModuleInterop on. So allowSyntheticDefaultImports will not report an error if we want to import default from a third-party module which doesn't have a default export.

Nginx location priority

It fires in this order.

  1. = (exactly)

    location = /path

  2. ^~ (forward match)

    location ^~ /path

  3. ~ (regular expression case sensitive)

    location ~ /path/

  4. ~* (regular expression case insensitive)

    location ~* .(jpg|png|bmp)

  5. /

    location /path

Generating a PNG with matplotlib when DISPLAY is undefined

When signing into the server to execute the code use this instead:

ssh -X username@servername

the -X will get rid of the no display name and no $DISPLAY environment variable error

:)

Python map object is not subscriptable

map() doesn't return a list, it returns a map object.

You need to call list(map) if you want it to be a list again.

Even better,

from itertools import imap
payIntList = list(imap(int, payList))

Won't take up a bunch of memory creating an intermediate object, it will just pass the ints out as it creates them.

Also, you can do if choice.lower() == 'n': so you don't have to do it twice.

Python supports +=: you can do payIntList[i] += 1000 and numElements += 1 if you want.

If you really want to be tricky:

from itertools import count
for numElements in count(1):
    payList.append(raw_input("Enter the pay amount: "))
    if raw_input("Do you wish to continue(y/n)?").lower() == 'n':
         break

and / or

for payInt in payIntList:
    payInt += 1000
    print payInt

Also, four spaces is the standard indent amount in Python.

How to open generated pdf using jspdf in new window

This solution working for me

window.open(doc.output('bloburl'))

Extract code country from phone number [libphonenumber]

Here's a an answer how to find country calling code without using third-party libraries (as real developer does):

Get list of all available country codes, Wikipedia can help here: https://en.wikipedia.org/wiki/List_of_country_calling_codes

Parse data in a tree structure where each digit is a branch.

Traverse your tree digit by digit until you are at the last branch - that's your country code.

Xpath for href element

Try below locator.

selenium.click("css=a[href*='listDetails.do'][id='oldcontent']");

or

selenium.click("xpath=//a[contains(@href,'listDetails.do') and @id='oldcontent']");

How to install PIP on Python 3.6?

I Used these commands in Centos 7

yum install python36
yum install python36-devel
yum install python36-pip
yum install python36-setuptools
easy_install-3.6 pip

to check the pip version:

pip3 -V
pip 18.0 from /usr/local/lib/python3.6/site-packages/pip-18.0-py3.6.egg/pip (python 3.6)

I'm trying to use python in powershell

The Directory is not set correctly so Please follow these steps.

  1. "MyComputer">Right Click>Properties>"System Properties">"Advanced" tab
  2. "Environment Variables">"Path">"Edit"
  3. In the "Variable value" box, Make sure you see following:

    ;c:\python27\;c:\python27\scripts

  4. Click "OK", Test this change by restarting your windows powershell. Type

    python

  5. Now python version 2 runs! yay!

Does swift have a trim method on String?

I created this function that allows to enter a string and returns a list of string trimmed by any character

 func Trim(input:String, character:Character)-> [String]
{
    var collection:[String] = [String]()
    var index  = 0
    var copy = input
    let iterable = input
    var trim = input.startIndex.advancedBy(index)

    for i in iterable.characters

    {
        if (i == character)
        {

            trim = input.startIndex.advancedBy(index)
            // apennding to the list
            collection.append(copy.substringToIndex(trim))

            //cut the input
            index += 1
            trim = input.startIndex.advancedBy(index)
            copy = copy.substringFromIndex(trim)

            index = 0
        }
        else
        {
            index += 1
        }
    }
    collection.append(copy)
    return collection

}

as didn't found a way to do this in swift (compiles and work perfectly in swift 2.0)

How to load up CSS files using Javascript?

There is a general jquery plugin that loads css and JS files synch and asych on demand. It also keeps track off what is already been loaded :) see: http://code.google.com/p/rloader/

How to set session attribute in java?

Try this.

<%@page language="java" session="true" %>

Best TCP port number range for internal applications

I decided to download the assigned port numbers from IANA, filter out the used ports, and sort each "Unassigned" range in order of most ports available, descending. This did not work, since the csv file has ranges marked as "Unassigned" that overlap other port number reservations. I manually expanded the ranges of assigned port numbers, leaving me with a list of all assigned port numbers. I then sorted that list and generated my own list of unassigned ranges.

Since this stackoverflow.com page ranked very high in my search about the topic, I figured I'd post the largest ranges here for anyone else who is interested. These are for both TCP and UDP where the number of ports in the range is at least 500.

Total   Start   End
829     29170   29998
815     38866   39680
710     41798   42507
681     43442   44122
661     46337   46997
643     35358   36000
609     36866   37474
596     38204   38799
592     33657   34248
571     30261   30831
563     41231   41793
542     21011   21552
528     28590   29117
521     14415   14935
510     26490   26999

Source (via the CSV download button):

http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml

Set timeout for ajax (jQuery)

You could use the timeout setting in the ajax options like this:

$.ajax({
    url: "test.html",
    timeout: 3000,
    error: function(){
        //do something
    },
    success: function(){
        //do something
    }
});

Read all about the ajax options here: http://api.jquery.com/jQuery.ajax/

Remember that when a timeout occurs, the error handler is triggered and not the success handler :)

Create a <ul> and fill it based on a passed array

You may also consider the following solution:

let sum = options.set0.concat(options.set1);
const codeHTML = '<ol>' + sum.reduce((html, item) => {
    return html + "<li>" + item + "</li>";
        }, "") + '</ol>';
document.querySelector("#list").innerHTML = codeHTML;

How to read a file in Groovy into a string?

The shortest way is indeed just

String fileContents = new File('/path/to/file').text

but in this case you have no control on how the bytes in the file are interpreted as characters. AFAIK groovy tries to guess the encoding here by looking at the file content.

If you want a specific character encoding you can specify a charset name with

String fileContents = new File('/path/to/file').getText('UTF-8')

See API docs on File.getText(String) for further reference.

How to use the toString method in Java?

toString() returns a string/textual representation of the object. Commonly used for diagnostic purposes like debugging, logging etc., the toString() method is used to read meaningful details about the object.

It is automatically invoked when the object is passed to println, print, printf, String.format(), assert or the string concatenation operator.

The default implementation of toString() in class Object returns a string consisting of the class name of this object followed by @ sign and the unsigned hexadecimal representation of the hash code of this object using the following logic,

getClass().getName() + "@" + Integer.toHexString(hashCode())

For example, the following

public final class Coordinates {

    private final double x;
    private final double y;

    public Coordinates(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public static void main(String[] args) {
        Coordinates coordinates = new Coordinates(1, 2);
        System.out.println("Bourne's current location - " + coordinates);
    }
}

prints

Bourne's current location - Coordinates@addbf1 //concise, but not really useful to the reader

Now, overriding toString() in the Coordinates class as below,

@Override
public String toString() {
    return "(" + x + ", " + y + ")";
}

results in

Bourne's current location - (1.0, 2.0) //concise and informative

The usefulness of overriding toString() becomes even more when the method is invoked on collections containing references to these objects. For example, the following

public static void main(String[] args) {
    Coordinates bourneLocation = new Coordinates(90, 0);
    Coordinates bondLocation = new Coordinates(45, 90);
    Map<String, Coordinates> locations = new HashMap<String, Coordinates>();
    locations.put("Jason Bourne", bourneLocation);
    locations.put("James Bond", bondLocation);
    System.out.println(locations);
}

prints

{James Bond=(45.0, 90.0), Jason Bourne=(90.0, 0.0)}

instead of this,

{James Bond=Coordinates@addbf1, Jason Bourne=Coordinates@42e816}

Few implementation pointers,

  1. You should almost always override the toString() method. One of the cases where the override wouldn't be required is utility classes that group static utility methods, in the manner of java.util.Math. The case of override being not required is pretty intuitive; almost always you would know.
  2. The string returned should be concise and informative, ideally self-explanatory.
  3. At least, the fields used to establish equivalence between two different objects i.e. the fields used in the equals() method implementation should be spit out by the toString() method.
  4. Provide accessors/getters for all of the instance fields that are contained in the string returned. For example, in the Coordinates class,

    public double getX() {
        return x;
    }
    public double getY() {
        return y;
    }
    

A comprehensive coverage of the toString() method is in Item 10 of the book, Effective Java™, Second Edition, By Josh Bloch.

Retrieve specific commit from a remote Git repository

Finally i found a way to clone specific commit using git cherry-pick. Assuming you don't have any repository in local and you are pulling specific commit from remote,

1) create empty repository in local and git init

2) git remote add origin "url-of-repository"

3) git fetch origin [this will not move your files to your local workspace unless you merge]

4) git cherry-pick "Enter-long-commit-hash-that-you-need"

Done.This way, you will only have the files from that specific commit in your local.

Enter-long-commit-hash:

You can get this using -> git log --pretty=oneline

Query EC2 tags from within instance

You can use a combination of the AWS metadata tool (to retrieve your instance ID) and the new Tag API to retrieve the tags for the current instance.

Pull is not possible because you have unmerged files, git stash doesn't work. Don't want to commit

I've had the same error and I solve it with: git merge -s recursive -X theirs origin/master

How can you debug a CORS request with cURL?

The bash script "corstest" below works for me. It is based on Jun's comment above.

usage

corstest [-v] url

examples

./corstest https://api.coindesk.com/v1/bpi/currentprice.json
https://api.coindesk.com/v1/bpi/currentprice.json Access-Control-Allow-Origin: *

the positive result is displayed in green

./corstest https://github.com/IonicaBizau/jsonrequest
https://github.com/IonicaBizau/jsonrequest does not support CORS
you might want to visit https://enable-cors.org/ to find out how to enable CORS

the negative result is displayed in red and blue

the -v option will show the full curl headers

corstest

#!/bin/bash
# WF 2018-09-20
# https://stackoverflow.com/a/47609921/1497139

#ansi colors
#http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
blue='\033[0;34m'  
red='\033[0;31m'  
green='\033[0;32m' # '\e[1;32m' is too bright for white bg.
endColor='\033[0m'

#
# a colored message 
#   params:
#     1: l_color - the color of the message
#     2: l_msg - the message to display
#
color_msg() {
  local l_color="$1"
  local l_msg="$2"
  echo -e "${l_color}$l_msg${endColor}"
}


#
# show the usage
#
usage() {
  echo "usage: [-v] $0 url"
  echo "  -v |--verbose: show curl result" 
  exit 1 
}

if [ $# -lt 1 ]
then
  usage
fi

# commandline option
while [  "$1" != ""  ]
do
  url=$1
  shift

  # optionally show usage
  case $url in      
    -v|--verbose)
       verbose=true;
       ;;          
  esac
done  


if [ "$verbose" = "true" ]
then
  curl -s -X GET $url -H 'Cache-Control: no-cache' --head 
fi
origin=$(curl -s -X GET $url -H 'Cache-Control: no-cache' --head | grep -i access-control)


if [ $? -eq 0 ]
then
  color_msg $green "$url $origin"
else
  color_msg $red "$url does not support CORS"
  color_msg $blue "you might want to visit https://enable-cors.org/ to find out how to enable CORS"
fi

PHP Warning: Invalid argument supplied for foreach()

This means that you are doing a foreach on something that is not an array.

Check out all your foreach statements, and look if the thing before the as, to make sure it is actually an array. Use var_dump to dump it.

Then fix the one where it isn't an array.

How to reproduce this error:

<?php
$skipper = "abcd";
foreach ($skipper as $item){       //the warning happens on this line.
    print "ok";
}
?>

Make sure $skipper is an array.

How to hide html source & disable right click and text copy?

You potentially can not prevent user from viewing the HTML source content. The site that you have listed prevents user from right click. but fact is you can still do CTRL + U in Firefox to view source!

How to replace a character with a newline in Emacs?

inline just: C-M-S-% (if binding keys still default) than replace-string^J

WebSockets and Apache proxy : how to configure mod_proxy_wstunnel?

For "polling" transport.

Apache side:

<VirtualHost *:80>
    ServerName mysite.com
    DocumentRoot /my/path


    ProxyRequests Off

    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    ProxyPass /my-connect-3001 http://127.0.0.1:3001/socket.io
    ProxyPassReverse /my-connect-3001 http://127.0.0.1:3001/socket.io   
</VirtualHost>

Client side:

var my_socket = new io.Manager(null, {
    host: 'mysite.com',
    path: '/my-connect-3001'
    transports: ['polling'],
}).socket('/');

Starting of Tomcat failed from Netbeans

None of the answers here solved my issue (as at February 2020), so I raised an issue at https://issues.apache.org/jira/browse/NETBEANS-3903 and Netbeans fixed the issue!

They're working on a pull request so the fix will be in a future .dmg installer soon, but in the meantime you can copy a file referenced in the bug and replace one in your netbeans modules folder.

Tip - if you right click on Applications > Netbeans and choose Show Package Contents Show Package Contents then you can find and replace the file org-netbeans-modules-tomcat5.jar that they refer to in your Netbeans folder, e.g. within /Applications/NetBeans/Apache NetBeans 11.2.app/Contents/Resources/NetBeans/netbeans/enterprise/modules

How to find schema name in Oracle ? when you are connected in sql session using read only user

How about the following 3 statements?

-- change to your schema

ALTER SESSION SET CURRENT_SCHEMA=yourSchemaName;

-- check current schema

SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL;

-- generate drop table statements

SELECT 'drop table ', table_name, 'cascade constraints;' FROM ALL_TABLES WHERE OWNER = 'yourSchemaName';

COPY the RESULT and PASTE and RUN.

How to use a PHP class from another file?

Use include_once instead.
This error means that you have already included this file.

include_once(LIB.'/class.php');

How to access a dictionary key value present inside a list?

Index the list then the dict.

print L[1]['d']

Node.js get file extension

import extname in order to return the extension the file:

import { extname } from 'path';
extname(file.originalname);

where file is the file 'name' of form

How to prevent a double-click using jQuery?

I have the similar issue. You can use setTimeout() to avoid the double-click.

//some codes here above after the click then disable it

// also check here if there's an attribute disabled

// if there's an attribute disabled in the btn tag then // return. Convert that into js.

$('#btn1').prop("disabled", true);

setTimeout(function(){
    $('#btn1').prop("disabled", false);
}, 300);

Spring Could not Resolve placeholder

Hopefully it will be still helpful, the application.properties (or application.yml) file must be in both the paths:

  • src/main/resource/config
  • src/test/resource/config

containing the same property you are referring

How can I create a link to a local file on a locally-run web page?

Janky at best

<a href="file://///server/folders/x/x/filename.ext">right click </a></td>

and then right click, select "copy location" option, and then paste into url.

How can I get a channel ID from YouTube?

An alternative to get youtube channel ID by channel url without API:

function get_youtube_channel_ID($url){
  $html = file_get_contents($url);
  preg_match("'<meta itemprop=\"channelId\" content=\"(.*?)\"'si", $html, $match);
  if($match && $match[1])
    return $match[1];
}

Laravel - display a PDF file in storage without forcing download?

I am using Laravel 5.4 and response()->file('path/to/file.ext') to open e.g. a pdf in inline-mode in browsers. This works quite well, but when a user wants to save the file, the save-dialog suggests the last part of the url as filename.

I already tried adding a headers-array like mentioned in the Laravel-docs, but this doesn't seem to override the header set by the file()-method:

return response()->file('path/to/file.ext', [
  'Content-Disposition' => 'inline; filename="'. $fileNameFromDb .'"'
]);

Copy files on Windows Command Line with Progress

I used the copy command with the /z switch for copying over network drives. Also works for copying between local drives. Tested on XP Home edition.

Should I use Python 32bit or Python 64bit

Use the 64 bit version only if you have to work with heavy amounts of data, in that scenario, the 64 bits performs better with the inconvenient that John La Rooy said; if not, stick with the 32 bits.

How should a model be structured in MVC?

In my case I have a database class that handle all the direct database interaction such as querying, fetching, and such. So if I had to change my database from MySQL to PostgreSQL there won't be any problem. So adding that extra layer can be useful.

Each table can have its own class and have its specific methods, but to actually get the data, it lets the database class handle it:

File Database.php

class Database {
    private static $connection;
    private static $current_query;
    ...

    public static function query($sql) {
        if (!self::$connection){
            self::open_connection();
        }
        self::$current_query = $sql;
        $result = mysql_query($sql,self::$connection);

        if (!$result){
            self::close_connection();
            // throw custom error
            // The query failed for some reason. here is query :: self::$current_query
            $error = new Error(2,"There is an Error in the query.\n<b>Query:</b>\n{$sql}\n");
            $error->handleError();
        }
        return $result;
    }
 ....

    public static function find_by_sql($sql){
        if (!is_string($sql))
            return false;

        $result_set = self::query($sql);
        $obj_arr = array();
        while ($row = self::fetch_array($result_set))
        {
            $obj_arr[] = self::instantiate($row);
        }
        return $obj_arr;
    }
}

Table object classL

class DomainPeer extends Database {

    public static function getDomainInfoList() {
        $sql = 'SELECT ';
        $sql .='d.`id`,';
        $sql .='d.`name`,';
        $sql .='d.`shortName`,';
        $sql .='d.`created_at`,';
        $sql .='d.`updated_at`,';
        $sql .='count(q.id) as queries ';
        $sql .='FROM `domains` d ';
        $sql .='LEFT JOIN queries q on q.domainId = d.id ';
        $sql .='GROUP BY d.id';
        return self::find_by_sql($sql);
    }

    ....
}

I hope this example helps you create a good structure.

Ordering by the order of values in a SQL IN() clause

Two solutions that spring to mind:

  1. order by case id when 123 then 1 when 456 then 2 else null end asc

  2. order by instr(','||id||',',',123,456,') asc

(instr() is from Oracle; maybe you have locate() or charindex() or something like that)

getResources().getColor() is deprecated

It looks like the best approach is to use:

ContextCompat.getColor(context, R.color.color_name)

eg:

yourView.setBackgroundColor(ContextCompat.getColor(applicationContext,
                            R.color.colorAccent))

This will choose the Marshmallow two parameter method or the pre-Marshmallow method appropriately.

Should CSS always preceed Javascript?

I think this wont be true for all the cases. Because css will download parallel but js cant. Consider for the same case,

Instead of having single css, take 2 or 3 css files and try it out these ways,

1) css..css..js 2) css..js..css 3) js..css..css

I'm sure css..css..js will give better result than all others.

Filter rows which contain a certain string

edit included the newer across() syntax

Here's another tidyverse solution, using filter(across()) or previously filter_at. The advantage is that you can easily extend to more than one column.

Below also a solution with filter_all in order to find the string in any column, using diamonds as example, looking for the string "V"

library(tidyverse)

String in only one column

# for only one column... extendable to more than one creating a column list in `across` or `vars`!
mtcars %>% 
  rownames_to_column("type") %>% 
  filter(across(type, ~ !grepl('Toyota|Mazda', .))) %>%
  head()
#>                type  mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#> 1        Datsun 710 22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
#> 2    Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
#> 3 Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
#> 4           Valiant 18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
#> 5        Duster 360 14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
#> 6         Merc 240D 24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2

The now superseded syntax for the same would be:

mtcars %>% 
  rownames_to_column("type") %>% 
  filter_at(.vars= vars(type), all_vars(!grepl('Toyota|Mazda',.))) 

String in all columns:

# remove all rows where any column contains 'V'
diamonds %>%
  filter(across(everything(), ~ !grepl('V', .))) %>%
  head
#> # A tibble: 6 x 10
#>   carat cut     color clarity depth table price     x     y     z
#>   <dbl> <ord>   <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#> 1  0.23 Ideal   E     SI2      61.5    55   326  3.95  3.98  2.43
#> 2  0.21 Premium E     SI1      59.8    61   326  3.89  3.84  2.31
#> 3  0.31 Good    J     SI2      63.3    58   335  4.34  4.35  2.75
#> 4  0.3  Good    J     SI1      64      55   339  4.25  4.28  2.73
#> 5  0.22 Premium F     SI1      60.4    61   342  3.88  3.84  2.33
#> 6  0.31 Ideal   J     SI2      62.2    54   344  4.35  4.37  2.71

The now superseded syntax for the same would be:

diamonds %>% 
  filter_all(all_vars(!grepl('V', .))) %>%
  head

I tried to find an across alternative for the following, but I didn't immediately come up with a good solution:

    #get all rows where any column contains 'V'
    diamonds %>%
    filter_all(any_vars(grepl('V',.))) %>%
      head
    #> # A tibble: 6 x 10
    #>   carat cut       color clarity depth table price     x     y     z
    #>   <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
    #> 1 0.23  Good      E     VS1      56.9    65   327  4.05  4.07  2.31
    #> 2 0.290 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63
    #> 3 0.24  Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48
    #> 4 0.24  Very Good I     VVS1     62.3    57   336  3.95  3.98  2.47
    #> 5 0.26  Very Good H     SI1      61.9    55   337  4.07  4.11  2.53
    #> 6 0.22  Fair      E     VS2      65.1    61   337  3.87  3.78  2.49

Update: Thanks to user Petr Kajzar in this answer, here also an approach for the above:

diamonds %>%
   filter(rowSums(across(everything(), ~grepl("V", .x))) > 0)

How do I tell if .NET 3.5 SP1 is installed?

Use Add/Remove programs from the Control Panel.

How can I overwrite file contents with new content in PHP?

Use file_put_contents()

file_put_contents('file.txt', 'bar');
echo file_get_contents('file.txt'); // bar
file_put_contents('file.txt', 'foo');
echo file_get_contents('file.txt'); // foo

Alternatively, if you're stuck with fopen() you can use the w or w+ modes:

'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

How do I disable directory browsing?

Try this in .htaccess:

IndexIgnore *.jpg

Converting int to string in C

Before I continue, I must warn you that itoa is NOT an ANSI function — it's not a standard C function. You should use sprintf to convert an int into a string.

itoa takes three arguments.

  • The first one is the integer to be converted.
  • The second is a pointer to an array of characters - this is where the string is going to be stored. The program may crash if you pass in a char * variable, so you should pass in a normal sized char array and it will work fine.
  • The last one is NOT the size of the array, but it's the BASE of your number - base 10 is the one you're most likely to use.

The function returns a pointer to its second argument — where it has stored the converted string.

itoa is a very useful function, which is supported by some compilers - it's a shame it isn't support by all, unlike atoi.

If you still want to use itoa, here is how should you use it. Otherwise, you have another option using sprintf (as long as you want base 8, 10 or 16 output):

char str[5];
printf("15 in binary is %s\n",  itoa(15, str, 2));

How to subtract 30 days from the current date using SQL Server

SELECT DATEADD(day,-30,date) AS before30d 
FROM...

But it is strongly recommended to keep date in datetime column, not varchar.

opening a window form from another form programmatically

This is an old question, but answering for gathering knowledge. We have an original form with a button to show the new form.

enter image description here

The code for the button click is below

private void button1_Click(object sender, EventArgs e)
{
    New_Form new_Form = new New_Form();
    new_Form.Show();
}

Now when click is made, New Form is shown. Since, you want to hide after 2 seconds we are adding a onload event to the new form designer

this.Load += new System.EventHandler(this.OnPageLoad);

This OnPageLoad function runs when that form is loaded

In NewForm.cs ,

public partial class New_Form : Form
{
    private Timer formClosingTimer;

    private void OnPageLoad(object sender, EventArgs e)
    {
        formClosingTimer = new Timer();  // Creating a new timer 
        formClosingTimer.Tick += new EventHandler(CloseForm); // Defining tick event to invoke after a time period
        formClosingTimer.Interval = 2000; // Time Interval in miliseconds
        formClosingTimer.Start(); // Starting a timer
    }
    private void CloseForm(object sender, EventArgs e)
    {
        formClosingTimer.Stop(); // Stoping timer. If we dont stop, function will be triggered in regular intervals
        this.Close(); // Closing the current form
    }
}

In this new form , a timer is used to invoke a method which closes that form.

Here is the new form which automatically closes after 2 seconds, we will be able operate on both the forms where no interference between those two forms.

enter image description here

For your knowledge,

form.close() will free the memory and we can never interact with that form again form.hide() will just hide the form, where the code part can still run

For more details about timer refer this link, https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.7.2

What is the recommended way to make a numeric TextField in JavaFX?

This is what I use:

private TextField textField;
textField.textProperty().addListener(new ChangeListener<String>() {
    @Override
    public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
        if(!newValue.matches("[0-9]*")){
            textField.setText(oldValue);
        }

    }
});

The same in lambda notation would be:

private TextField textField;
textField.textProperty().addListener((observable, oldValue, newValue) -> {
    if(!newValue.matches("[0-9]*")){
        textField.setText(oldValue);
    }
});

how to remove the first two columns in a file using shell (awk, sed, whatever)

awk '{$1=$2="";$0=$0;$1=$1}1'

Input

a b c d

Output

c d

How to turn on WCF tracing?

Instead of you manual adding the tracing enabling bit into web.config you can also try using the WCF configuration editor which comes with VS SDK to enable tracing

https://stackoverflow.com/a/16715631/2218571

Link to the issue number on GitHub within a commit message

If you want to link to a GitHub issue and close the issue, you can provide the following lines in your Git commit message:

Closes #1.
Closes GH-1.
Closes gh-1.

(Any of the three will work.) Note that this will link to the issue and also close it. You can find out more in this blog post (start watching the embedded video at about 1:40).

I'm not sure if a similar syntax will simply link to an issue without closing it.

How do I include inline JavaScript in Haml?

You can actually do what Chris Chalmers does in his answer, but you must make sure that HAML doesn't parse the JavaScript. This approach is actually useful when you need to use a different type than text/javascript, which is was I needed to do for MathJax.

You can use the plain filter to keep HAML from parsing the script and throwing an illegal nesting error:

%script{type: "text/x-mathjax-config"}
  :plain
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [["$","$"],["\\(","\\)"]]
      }
    });

How do include paths work in Visual Studio?

@RichieHindle solution is now deprecated as of Visual Studio 2012. As the VS studio prompt now states:

VC++ Directories are now available as a user property sheet that is added by default to all projects.

To set an include path you now must right-click a project and go to:

Properties/VC++ Directories/General/Include Directories

Screenshot: enter image description here

How to add a browser tab icon (favicon) for a website?

I've successfully done this for my website.

Only exception is, the SeaMonkey browser requires HTML code inserted in your <head>; whereas, the other browsers will still display the favicon.ico without any HTML insertion. Also, any browser other than IE may use other types of images, not just the .ico format. I hope this helps.

jquery-ui-dialog - How to hook into dialog close event

$( "#dialogueForm" ).dialog({
              autoOpen: false,
              height: "auto",
              width: "auto",
              modal: true,
                my: "center",
                at: "center",
                of: window,
              close : function(){
                  // functionality goes here
              }  
              });

"close" property of dialog gives the close event for the same.

-XX:MaxPermSize with or without -XX:PermSize

If you're doing some performance tuning it's often recommended to set both -XX:PermSize and -XX:MaxPermSize to the same value to increase JVM efficiency.

Here is some information:

  1. Support for large page heap on x86 and amd64 platforms
  2. Java Support for Large Memory Pages
  3. Setting the Permanent Generation Size

You can also specify -XX:+CMSClassUnloadingEnabled to enable class unloading option if you are using CMS GC. It may help to decrease the probability of Java.lang.OutOfMemoryError: PermGen space

Alternative Windows shells, besides CMD.EXE?

Try Clink. It's awesome, especially if you are used to bash keybindings and features.

(As already pointed out - there is a similar question: Is there a better Windows Console Window?)

Saving awk output to variable

#!/bin/bash

variable=`ps -ef | grep "port 10 -" | grep -v "grep port 10 -" | awk '{printf $12}'`
echo $variable

Notice that there's no space after the equal sign.

You can also use $() which allows nesting and is readable.

Matplotlib (pyplot) savefig outputs blank image

let's me give a more detail example:

import numpy as np
import matplotlib.pyplot as plt


def draw_result(lst_iter, lst_loss, lst_acc, title):
    plt.plot(lst_iter, lst_loss, '-b', label='loss')
    plt.plot(lst_iter, lst_acc, '-r', label='accuracy')

    plt.xlabel("n iteration")
    plt.legend(loc='upper left')
    plt.title(title)
    plt.savefig(title+".png")  # should before plt.show method

    plt.show()


def test_draw():
    lst_iter = range(100)
    lst_loss = [0.01 * i + 0.01 * i ** 2 for i in xrange(100)]
    # lst_loss = np.random.randn(1, 100).reshape((100, ))
    lst_acc = [0.01 * i - 0.01 * i ** 2 for i in xrange(100)]
    # lst_acc = np.random.randn(1, 100).reshape((100, ))
    draw_result(lst_iter, lst_loss, lst_acc, "sgd_method")


if __name__ == '__main__':
    test_draw()

enter image description here

WRONGTYPE Operation against a key holding the wrong kind of value php

I faced this issue when trying to set something to redis. The problem was that I previously used "set" method to set data with a certain key, like

$redis->set('persons', $persons)

Later I decided to change to "hSet" method, and I tried it this way

foreach($persons as $person){
    $redis->hSet('persons', $person->id, $person);
}

Then I got the aforementioned error. So, what I had to do is to go to redis-cli and manually delete "persons" entry with

del persons

It simply couldn't write different data structure under existing key, so I had to delete the entry and hSet then.

ES6 export default with multiple functions referring to each other

The export default {...} construction is just a shortcut for something like this:

const funcs = {
    foo() { console.log('foo') }, 
    bar() { console.log('bar') },
    baz() { foo(); bar() }
}

export default funcs

It must become obvious now that there are no foo, bar or baz functions in the module's scope. But there is an object named funcs (though in reality it has no name) that contains these functions as its properties and which will become the module's default export.

So, to fix your code, re-write it without using the shortcut and refer to foo and bar as properties of funcs:

const funcs = {
    foo() { console.log('foo') }, 
    bar() { console.log('bar') },
    baz() { funcs.foo(); funcs.bar() } // here is the fix
}

export default funcs

Another option is to use this keyword to refer to funcs object without having to declare it explicitly, as @pawel has pointed out.

Yet another option (and the one which I generally prefer) is to declare these functions in the module scope. This allows to refer to them directly:

function foo() { console.log('foo') }
function bar() { console.log('bar') }
function baz() { foo(); bar() }

export default {foo, bar, baz}

And if you want the convenience of default export and ability to import items individually, you can also export all functions individually:

// util.js

export function foo() { console.log('foo') }
export function bar() { console.log('bar') }
export function baz() { foo(); bar() }

export default {foo, bar, baz}

// a.js, using default export

import util from './util'
util.foo()

// b.js, using named exports

import {bar} from './util'
bar()

Or, as @loganfsmyth suggested, you can do without default export and just use import * as util from './util' to get all named exports in one object.

Key value pairs using JSON

var object = {
    key1 : {
        name : 'xxxxxx',
        value : '100.0'
    },
    key2 : {
        name : 'yyyyyyy',
        value : '200.0'
    },
    key3 : {
        name : 'zzzzzz',
        value : '500.0'
    },
}

If thats how your object looks and you want to loop each name and value then I would try and do something like.

$.each(object,function(key,innerjson){
    /*
        key would be key1,key2,key3
        innerjson would be the name and value **
    */

    //Alerts and logging of the variable.
    console.log(innerjson); //should show you the value    
    alert(innerjson.name); //Should say xxxxxx,yyyyyy,zzzzzzz
});

.setAttribute("disabled", false); changes editable attribute to false

the disabled attributes value is actally not considered.. usually if you have noticed the attribute is set as disabled="disabled" the "disabled" here is not necessary persay.. thus the best thing to do is to remove the attribute.

element.removeAttribute("disabled");     

also you could do

element.disabled=false;

Copy row but with new id

Let us say your table has following fields:

( pk_id int not null auto_increment primary key,
  col1 int,
  col2 varchar(10)
)

then, to copy values from one row to the other row with new key value, following query may help

insert into my_table( col1, col2 ) select col1, col2 from my_table where pk_id=?;

This will generate a new value for pk_id field and copy values from col1, and col2 of the selected row.

You can extend this sample to apply for more fields in the table.

UPDATE:
In due respect to the comments from JohnP and Martin -

We can use temporary table to buffer first from main table and use it to copy to main table again. Mere update of pk reference field in temp table will not help as it might already be present in the main table. Instead we can drop the pk field from the temp table and copy all other to the main table.

With reference to the answer by Tim Ruehsen in the referred posting:

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

Hope this helps.

Html.RenderPartial() syntax with Razor

If you are given this format it takes like a link to another page or another link.partial view majorly used for renduring the html files from one place to another.

combining two data frames of different lengths

I don't actually get an error with this.

a <- as.data.frame(matrix(c(sample(letters,50, replace=T),runif(100)), nrow=50))
b <- sample(letters,10, replace=T)
c <- cbind(a,b)

I used letters incase joining all numerics had different functionality (which it didn't). Your 'first data frame', which is actually just a vector', is just repeated 5 times in that 4th column...

But all the comments from the gurus to the question are still relevant :)

Delete an element in a JSON object

Let's assume you want to overwrite the same file:

import json

with open('data.json', 'r') as data_file:
    data = json.load(data_file)

for element in data:
    element.pop('hours', None)

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

dict.pop(<key>, not_found=None) is probably what you where looking for, if I understood your requirements. Because it will remove the hours key if present and will not fail if not present.

However I am not sure I understand why it makes a difference to you whether the hours key contains some days or not, because you just want to get rid of the whole key / value pair, right?

Now, if you really want to use del instead of pop, here is how you could make your code work:

import json

with open('data.json') as data_file:
    data = json.load(data_file)

for element in data:
    if 'hours' in element:
        del element['hours']

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

EDIT So, as you can see, I added the code to write the data back to the file. If you want to write it to another file, just change the filename in the second open statement.

I had to change the indentation, as you might have noticed, so that the file has been closed during the data cleanup phase and can be overwritten at the end.

with is what is called a context manager, whatever it provides (here the data_file file descriptor) is available ONLY within that context. It means that as soon as the indentation of the with block ends, the file gets closed and the context ends, along with the file descriptor which becomes invalid / obsolete.

Without doing this, you wouldn't be able to open the file in write mode and get a new file descriptor to write into.

I hope it's clear enough...

SECOND EDIT

This time, it seems clear that you need to do this:

with open('dest_file.json', 'w') as dest_file:
    with open('source_file.json', 'r') as source_file:
        for line in source_file:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            dest_file.write(json.dumps(element))

How do I find a particular value in an array and return its index?

The syntax you have there for your function doesn't make sense (why would the return value have a member called arr?).

To find the index, use std::distance and std::find from the <algorithm> header.

int x = std::distance(arr, std::find(arr, arr + 5, 3));

Or you can make it into a more generic function:

template <typename Iter>
size_t index_of(Iter first, Iter last, typename const std::iterator_traits<Iter>::value_type& x)
{
    size_t i = 0;
    while (first != last && *first != x)
      ++first, ++i;
    return i;
}

Here, I'm returning the length of the sequence if the value is not found (which is consistent with the way the STL algorithms return the last iterator). Depending on your taste, you may wish to use some other form of failure reporting.

In your case, you would use it like so:

size_t x = index_of(arr, arr + 5, 3);

How to call loading function with React useEffect only once

useMountEffect hook

Running a function only once after component mounts is such a common pattern that it justifies a hook of it's own that hides implementation details.

const useMountEffect = (fun) => useEffect(fun, [])

Use it in any functional component.

function MyComponent() {
    useMountEffect(function) // function will run only once after it has mounted. 
    return <div>...</div>;
}

About the useMountEffect hook

When using useEffect with a second array argument, React will run the callback after mounting (initial render) and after values in the array have changed. Since we pass an empty array, it will run only after mounting.

How to store a dataframe using Pandas

Numpy file formats are pretty fast for numerical data

I prefer to use numpy files since they're fast and easy to work with. Here's a simple benchmark for saving and loading a dataframe with 1 column of 1million points.

import numpy as np
import pandas as pd

num_dict = {'voltage': np.random.rand(1000000)}
num_df = pd.DataFrame(num_dict)

using ipython's %%timeit magic function

%%timeit
with open('num.npy', 'wb') as np_file:
    np.save(np_file, num_df)

the output is

100 loops, best of 3: 5.97 ms per loop

to load the data back into a dataframe

%%timeit
with open('num.npy', 'rb') as np_file:
    data = np.load(np_file)

data_df = pd.DataFrame(data)

the output is

100 loops, best of 3: 5.12 ms per loop

NOT BAD!

CONS

There's a problem if you save the numpy file using python 2 and then try opening using python 3 (or vice versa).

How to prevent a file from direct URL Access?

When I used it on my Webserver, can I only rename local host, like this:

RewriteEngine on 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com [NC] 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com.*$ [NC] 
RewriteRule \.(gif|jpg)$ - [F]

Select option padding not working in chrome

It seems that

Unfortunately, webkit browsers do not support styling of option tags yet.

you may find similar question here

  1. How to style a select tag's option element?
  2. Styling option value in select drop down html not work on Chrome & Safari

The most widely used cross browser solution is to use ul li

Hope it helps!

Use of "global" keyword in Python

Global makes the variable "Global"

def out():
    global x
    x = 1
    print(x)
    return


out()

print (x)

This makes 'x' act like a normal variable outside the function. If you took the global out then it would give an error since it cannot print a variable inside a function.

def out():
     # Taking out the global will give you an error since the variable x is no longer 'global' or in other words: accessible for other commands
    x = 1
    print(x)
    return


out()

print (x)

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

I ran into the same issue running Chrome via Behat/Mink and Selenium in a Docker container. After some fiddling, I arrived at the following behat.yml which supplies the switches mentioned above. Note that all of them were required for me to get it running successfully.

default:
    extensions:
        Behat\MinkExtension:
            base_url: https://my.app/
            default_session: selenium2
            selenium2:
                browser: chrome
                capabilities:
                    extra_capabilities:
                        chromeOptions:
                            args:
                                - "headless"
                                - "no-sandbox"
                                - "disable-dev-shm-usage"

Windows batch command(s) to read first line from text file

Here is a workaround using powershell:

powershell (Get-Content file.txt)[0]

(You can easily read also a range of lines with powershell (Get-Content file.txt)[0..3])

If you need to set a variable inside a batch script as the first line of file.txt you may use:

for /f "usebackq delims=" %%a in (`powershell ^(Get-Content file.txt^)[0]`) do (set "head=%%a")

Difference between DTO, VO, POJO, JavaBeans?

POJO : It is a java file(class) which doesn't extend or implement any other java file(class).

Bean: It is a java file(class) in which all variables are private, methods are public and appropriate getters and setters are used for accessing variables.

Normal class: It is a java file(class) which may consist of public/private/default/protected variables and which may or may not extend or implement another java file(class).

"Sources directory is already netbeans project" error when opening a project from existing sources

I checked the "Put NetBeans metadata in separate directory" tick and it works fine.

This is in 2. Name and Location after you choose PHP from existing source

php - add + 7 days to date format mm dd, YYYY

Another more recent and object style way to do it :

$date = new DateTime('now');
$date->add(new DateInterval('P7D'));

php doc of datetime add

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

Changing the ng-src value is actually very simple. Like this:

<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>

Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/

Substring in VBA

Test for ':' first, then take test string up to ':' or end, depending on if it was found

Dim strResult As String

' Position of :
intPos = InStr(1, strTest, ":")
If intPos > 0 Then
    ' : found, so take up to :
    strResult = Left(strTest, intPos - 1)
Else
    ' : not found, so take whole string
    strResult = strTest
End If

How do I make JavaScript beep?

There's no crossbrowser way to achieve this with pure javascript. Instead you could use a small .wav file that you play using embed or object tags.

How do you create a UIImage View Programmatically - Swift

First create UIImageView then add image in UIImageView .

    var imageView : UIImageView
    imageView  = UIImageView(frame:CGRectMake(10, 50, 100, 300));
    imageView.image = UIImage(named:"image.jpg")
    self.view.addSubview(imageView)

Only mkdir if it does not exist

Do a test

[[ -d dir ]] || mkdir dir

Or use -p option:

mkdir -p dir

C# List<string> to string with delimiter

You can use String.Join. If you have a List<string> then you can call ToArray first:

List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join(", ", names.ToArray());

In .NET 4 you don't need the ToArray anymore, since there is an overload of String.Join that takes an IEnumerable<string>.

Results:


John, Anna, Monica

How to create PDFs in an Android app?

A bit late and I have not yet tested it yet myself but another library that is under the BSD license is Android PDF Writer.

Update I have tried the library myself. Works ok with simple pdf generations (it provide methods for adding text, lines, rectangles, bitmaps, fonts). The only problem is that the generated PDF is stored in a String in memory, this may cause memory issues in large documents.

How to remove trailing and leading whitespace for user-provided input in a batch file?

I had to create a Function.

Use it as:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION


set "TextString=    Purple Cows are flying in the Air Tonight         "
echo REM ^^Notice there is whitespace at the start and end of the TextString
echo "!TextString!"
CALL:trimWhiteSpace "!TextString!" OutPutString
echo Resulting Trimmed Text: "!OutPutString!"
echo REM ^^Now there should be no White space at the start or end.

Exit /B

Add this to the bottom of your batch file:

:FUNCTIONS
@REM FUNCTIONS AREA
GOTO:EOF
EXIT /B


::TRIM FUNCTIONS AREA::
:: USAGE:
:: trimWhiteSpace "!InputText!" OutputText
:: Remember to use the "! on the input text, but NOT on the Output text.
:: The Following is Wrong: trimWhiteSpace "!InputText!" !OutputText!
:: ^^Because it has a ! around the OutPutText
:: Make Sure to add " around the InputText when running the call.
:: If you don't add the " then it will only accept the first word before a space.
::Example:
::  set "TextString=    Purple Cows are flying in the Air Tonight         "
::  echo REM ^^Notice there is whitespace at the start and end of the TextString
::  echo "!TextString!"
::  CALL:trimWhiteSpace "!TextString!" OutPutString
::  echo Resulting Trimmed Text: "!OutPutString!"
::  echo REM ^^Now there should be no White space at the start or end.

:trimWhiteSpace
set textToTrim=%~1
CALL:trimWhiteSpaceOnTheRight "!textToTrim!" OutPutString
SET textToTrim=!OutPutString!
CALL:trimWhiteSpaceOnTheLeft "!textToTrim!" OutPutString
SET %2=!OutPutString!
GOTO:EOF

:trimWhiteSpaceOnTheRight
set str=%~1
for /l %%a in (1,1,31) do if "!str:~-1!"==" " set str=!str:~0,-1!
SET %2=%str%
GOTO:EOF

:trimWhiteSpaceOnTheLeft
set str=%~1
for /f "tokens=* delims= " %%a in ("%str%") do set str=%%a
SET %2=%str%
GOTO:EOF

And remember you MUST add "SETLOCAL ENABLEDELAYEDEXPANSION" to the top of your batch file or else none of this will work properly.

SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.

Tick symbol in HTML/XHTML

I run into the same problem and none of the suggestions worked (Firefox on Windows XP).

So I found a possible workaround using image data to display a little checkmark:

span:before {
    content:url("data:image/gif;base64,R0lGODlhCgAKAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAKAAoAAAISlG8AeMq5nnsiSlsjzmpzmj0FADs=");
}

Of course you can create your own checkmark image and use a converter to add it as data:image/gif. Hope this helps.

Exploring Docker container's file system

If you are using Docker v19.03, you follow the below steps.

# find ID of your running container:

  docker ps

# create image (snapshot) from container filesystem

  docker commit 12345678904b5 mysnapshot

# explore this filesystem 

  docker run -t -i mysnapshot /bin/sh

How To Launch Git Bash from DOS Command Line?

You can add git path to environment variables

  • For x86

%SYSTEMDRIVE%\Program Files (x86)\Git\bin\

  • For x64

%PROGRAMFILES%\Git\bin\

Open cmd and write this command to open git bash

sh --login

OR

bash --login

OR

sh

OR

bash

You can see this GIF image for more details:

https://media1.giphy.com/media/WSxbZkPFY490wk3abN/giphy.gif

javascript regex : only english letters allowed

The answer that accepts empty string:

/^[a-zA-Z]*$/.test('something')

the * means 0 or more occurrences of the preceding item.

How to view the contents of an Android APK file?

There is a online decompiler for android apks

http://www.decompileandroid.com/

Upload apk from local machine

Wait some moments

download source code in zip format.

Unzip it, you can view all resources correctly but all java files are not correctly decompiled.

For full detail visit this answer

What's the difference between F5 refresh and Shift+F5 in Google Chrome browser?

The difference is not just for Chrome but for most of the web browsers.

enter image description here

F5 refreshes the web page and often reloads the same page from the cached contents of the web browser. However, reloading from cache every time is not guaranteed and it also depends upon the cache expiry.

Shift + F5 forces the web browser to ignore its cached contents and retrieve a fresh copy of the web page into the browser.

Shift + F5 guarantees loading of latest contents of the web page.
However, depending upon the size of page, it is usually slower than F5.

You may want to refer to: What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

printf formatting (%d versus %u)

The difference is simple: they cause different warning messages to be emitted when compiling:

1156942.c:7:31: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
     printf("memory address = %d\n", &a); // prints "memory add=-12"
                               ^
1156942.c:8:31: warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
     printf("memory address = %u\n", &a); // prints "memory add=65456"
                               ^

If you pass your pointer as a void* and use %p as the conversion specifier, then you get no error message:

#include <stdio.h>

int main()
{
    int a = 5;
    // check the memory address
    printf("memory address = %d\n", &a); /* wrong */
    printf("memory address = %u\n", &a); /* wrong */
    printf("memory address = %p\n", (void*)&a); /* right */
}

Java abstract interface

Why is it necessary for an interface to be "declared" abstract?

It's not.

public abstract interface Interface {
       \___.__/
           |
           '----> Neither this...

    public void interfacing();
    public abstract boolean interfacing(boolean really);
           \___.__/
               |
               '----> nor this, are necessary.
}

Interfaces and their methods are implicitly abstract and adding that modifier makes no difference.

Is there other rules that applies with an abstract interface?

No, same rules apply. The method must be implemented by any (concrete) implementing class.

If abstract is obsolete, why is it included in Java? Is there a history for abstract interface?

Interesting question. I dug up the first edition of JLS, and even there it says "This modifier is obsolete and should not be used in new Java programs".

Okay, digging even further... After hitting numerous broken links, I managed to find a copy of the original Oak 0.2 Specification (or "manual"). Quite interesting read I must say, and only 38 pages in total! :-)

Under Section 5, Interfaces, it provides the following example:

public interface Storing {
    void freezeDry(Stream s) = 0;
    void reconstitute(Stream s) = 0;
}

And in the margin it says

In the future, the " =0" part of declaring methods in interfaces may go away.

Assuming =0 got replaced by the abstract keyword, I suspect that abstract was at some point mandatory for interface methods!


Related article: Java: Abstract interfaces and abstract interface methods

Switch: Multiple values in one case?

You have to do something like:

case 1:
case 2:
case 3:
//do stuff
break;

Newtonsoft JSON Deserialize

As per the Newtonsoft Documentation you can also deserialize to an anonymous object like this:

var definition = new { Name = "" };

string json1 = @"{'Name':'James'}";
var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);

Console.WriteLine(customer1.Name);
// James

char initial value in Java

As you will see in linked discussion there is no need for initializing char with special character as it's done for us and is represented by '\u0000' character code.

So if we want simply to check if specified char was initialized just write:

if(charVariable != '\u0000'){
 actionsOnInitializedCharacter();
}

Link to question: what's the default value of char?

Shell script variable not empty (-z option)

Why would you use -z? To test if a string is non-empty, you typically use -n:

if test -n "$errorstatus"; then
  echo errorstatus is not empty
fi

What are alternatives to document.write?

Here is code that should replace document.write in-place:

document.write=function(s){
    var scripts = document.getElementsByTagName('script');
    var lastScript = scripts[scripts.length-1];
    lastScript.insertAdjacentHTML("beforebegin", s);
}

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

What is the difference between Html.Hidden and Html.HiddenFor

Every method in HtmlHelper class has a twin with For suffix. Html.Hidden takes a string as an argument that you must provide but Html.HiddenFor takes an Expression that if you view is a strongly typed view you can benefit from this and feed that method a lambda expression like this

o=>o.SomeProperty 

instead of "SomeProperty" in the case of using Html.Hidden method.

How to delete files recursively from an S3 bucket

Just saw that Amazon added a "How to Empty a Bucket" option to the AWS console menu:

http://docs.aws.amazon.com/AmazonS3/latest/UG/DeletingaBucket.html

TypeError: unsupported operand type(s) for -: 'list' and 'list'

The operations needed to be performed, require numpy arrays either created via

np.array()

or can be converted from list to an array via

np.stack()

As in the above mentioned case, 2 lists are inputted as operands it triggers the error.

Correct way to remove plugin from Eclipse

Correct way to remove install plug-in from Eclipse/STS :

Go to install folder of eclipse ----> plugin --> select required plugin and remove it.

Ex-

Step 1. 
E:\springsource\sts-3.4.0.RELEASE\plugins

Step 2. 
select and remove related plugins jars.

Why does sudo change the PATH?

PATH is an environment variable, and as such is by default reset by sudo.

You need special permissions to be permitted to do this.

From man sudo

       -E  The -E (preserve environment) option will override the env_reset
           option in sudoers(5)).  It is only available when either the match-
           ing command has the SETENV tag or the setenv option is set in sudo-
           ers(5).
       Environment variables to be set for the command may also be passed on
       the command line in the form of VAR=value, e.g.
       LD_LIBRARY_PATH=/usr/local/pkg/lib.  Variables passed on the command
       line are subject to the same restrictions as normal environment vari-
       ables with one important exception.  If the setenv option is set in
       sudoers, the command to be run has the SETENV tag set or the command
       matched is ALL, the user may set variables that would overwise be for-
       bidden.  See sudoers(5) for more information.

An Example of usage:

cat >> test.sh
env | grep "MYEXAMPLE" ;
^D
sh test.sh 
MYEXAMPLE=1 sh test.sh
# MYEXAMPLE=1
MYEXAMPLE=1 sudo sh test.sh 
MYEXAMPLE=1 sudo MYEXAMPLE=2 sh test.sh 
# MYEXAMPLE=2

update

man 5 sudoers : 

     env_reset       If set, sudo will reset the environment to only contain
                       the LOGNAME, SHELL, USER, USERNAME and the SUDO_* vari-
                       ables.  Any variables in the caller's environment that
                       match the env_keep and env_check lists are then added.
                       The default contents of the env_keep and env_check
                       lists are displayed when sudo is run by root with the
                       -V option.  If sudo was compiled with the SECURE_PATH
                       option, its value will be used for the PATH environment
                       variable.  This flag is on by default.

So may need to check that this is/is not compiled in.

It is by default in Gentoo

# ( From the build Script )
....
ROOTPATH=$(cleanpath /bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/opt/bin${ROOTPATH:+:${ROOTPATH}})
....
econf --with-secure-path="${ROOTPATH}" 

DirectX SDK (June 2010) Installation Problems: Error Code S1023

I've had the same problem twice already and the easiest and most concise solution that I found is located here (in MSDN Blogs -> Games for Windows and the DirectX SDK). However, just in case that page goes down, here's the method:

  1. Remove the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1) from the system (both x86 and x64 if applicable). This can be easily done via a command-line with administrator rights:

    MsiExec.exe /passive /X{F0C3E5D1-1ADE-321E-8167-68EF0DE699A5}
    MsiExec.exe /passive /X{1D8E6291-B0D5-35EC-8441-6616F567A0F7}
    
  2. Install the DirectX SDK (June 2010)

  3. Reinstall the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1). On an x64 system, you should install both the x86 and x64 versions of the C++ REDIST. Be sure to install the most current version available, which at this point is the KB 2565063 with a security fix.

Note: This issue does not affect earlier version of the DirectX SDK which deploy the VS 2005 / VS 2008 CRT REDIST and do not deploy the VS 2010 CRT REDIST. This issue does not affect the DirectX End-User Runtime web or stand-alone installer as those packages do not deploy any version of the VC++ CRT.

File Checksum Integrity Verifier: This of course assumes you actually have an uncorrupted copy of the DirectX SDK setup package. The best way to validate this it to run

fciv -sha1 DXSDK_Jun10.exe

and verify you get

8fe98c00fde0f524760bb9021f438bd7d9304a69 dxsdk_jun10.exe