Programs & Examples On #Nhlambdaextensions

How to generate and auto increment Id with Entity Framework

You have a bad table design. You can't autoincrement a string, that doesn't make any sense. You have basically two options:

1.) change type of ID to int instead of string
2.) not recommended!!! - handle autoincrement by yourself. You first need to get the latest value from the database, parse it to the integer, increment it and attach it to the entity as a string again. VERY BAD idea

First option requires to change every table that has a reference to this table, BUT it's worth it.

How can I find out if an .EXE has Command-Line Options?

The easiest way would be to use use ProcessExplorer but it would still require some searching.

Make sure your exe is running and open ProcessExplorer. In ProcessExplorer find the name of your binary file and double click it to show properties. Click the Strings tab. Search down the list of string found in the binary file. Most strings will be garbage so they can be ignored. Search for anything that might possibly resemble a command line switch. Test this switch from the command line and see if it does anything.

Note that it might be your binary simply has no command line switches.

For reference here is the above steps applied to the Chrome executable. The command line switches accepted by Chrome can be seen in the list:

Process explorer analyzing Chrome.exe

Figure out size of UILabel based on String in Swift

This is my answer in Swift 4.1 and Xcode 9.4.1

//This is your label
let proNameLbl = UILabel(frame: CGRect(x: 0, y: 20, width: 300, height: height))
proNameLbl.text = "This is your text"
proNameLbl.font = UIFont.systemFont(ofSize: 17)
proNameLbl.numberOfLines = 0
proNameLbl.lineBreakMode = .byWordWrapping
infoView.addSubview(proNameLbl)

//Function to calculate height for label based on text
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat {
    let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = font
    label.text = text

    label.sizeToFit()
    return label.frame.height
}

Now you call this function

//Call this function
let height = heightForView(text: "This is your text", font: UIFont.systemFont(ofSize: 17), width: 300)
print(height)//Output : 41.0

Self-references in object literals / initializers

If you want to use native JS, the other answers provide good solutions.

But if you're willing to write self-referencing objects like:

{ 
  a: ...,
  b: "${this.a + this.a}",
}

I wrote an npm library called self-referenced-object that supports that syntax and returns a native object.

Write to Windows Application Event Log

You can using the EventLog class, as explained on How to: Write to the Application Event Log (Visual C#):

var appLog = new EventLog("Application");
appLog.Source = "MySource";
appLog.WriteEntry("Test log message");

However, you'll need to configure this source "MySource" using administrative privileges:

Use WriteEvent and WriteEntry to write events to an event log. You must specify an event source to write events; you must create and configure the event source before writing the first entry with the source.

jQuery location href

Use:

window.location.replace(...)

See this Stack Overflow question for more information:

How do I redirect to another webpage?

Or perhaps it was this you remember:

var url = "http://stackoverflow.com";
$(location).attr('href',url);

What is the 'open' keyword in Swift?

open come to play when dealing with multiple modules.

open class is accessible and subclassable outside of the defining module. An open class member is accessible and overridable outside of the defining module.

Genymotion Android emulator - adb access?

We need to connect with IP address to the emulator, so look for the IP address of the running emulator (it's shown in the emulator title bar) and use something like:

adb connect 192.168.56.102:5555

Afterward adb works normally. You may also find out the IP address of a running emulator by starting "Genymotion Shell" and typing 'devices list'

I also find out that occasionally I have to do the above when the emulator is running for a longer time and somehow ADB disconnects from it.

Greg

Using Java 8's Optional with Stream::flatMap

Null is supported by the Stream provided My library AbacusUtil. Here is code:

Stream.of(things).map(e -> resolve(e).orNull()).skipNull().first();

How can I kill whatever process is using port 8080 so that I can vagrant up?

Run: nmap -p 8080 localhost (Install nmap with MacPorts or Homebrew if you don't have it on your system yet)

Nmap scan report for localhost (127.0.0.1)

Host is up (0.00034s latency).

Other addresses for localhost (not scanned): ::1

PORT STATE SERVICE

8080/tcp open http-proxy

Run: ps -ef | grep http-proxy

UID PID PPID C STIME TTY TIME CMD

640 99335 88310 0 12:26pm ttys002 0:00.01 grep http-proxy"

Run: ps -ef 640 (replace 501 with your UID)

/System/Library/PrivateFrameworks/PerformanceAnalysis.framework/Versions/A/XPCServices/com.apple.PerformanceAnalysis.animationperfd.xpc/Contents/MacOS/com.apple.PerformanceAnalysis.animationperfd

Port 8080 on mac osx is used by something installed with XCode SDK

Getting the object's property name

Quick & dirty:

function getObjName(obj) {
  return (wrap={obj}) && eval('for(p in obj){p}') && (wrap=null);
}

How to know installed Oracle Client is 32 bit or 64 bit?

One thing that was super easy and worked well for me was doing a TNSPing from a cmd prompt:

TNS Ping Utility for 32-bit Windows: Version 11.2.0.3.0 - Production on 13-MAR-2015 16:35:32

LINQ where clause with lambda expression having OR clauses and null values returning incomplete results

Try writting the lambda with the same conditions as the delegate. like this:

  List<AnalysisObject> analysisObjects = 
    analysisObjectRepository.FindAll().Where(
    (x => 
       (x.ID == packageId)
    || (x.Parent != null && x.Parent.ID == packageId)
    || (x.Parent != null && x.Parent.Parent != null && x.Parent.Parent.ID == packageId)
    ).ToList();

Test process.env with Jest

In my opinion, it's much cleaner and easier to understand if you extract the retrieval of environment variables into a utility (you probably want to include a check to fail fast if an environment variable is not set anyway), and then you can just mock the utility.

// util.js
exports.getEnv = (key) => {
    const value = process.env[key];
    if (value === undefined) {
      throw new Error(`Missing required environment variable ${key}`);
    }
    return value;
};

// app.test.js
const util = require('./util');
jest.mock('./util');

util.getEnv.mockImplementation(key => `fake-${key}`);

test('test', () => {...});

Package doesn't exist error in intelliJ

Maven reimport, rebuild and invalidate caches did not work. I solved it by opening a terminal and executing maven clean install in the root folder project. (IntelliJ was opened and I was able to see the IDE updating and triggering reindexation while maven was doing his job)

Compare two dates in Java

public static double periodOfTimeInMillis(Date date1, Date date2) {
    return (date2.getTime() - date1.getTime());
}

public static double periodOfTimeInSec(Date date1, Date date2) {
    return (date2.getTime() - date1.getTime()) / 1000;
}

public static double periodOfTimeInMin(Date date1, Date date2) {
    return (date2.getTime() - date1.getTime()) / (60 * 1000);
}

public static double periodOfTimeInHours(Date date1, Date date2) {
    return (date2.getTime() - date1.getTime()) / (60 * 60 * 1000);
}

public static double periodOfTimeInDays(Date date1, Date date2) {
    return (date2.getTime() - date1.getTime()) / (24 * 60 * 60 * 1000L);
}

What does __FILE__ mean in Ruby?

In Ruby, the Windows version anyways, I just checked and __FILE__ does not contain the full path to the file. Instead it contains the path to the file relative to where it's being executed from.

In PHP __FILE__ is the full path (which in my opinion is preferable). This is why, in order to make your paths portable in Ruby, you really need to use this:

File.expand_path(File.dirname(__FILE__) + "relative/path/to/file")

I should note that in Ruby 1.9.1 __FILE__ contains the full path to the file, the above description was for when I used Ruby 1.8.7.

In order to be compatible with both Ruby 1.8.7 and 1.9.1 (not sure about 1.9) you should require files by using the construct I showed above.

Java character array initializer

Here's how you convert a String to a char array:

String str = "someString"; 
char[] charArray = str.toCharArray();

I'd recommend that you use an IDE when programming, to easily see which methods a class contains (in this case you'd be able to find toCharArray()) and compile errors like the one you have above. You should also familiarize yourself with the documentation, which in this case would be this String documentation.

Also, always post which compile errors you're getting. In this case it was easy to spot, but when it isn't you won't be able to get any answers if you don't include it in the post.

How to debug "ImagePullBackOff"?

You can use the 'describe pod' syntax

For OpenShift use:

oc describe pod <pod-id>  

For vanilla Kubernetes:

kubectl describe pod <pod-id>  

Examine the events of the output. In my case it shows Back-off pulling image coredns/coredns:latest

In this case the image coredns/coredns:latest can not be pulled from the Internet.

Events:
  FirstSeen LastSeen    Count   From                SubObjectPath           Type        Reason      Message
  --------- --------    -----   ----                -------------           --------    ------      -------
  5m        5m      1   {default-scheduler }                        Normal      Scheduled   Successfully assigned coredns-4224169331-9nhxj to 192.168.122.190
  5m        1m      4   {kubelet 192.168.122.190}   spec.containers{coredns}    Normal      Pulling     pulling image "coredns/coredns:latest"
  4m        26s     4   {kubelet 192.168.122.190}   spec.containers{coredns}    Warning     Failed      Failed to pull image "coredns/coredns:latest": Network timed out while trying to connect to https://index.docker.io/v1/repositories/coredns/coredns/images. You may want to check your internet connection or if you are behind a proxy.
  4m        26s     4   {kubelet 192.168.122.190}                   Warning     FailedSync  Error syncing pod, skipping: failed to "StartContainer" for "coredns" with ErrImagePull: "Network timed out while trying to connect to https://index.docker.io/v1/repositories/coredns/coredns/images. You may want to check your Internet connection or if you are behind a proxy."

  4m    2s  7   {kubelet 192.168.122.190}   spec.containers{coredns}    Normal  BackOff     Back-off pulling image "coredns/coredns:latest"
  4m    2s  7   {kubelet 192.168.122.190}                   Warning FailedSync  Error syncing pod, skipping: failed to "StartContainer" for "coredns" with ImagePullBackOff: "Back-off pulling image \"coredns/coredns:latest\""

Additional debuging steps

  1. try to pull the docker image and tag manually on your computer
  2. Identify the node by doing a 'kubectl/oc get pods -o wide'
  3. ssh into the node (if you can) that can not pull the docker image
  4. check that the node can resolve the DNS of the docker registry by performing a ping.
  5. try to pull the docker image manually on the node
  6. If you are using a private registry, check that your secret exists and the secret is correct. Your secret should also be in the same namespace. Thanks swenzel
  7. Some registries have firewalls that limit ip address access. The firewall may block the pull
  8. Some CIs create deployments with temporary docker secrets. So the secret expires after a few days (You are asking for production failures...)

Twig for loop for arrays with keys

These are extended operations (e.g., sort, reverse) for one dimensional and two dimensional arrays in Twig framework:

1D Array

Without Key Sort and Reverse

{% for key, value in array_one_dimension %}
    <div>{{ key }}</div>
    <div>{{ value }}</div>
{% endfor %}

Key Sort

{% for key, value in array_one_dimension|keys|sort %}
    <div>{{ key }}</div>
    <div>{{ value }}</div>
{% endfor %}

Key Sort and Reverse

{% for key, value in array_one_dimension|keys|sort|reverse %}
    <div>{{ key }}</div>
    <div>{{ value }}</div>
{% endfor %}

2D Arrays

Without Key Sort and Reverse

{% for key_a, value_a in array_two_dimension %}
    {% for key_b, value_b in array_two_dimension[key_a] %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Key Sort on Outer Array

{% for key_a, value_a in array_two_dimension|keys|sort %}
    {% for key_b, value_b in array_two_dimension[key_a] %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Key Sort on Both Outer and Inner Arrays

{% for key_a, value_a in array_two_dimension|keys|sort %}
    {% for key_b, value_b in array_two_dimension[key_a]|keys|sort %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Key Sort on Outer Array & Key Sort and Reverse on Inner Array

{% for key_a, value_a in array_two_dimension|keys|sort %}
    {% for key_b, value_b in array_two_dimension[key_a]|keys|sort|reverse %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Key Sort and Reverse on Outer Array & Key Sort on Inner Array

{% for key_a, value_a in array_two_dimension|keys|sort|reverse %}
    {% for key_b, value_b in array_two_dimension[key_a]|keys|sort %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Key Sort and Reverse on Both Outer and Inner Array

{% for key_a, value_a in array_two_dimension|keys|sort|reverse %}
    {% for key_b, value_b in array_two_dimension[key_a]|keys|sort|reverse %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

How to select specific form element in jQuery?

$("#name", '#form2').val("Hello World")

Fixed header table with horizontal scrollbar and vertical scrollbar on

you can use following CSS code..

body {
    margin:0;
    padding:0;
    height: 100%;
    width: 100%;
}
table {
    border-collapse: collapse; /* make simple 1px lines borders if border defined */
}
tr {
    width: 100%;
}

.outer-container {
    background-color: #ccc;    
    top:0;
    left: 0;
    right: 300px;
    bottom:40px;
    overflow:hidden;

}
.inner-container {
    width: 100%;
    height: 100%;
    position: relative;

}
.table-header {
    float:left;
    width: 100%;
}
.table-body {
    float:left;
    height: 100%;
    width: inherit;

}
.header-cell {
    background-color: yellow;
    text-align: left;
    height: 40px;
}
.body-cell {
    background-color: blue;
    text-align: left;
}
.col1, .col3, .col4, .col5 {
    width:120px;
    min-width: 120px;
}
.col2 {
    min-width: 300px;
}

Mockito: InvalidUseOfMatchersException

For my case, the exception was raised because I tried to mock a package-access method. When I changed the method access level from package to protected the exception went away. E.g. inside below Java class,

public class Foo {
    String getName(String id) {
        return mMap.get(id);
    }
}

the method String getName(String id) has to be AT LEAST protected level so that the mocking mechanism (sub-classing) can work.

html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button

I know this is an old question but I came across it while trying to solve this same issue. I thought it'd be worth sharing this solution I hadn't found anywhere else.

Basically the solution is to use CSS to hide the <input> element and style a <label> around it to look like a button. Click the 'Run code snippet' button to see the results.

I had used a JavaScript solution before that worked fine too but it is nice to solve a 'presentation' issue with just CSS.

_x000D_
_x000D_
label.cameraButton {_x000D_
  display: inline-block;_x000D_
  margin: 1em 0;_x000D_
_x000D_
  /* Styles to make it look like a button */_x000D_
  padding: 0.5em;_x000D_
  border: 2px solid #666;_x000D_
  border-color: #EEE #CCC #CCC #EEE;_x000D_
  background-color: #DDD;_x000D_
}_x000D_
_x000D_
/* Look like a clicked/depressed button */_x000D_
label.cameraButton:active {_x000D_
  border-color: #CCC #EEE #EEE #CCC;_x000D_
}_x000D_
_x000D_
/* This is the part that actually hides the 'Choose file' text box for camera inputs */_x000D_
label.cameraButton input[accept*="camera"] {_x000D_
  display: none;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>Nice image capture button</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <label class="cameraButton">Take a picture_x000D_
    <input type="file" accept="image/*;capture=camera">_x000D_
  </label>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Disable Required validation attribute under certain circumstances

This problem can be easily solved by using view models. View models are classes that are specifically tailored to the needs of a given view. So for example in your case you could have the following view models:

public UpdateViewView
{
    [Required]
    public string Id { get; set; }

    ... some other properties
}

public class InsertViewModel
{
    public string Id { get; set; }

    ... some other properties
}

which will be used in their corresponding controller actions:

[HttpPost]
public ActionResult Update(UpdateViewView model)
{
    ...
}

[HttpPost]
public ActionResult Insert(InsertViewModel model)
{
    ...
}

What exactly is Apache Camel?

What exactly is it?

Apache Camel is a lightweight integration framework which implements many Enterprise Integration patterns.You can easily integrate different applications using the required patterns.

You can use Java, Spring XML, Scala or Groovy. Almost every technology you can imagine is available, for example HTTP, FTP, JMS, EJB, JPA, RMI, JMS, JMX, LDAP, Netty etc.

Have a look at this article and EIP pattern article

How does it interact with an application written in Java?

Camel uses a Java Domain Specific Language or DSL for creating Enterprise Integration Patterns or Routes in a variety of domain-specific languages (DSL) as listed below.

Java DSL - A Java based DSL using the fluent builder style.

The story of Enterprise Integration Pattern resolves around these concepts :

Message, End Point, Producer, Consumer, Routing, Bus, Transform and Process.

Have a look at this article By Anirban Konar for one of real time use cases.

Is it something that goes together with the server?

It acts as a bridge across multiple enterprise sub systems.

Is it an independent program?

Apache Camel, an integration framework, integrates different independent applications.

The major advantage of Camel : You can integrate different applications with different technologies (and different protocols) by using same same concepts for every integration.

Display the current time and date in an Android application

Okay, not that hard as there are several methods to do this. I assume you want to put the current date & time into a TextView.

String currentDateTimeString = java.text.DateFormat.getDateTimeInstance().format(new Date());

// textView is the TextView view that should display it
textView.setText(currentDateTimeString);

There is more to read in the documentation that can easily be found here . There you'll find more information on how to change the format used for conversion.

MessageBodyWriter not found for media type=application/json

Uncommenting the below code helped

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
</dependency>

which was present in pom.xml in my maven based project resolved this error for me.

gcc-arm-linux-gnueabi command not found

got the same error when trying to cross compile the raspberry pi kernel on ubunto 14.04.03 64bit under VM. the solution was found here:

-Install packages used for cross compiling on the Ubuntu box.

sudo apt-get install gcc-arm-linux-gnueabi make git-core ncurses-dev

-Download the toolchain

cd ~
git clone https://github.com/raspberrypi/tools

-Add the toolchain to your path

PATH=$PATH:~/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian:~/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin

notice the x64 version in the path command

C++ equivalent of java's instanceof

dynamic_cast is known to be inefficient. It traverses up the inheritance hierarchy, and it is the only solution if you have multiple levels of inheritance, and need to check if an object is an instance of any one of the types in its type hierarchy.

But if a more limited form of instanceof that only checks if an object is exactly the type you specify, suffices for your needs, the function below would be a lot more efficient:

template<typename T, typename K>
inline bool isType(const K &k) {
    return typeid(T).hash_code() == typeid(k).hash_code();
}

Here's an example of how you'd invoke the function above:

DerivedA k;
Base *p = &k;

cout << boolalpha << isType<DerivedA>(*p) << endl;  // true
cout << boolalpha << isType<DerivedB>(*p) << endl;  // false

You'd specify template type A (as the type you're checking for), and pass in the object you want to test as the argument (from which template type K would be inferred).

How to delete an SMS from the inbox in Android programmatically?

You'll need to find the URI of the message. But once you do I think you should be able to android.content.ContentResolver.delete(...) it.

Here's some more info.

C++ - Assigning null to a std::string

You cannot assign NULL or 0 to a C++ std::string object, because the object is not a pointer. This is one key difference from C-style strings; a C-style string can either be NULL or a valid string, whereas C++ std::strings always store some value.

There is no easy fix to this. If you'd like to reserve a sentinel value (say, the empty string), then you could do something like

const std::string NOT_A_STRING = "";

mValue = NOT_A_STRING;

Alternatively, you could store a pointer to a string so that you can set it to null:

std::string* mValue = NULL;

if (value) {
    mValue = new std::string(value);
}

Hope this helps!

VSCode cannot find module '@angular/core' or any other modules

Delete Node Modules folder from project folder.Run below command

npm cache clean --force npm install

It should work.

Storing Objects in HTML5 localStorage

localStorage.setItem('user', JSON.stringify(user));

Then to retrieve it from the store and convert to an object again:

var user = JSON.parse(localStorage.getItem('user'));

If we need to delete all entries of the store we can simply do:

localStorage.clear();

Bash ignoring error for a particular command

Don't stop and also save exit status

Just in case if you want your script not to stop if a particular command fails and you also want to save error code of failed command:

set -e
EXIT_CODE=0
command || EXIT_CODE=$?
echo $EXIT_CODE

Programmatically Add CenterX/CenterY Constraints

In Swift 5 it looks like this:

label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: vc.view.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: vc.view.centerYAnchor).isActive = true

Merge Two Lists in R

This is a very simple adaptation of the modifyList function by Sarkar. Because it is recursive, it will handle more complex situations than mapply would, and it will handle mismatched name situations by ignoring the items in 'second' that are not in 'first'.

appendList <- function (x, val) 
{
    stopifnot(is.list(x), is.list(val))
    xnames <- names(x)
    for (v in names(val)) {
        x[[v]] <- if (v %in% xnames && is.list(x[[v]]) && is.list(val[[v]])) 
            appendList(x[[v]], val[[v]])
        else c(x[[v]], val[[v]])
    }
    x
}

> appendList(first,second)
$a
[1] 1 2

$b
[1] 2 3

$c
[1] 3 4

pass parameter by link_to ruby on rails

Try:

<%= link_to "Add to cart", {:controller => "car", :action => "add_to_cart", :car => car.id }%>

and then in your controller

@car = Car.find(params[:car])

which, will find in your 'cars' table (as with rails pluralization) in your DB a car with id == to car.id

hope it helps! happy coding

more than a year later, but if you see it or anyone does, i could use the points ;D

GC overhead limit exceeded

From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning

the following

Excessive GC Time and OutOfMemoryError

The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.

The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).

in conjunction with a passage further down

One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,

java -Dsun.rmi.dgc.client.gcInterval=3600000

-Dsun.rmi.dgc.server.gcInterval=3600000 specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.

Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.

Of course, other interpretations are possible.

WPF C# button style

To solve your question definitely need to use the Style and Template for the Button. But how exactly does he look like? Decisions may be several. For example, Button are two texts to better define the relevant TextBlocks? Can be directly in the template, but then use the buttons will be limited, because the template can be only one ContentPresenter. I decided to do things differently, to identify one ContentPresenter with an icon in the form of a Path, and the content is set using the buttons on the side.

The style:

<Style TargetType="{x:Type Button}">
    <Setter Property="Background" Value="#373737" />
    <Setter Property="Foreground" Value="White" />
    <Setter Property="FontSize" Value="15" />
    <Setter Property="SnapsToDevicePixels" Value="True" />

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border CornerRadius="4" Background="{TemplateBinding Background}">
                    <Grid>
                        <Path x:Name="PathIcon" Width="15" Height="25" Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z "/>
                        <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />                                
                    </Grid>
                </Border>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="#E59400" />
                        <Setter Property="Foreground" Value="White" />
                        <Setter TargetName="PathIcon" Property="Fill" Value="Black" />
                    </Trigger>

                    <Trigger Property="IsPressed" Value="True">
                        <Setter Property="Background" Value="OrangeRed" />
                        <Setter Property="Foreground" Value="White" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Sample of using:

<Button Width="200" Height="50" VerticalAlignment="Top" Margin="0,20,0,0" />
    <Button.Content>
        <StackPanel>
            <TextBlock Text="Watch Now" FontSize="20" />
            <TextBlock Text="Duration: 50m" FontSize="12" Foreground="Gainsboro" />
        </StackPanel>
    </Button.Content>
</Button>

Output

enter image description here

It is best to StackPanel determine the Resources and set the Button so:

<Window.Resources>
    <StackPanel x:Key="MyStackPanel">
        <TextBlock Name="MainContent" Text="Watch Now" FontSize="20" />
        <TextBlock Name="DurationValue" Text="Duration: 50m" FontSize="12" Foreground="Gainsboro" />
    </StackPanel>
</Window.Resources>

<Button Width="200" Height="50" Content="{StaticResource MyStackPanel}" VerticalAlignment="Top" Margin="0,20,0,0" />

The question remains with setting the value for TextBlock Duration, because this value must be dynamic. I implemented it using attached DependencyProperty. Set it to the window, like that:

<Window Name="MyWindow" local:MyDependencyClass.CurrentDuration="Duration: 50m" ... />

Using in TextBlock:

<TextBlock Name="DurationValue" Text="{Binding ElementName=MyWindow, Path=(local:MyDependencyClass.CurrentDuration)}" FontSize="12" Foreground="Gainsboro" />

In fact, there is no difference for anyone to determine the attached DependencyProperty, because it is the predominant feature.

Example of set value:

private void Button_Click(object sender, RoutedEventArgs e)
{
    MyDependencyClass.SetCurrentDuration(MyWindow, "Duration: 101m");
}

A complete listing of examples:

XAML

<Window x:Class="ButtonHelp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ButtonHelp"
    Name="MyWindow"
    Title="MainWindow" Height="350" Width="525"
    WindowStartupLocation="CenterScreen"
    local:MyDependencyClass.CurrentDuration="Duration: 50m">

<Window.Resources>
    <Style TargetType="{x:Type Button}">
        <Setter Property="Background" Value="#373737" />
        <Setter Property="Foreground" Value="White" />
        <Setter Property="FontSize" Value="15" />
        <Setter Property="FontFamily" Value="./#Segoe UI" />
        <Setter Property="SnapsToDevicePixels" Value="True" />

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border CornerRadius="4" Background="{TemplateBinding Background}">
                        <Grid>
                            <Path x:Name="PathIcon" Width="15" Height="25" Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z "/>
                            <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />                                
                        </Grid>
                    </Border>

                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="#E59400" />
                            <Setter Property="Foreground" Value="White" />
                            <Setter TargetName="PathIcon" Property="Fill" Value="Black" />
                        </Trigger>

                        <Trigger Property="IsPressed" Value="True">
                            <Setter Property="Background" Value="OrangeRed" />
                            <Setter Property="Foreground" Value="White" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <StackPanel x:Key="MyStackPanel">
        <TextBlock Name="MainContent" Text="Watch Now" FontSize="20" />
        <TextBlock Name="DurationValue" Text="{Binding ElementName=MyWindow, Path=(local:MyDependencyClass.CurrentDuration)}" FontSize="12" Foreground="Gainsboro" />
    </StackPanel>
</Window.Resources>

<Grid>        
    <Button Width="200" Height="50" Content="{StaticResource MyStackPanel}" VerticalAlignment="Top" Margin="0,20,0,0" />

    <Button Content="Set some duration" Style="{x:Null}" Width="140" Height="30" VerticalAlignment="Top" HorizontalAlignment="Left" Click="Button_Click" />
</Grid>

Code behind

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MyDependencyClass.SetCurrentDuration(MyWindow, "Duration: 101m");
    }
}

public class MyDependencyClass : DependencyObject
{
    public static readonly DependencyProperty CurrentDurationProperty;        

    public static void SetCurrentDuration(DependencyObject DepObject, string value)
    {
        DepObject.SetValue(CurrentDurationProperty, value);
    }

    public static string GetCurrentDuration(DependencyObject DepObject)
    {
        return (string)DepObject.GetValue(CurrentDurationProperty);
    }

    static MyDependencyClass()
    {
        PropertyMetadata MyPropertyMetadata = new PropertyMetadata("Duration: 0m");

        CurrentDurationProperty = DependencyProperty.RegisterAttached("CurrentDuration",
                                                            typeof(string),
                                                            typeof(MyDependencyClass),
                                                            MyPropertyMetadata);
    }
}

Servlet Mapping using web.xml

It allows servlets to have multiple servlet mappings:

<servlet>
    <servlet-name>Servlet1</servlet-name>
    <servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/bill</url-pattern>
</servlet-mapping>

It allows filters to be mapped on the particular servlet:

<filter-mapping>
    <filter-name>Filter1</filter-name>
    <servlet-name>Servlet1</servlet-name>
</filter-mapping>

Your proposal would support neither of them. Note that the web.xml is read and parsed only once during application's startup, not on every HTTP request as you seem to think.

Since Servlet 3.0, there's the @WebServlet annotation which minimizes this boilerplate:

@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {

See also:

How to undo a SQL Server UPDATE query?

If you already have a full backup from your database, fortunately, you have an option in SQL Management Studio. In this case, you can use the following steps:

  1. Right click on database -> Tasks -> Restore -> Database.

  2. In General tab, click on Timeline -> select Specific date and time option.

  3. Move the timeline slider to before update command time -> click OK.

  4. In the destination database name, type a new name.

  5. In the Files tab, check in Reallocate all files to folder and then select a new path to save your recovered database.

  6. In the options tab, check in Overwrite ... and remove Take tail-log... check option.

  7. Finally, click on OK and wait until the recovery process is over.

I have used this method myself in an operational database and it was very useful.

Edit seaborn legend

If you just want to change the legend title, you can do the following:

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

g = sns.lmplot(
    x="total_bill", 
    y="tip", 
    hue="smoker", 
    data=tips,  
    legend=True
)

g._legend.set_title("New Title")

How to add items to array in nodejs

Here is example which can give you some hints to iterate through existing array and add items to new array. I use UnderscoreJS Module to use as my utility file.

You can download from (https://npmjs.org/package/underscore)

$ npm install underscore

Here is small snippet to demonstrate how you can do it.

var _ = require("underscore");
var calendars = [1, "String", {}, 1.1, true],
    newArray = [];

_.each(calendars, function (item, index) {
    newArray.push(item);
});

console.log(newArray);

jquery UI dialog: how to initialize without a title bar?

Try using

$("#mydialog").closest(".ui-dialog-titlebar").hide();

This will hide all dialogs titles

$(".ui-dialog-titlebar").hide();

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

If you want to apply some condition on form submit then you can use this method

<form onsubmit="return checkEmpData();" method="post" action="process.html">
  <input type="text" border="0" name="submit" />
  <button value="submit">submit</button>
</form>

One thing always keep in mind that method and action attribute write after onsubmit attributes

javascript code

function checkEmpData()
{
  var a = 0;

  if(a != 0)
  {
    return confirm("Do you want to generate attendance?");
  }
   else
   {
      alert('Please Select Employee First');
      return false;
   }  
}

Five equal columns in twitter bootstrap

In bootstrap v4.3.1, it’s a column which is 12 / 5 = 2.4 columns wide. let’s call it col-2dot4 (and col-sm-2dot4, col-md-2dot4, …).

And each column should have 20% of the available space.

The SCSS code which comes out as below:

@mixin make-5-grid-column($columns: $grid-columns, $gutter: $grid-gutter-width, $breakpoints: $grid-breakpoints) {

  // Common properties for all breakpoints
  %grid-column {
    position: relative;
    width: 100%;
    padding-right: $gutter / 2;
    padding-left: $gutter / 2;
  }

  @each $breakpoint in map-keys($breakpoints) {
    $infix: breakpoint-infix($breakpoint, $breakpoints);

    .col#{$infix}-2dot4 {
      @extend %grid-column;
    }

    .col#{$infix},
    .col#{$infix}-auto {
      @extend %grid-column;
    }

    @include media-breakpoint-up($breakpoint, $breakpoints) {

      // Provide basic `.col-{bp}` classes for equal-width flexbox columns
      .col#{$infix} {
        flex-basis: 0;
        flex-grow: 1;
        max-width: 100%;
      }

      .col#{$infix}-auto {
        flex: 0 0 auto;
        width: auto;
        max-width: 100%; // Reset earlier grid tiers
      }


      .col#{$infix}-2dot4 {
        @include make-col(1, 5);
      }
    }
  }
}

@if $enable-grid-classes {
  @include make-5-grid-column();
}

What is the maximum characters for the NVARCHAR(MAX)?

The max size for a column of type NVARCHAR(MAX) is 2 GByte of storage.

Since NVARCHAR uses 2 bytes per character, that's approx. 1 billion characters.

Leo Tolstoj's War and Peace is a 1'440 page book, containing about 600'000 words - so that might be 6 million characters - well rounded up. So you could stick about 166 copies of the entire War and Peace book into each NVARCHAR(MAX) column.

Is that enough space for your needs? :-)

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

What caused this error in my case was having two @GET methods with the same path in a single resource. Changing the @Path of one of the methods solved it for me.

CSS-Only Scrollable Table with fixed headers

Inspired by @Purag's answer, here's another flexbox solution:

_x000D_
_x000D_
/* basic settings */_x000D_
table { display: flex; flex-direction: column; width: 200px; }_x000D_
tr { display: flex; }_x000D_
th:nth-child(1), td:nth-child(1) { flex-basis: 35%; }_x000D_
th:nth-child(2), td:nth-child(2) { flex-basis: 65%; }_x000D_
thead, tbody { overflow-y: scroll; }_x000D_
tbody { height: 100px; }_x000D_
_x000D_
/* color settings*/_x000D_
table, th, td { border: 1px solid black; }_x000D_
tr:nth-child(odd) { background: #EEE; }_x000D_
tr:nth-child(even) { background: #AAA; }_x000D_
thead tr:first-child { background: #333; }_x000D_
th:first-child, td:first-child { background: rgba(200,200,0,0.7); }_x000D_
th:last-child, td:last-child { background: rgba(255,200,0,0.7); }
_x000D_
<table>_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th>a_x000D_
        <th>bbbb_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>fooo vsync dynamic_x000D_
        <td>bar_x000D_
      <tr>_x000D_
        <td>a_x000D_
        <td>b_x000D_
      <tr>_x000D_
        <td>a_x000D_
        <td>b_x000D_
      <tr>_x000D_
        <td>a_x000D_
        <td>b_x000D_
      <tr>_x000D_
        <td>a_x000D_
        <td>b_x000D_
      <tr>_x000D_
        <td>a_x000D_
        <td>b_x000D_
      <tr>_x000D_
        <td>a_x000D_
        <td>b_x000D_
  </table>
_x000D_
_x000D_
_x000D_

Environment variable substitution in sed

VAR=8675309
echo "abcde:jhdfj$jhbsfiy/.hghi$jh:12345:dgve::" |\
sed 's/:[0-9]*:/:'$VAR':/1' 

where VAR contains what you want to replace the field with

Is it possible to use a div as content for Twitter's Popover

All of these answers miss a very important aspect!

By using .html or innerHtml or outerHtml you are not actually using the referenced element. You are using a copy of the element's html. This has some serious draw backs.

  1. You can't use any ids because the ids will be duplicated.
  2. If you load the contents every time that the popover is shown you will lose all of the user's input.

What you want to do is load the object itself into the popover.

https://jsfiddle.net/shrewmouse/ex6tuzm2/4/

HTML:

<h1> Test </h1>

<div><button id="target">click me</button></div>

<!-- This will be the contents of our popover -->
<div class='_content' id='blah'>
<h1>Extra Stuff</h1>
<input type='number' placeholder='number'/>
</div>

JQuery:

$(document).ready(function() {

    // We don't want to see the popover contents until the user clicks the target.
    // If you don't hide 'blah' first it will be visible outside of the popover.
    //
    $('#blah').hide();

    // Initialize our popover
    //
    $('#target').popover({
        content: $('#blah'), // set the content to be the 'blah' div
        placement: 'bottom',
        html: true
    });
    // The popover contents will not be set until the popover is shown.  Since we don't 
    // want to see the popover when the page loads, we will show it then hide it.
    //
    $('#target').popover('show');
    $('#target').popover('hide');

    // Now that the popover's content is the 'blah' dive we can make it visisble again.
    //
    $('#blah').show();


});

Abstraction VS Information Hiding VS Encapsulation

After reading all the above answers one by one I cant stop myself from posting that

abstraction involves the facility to define objects that represent abstract "actors" that can perform work, report on and change their state, and "communicate" with other objects in the system.

Encapsulation is quite clear from above however ->

The term encapsulation refers to the hiding of state details, but extending the concept of data type from earlier programming languages to associate behavior most strongly with the data, and standardizing the way that different data types interact, is the beginning of abstraction.

reference wiki

Shell script to copy files from one location to another location and rename add the current date to every file

There is a proper way to split the filename and the extension: Extract filename and extension in Bash

You can apply it like this:

date=$(date +"%m%d%y")
for FILE in folder1/*.csv
do
    bname=$(basename "$FILE")
    extension="${bname##*.}"
    filenamewoext="${bname%.*}"
    newfilename="${filenamewoext}${date}.${extension}
    cp folder1/${FILE} folder2/${newfilename}
done

COUNT DISTINCT with CONDITIONS

You can try this:

select
  count(distinct tag) as tag_count,
  count(distinct (case when entryId > 0 then tag end)) as positive_tag_count
from
  your_table_name;

The first count(distinct...) is easy. The second one, looks somewhat complex, is actually the same as the first one, except that you use case...when clause. In the case...when clause, you filter only positive values. Zeros or negative values would be evaluated as null and won't be included in count.

One thing to note here is that this can be done by reading the table once. When it seems that you have to read the same table twice or more, it can actually be done by reading once, in most of the time. As a result, it will finish the task a lot faster with less I/O.

How to set the font style to bold, italic and underlined in an Android TextView?

This is an easy way to add an underline, while maintaining other settings:

textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

How to set a class attribute to a Symfony2 form input

You can do it with FormBuilder. Add this to the array in your FormBuilder:

'attr'=> array('class'=>'span2')

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

java.net.MalformedURLException: no protocol

The documentation could help you : http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilder.html

The method DocumentBuilder.parse(String) takes a URI and tries to open it. If you want to directly give the content, you have to give it an InputStream or Reader, for example a StringReader. ... Welcome to the Java standard levels of indirections !

Basically :

DocumentBuilder db = ...;
String xml = ...;
db.parse(new InputSource(new StringReader(xml)));

Note that if you read your XML from a file, you can directly give the File object to DocumentBuilder.parse() .

As a side note, this is a pattern you will encounter a lot in Java. Usually, most API work with Streams more than with Strings. Using Streams means that potentially not all the content has to be loaded in memory at the same time, which can be a great idea !

How to use java.net.URLConnection to fire and handle HTTP requests?

I suggest you take a look at the code on kevinsawicki/http-request, its basically a wrapper on top of HttpUrlConnection it provides a much simpler API in case you just want to make the requests right now or you can take a look at the sources (it's not too big) to take a look at how connections are handled.

Example: Make a GET request with content type application/json and some query parameters:

// GET http://google.com?q=baseball%20gloves&size=100
String response = HttpRequest.get("http://google.com", true, "q", "baseball gloves", "size", 100)
        .accept("application/json")
        .body();
System.out.println("Response was: " + response);

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

XHR polling vs SSE vs WebSockets

  • XHR polling A Request is answered when the event occurs (could be straight away, or after a delay). Subsequent requests will need to made to receive further events.

    The browser makes an asynchronous request of the server, which may wait for data to be available before responding. The response can contain encoded data (typically XML or JSON) or Javascript to be executed by the client. At the end of the processing of the response, the browser creates and sends another XHR, to await the next event. Thus the browser always keeps a request outstanding with the server, to be answered as each event occurs. Wikipedia

  • Server Sent Events Client sends request to server. Server sends new data to webpage at any time.

    Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page. Mozilla

  • WebSockets After the initial handshake (via HTTP protocol). Communication is done bidirectionally using the WebSocket protocol.

    The handshake starts with an HTTP request/response, allowing servers to handle HTTP connections as well as WebSocket connections on the same port. Once the connection is established, communication switches to a bidirectional binary protocol which does not conform to the HTTP protocol. Wikipedia

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

You should initialize yours recordings. You are passing to adapter null

ArrayList<String> recordings = null; //You are passing this null

css3 transition animation on load?

Not really, as CSS is applied as soon as possible, but the elements might not be drawn yet. You could guess a delay of 1 or 2 seconds, but this won't look right for most people, depending on the speed of their internet.

In addition, if you want to fade something in for instance, it would require CSS that hides the content to be delivered. If the user doesn't have CSS3 transitions then they would never see it.

I'd recommend using jQuery (for ease of use + you may wish to add animation for other UAs) and some JS like this:

$(document).ready(function() {
    $('#id_to_fade_in')
        .css({"opacity":0})   // Set to 0 as soon as possible – may result in flicker, but it's not hidden for users with no JS (Googlebot for instance!)
        .delay(200)           // Wait for a bit so the user notices it fade in
        .css({"opacity":1});  // Fade it back in. Swap css for animate in legacy browsers if required.
});

Along with the transitions added in the CSS. This has the advantage of easily allowing the use of animate instead of the second CSS in legacy browsers if required.

Android view pager with page indicator

You Can create a Linear layout containing an array of TextView (mDots). To represent the textView as Dots provide this HTML source in your code . refer my code . I got this information from Youtube Channel TVAC Studio . here the code : `

    addDotsIndicator(0);
    viewPager.addOnPageChangeListener(viewListener);
}

public void addDotsIndicator(int position)
{
        mDots = new TextView[5];
        mDotLayout.removeAllViews();

        for (int i = 0; i<mDots.length ; i++)
        {
             mDots[i]=new TextView(this);
             mDots[i].setText(Html.fromHtml("&#8226;"));            //HTML for dots
             mDots[i].setTextSize(35);
             mDots[i].setTextColor(getResources().getColor(R.color.colorAccent));

             mDotLayout.addView(mDots[i]);
        }

        if(mDots.length>0)
        {
            mDots[position].setTextColor(getResources().getColor(R.color.orange));
        }
}

ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageScrolled(int position, float positionOffset, int 
   positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

        addDotsIndicator(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
};`

no operator "<<" matches these operands

You're not including the standard <string> header.

You got [un]lucky that some of its pertinent definitions were accidentally made available by the other standard headers that you did include ... but operator<< was not.

How to write DataFrame to postgres table?

This is how I did it.

It may be faster because it is using execute_batch:

# df is the dataframe
if len(df) > 0:
    df_columns = list(df)
    # create (col1,col2,...)
    columns = ",".join(df_columns)

    # create VALUES('%s', '%s",...) one '%s' per column
    values = "VALUES({})".format(",".join(["%s" for _ in df_columns])) 

    #create INSERT INTO table (columns) VALUES('%s',...)
    insert_stmt = "INSERT INTO {} ({}) {}".format(table,columns,values)

    cur = conn.cursor()
    psycopg2.extras.execute_batch(cur, insert_stmt, df.values)
    conn.commit()
    cur.close()

Make the current Git branch a master branch

The solutions given here (renaming the branch in 'master') don't insist on the consequences for the remote (GitHub) repo:

  • if you hadn't push anything since making that branch, you can rename it and push it without any problem.
  • if you had push master on GitHub, you will need to 'git push -f' the new branch: you can no longer push in a fast forward mode.
    -f
    --force

Usually, the command refuses to update a remote ref that is not an ancestor of the local ref used to overwrite it. This flag disables the check. This can cause the remote repository to lose commits; use it with care.

If others have already pulled your repo, they won't be able to pull that new master history without replacing their own master with that new GitHub master branch (or dealing with lots of merges).
There are alternatives to a git push --force for public repos.
Jefromi's answer (merging the right changes back to the original master) is one of them.

Why does this SQL code give error 1066 (Not unique table/alias: 'user')?

    SELECT art.* , sec.section.title, cat.title, use1.name, use2.name as modifiedby
FROM article art
INNER JOIN section sec ON art.section_id = sec.section.id
INNER JOIN category cat ON art.category_id = cat.id
INNER JOIN user use1 ON art.author_id = use1.id
LEFT JOIN user use2 ON art.modified_by = use2.id
WHERE art.id = '1';

Hope This Might Help

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

  • z means (un)z_ip.
  • x means ex_tract files from the archive.
  • v means print the filenames v_erbosely.
  • f means the following argument is a f_ilename.

For more details, see tar's man page.

Splitting a string into separate variables

An array is created with the -split operator. Like so,

$myString="Four score and seven years ago"
$arr = $myString -split ' '
$arr # Print output
Four
score
and
seven
years
ago

When you need a certain item, use array index to reach it. Mind that index starts from zero. Like so,

$arr[2] # 3rd element
and
$arr[4] # 5th element
years

How to set standard encoding in Visual Studio

Do you want the files to save as UTF-8 because you are using special characters that would be lost in ASCII encoding? If that's the case, then there is a VS2008 global setting in Tools > Options > Environment > Documents, named Save documents as Unicode when data cannot be saved in codepage. When this is enabled, VS2008 will save as Unicode if certain characters cannot be represented in the otherwise-default codepage.

Also, which files are not being saved as UTF-8? All of my .cs, .csproj, .sln, .config, .as*x, etc, all save as UTF-8 (with signature, the byte order marks), by default.

std::wstring VS std::string

When should you NOT use wide-characters?

When you're writing code before the year 1990.

Obviously, I'm being flip, but really, it's the 21st century now. 127 characters have long since ceased to be sufficient. Yes, you can use UTF8, but why bother with the headaches?

What's the easy way to auto create non existing dir in ansible

copy module creates the directory if it's not there. In this case it created the resolved.conf.d directory

- name: put fallback_dns.conf in place                                                                 
  copy:                                                                                                
    src: fallback_dns.conf                                                                             
    dest: /etc/systemd/resolved.conf.d/                                                                
    mode: '0644'                                                                                       
    owner: root                                                                                        
    group: root                                                                                        
  become: true                                                                                         
  tags: testing

unable to set private key file: './cert.pem' type PEM

I faced this issue when I had used Open SSL and the solution was to split the cert in 3 files and use all of them doing the call with Curl:

openssl pkcs12 -in mycert.p12 -out ca.pem -cacerts -nokeys
openssl pkcs12 -in mycert.p12 -out client.pem -clcerts -nokeys 
openssl pkcs12 -in mycert.p12 -out key.pem -nocerts

curl --insecure --key key.pem --cacert ca.pem --cert client.pem:KeyChoosenByMeWhenIrunOpenSSL https://thesite

Certificate has either expired or has been revoked

1.Change the setting of your Mac Timing to Automatic(Open Date& Time Preferences Check on set the Date and Time Automatically).

2.After that go to your X Code, Clean and Run The Code.

3.If it failed, log out of your Apple Profile and Delete all the Automatically Created Provisioning Profiles in XCode -- Preferences and Move all the Provisioning profiles to trash and download as a new file.Then LogIn again and Run your Code.

Comparing Class Types in Java

If you had two Strings and compared them using == by calling the getClass() method on them, it would return true. What you get is a reference on the same object.

This is because they are both references on the same class object. This is true for all classes in a java application. Java only loads the class once, so you have only one instance of a given class at a given time.

String hello  = "Hello";
String world = "world";

if (hello.getClass() == world.getClass()) {
    System.out.println("true");
} // prints true

How to have comments in IntelliSense for function in Visual Studio?

use /// to begin each line of the comment and have the comment contain the appropriate xml for the meta data reader.

///<summary>
/// this method says hello
///</summary>
public void SayHello();

Although personally, I believe that these comments are usually misguided, unless you are developing classes where the code cannot be read by its consumers.

How to compare two java objects

You need to Override equals and hashCode.
equals will compare the objects for equality according to the properties you need and hashCode is mandatory in order for your objects to be used correctly in Collections and Maps

MATLAB, Filling in the area between two sets of data, lines in one figure

You can accomplish this using the function FILL to create filled polygons under the sections of your plots. You will want to plot the lines and polygons in the order you want them to be stacked on the screen, starting with the bottom-most one. Here's an example with some sample data:

x = 1:100;             %# X range
y1 = rand(1,100)+1.5;  %# One set of data ranging from 1.5 to 2.5
y2 = rand(1,100)+0.5;  %# Another set of data ranging from 0.5 to 1.5
baseLine = 0.2;        %# Baseline value for filling under the curves
index = 30:70;         %# Indices of points to fill under

plot(x,y1,'b');                              %# Plot the first line
hold on;                                     %# Add to the plot
h1 = fill(x(index([1 1:end end])),...        %# Plot the first filled polygon
          [baseLine y1(index) baseLine],...
          'b','EdgeColor','none');
plot(x,y2,'g');                              %# Plot the second line
h2 = fill(x(index([1 1:end end])),...        %# Plot the second filled polygon
          [baseLine y2(index) baseLine],...
          'g','EdgeColor','none');
plot(x(index),baseLine.*ones(size(index)),'r');  %# Plot the red line

And here's the resulting figure:

enter image description here

You can also change the stacking order of the objects in the figure after you've plotted them by modifying the order of handles in the 'Children' property of the axes object. For example, this code reverses the stacking order, hiding the green polygon behind the blue polygon:

kids = get(gca,'Children');        %# Get the child object handles
set(gca,'Children',flipud(kids));  %# Set them to the reverse order

Finally, if you don't know exactly what order you want to stack your polygons ahead of time (i.e. either one could be the smaller polygon, which you probably want on top), then you could adjust the 'FaceAlpha' property so that one or both polygons will appear partially transparent and show the other beneath it. For example, the following will make the green polygon partially transparent:

set(h2,'FaceAlpha',0.5);

Count all occurrences of a string in lots of files with grep

Grep only solution which I tested with grep for windows:

grep -ro "pattern to find in files" "Directory to recursively search" | grep -c "pattern to find in files"

This solution will count all occurrences even if there are multiple on one line. -r recursively searches the directory, -o will "show only the part of a line matching PATTERN" -- this is what splits up multiple occurences on a single line and makes grep print each match on a new line; then pipe those newline-separated-results back into grep with -c to count the number of occurrences using the same pattern.

Find child element in AngularJS directive

jQlite (angular's "jQuery" port) doesn't support lookup by classes.

One solution would be to include jQuery in your app.

Another is using QuerySelector or QuerySelectorAll:

link: function(scope, element, attrs) {
   console.log(element[0].querySelector('.list-scrollable'))
}

We use the first item in the element array, which is the HTML element. element.eq(0) would yield the same.

FIDDLE

Convert java.util.date default format to Timestamp in Java

You can use the Calendar class to convert Date

public long getDifference()
{
    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
    Date d = sdf.parse("Mon May 27 11:46:15 IST 2013");

    Calendar c = Calendar.getInstance();
    c.setTime(d);
    long time = c.getTimeInMillis();
    long curr = System.currentTimeMillis();
    long diff = curr - time;    //Time difference in milliseconds
    return diff/1000;
}

__init__() missing 1 required positional argument

You're receiving this error because you did not pass a data variable to the DHT constructor.

aIKid and Alexander's answers are nice but it wont work because you still have to initialize self.data in the class constructor like this:

class DHT:
   def __init__(self, data=None):
      if data is None:
         data = {}
      else:
         self.data = data
      self.data['one'] = '1'
      self.data['two'] = '2'
      self.data['three'] = '3'
   def showData(self):
      print(self.data)

And then calling the method showData like this:

DHT().showData()

Or like this:

DHT({'six':6,'seven':'7'}).showData()

or like this:

# Build the class first
dht = DHT({'six':6,'seven':'7'})
# The call whatever method you want (In our case only 1 method available)
dht.showData()

How do change the color of the text of an <option> within a <select>?

Here is my demo with jQuery

<!doctype html>
<html>
<head>
<style>
    select{
        color:#aaa;
    }
    option:not(first-child) {
        color: #000;
    }
</style>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function(){
        $("select").change(function(){
            if ($(this).val()=="") $(this).css({color: "#aaa"});
            else $(this).css({color: "#000"});
        });
    }); 
</script>
<meta charset="utf-8">
</head>
<body>
<select>
    <option disable hidden value="">CHOOSE</option>
    <option>#1</option>
    <option>#2</option>
    <option>#3</option>
    <option>#4</option>
</select>
</body>
</html> 

https://jsfiddle.net/monster75/cnt73375/1/

Convert DateTime to long and also the other way around

There are several possibilities (note that the those long values aren't the same as the Unix epoch.

For your example (to reverse ToFileTime()) just use DateTime.FromFileTime(t).

Python regular expressions return true/false

You can use re.match() or re.search(). Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default). refer this

How To Set Text In An EditText

String string="this is a text";
editText.setText(string)

I have found String to be a useful Indirect Subclass of CharSequence

http://developer.android.com/reference/android/widget/TextView.html find setText(CharSequence text)

http://developer.android.com/reference/java/lang/CharSequence.html

This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console

Since the google policies update, you need to enable billing to access Map API.

Make XAMPP / Apache serve file outside of htdocs folder

If you're trying to get XAMPP to use a network drive as your document root you have to use UNC paths in httpd.conf. XAMPP will not recognize your mapped network drives.

For example the following won't work, DocumentRoot "X:/webroot"

But this will, DocumentRoot "//192.168.10.100/webroot" (note the forward slashes, not back slashes)

Load a Bootstrap popover content with AJAX. Is this possible?

I tried some of the suggestions here and I would like to present mine (which is a bit different) - I hope it will help someone. I wanted to show the popup on first click and hide it on second click (of course with updating the data each time). I used an extra variable visable to know whether the popover is visable or not. Here is my code: HTML:

<button type="button" id="votingTableButton" class="btn btn-info btn-xs" data-container="body" data-toggle="popover" data-placement="left" >Last Votes</button>

Javascript:

$('#votingTableButton').data("visible",false);

$('#votingTableButton').click(function() {  
if ($('#votingTableButton').data("visible")) {
    $('#votingTableButton').popover("hide");
    $('#votingTableButton').data("visible",false);          
}
else {
    $.get('votingTable.json', function(data) {
        var content = generateTableContent(data);
        $('#votingTableButton').popover('destroy');
        $('#votingTableButton').popover({title: 'Last Votes', 
                                content: content, 
                                trigger: 'manual',
                                html:true});
        $('#votingTableButton').popover("show");
        $('#votingTableButton').data("visible",true);   
    });
}   
});

Cheers!

How to label scatterplot points by name?

Another convoluted answer which should technically work and is ok for a small number of data points is to plot all your data points as 1 series in order to get your connecting line. Then plot each point as its own series. Then format data labels to display series name for each of the individual data points.

In short it works ok for a small data set or just key points from a data set.

Reading Email using Pop3 in C#

HigLabo.Mail is easy to use. Here is a sample usage:

using (Pop3Client cl = new Pop3Client()) 
{ 
    cl.UserName = "MyUserName"; 
    cl.Password = "MyPassword"; 
    cl.ServerName = "MyServer"; 
    cl.AuthenticateMode = Pop3AuthenticateMode.Pop; 
    cl.Ssl = false; 
    cl.Authenticate(); 
    ///Get first mail of my mailbox 
    Pop3Message mg = cl.GetMessage(1); 
    String MyText = mg.BodyText; 
    ///If the message have one attachment 
    Pop3Content ct = mg.Contents[0];         
    ///you can save it to local disk 
    ct.DecodeData("your file path"); 
} 

you can get it from https://github.com/higty/higlabo or Nuget [HigLabo]

Moment.js with ReactJS (ES6)

Since you are using webpack you should be able to just import or require moment and then use it:

import moment from 'moment'

...
render() {
    return (
        <div>
            { 
            this.props.data.map((post,key) => 
                <div key={key} className="post-detail">
                    <h1>{post.title}</h1>
                    <p>{moment(post.date).format()}</p>
                    <p dangerouslySetInnerHTML={{__html: post.content}}></p>
                    <hr />
                </div>
            )}
        </div>
    );
}
...

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

Just go to Web.Config from Main folder, not the one in Views Folder:

configSections

section name="entityFramework" type="System.Data. .....,Version=" <strong>5</strong>.0.0.0"..

<..>

ADJUST THE VERSION OF EntityFramework you have installed, ex. like Version 6.0.0.0"

Changing MongoDB data store directory

In debian/ubuntu, you'll need to edit the /etc/init.d/mongodb script. Really, this file should be pulling the settings from /etc/mongodb.conf but it doesn't seem to pull the default directory (probably a bug)

This is a bit of a hack, but adding these to the script made it start correctly:

add:

DBDIR=/database/mongodb

change:

DAEMON_OPTS=${DAEMON_OPTS:-"--unixSocketPrefix=$RUNDIR --config $CONF run"}

to:

DAEMON_OPTS=${DAEMON_OPTS:-"--unixSocketPrefix=$RUNDIR --dbpath $DBDIR --config $CONF run"}

Stretch Image to Fit 100% of Div Height and Width

Or you can put in the CSS,

<style>
div#img {
  background-image: url(“file.png");
  color:yellow (this part doesn't matter;
  height:100%;
  width:100%;
}
</style>

How can I add a table of contents to a Jupyter / JupyterLab notebook?

As Ian already pointed out, there is a table-of-contents extension by minrk for the IPython Notebook. I had some trouble to make it work and made this IPython Notebook which semi-automatically generates the files for minrk's table of contents extension in Windows. It does not use the 'curl'-commands or links, but writes the *.js and *.css files directly into your IPython Notebook-profile-directory.

There is a section in the notebook called 'What you need to do' - follow it and have a nice floating table of contents : )

Here is an html version which already shows it: http://htmlpreview.github.io/?https://github.com/ahambi/140824-TOC/blob/master/A%20floating%20table%20of%20contents.htm

How to get a path to a resource in a Java JAR file

private static final String FILE_LOCATION = "com/input/file/somefile.txt";

//Method Body


InputStream invalidCharacterInputStream = URLClassLoader.getSystemResourceAsStream(FILE_LOCATION);

Getting this from getSystemResourceAsStream is the best option. By getting the inputstream rather than the file or the URL, works in a JAR file and as stand alone.

How do I determine whether my calculation of pi is accurate?

The Taylor series is one way to approximate pi. As noted it converges slowly.

The partial sums of the Taylor series can be shown to be within some multiplier of the next term away from the true value of pi.

Other means of approximating pi have similar ways to calculate the max error.

We know this because we can prove it mathematically.

How to make Python script run as service?

first import os module in your app than with use from getpid function get pid's app and save in a file.for example :

import os
pid = os.getpid()
op = open("/var/us.pid","w")
op.write("%s" % pid)
op.close()

and create a bash file in /etc/init.d path: /etc/init.d/servername

PATHAPP="/etc/bin/userscript.py &"
PIDAPP="/var/us.pid"
case $1 in 
        start)
                echo "starting"
                $(python $PATHAPP)
        ;;
        stop)
                echo "stoping"
                PID=$(cat $PIDAPP)
                kill $PID
        ;;

esac

now , u can start and stop ur app with down command:

service servername stop service servername start

or

/etc/init.d/servername stop /etc/init.d/servername start

$_POST Array from html form

You should get the array like in $_POST['id']. So you should be able to do this:

foreach ($_POST['id'] as $key => $value) {
    echo $value . "<br />";
}

Input names should be same:

<input name='id[]' type='checkbox' value='1'>
<input name='id[]' type='checkbox' value='2'>
...

Protect image download

Try this one-

<script>
    (function($){
      $(document).on('contextmenu', 'img', function() {
          return false;
      })
    })(jQuery);
  </script>

How to check the version of GitLab?

For omnibus versions:\

sudo gitlab-rake gitlab:env:info

Example:

System information
System:     Ubuntu 12.04
Current User:   git
Using RVM:  no
Ruby Version:   2.1.7p400
Gem Version:    2.2.5
Bundler Version:1.10.6
Rake Version:   10.4.2
Sidekiq Version:3.3.0

GitLab information
Version:    8.2.2
Revision:   08fae2f
Directory:  /opt/gitlab/embedded/service/gitlab-rails
DB Adapter: postgresql
URL:        https://your.hostname
HTTP Clone URL: https://your.hostname/some-group/some-project.git
SSH Clone URL:  [email protected]:some-group/some-project.git
Using LDAP: yes
Using Omniauth: no

GitLab Shell
Version:    2.6.8
Repositories:   /var/opt/gitlab/git-data/repositories
Hooks:      /opt/gitlab/embedded/service/gitlab-shell/hooks/
Git:        /opt/gitlab/embedded/bin/git

How do I use shell variables in an awk script?

I had to insert date at the beginning of the lines of a log file and it's done like below:

DATE=$(date +"%Y-%m-%d")
awk '{ print "'"$DATE"'", $0; }' /path_to_log_file/log_file.log

It can be redirect to another file to save

Onchange open URL via select - jQuery

Try this code its working Firefox, Chrome, IE

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
<option value="" selected>---Select---</option>
<option value="https://www.google.com">Google</option>
<option value="https://www.google.com">Google</option>
<option value="https://www.google.com">Google</option>
<option value="https://www.google.com">Google</option>

How do I convert a org.w3c.dom.Document object to a String?

use some thing like

import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

//method to convert Document to String
public String getStringFromDocument(Document doc)
{
    try
    {
       DOMSource domSource = new DOMSource(doc);
       StringWriter writer = new StringWriter();
       StreamResult result = new StreamResult(writer);
       TransformerFactory tf = TransformerFactory.newInstance();
       Transformer transformer = tf.newTransformer();
       transformer.transform(domSource, result);
       return writer.toString();
    }
    catch(TransformerException ex)
    {
       ex.printStackTrace();
       return null;
    }
} 

Converting List<String> to String[] in Java

public static void main(String[] args) {
    List<String> strlist = new ArrayList<String>();
    strlist.add("sdfs1");
    strlist.add("sdfs2");

    String[] strarray = new String[strlist.size()]
    strlist.toArray(strarray );

    System.out.println(strarray);


}

Difference between window.location.href=window.location.href and window.location.reload()

A difference in Firefox (12.0) is that on a page rendered from a POST, reload() will pop up a warning and do a re-post, while a URL assignment will do a GET.

Google Chrome does a GET for both.

Function to check if a string is a date

If your heart is set on using regEx then txt2re.com is always a good resource:

<?php

  $txt='2012-06-14 01:46:28';
  $re1='((?:2|1)\\d{3}(?:-|\\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:T|\\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9]))';    # Time Stamp 1

  if ($c=preg_match_all ("/".$re1."/is", $txt, $matches))
  {
      $timestamp1=$matches[1][0];
      print "($timestamp1) \n";
  }

?>

pandas get column average/mean

You can easily follow the following code

import pandas as pd 
import numpy as np 
        
classxii = {'Name':['Karan','Ishan','Aditya','Anant','Ronit'],
            'Subject':['Accounts','Economics','Accounts','Economics','Accounts'],
            'Score':[87,64,58,74,87],
            'Grade':['A1','B2','C1','B1','A2']}

df = pd.DataFrame(classxii,index = ['a','b','c','d','e'],columns=['Name','Subject','Score','Grade'])
print(df)

#use the below for mean if you already have a dataframe
print('mean of score is:')
print(df[['Score']].mean())

How do I calculate r-squared using Python and Numpy?

From scipy.stats.linregress source. They use the average sum of squares method.

import numpy as np

x = np.array(x)
y = np.array(y)

# average sum of squares:
ssxm, ssxym, ssyxm, ssym = np.cov(x, y, bias=1).flat

r_num = ssxym
r_den = np.sqrt(ssxm * ssym)
r = r_num / r_den

if r_den == 0.0:
    r = 0.0
else:
    r = r_num / r_den

    if r > 1.0:
        r = 1.0
    elif r < -1.0:
        r = -1.0

Reading Datetime value From Excel sheet

Alternatively, if your cell is already a real date, just use .Value instead of .Value2:

excelApp.Range[namedRange].Value
{21/02/2013 00:00:00}
    Date: {21/02/2013 00:00:00}
    Day: 21
    DayOfWeek: Thursday
    DayOfYear: 52
    Hour: 0
    Kind: Unspecified
    Millisecond: 0
    Minute: 0
    Month: 2
    Second: 0
    Ticks: 634970016000000000
    TimeOfDay: {00:00:00}
    Year: 2013

excelApp.Range[namedRange].Value2
41326.0

How to select a drop-down menu value with Selenium using Python?

As per the HTML provided:

<select id="fruits01" class="select" name="fruits">
  <option value="0">Choose your fruits:</option>
  <option value="1">Banana</option>
  <option value="2">Mango</option>
</select>

To select an <option> element from a menu you have to use the Select Class. Moreover, as you have to interact with the you have to induce WebDriverWait for the element_to_be_clickable().

To select the <option> with text as Mango from the you can use you can use either of the following Locator Strategies:

  • Using ID attribute and select_by_visible_text() method:

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.ui import Select
    
    select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "fruits01"))))
    select.select_by_visible_text("Mango")
    
  • Using CSS-SELECTOR and select_by_value() method:

    select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "select.select[name='fruits']"))))
    select.select_by_value("2")
    
  • Using XPATH and select_by_index() method:

    select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "//select[@class='select' and @name='fruits']"))))
    select.select_by_index(2)
    

How do I show my global Git configuration?

You can also call git config -e to open the configuration file in your editor directly. The Git configuration file is much more readable that the -l output, so I always tend to use the -e flag.

So to summarise:

git config -l  # List Git configuration settings (same as --list)
git config -e  # Opens Git configuration in the default editor (same as --edit)
  • Without parameters it interacts with the local .git/config.
  • With --global it interacts with ~/.gitconfig.
  • And with --system it interacts with $(prefix)/etc/gitconfig.

(I couldn't really find what $(prefix) means, but it seems to default to $HOME.)

Moment js get first and last day of current month

Assuming you are using a Date range Picker to retrieve the dates. You could do something like to to get what you want.

$('#daterange-btn').daterangepicker({
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            },
            startDate: moment().subtract(29, 'days'),
            endDate: moment()
        }, function (start, end) {
      alert( 'Date is between' + start.format('YYYY-MM-DD h:m') + 'and' + end.format('YYYY-MM-DD h:m')}

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

Steps for Window10:

  • Go to https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python
  • Download the right version according to python version and hardware specs: for my case, mysqlclient-1.4.2-cp37-cp37m-win32.whl works for python3.7 and Intel CPU.
  • While your env is still activated, go to the download folder and run pip install mysqlclient-1.4.2-cp37-cp37m-win32.whl

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

I solved this issue by running the following command in an elevated command prompt as specified in this post.

net start mssqlserver

adb connection over tcp not working now

This answer is late, but hopefully it helps others.

I have had the same experience of not being able to connect. Rebooting phone and PC does not help. I found the fix at: http://developer.android.com/tools/help/adb.html at the bottom of the page.

Basically you follow these steps:

  1. Connect phone with usb cable to PC.
  2. Issue command: adb usb
  3. Issue command: adb tcpip 5555
  4. Issue command: adb connect xxx.xxx.xxx.xxx

Where xxx.xxx.xxx.xxx is your phone's IP address.

Cut off text in string after/before separator in powershell

$pos = $name.IndexOf(";")
$leftPart = $name.Substring(0, $pos)
$rightPart = $name.Substring($pos+1)

Internally, PowerShell uses the String class.

How do I access previous promise results in a .then() chain?

I am not going to use this pattern in my own code since I'm not a big fan of using global variables. However, in a pinch it will work.

User is a promisified Mongoose model.

var globalVar = '';

User.findAsync({}).then(function(users){
  globalVar = users;
}).then(function(){
  console.log(globalVar);
});

Change EditText hint color when using TextInputLayout

android:textColorHint="#FFFFFF" sometime works and sometime doesnt. For me below solution works perfectly

Try The Below Code It Works In your XML file and TextLabel theme is defined in style.xml

 <android.support.design.widget.TextInputLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:theme="@style/MyTextLabel">

     <EditText
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:hint="Floating Label"
         android:id="@+id/edtText"/>

 </android.support.design.widget.TextInputLayout>

In Styles Folder TextLabel Code

 <style name="MyTextLabel" parent="TextAppearance.AppCompat">
    <!-- Hint color and label color in FALSE state -->
    <item name="android:textColorHint">@color/Color Name</item> 
<!--The size of the text appear on label in false state -->
    <item name="android:textSize">20sp</item>
    <!-- Label color in TRUE state and bar color FALSE and TRUE State -->
    <item name="colorAccent">@color/Color Name</item>
    <item name="colorControlNormal">@color/Color Name</item>
    <item name="colorControlActivated">@color/Color Name</item>
 </style>

If you just want to change the color of label in false state then colorAccent , colorControlNormal and colorControlActivated are not required

How to simulate a button click using code?

there is a better way.

View.performClick();

http://developer.android.com/reference/android/view/View.html#performClick()

this should answer all your problems. every View inherits this function, including Button, Spinner, etc.

Just to clarify, View does not have a static performClick() method. You must call performClick() on an instance of View. For example, you can't just call

View.performClick();

Instead, do something like:

View myView = findViewById(R.id.myview);
myView.performClick();

How to call a shell script from python code?

Please Try the following codes :

Import Execute 

Execute("zbx_control.sh")

Extract and delete all .gz in a directory- Linux

There's more than one way to do this obviously.

    # This will find files recursively (you can limit it by using some 'find' parameters. 
    # see the man pages
    # Final backslash required for exec example to work
    find . -name '*.gz' -exec gunzip '{}' \;

    # This will do it only in the current directory
    for a in *.gz; do gunzip $a; done

I'm sure there's other ways as well, but this is probably the simplest.

And to remove it, just do a rm -rf *.gz in the applicable directory

How do I send an HTML Form in an Email .. not just MAILTO

You are making sense, but you seem to misunderstand the concept of sending emails.

HTML is parsed on the client side, while the e-mail needs to be sent from the server. You cannot do it in pure HTML. I would suggest writing a PHP script that will deal with the email sending for you.

Basically, instead of the MAILTO, your form's action will need to point to that PHP script. In the script, retrieve the values passed by the form (in PHP, they are available through the $_POST superglobal) and use the email sending function (mail()).

Of course, this can be done in other server-side languages as well. I'm giving a PHP solution because PHP is the language I work with.

A simple example code:

form.html:

<form method="post" action="email.php">
    <input type="text" name="subject" /><br />
    <textarea name="message"></textarea>
</form>

email.php:

<?php
    mail('[email protected]', $_POST['subject'], $_POST['message']);
?>
<p>Your email has been sent.</p>

Of course, the script should contain some safety measures, such as checking whether the $_POST valies are at all available, as well as additional email headers (sender's email, for instance), perhaps a way to deal with character encoding - but that's too complex for a quick example ;).

How do I do a not equal in Django queryset filtering?

the field=value syntax in queries is a shorthand for field__exact=value. That is to say that Django puts query operators on query fields in the identifiers. Django supports the following operators:

exact
iexact
contains
icontains
in
gt
gte
lt
lte
startswith
istartswith
endswith
iendswith
range

date
year
iso_year
month
day
week
week_day
iso_week_day
quarter
time
hour
minute
second

isnull
regex
iregex

I'm sure by combining these with the Q objects as Dave Vogt suggests and using filter() or exclude() as Jason Baker suggests you'll get exactly what you need for just about any possible query.

Select distinct using linq

myList.GroupBy(i => i.id).Select(group => group.First())

Ant task to run an Ant target only if a file exists?

Available and Condition

<target name="check-abc">
    <available file="abc.txt" property="abc.present"/>
</target>

<target name="do-if-abc" depends="check-abc" if="abc.present">
    ...
</target> 

How to get the height of a body element

We were trying to avoid using the IE specific

$window[0].document.body.clientHeight 

And found that the following jQuery will not consistently yield the same value but eventually does at some point in our page load scenario which worked for us and maintained cross-browser support:

$(document).height()

MySQL Like multiple values

Your query should be SELECT * FROM `table` WHERE find_in_set(interests, "sports,pub")>0

What I understand is that you store the interests in one field of your table, which is a misconception. You should definitively have an "interest" table.

Installing pip packages to $HOME folder

I would use virtualenv at your HOME directory.

$ sudo easy_install -U virtualenv
$ cd ~
$ virtualenv .
$ bin/pip ...

You could then also alter ~/.(login|profile|bash_profile), whichever is right for your shell to add ~/bin to your PATH and then that pip|python|easy_install would be the one used by default.

HTTP 1.0 vs 1.1

A key compatibility issue is support for persistent connections. I recently worked on a server that "supported" HTTP/1.1, yet failed to close the connection when a client sent an HTTP/1.0 request. When writing a server that supports HTTP/1.1, be sure it also works well with HTTP/1.0-only clients.

Move div to new line

Try this

#movie_item {
    display: block;
    margin-top: 10px;
    height: 175px;
}

.movie_item_poster {
    float: left;
    height: 150px;
    width: 100px;
    background: red;
}

#movie_item_content {
    float: left;
    background: gold;
}

.movie_item_content_title {
    display: block;
}

.movie_item_content_year {
    float: right;
}

.movie_item_content_plot {
    display: block;

}

.movie_item_toolbar {
    clear: both;
    vertical-align: bottom;
    width: 100%;
    height: 25px;
}

In Html

<div id="movie_item">
    <div class="movie_item_poster">
        <img src="..." style="max-width: 100%; max-height: 100%;">
    </div>

     <div id="movie_item_content">
            <div class="movie_item_content_year">(1890-)</div>
        <div class="movie_item_content_title">title my film is a long word</div>
        <div class="movie_item_content_plot">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officia, ratione, aliquam, earum, quibusdam libero rerum iusto exercitationem reiciendis illo corporis nulla ducimus suscipit nisi dolore explicabo. Accusantium porro reprehenderit ad!</div>
    </div>

    <div class="movie_item_toolbar">
        Lorem Ipsum...
    </div>
</div>

I change position div year.

Which is faster: Stack allocation or Heap allocation

Stack is much faster. It literally only uses a single instruction on most architectures, in most cases, e.g. on x86:

sub esp, 0x10

(That moves the stack pointer down by 0x10 bytes and thereby "allocates" those bytes for use by a variable.)

Of course, the stack's size is very, very finite, as you will quickly find out if you overuse stack allocation or try to do recursion :-)

Also, there's little reason to optimize the performance of code that doesn't verifiably need it, such as demonstrated by profiling. "Premature optimization" often causes more problems than it's worth.

My rule of thumb: if I know I'm going to need some data at compile-time, and it's under a few hundred bytes in size, I stack-allocate it. Otherwise I heap-allocate it.

How to change MySQL timezone in a database connection using Java?

For applications such as Squirrel SQL Client (http://squirrel-sql.sourceforge.net/) version 4 you can set "serverTimezone" under "driver properties" to GMT+1 (example of timezone "Europe/Vienna).

Java :Add scroll into text area

The Easiest way to implement scrollbar using java swing is as below :

  1. Navigate to Design view
  2. right click on textArea
  3. Select surround with JScrollPane

Wait for page load in Selenium

The best way I've seen is to utilize the stalenessOf ExpectedCondition, to wait for the old page to become stale.

Example:

WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 10);

WebElement oldHtml = driver.findElement(By.tagName("html"));
wait.until(ExpectedConditions.stalenessOf(oldHtml));

It'll wait for ten seconds for the old HTML tag to become stale, and then throw an exception if it doesn't happen.

display HTML page after loading complete

The easiest thing to do is putting a div with the following CSS in the body:

#hideAll
 {
   position: fixed;
   left: 0px; 
   right: 0px; 
   top: 0px; 
   bottom: 0px; 
   background-color: white;
   z-index: 99; /* Higher than anything else in the document */

 }

(Note that position: fixed won't work in IE6 - I know of no sure-fire way of doing this in that browser)

Add the DIV like so (directly after the opening body tag):

<div style="display: none" id="hideAll">&nbsp;</div>

show the DIV directly after :

 <script type="text/javascript">
   document.getElementById("hideAll").style.display = "block";
 </script> 

and hide it onload:

 window.onload = function() 
  { document.getElementById("hideAll").style.display = "none"; }

or using jQuery

 $(window).load(function() {  document.getElementById("hideAll").style.display = "none"; });

this approach has the advantage that it will also work for clients who have JavaScript turned off. It shouldn't cause any flickering or other side-effects, but not having tested it, I can't entirely guarantee it for every browser out there.

How does delete[] know it's an array?

This is very similar to this question and it has many of the details your are looking for.

But suffice to say, it is not the job of the OS to track any of this. It's actually the runtime libraries or the underlying memory manager that will track the size of the array. This is usually done by allocating extra memory up front and storing the size of the array in that location (most use a head node).

This is viewable on some implementations by executing the following code

int* pArray = new int[5];
int size = *(pArray-1);

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

In my case (.Net Core Web API) for this issue HTTP Error 500.19 – Internal Server Error 0x8007000d

First download dotnet-hosting-3.0.0-preview5-19227-01-win (.Net Core 3) or dotnetcore 2 hasting windows

https://download.visualstudio.microsoft.com/download/pr/5bed16f2-fd1a-4027-bee3-3d6a1b5844cc/dd22ca2820fadb57fd5378e1763d27cd/dotnet-hosting-3.1.4-win.exe

Any .net core 3.1 application either angular or mvc application would need this.

Second install it as Administrator Open cmd as administrator, type iisreset, press enter

So refresh your localhost app

Best regard M.M.Tofighi from Iran

What throws an IOException in Java?

Java documentation is helpful to know the root cause of a particular IOException.

Just have a look at the direct known sub-interfaces of IOException from the documentation page:

ChangedCharSetException, CharacterCodingException, CharConversionException, ClosedChannelException, EOFException, FileLockInterruptionException, FileNotFoundException, FilerException, FileSystemException, HttpRetryException, IIOException, InterruptedByTimeoutException, InterruptedIOException, InvalidPropertiesFormatException, JMXProviderException, JMXServerErrorException, MalformedURLException, ObjectStreamException, ProtocolException, RemoteException, SaslException, SocketException, SSLException, SyncFailedException, UnknownHostException, UnknownServiceException, UnsupportedDataTypeException, UnsupportedEncodingException, UserPrincipalNotFoundException, UTFDataFormatException, ZipException

Most of these exceptions are self-explanatory.

A few IOExceptions with root causes:

EOFException: Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal the end of the stream.

SocketException: Thrown to indicate that there is an error creating or accessing a Socket.

RemoteException: A RemoteException is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call. Each method of a remote interface, an interface that extends java.rmi.Remote, must list RemoteException in its throws clause.

UnknownHostException: Thrown to indicate that the IP address of a host could not be determined (you may not be connected to Internet).

MalformedURLException: Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.

Guzzlehttp - How get the body of a response from Guzzle 6?

For get response in JSON format :

  1.$response = (string) $res->getBody();
      $response =json_decode($response); // Using this you can access any key like below
     
     $key_value = $response->key_name; //access key  

  2. $response = json_decode($res->getBody(),true);
     
     $key_value =   $response['key_name'];//access key

Only variables should be passed by reference

Since it raise a flag for over 10 years, but works just fine and return the expected value, a little stfu operator is the goodiest bad practice you are all looking for:

$file_extension = @end(explode('.', $file_name));

But warning, don't use in loops due to a performance hit. Newest version of php 7.3+ offer the method array_key_last() and array_key_first().

https://www.php.net/manual/en/function.array-key-last.php

Exception: Can't bind to 'ngFor' since it isn't a known native property

In my case I made the mistake of copying *ng-for= from the docs.

https://angular.io/guide/user-input

Correct me if I am wrong. But it seems *ng-for= has been changed to *ngFor=

How can I put CSS and HTML code in the same file?

You can include CSS styles in an html document with <style></style> tags.

Example:

<style>
  .myClass { background: #f00; }

  .myOtherClass { font-size: 12px; }
</style>

Error: expected type-specifier before 'ClassName'

First of all, let's try to make your code a little simpler:

// No need to create a circle unless it is clearly necessary to
// demonstrate the problem

// Your Rect2f defines a default constructor, so let's use it for simplicity.
shared_ptr<Shape> rect(new Rect2f());

Okay, so now we see that the parentheses are clearly balanced. What else could it be? Let's check the following code snippet's error:

int main() {
    delete new T();
}

This may seem like weird usage, and it is, but I really hate memory leaks. However, the output does seem useful:

In function 'int main()':
Line 2: error: expected type-specifier before 'T'

Aha! Now we're just left with the error about the parentheses. I can't find what causes that; however, I think you are forgetting to include the file that defines Rect2f.

How do you append an int to a string in C++?

These work for general strings (in case you do not want to output to file/console, but store for later use or something).

boost.lexical_cast

MyStr += boost::lexical_cast<std::string>(MyInt);

String streams

//sstream.h
std::stringstream Stream;
Stream.str(MyStr);
Stream << MyInt;
MyStr = Stream.str();

// If you're using a stream (for example, cout), rather than std::string
someStream << MyInt;

Use a JSON array with objects with javascript

_x000D_
_x000D_
var datas = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}];_x000D_
document.writeln("<table border = '1' width = 100 >");_x000D_
document.writeln("<tr><td>No Id</td><td>Title</td></tr>"); _x000D_
for(var i=0;i<datas.length;i++){_x000D_
document.writeln("<tr><td>"+datas[i].id+"</td><td>"+datas[i].Title+"</td></tr>");_x000D_
}_x000D_
document.writeln("</table>");
_x000D_
_x000D_
_x000D_

Is there a method that tells my program to quit?

See sys.exit. That function will quit your program with the given exit status.

How to delete from select in MySQL?

If you want to delete all duplicates, but one out of each set of duplicates, this is one solution:

DELETE posts
FROM posts
LEFT JOIN (
    SELECT id
    FROM posts
    GROUP BY id
    HAVING COUNT(id) = 1

    UNION

    SELECT id
    FROM posts
    GROUP BY id
    HAVING COUNT(id) != 1
) AS duplicate USING (id)
WHERE duplicate.id IS NULL;

Could you explain STA and MTA?

The COM threading model is called an "apartment" model, where the execution context of initialized COM objects is associated with either a single thread (Single Thread Apartment) or many threads (Multi Thread Apartment). In this model, a COM object, once initialized in an apartment, is part of that apartment for the duration of its runtime.

The STA model is used for COM objects that are not thread safe. That means they do not handle their own synchronization. A common use of this is a UI component. So if another thread needs to interact with the object (such as pushing a button in a form) then the message is marshalled onto the STA thread. The windows forms message pumping system is an example of this.

If the COM object can handle its own synchronization then the MTA model can be used where multiple threads are allowed to interact with the object without marshalled calls.

Adding background image to div using CSS

Use:

.content {
    background: url('http://www.gransebryan.com/wp-content/uploads/2016/03/bryan-ganzon-granse-who.png') center no-repeat;
 }

.displaybg {
   text-align: center;
   color: #FFF;
}

Get drop down value

<select onchange = "selectChanged(this.value)">
  <item value = "1">one</item>
  <item value = "2">two</item>
</select>

and then the javascript...

function selectChanged(newvalue) {
  alert("you chose: " + newvalue);
}

Parsing a pcap file in python

I would use python-dpkt. Here is the documentation: http://www.commercialventvac.com/dpkt.html

This is all I know how to do though sorry.

#!/usr/local/bin/python2.7

import dpkt

counter=0
ipcounter=0
tcpcounter=0
udpcounter=0

filename='sampledata.pcap'

for ts, pkt in dpkt.pcap.Reader(open(filename,'r')):

    counter+=1
    eth=dpkt.ethernet.Ethernet(pkt) 
    if eth.type!=dpkt.ethernet.ETH_TYPE_IP:
       continue

    ip=eth.data
    ipcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_TCP: 
       tcpcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_UDP:
       udpcounter+=1

print "Total number of packets in the pcap file: ", counter
print "Total number of ip packets: ", ipcounter
print "Total number of tcp packets: ", tcpcounter
print "Total number of udp packets: ", udpcounter

Update:

Project on GitHub, documentation here

Carry Flag, Auxiliary Flag and Overflow Flag in Assembly

Carry Flag

The rules for turning on the carry flag in binary/integer math are two:

  1. The carry flag is set if the addition of two numbers causes a carry out of the most significant (leftmost) bits added. 1111 + 0001 = 0000 (carry flag is turned on)

  2. The carry (borrow) flag is also set if the subtraction of two numbers requires a borrow into the most significant (leftmost) bits subtracted. 0000 - 0001 = 1111 (carry flag is turned on) Otherwise, the carry flag is turned off (zero).

    • 0111 + 0001 = 1000 (carry flag is turned off [zero])
    • 1000 - 0001 = 0111 (carry flag is turned off [zero])

In unsigned arithmetic, watch the carry flag to detect errors.

In signed arithmetic, the carry flag tells you nothing interesting.

Overflow Flag

The rules for turning on the overflow flag in binary/integer math are two:

  1. If the sum of two numbers with the sign bits off yields a result number with the sign bit on, the "overflow" flag is turned on. 0100 + 0100 = 1000 (overflow flag is turned on)

  2. If the sum of two numbers with the sign bits on yields a result number with the sign bit off, the "overflow" flag is turned on. 1000 + 1000 = 0000 (overflow flag is turned on)

Otherwise the "overflow" flag is turned off

  • 0100 + 0001 = 0101 (overflow flag is turned off)
  • 0110 + 1001 = 1111 (overflow flag turned off)
  • 1000 + 0001 = 1001 (overflow flag turned off)
  • 1100 + 1100 = 1000 (overflow flag is turned off)

Note that you only need to look at the sign bits (leftmost) of the three numbers to decide if the overflow flag is turned on or off.

If you are doing two's complement (signed) arithmetic, overflow flag on means the answer is wrong - you added two positive numbers and got a negative, or you added two negative numbers and got a positive.

If you are doing unsigned arithmetic, the overflow flag means nothing and should be ignored.

For more clarification please refer: http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt

Android - running a method periodically using postDelayed() call

Why don't you create service and put logic in onCreate(). In this case even if you press back button service will keep on executing. and once you enter into application it will not call onCreate() again. Rather it will call onStart()

MySQL Install: ERROR: Failed to build gem native extension

I had a similar experience, so here are the things that I tried

Firstly, I tried to install mysql's required packages by running the command below in my terminal

sudo apt-get install build-essential libmysqlclient-dev

Secondly, I tried updating rubygems on my system by running the command below in my terminal

sudo gem update --system

But I was still experiencing the same issue. After much research I realized that I was using an almost out-of-date version of the mysql gem. I simply needed to use the mysql2 gem (mysql2 gem)and not the mysql gem, so I fixed it by running the command below in my terminal

gem install mysql2

This worked fine for me. Before running the last command, ensure that you've ran the first and second commands to be sure that everything is fine on your system.

That's all.

I hope this helps

Binding an Image in WPF MVVM

@Sheridan thx.. if I try your example with "DisplayedImagePath" on both sides, it works with absolute path as you show.

As for the relative paths, this is how I always connect relative paths, I first include the subdirectory (!) and the image file in my project.. then I use ~ character to denote the bin-path..

    public string DisplayedImagePath
    {
        get { return @"~\..\images\osc.png"; }
    }

This was tested, see below my Solution Explorer in VS2015..

example of image binding in VS2015)

Note: if you want a Click event, use the Button tag around the image,

_x000D_
_x000D_
<Button Click="image_Click" Width="128" Height="128"  Grid.Row="2" VerticalAlignment="Top" HorizontalAlignment="Left">_x000D_
  <Image x:Name="image" Source="{Binding DisplayedImagePath}" Margin="0,0,0,0" />_x000D_
</Button>
_x000D_
_x000D_
_x000D_

Creating the Singleton design pattern in PHP5

I know this is probably going to cause an unnecessary flame war, but I can see how you might want more than one database connection, so I would concede the point that singleton might not be the best solution for that... however, there are other uses of the singleton pattern that I find extremely useful.

Here's an example: I decided to roll my own MVC and templating engine because I wanted something really lightweight. However, the data that I want to display contains a lot of special math characters such as ≥ and μ and what have you... The data is stored as the actual UTF-8 character in my database rather than pre-HTML-encoded because my app can deliver other formats such as PDF and CSV in addition to HTML. The appropriate place to format for HTML is inside the template ("view" if you will) that is responsible for rendering that page section (snippet). I want to convert them to their appropriate HTML entities, but PHPs get_html_translation_table() function is not super fast. It makes better sense to retrieve the data one time and store as an array, making it available for all to use. Here's a sample I knocked together to test the speed. Presumably, this would work regardless of whether the other methods you use (after getting the instance) were static or not.

class EncodeHTMLEntities {

    private static $instance = null;//stores the instance of self
    private $r = null;//array of chars elligalbe for replacement

    private function __clone(){
    }//disable cloning, no reason to clone

    private function __construct()
    {
        $allEntities = get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES);
        $specialEntities = get_html_translation_table(HTML_SPECIALCHARS, ENT_NOQUOTES);
        $this->r = array_diff($allEntities, $specialEntities);
    }

    public static function replace($string)
    {
        if(!(self::$instance instanceof self) ){
            self::$instance = new self();
        }
        return strtr($string, self::$instance->r);
    }
}
//test one million encodings of a string
$start = microtime(true);
for($x=0; $x<1000000; $x++){
    $dump = EncodeHTMLEntities::replace("Reference method for diagnosis of CDAD, but clinical usefulness limited due to extended turnaround time (=96 hrs)");
}
$end = microtime(true);
echo "Run time: ".($end-$start)." seconds using singleton\n";
//now repeat the same without using singleton
$start = microtime(true);
for($x=0; $x<1000000; $x++){
    $allEntities = get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES);
    $specialEntities = get_html_translation_table(HTML_SPECIALCHARS, ENT_NOQUOTES);
    $r = array_diff($allEntities, $specialEntities);
    $dump = strtr("Reference method for diagnosis of CDAD, but clinical usefulness limited due to extended turnaround time (=96 hrs)", $r);
}
$end = microtime(true);
echo "Run time: ".($end-$start)." seconds without using singleton";

Basically, I saw typical results like this:

php test.php
Run time: 27.842966794968 seconds using singleton
Run time: 237.78191494942 seconds without using singleton

So while I'm certainly no expert, I don't see a more convenient and reliable way to reduce the overhead of slow calls for some kind of data, while making it super simple (single line of code to do what you need). Granted my example only has one useful method, and therefore is no better than a globally defined function, but as soon as you have two methods, you're going to want to group them together, right? Am I way off base?

Also, I prefer examples that actually DO something, since sometimes it's hard to visualise when an example includes statements like "//do something useful here" which I see all the time when searching for tutorials.

Anyway, I'd love any feedback or comments on why using a singleton for this type of thing is detrimental (or overly complicated).

How to multi-line "Replace in files..." in Notepad++

It's easy to do multiline replace in Notepad++. You have to use \n to represent the newline in your string, and it works for both search and replace strings. You have to make sure to select "Extended" search mode in the bottom left corner of the search window.

I found a good article describing the features here: http://markantoniou.blogspot.com/2008/06/notepad-how-to-use-regular-expressions.html

Better way to remove specific characters from a Perl string

You've misunderstood how character classes are used:

$varTemp =~ s/[\$#@~!&*()\[\];.,:?^ `\\\/]+//g;

does the same as your regex (assuming you didn't mean to remove ' characters from your strings).

Edit: The + allows several of those "special characters" to match at once, so it should also be faster.

Failed to install *.apk on device 'emulator-5554': EOF

Try window->show view->devices->view menu->Reset adb and again run application.

How can I scale the content of an iframe?

For those of you having trouble getting this to work in IE, it is helpful to use -ms-zoom as suggested below and use the zoom function on the #wrap div, not the iframe id. In my experience, with the zoom function trying to scale the iframe div of #frame, it would scale the iframe size and not the content within it (which is what you're going for).

Looks like this. Works for me on IE8, Chrome and FF.

#wrap {
  overflow: hidden;
  position: relative;
  width:800px;
  height:850px;
  -ms-zoom: 0.75;
}

Count the number of commits on a Git branch

If you are using a UNIX system, you could do

git log|grep "Author"|wc -l

How to disable postback on an asp Button (System.Web.UI.WebControls.Button)

YourButton.Attributes.Add("onclick", "return false");

or

<asp:button runat="server" ... OnClientClick="return false" />

How to "inverse match" with regex?

(?!Andrea).{6}

Assuming your regexp engine supports negative lookaheads..

Edit: ..or maybe you'd prefer to use [A-Za-z]{6} in place of .{6}

Edit (again): Note that lookaheads and lookbehinds are generally not the right way to "inverse" a regular expression match. Regexps aren't really set up for doing negative matching, they leave that to whatever language you are using them with.

How to get the type of T from a member of a generic class or method?

Using 3dGrabber's solution:

public static T GetEnumeratedType<T>(this IEnumerable<T> _)
{
    return default(T);
}

//and now 

var list = new Dictionary<string, int>();
var stronglyTypedVar = list.GetEnumeratedType();

how to get the value of css style using jquery

You code is correct. replace items with .items as below

<script>
  var n = $(".items").css("left");
  if(n == -900){
    $(".items span").fadeOut("slow");
  }
</script>

Logical operators ("and", "or") in DOS batch

Try the negation operand - 'not'!

Well, if you can perform 'AND' operation on an if statement using nested 'if's (refer previous answers), then you can do the same thing with 'if not' to perform an 'or' operation.

If you haven't got the idea quite as yet, read on. Otherwise, just don't waste your time and get back to programming.

Just as nested 'if's are satisfied only when all conditions are true, nested 'if not's are satisfied only when all conditions are false. This is similar to what you want to do with an 'or' operand, isn't it?

Even when any one of the conditions in the nested 'if not' is true, the whole statement remains non-satisfied. Hence, you can use negated 'if's in succession by remembering that the body of the condition statement should be what you wanna do if all your nested conditions are false. The body that you actually wanted to give should come under the else statement.

And if you still didn't get the jist of the thing, sorry, I'm 16 and that's the best I can do to explain.

How to get the difference between two arrays of objects in JavaScript

For those who like one-liner solutions in ES6, something like this:

_x000D_
_x000D_
const arrayOne = [ _x000D_
  { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer" },_x000D_
  { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed" },_x000D_
  { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi" },_x000D_
  { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal" },_x000D_
  { value: "a63a6f77-c637-454e-abf2-dfb9b543af6c", display: "Ryan" },_x000D_
];_x000D_
          _x000D_
const arrayTwo = [_x000D_
  { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer"},_x000D_
  { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed"},_x000D_
  { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi"},_x000D_
  { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal"},_x000D_
];_x000D_
_x000D_
const results = arrayOne.filter(({ value: id1 }) => !arrayTwo.some(({ value: id2 }) => id2 === id1));_x000D_
_x000D_
console.log(results);
_x000D_
_x000D_
_x000D_

How to assign pointer address manually in C programming language?

Your code would be like this:

int *p = (int *)0x28ff44;

int needs to be the type of the object that you are referencing or it can be void.

But be careful so that you don't try to access something that doesn't belong to your program.

Webpack how to build production code and how to use it

You can use argv npm module (install it by running npm install argv --save) for getting params in your webpack.config.js file and as for production you use -p flag "build": "webpack -p", you can add condition in webpack.config.js file like below

plugins: [
    new webpack.DefinePlugin({
        'process.env':{
            'NODE_ENV': argv.p ? JSON.stringify('production') : JSON.stringify('development')
        }
    })
]

And thats it.

:first-child not working as expected

:first-child selects the first h1 if and only if it is the first child of its parent element. In your example, the ul is the first child of the div.

The name of the pseudo-class is somewhat misleading, but it's explained pretty clearly here in the spec.

jQuery's :first selector gives you what you're looking for. You can do this:

$('.detail_container h1:first').css("color", "blue");

Android: how to make an activity return results to the activity which calls it?

Your error is in resultCode = Activity.RESULT_CANCELED, you should instance like resultCode == Activity.RESULT_CANCELED ==

React-Native: Module AppRegistry is not a registered callable module

I solved this problem by doing the following:

  1. cd android
  2. ./gradlew clean
  3. taskkill /f /im node.exe
  4. uninstall app from android

Omitting the second expression when using the if-else shorthand

Another option:

x === 2 ? doSomething() : void 0;

make script execution to unlimited

Your script could be stopping, not because of the PHP timeout but because of the timeout in the browser you're using to access the script (ie. Firefox, Chrome, etc). Unfortunately there's seldom an easy way to extend this timeout, and in most browsers you simply can't. An option you have here is to access the script over a terminal. For example, on Windows you would make sure the PHP executable is in your path variable and then I think you execute:

C:\path\to\script> php script.php

Or, if you're using the PHP CGI, I think it's:

C:\path\to\script> php-cgi script.php

Plus, you would also set ini_set('max_execution_time', 0); in your script as others have mentioned. When running a PHP script this way, I'm pretty sure you can use buffer flushing to echo out the script's progress to the terminal periodically if you wish. The biggest issue I think with this method is there's really no way of stopping the script once it's started, other than stopping the entire PHP process or service.

How to configure SMTP settings in web.config

Web.Config file:

<configuration>
 <system.net>
        <mailSettings>
            <smtp from="[email protected]">
                <network host="smtp.gmail.com" 
                 port="587" 
                 userName="[email protected]" 
                 password="yourpassword" 
                 enableSsl="true"/>
            </smtp>
        </mailSettings>
</system.net>
</configuration>

Force decimal point instead of comma in HTML5 number input (client-side)

Sadly, the coverage of this input field in the modern browsers is very low:

http://caniuse.com/#feat=input-number

Therefore, I recommend to expect the fallback and rely on a heavy-programmatically-loaded input[type=text] to do the job, until the field is generally accepted.

So far, only Chrome, Safari and Opera have a neat implementation, but all other browsers are buggy. Some of them, don't even seem to support decimals (like BB10)!

Android: how to hide ActionBar on certain activities

Apply the following in your Theme for the Activity in AndroidManifest.xml:

<activity android:name=".DashboardActivity"
        android:theme="@style/AppFullScreenTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

Then Apply the following in your Style in style.xml

<style name="AppFullScreenTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

Are global variables bad?

Global variables are generally bad, especially if other people are working on the same code and don't want to spend 20mins searching for all the places the variable is referenced. And adding threads that modify the variables brings in a whole new level of headaches.

Global constants in an anonymous namespace used in a single translation unit are fine and ubiquitous in professional apps and libraries. But if the data is mutable, and/or it has to be shared between multiple TUs, you may want to encapsulate it--if not for design's sake, then for the sake of anybody debugging or working with your code.

How to convert seconds to time format?

something like this?

if(is_numeric($time)){
    $value = array(
        "years" => 0, "days" => 0, "hours" => 0,
        "minutes" => 0, "seconds" => 0,
    );
    if($time >= 31556926){
        $value["years"] = floor($time/31556926);
        $time = ($time%31556926);
    }
    if($time >= 86400){
        $value["days"] = floor($time/86400);
        $time = ($time%86400);
    }
    if($time >= 3600){
        $value["hours"] = floor($time/3600);
        $time = ($time%3600);
    }
    if($time >= 60){
        $value["minutes"] = floor($time/60);
        $time = ($time%60);
    }

    $value["seconds"] = floor($time);
    return (array) $value;
    
} else{
    return (bool) FALSE;
}

grabbed from: http://www.ckorp.net/sec2time.php

How to skip a iteration/loop in while-loop

Try to add continue; where you want to skip 1 iteration.

Unlike the break keyword, continue does not terminate a loop. Rather, it skips to the next iteration of the loop, and stops executing any further statements in this iteration. This allows us to bypass the rest of the statements in the current sequence, without stopping the next iteration through the loop.

http://www.javacoffeebreak.com/articles/loopyjava/index.html

PIG how to count a number of rows in alias

Basic counting is done as was stated in other answers, and in the pig documentation:

logs = LOAD 'log';
all_logs_in_a_bag = GROUP logs ALL;
log_count = FOREACH all_logs_in_a_bag GENERATE COUNT(logs);
dump log_count

You are right that counting is inefficient, even when using pig's builtin COUNT because this will use one reducer. However, I had a revelation today that one of the ways to speed it up would be to reduce the RAM utilization of the relation we're counting.

In other words, when counting a relation, we don't actually care about the data itself so let's use as little RAM as possible. You were on the right track with your first iteration of the count script.

logs = LOAD 'log'
ones = FOREACH logs GENERATE 1 AS one:int;
counter_group = GROUP ones ALL;
log_count = FOREACH counter_group GENERATE COUNT(ones);
dump log_count

This will work on much larger relations than the previous script and should be much faster. The main difference between this and your original script is that we don't need to sum anything.

This also doesn't have the same problem as other solutions where null values would impact the count. This will count all the rows, regardless of if the first column is null or not.

subquery in FROM must have an alias

In the case of nested tables, some DBMS require to use an alias like MySQL and Oracle but others do not have such a strict requirement, but still allow to add them to substitute the result of the inner query.

How do I list loaded plugins in Vim?

Not a VIM user myself, so forgive me if this is totally offbase. But according to what I gather from the following VIM Tips site:

" where was an option set  
:scriptnames            : list all plugins, _vimrcs loaded (super)  
:verbose set history?   : reveals value of history and where set  
:function               : list functions  
:func SearchCompl       : List particular function

How can I debug a HTTP POST in Chrome?

You can filter for HTTP POST requests with the Chrome DevTools. Just do the following:

  1. Open Chrome DevTools (Cmd+Opt+I on Mac, Ctrl+Shift+I or F12 on Windows) and click on the "Network" tab
  2. Click on the "Filter" icon
  3. Enter your filter method: method:POST
  4. Select the request you want to debug
  5. View the details of the request you want to debug

Screenshot

Chrome DevTools

Tested with Chrome Version 53.

'Must Override a Superclass Method' Errors after importing a project into Eclipse

In my case this problem happened when I imported a Maven project into Eclipse. To solve this, I added the following in pom.xml:

<properties>
   ...
   <maven.compiler.source>1.8</maven.compiler.source>
   <maven.compiler.target>1.8</maven.compiler.target>
</properties>

Then in the context menu of the project, go to "Maven -> Update Project ...", and press OK.

That's it. Hope this helps.

How to get all checked checkboxes

A simple for loop which tests the checked property and appends the checked ones to a separate array. From there, you can process the array of checkboxesChecked further if needed.

// Pass the checkbox name to the function
function getCheckedBoxes(chkboxName) {
  var checkboxes = document.getElementsByName(chkboxName);
  var checkboxesChecked = [];
  // loop over them all
  for (var i=0; i<checkboxes.length; i++) {
     // And stick the checked ones onto an array...
     if (checkboxes[i].checked) {
        checkboxesChecked.push(checkboxes[i]);
     }
  }
  // Return the array if it is non-empty, or null
  return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}

// Call as
var checkedBoxes = getCheckedBoxes("mycheckboxes");

Array slices in C#

Here's a simple extension method that returns a slice as a new array:

public static T[] Slice<T>(this T[] arr, uint indexFrom, uint indexTo) {
    if (indexFrom > indexTo) {
        throw new ArgumentOutOfRangeException("indexFrom is bigger than indexTo!");
    }

    uint length = indexTo - indexFrom;
    T[] result = new T[length];
    Array.Copy(arr, indexFrom, result, 0, length);

    return result;
}

Then you can use it as:

byte[] slice = foo.Slice(0, 40);

How to disable an input type=text?

You can get the DOM element and set disabled attribute to true/false.

If you use vue framework,here is a very easy demo.

_x000D_
_x000D_
  let vm = new Vue({
        el: "#app",
        data() {
            return { flag: true }
        },
        computed: {
            btnText() {
                return this.flag ? "Enable" : "Disable";
            }
        }
    })
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
    <input type="text" value="something" :disabled="flag" />
    <input type="button" :value="btnText" @click="flag=!flag">
</div>
_x000D_
_x000D_
_x000D_

Error: Expression must have integral or unscoped enum type

Your variable size is declared as: float size;

You can't use a floating point variable as the size of an array - it needs to be an integer value.

You could cast it to convert to an integer:

float *temp = new float[(int)size];

Your other problem is likely because you're writing outside of the bounds of the array:

   float *temp = new float[size];

    //Getting input from the user
    for (int x = 1; x <= size; x++){
        cout << "Enter temperature " << x << ": ";

        // cin >> temp[x];
        // This should be:
        cin >> temp[x - 1];
    }

Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.

#1273 - Unknown collation: 'utf8mb4_unicode_ci' cPanel

The technique in this post worked for me

1) Click the "Export" tab for the database

2) Click the "Custom" radio button

3) Go the section titled "Format-specific options" and change the dropdown for "Database system or older MySQL server to maximize output compatibility with:" from NONE to MYSQL40.

4) Scroll to the bottom and click "GO".

I'm not certain if doing this causes any data loss, however in the one time I've tried it I did not notice any. Neither did anyone who responded in the forums linked to above.

Edit 8/12/16 - I believe exporting a database in this way causes me to lose data saved in Black Studio TinyMCE Visual Editor widgets, though I haven't ran multiple tests to confirm.

How do I set up curl to permanently use a proxy?

Curl will look for a .curlrc file in your home folder when it starts. You can create (or edit) this file and add this line:

proxy = yourproxy.com:8080

What is a bus error?

You can also get SIGBUS when a code page cannot be paged in for some reason.

How can I expose more than 1 port with Docker?

Step1

In your Dockerfile, you can use the verb EXPOSE to expose multiple ports.
e.g.

EXPOSE 3000 80 443 22

Step2

You then would like to build an new image based on above Dockerfile.
e.g.

docker build -t foo:tag .

Step3

Then you can use the -p to map host port with the container port, as defined in above EXPOSE of Dockerfile.
e.g.

docker run -p 3001:3000 -p 23:22

In case you would like to expose a range of continuous ports, you can run docker like this:

docker run -it -p 7100-7120:7100-7120/tcp 

how to release localhost from Error: listen EADDRINUSE

On Linux (Ubuntu derivatives at least)

killall node

is easier than this form.

ps | grep <something>
kill <somepid>

Neither will work if you have a orphaned child holding the port. Instead, do this:

netstat -punta | grep <port>

If the port is being held you'll see something like this:

tcp           0      0.0.0.0:<port>          0.0.0.*       LISTEN     <pid>/<parent>

Now kill by pid:

kill -9 <pid>

curl.h no such file or directory

Instead of downloading curl, down libcurl.

curl is just the application, libcurl is what you need for your C++ program

http://packages.ubuntu.com/quantal/curl