Programs & Examples On #Disjoint sets

Anything related to disjoint sets, i.e. mathematical sets that have no element in common.

Java GC (Allocation Failure)

"Allocation Failure" is a cause of GC cycle to kick in.

"Allocation Failure" means that no more space left in Eden to allocate object. So, it is normal cause of young GC.

Older JVM were not printing GC cause for minor GC cycles.

"Allocation Failure" is almost only possible cause for minor GC. Another reason for minor GC to kick could be CMS remark phase (if +XX:+ScavengeBeforeRemark is enabled).

Are loops really faster in reverse?

It depends on placement of your array in memory and the hit ratio of memory pages while you are accessing that array.

In some cases accessing array members in column order is faster than row order because of the increase in hit ratio.

MySQL Error: #1142 - SELECT command denied to user

This is th privileges issue in your database users. first check and grant permission to user 'marco' in localhost

How to make flexbox items the same size?

Im no expert with flex but I got there by setting the basis to 50% for the two items i was dealing with. Grow to 1 and shrink to 0.

Inline styling: flex: '1 0 50%',

UITableViewCell Selected Background Color on Multiple Selection

You can also set cell's selectionStyle to.none in interface builder. The same solution as @AhmedLotfy provided, only from IB.

enter image description here

Intermediate language used in scalac?

maybe this will help you out:

http://lampwww.epfl.ch/~paltherr/phd/altherr-phd.pdf

or this page:

www.scala-lang.org/node/6372‎

How to Get the HTTP Post data in C#?

In my case because I assigned the post data to the header, this is how I get it:

protected void Page_Load(object sender, EventArgs e){
    ...
    postValue = Request.Headers["Key"];

This is how I attached the value and key to the POST:

var request = new NSMutableUrlRequest(url){
    HttpMethod = "POST", 
    Headers = NSDictionary.FromObjectAndKey(FromObject(value), FromObject("key"))
};
webView.LoadRequest(request);

Why are iframes considered dangerous and a security risk?

The IFRAME element may be a security risk if your site is embedded inside an IFRAME on hostile site. Google "clickjacking" for more details. Note that it does not matter if you use <iframe> or not. The only real protection from this attack is to add HTTP header X-Frame-Options: DENY and hope that the browser knows its job.

In addition, IFRAME element may be a security risk if any page on your site contains an XSS vulnerability which can be exploited. In that case the attacker can expand the XSS attack to any page within the same domain that can be persuaded to load within an <iframe> on the page with XSS vulnerability. This is because content from the same origin (same domain) is allowed to access the parent content DOM (practically execute JavaScript in the "host" document). The only real protection methods from this attack is to add HTTP header X-Frame-Options: DENY and/or always correctly encode all user submitted data (that is, never have an XSS vulnerability on your site - easier said than done).

That's the technical side of the issue. In addition, there's the issue of user interface. If you teach your users to trust that URL bar is supposed to not change when they click links (e.g. your site uses a big iframe with all the actual content), then the users will not notice anything in the future either in case of actual security vulnerability. For example, you could have an XSS vulnerability within your site that allows the attacker to load content from hostile source within your iframe. Nobody could tell the difference because the URL bar still looks identical to previous behavior (never changes) and the content "looks" valid even though it's from hostile domain requesting user credentials.

If somebody claims that using an <iframe> element on your site is dangerous and causes a security risk, he does not understand what <iframe> element does, or he is speaking about possibility of <iframe> related vulnerabilities in browsers. Security of <iframe src="..."> tag is equal to <img src="..." or <a href="..."> as long there are no vulnerabilities in the browser. And if there's a suitable vulnerability, it might be possible to trigger it even without using <iframe>, <img> or <a> element, so it's not worth considering for this issue.

However, be warned that content from <iframe> can initiate top level navigation by default. That is, content within the <iframe> is allowed to automatically open a link over current page location (the new location will be visible in the address bar). The only way to avoid that is to add sandbox attribute without value allow-top-navigation. For example, <iframe sandbox="allow-forms allow-scripts" ...>. Unfortunately, sandbox also disables all plugins, always. For example, Youtube content cannot be sandboxed because Flash player is still required to view all Youtube content. No browser supports using plugins and disallowing top level navigation at the same time.

Note that X-Frame-Options: DENY also protects from rendering performance side-channel attack that can read content cross-origin (also known as "Pixel perfect Timing Attacks").

Display current date and time without punctuation

If you're using Bash you could also use one of the following commands:

printf '%(%Y%m%d%H%M%S)T'       # prints the current time
printf '%(%Y%m%d%H%M%S)T' -1    # same as above
printf '%(%Y%m%d%H%M%S)T' -2    # prints the time the shell was invoked

You can use the Option -v varname to store the result in $varname instead of printing it to stdout:

printf -v varname '%(%Y%m%d%H%M%S)T'

While the date command will always be executed in a subshell (i.e. in a separate process) printf is a builtin command and will therefore be faster.

Specifying an Index (Non-Unique Key) Using JPA

It's not possible to do that using JPA annotation. And this make sense: where a UniqueConstraint clearly define a business rules, an index is just a way to make search faster. So this should really be done by a DBA.

Code coverage with Mocha

You need an additional library for code coverage, and you are going to be blown away by how powerful and easy istanbul is. Try the following, after you get your mocha tests to pass:

npm install nyc

Now, simply place the command nyc in front of your existing test command, for example:

{
  "scripts": {
    "test": "nyc mocha"
  }
}

How to make the HTML link activated by clicking on the <li>?

Or you can create an empty link at the end of your <li>:

<a href="link"></a>

.menu li{position:relative;padding:0;}
.link{
     bottom: 0;
     left: 0;
     position: absolute;
     right: 0;
     top: 0;
}

This will create a full clickable <li> and keep your formatting on your real link. It could be useful for <div> tag as well

Integrating the ZXing library directly into my Android application

Step by step to setup zxing 3.2.1 in eclipse

  1. Download zxing-master.zip from "https://github.com/zxing/zxing"
  2. Unzip zxing-master.zip, Use eclipse to import "android" project in zxing-master
  3. Download core-3.2.1.jar from "http://repo1.maven.org/maven2/com/google/zxing/core/3.2.1/"
  4. Create "libs" folder in "android" project and paste cor-3.2.1.jar into the libs folder
  5. Click on project: choose "properties" -> "Java Compiler" to change level to 1.7. Then click on "Android" change "Project build target" to android 4.4.2+, because using 1.7 requires compiling with Android 4.4
  6. If "CameraConfigurationUtils.java" don't exist in "zxing-master/android/app/src/main/java/com/google/zxing/client/android/camera/". You can copy it from "zxing-master/android-core/src/main/java/com/google/zxing/client/android/camera/" and paste to your project.
  7. Clean and build project. If your project show error about "switch - case", you should change them to "if - else".
  8. Completed. Clean and build project.
  9. Reference link: Using ZXing to create an android barcode scanning app

How to show x and y axes in a MATLAB graph?

Easiest solution:

plot([0,0],[0.0], xData, yData);

This creates an invisible line between the points [0,0] to [0,0] and since Matlab wants to include these points it will shows the axis.

Creating temporary files in Android

This is what I typically do:

File outputDir = context.getCacheDir(); // context being the Activity pointer
File outputFile = File.createTempFile("prefix", "extension", outputDir);

As for their deletion, I am not complete sure either. Since I use this in my implementation of a cache, I manually delete the oldest files till the cache directory size comes down to my preset value.

Using underscores in Java variables and method names

I think any style that breaks a language's own style guidelines (without due reason) is ugly and therefore "bad".

No doubt the code you've seen was written by someone who used to work on a language where underscores were acceptable.

Some people just cannot adapt to new coding styles...

When should I create a destructor?

UPDATE: This question was the subject of my blog in May of 2015. Thanks for the great question! See the blog for a long list of falsehoods that people commonly believe about finalization.

When should I manually create a destructor?

Almost never.

Typically one only creates a destructor when your class is holding on to some expensive unmanaged resource that must be cleaned up when the object goes away. It is better to use the disposable pattern to ensure that the resource is cleaned up. A destructor is then essentially an assurance that if the consumer of your object forgets to dispose it, the resource still gets cleaned up eventually. (Maybe.)

If you make a destructor be extremely careful and understand how the garbage collector works. Destructors are really weird:

  • They don't run on your thread; they run on their own thread. Don't cause deadlocks!
  • An unhandled exception thrown from a destructor is bad news. It's on its own thread; who is going to catch it?
  • A destructor may be called on an object after the constructor starts but before the constructor finishes. A properly written destructor will not rely on invariants established in the constructor.
  • A destructor can "resurrect" an object, making a dead object alive again. That's really weird. Don't do it.
  • A destructor might never run; you can't rely on the object ever being scheduled for finalization. It probably will be, but that's not a guarantee.

Almost nothing that is normally true is true in a destructor. Be really, really careful. Writing a correct destructor is very difficult.

When have you needed to create a destructor?

When testing the part of the compiler that handles destructors. I've never needed to do so in production code. I seldom write objects that manipulate unmanaged resources.

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

I use the following command to reload Nginx (version 1.5.9) only if a configuration test was successful:

/etc/init.d/nginx configtest && sudo /etc/init.d/nginx reload

If you need to do this often, you may want to use an alias. I use the following:

alias n='/etc/init.d/nginx configtest && sudo /etc/init.d/nginx reload'

The trick here is done by the "&&" which only executes the second command if the first was successful. You can see here a more detailed explanation of the use of the "&&" operator.

You can use "restart" instead of "reload" if you really want to restart the server.

ASP.Net Download file to client browser

Try changing it to.

 Response.Clear();
 Response.ClearHeaders();
 Response.ClearContent();
 Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
 Response.AddHeader("Content-Length", file.Length.ToString());
 Response.ContentType = "text/plain";
 Response.Flush();
 Response.TransmitFile(file.FullName);
 Response.End();

How to verify static void method has been called with power mockito

Thou the above answer is widely accepted and well documented, I found some of the reason to post my answer here :-

    doNothing().when(InternalUtils.class); //This is the preferred way
                                           //to mock static void methods.
    InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());

Here, I dont understand why we are calling InternalUtils.sendEmail ourself. I will explain in my code why we don't need to do that.

mockStatic(Internalutils.class);

So, we have mocked the class which is fine. Now, lets have a look how we need to verify the sendEmail(/..../) method.

@PrepareForTest({InternalService.InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest {

    @Mock
    private InternalService.Order order;

    private InternalService internalService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        internalService = new InternalService();
    }

    @Test
    public void processOrder() throws Exception {

        Mockito.when(order.isSuccessful()).thenReturn(true);
        PowerMockito.mockStatic(InternalService.InternalUtils.class);

        internalService.processOrder(order);

        PowerMockito.verifyStatic(times(1));
        InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
    }

}

These two lines is where the magic is, First line tells the PowerMockito framework that it needs to verify the class it statically mocked. But which method it need to verify ?? Second line tells which method it needs to verify.

PowerMockito.verifyStatic(times(1));
InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());

This is code of my class, sendEmail api twice.

public class InternalService {

    public void processOrder(Order order) {
        if (order.isSuccessful()) {
            InternalUtils.sendEmail("", new String[1], "", "");
            InternalUtils.sendEmail("", new String[1], "", "");
        }
    }

    public static class InternalUtils{

        public static void sendEmail(String from, String[]  to, String msg, String body){

        }

    }

    public class Order{

        public boolean isSuccessful(){
            return true;
        }

    }

}

As it is calling twice you just need to change the verify(times(2))... that's all.

How to get index of object by its property in JavaScript?

This might be useful

function showProps(obj, objName) {  
  var result = "";  
  for (var i in obj)  
    result += objName + "." + i + " = " + obj[i] + "\n";  
  return result;  
}

Copied this from https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects

What exactly does stringstream do?

To answer the question. stringstream basically allows you to treat a string object like a stream, and use all stream functions and operators on it.

I saw it used mainly for the formatted output/input goodness.

One good example would be c++ implementation of converting number to stream object.

Possible example:

template <class T>
string num2str(const T& num, unsigned int prec = 12) {
    string ret;
    stringstream ss;
    ios_base::fmtflags ff = ss.flags();
    ff |= ios_base::floatfield;
    ff |= ios_base::fixed;
    ss.flags(ff);
    ss.precision(prec);
    ss << num;
    ret = ss.str();
    return ret;
};

Maybe it's a bit complicated but it is quite complex. You create stringstream object ss, modify its flags, put a number into it with operator<<, and extract it via str(). I guess that operator>> could be used.

Also in this example the string buffer is hidden and not used explicitly. But it would be too long of a post to write about every possible aspect and use-case.

Note: I probably stole it from someone on SO and refined, but I don't have original author noted.

Drawing an image from a data URL to a canvas

Perhaps this fiddle would help ThumbGen - jsFiddle It uses File API and Canvas to dynamically generate thumbnails of images.

(function (doc) {
    var oError = null;
    var oFileIn = doc.getElementById('fileIn');
    var oFileReader = new FileReader();
    var oImage = new Image();
    oFileIn.addEventListener('change', function () {
        var oFile = this.files[0];
        var oLogInfo = doc.getElementById('logInfo');
        var rFltr = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i
        try {
            if (rFltr.test(oFile.type)) {
                oFileReader.readAsDataURL(oFile);
                oLogInfo.setAttribute('class', 'message info');
                throw 'Preview for ' + oFile.name;
            } else {
                oLogInfo.setAttribute('class', 'message error');
                throw oFile.name + ' is not a valid image';
            }
        } catch (err) {
            if (oError) {
                oLogInfo.removeChild(oError);
                oError = null;
                $('#logInfo').fadeOut();
                $('#imgThumb').fadeOut();
            }
            oError = doc.createTextNode(err);
            oLogInfo.appendChild(oError);
            $('#logInfo').fadeIn();
        }
    }, false);
    oFileReader.addEventListener('load', function (e) {
        oImage.src = e.target.result;
    }, false);
    oImage.addEventListener('load', function () {
        if (oCanvas) {
            oCanvas = null;
            oContext = null;
            $('#imgThumb').fadeOut();
        }
        var oCanvas = doc.getElementById('imgThumb');
        var oContext = oCanvas.getContext('2d');
        var nWidth = (this.width > 500) ? this.width / 4 : this.width;
        var nHeight = (this.height > 500) ? this.height / 4 : this.height;
        oCanvas.setAttribute('width', nWidth);
        oCanvas.setAttribute('height', nHeight);
        oContext.drawImage(this, 0, 0, nWidth, nHeight);
        $('#imgThumb').fadeIn();
    }, false);
})(document);

How to call javascript function from code-behind

If the order of the execution is not important and you need both some javascript AND some codebehind to be fired on an asp element, heres what you can do.

What you can take away from my example: I have a div covering the ASP control that I want both javascript and codebehind to be ran from. The div's onClick method AND the calendar's OnSelectionChanged event both get fired this way.

In this example, i am using an ASP Calendar control, and im controlling it from both javascript and codebehind:

Front end code:

        <div onclick="showHideModal();">
            <asp:Calendar 
                OnSelectionChanged="DatepickerDateChange" ID="DatepickerCalendar" runat="server" 
                BorderWidth="1px" DayNameFormat="Shortest" Font-Names="Verdana" 
                Font-Size="8pt" ShowGridLines="true" BackColor="#B8C9E1" BorderColor="#003E51" Width="100%"> 
                <OtherMonthDayStyle ForeColor="#6C5D34"> </OtherMonthDayStyle> 
                <DayHeaderStyle  ForeColor="black" BackColor="#D19000"> </DayHeaderStyle>
                <TitleStyle BackColor="#B8C9E1" ForeColor="Black"> </TitleStyle> 
                <DayStyle BackColor="White"> </DayStyle> 
                <SelectedDayStyle BackColor="#003E51" Font-Bold="True"> </SelectedDayStyle> 
            </asp:Calendar>
        </div>

Codebehind:

        protected void DatepickerDateChange(object sender, EventArgs e)
        {
            if (toFromPicked.Value == "MainContent_fromDate")
            {
                fromDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
            }
            else
            {
                toDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
            }
        }

Django, creating a custom 500/404 error page

Try moving your error templates to .../Django/mysite/templates/ ?

I'm note sure about this one, but i think these need to be "global" to the website.

how to get javaScript event source element?

I believe the solution by @slipset was correct, but wasn't cross-browser ready.

According to Javascript.info, events (when referenced outside markup events) are cross-browser ready once you assure it's defined with this simple line: event = event || window.event.

So the complete cross-browser ready function would look like this:

function doSomething(param){
  event = event || window.event;
  var source = event.target || event.srcElement;
  console.log(source);
}

Converting any string into camel case

Here's my suggestion:

function toCamelCase(string) {
  return `${string}`
    .replace(new RegExp(/[-_]+/, 'g'), ' ')
    .replace(new RegExp(/[^\w\s]/, 'g'), '')
    .replace(
      new RegExp(/\s+(.)(\w+)/, 'g'),
      ($1, $2, $3) => `${$2.toUpperCase() + $3.toLowerCase()}`
    )
    .replace(new RegExp(/\s/, 'g'), '')
    .replace(new RegExp(/\w/), s => s.toLowerCase());
}

or

String.prototype.toCamelCase = function() {
  return this
    .replace(new RegExp(/[-_]+/, 'g'), ' ')
    .replace(new RegExp(/[^\w\s]/, 'g'), '')
    .replace(
      new RegExp(/\s+(.)(\w+)/, 'g'),
      ($1, $2, $3) => `${$2.toUpperCase() + $3.toLowerCase()}`
    )
    .replace(new RegExp(/\s/, 'g'), '')
    .replace(new RegExp(/\w/), s => s.toLowerCase());
};

Test cases:

describe('String to camel case', function() {
  it('should return a camel cased string', function() {
    chai.assert.equal(toCamelCase('foo bar'), 'fooBar');
    chai.assert.equal(toCamelCase('Foo Bar'), 'fooBar');
    chai.assert.equal(toCamelCase('fooBar'), 'fooBar');
    chai.assert.equal(toCamelCase('FooBar'), 'fooBar');
    chai.assert.equal(toCamelCase('--foo-bar--'), 'fooBar');
    chai.assert.equal(toCamelCase('__FOO_BAR__'), 'fooBar');
    chai.assert.equal(toCamelCase('!--foo-¿?-bar--121-**%'), 'fooBar121');
  });
});

"git pull" or "git merge" between master and development branches

my rule of thumb is:

rebase for branches with the same name, merge otherwise.

examples for same names would be master, origin/master and otherRemote/master.

if develop exists only in the local repository, and it is always based on a recent origin/master commit, you should call it master, and work there directly. it simplifies your life, and presents things as they actually are: you are directly developing on the master branch.

if develop is shared, it should not be rebased on master, just merged back into it with --no-ff. you are developing on develop. master and develop have different names, because we want them to be different things, and stay separate. do not make them same with rebase.

Use ffmpeg to add text subtitles

ffmpeg supports the mov_text subtitle encoder which is about the only one supported in an MP4 container and playable by iTunes, Quicktime, iOS etc.

Your line would read:

ffmpeg -i input.mp4 -i input.srt -map 0:0 -map 0:1 -map 1:0 -c:s mov_text output.mp4

File Upload in WebView

This solution also works for Honeycomb and Ice Cream Sandwich. Seems like Google introduced a cool new feature (accept attribute) and forgot to to implement an overload for backwards compatibility.

protected class CustomWebChromeClient extends WebChromeClient
{
    // For Android 3.0+
    public void openFileChooser( ValueCallback<Uri> uploadMsg, String acceptType ) 
    {  
        context.mUploadMessage = uploadMsg;  
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);  
        i.addCategory(Intent.CATEGORY_OPENABLE);  
        i.setType("image/*");  
        context.startActivityForResult( Intent.createChooser( i, "File Chooser" ), MainActivity.FILECHOOSER_RESULTCODE );  
    }

    // For Android < 3.0
    public void openFileChooser( ValueCallback<Uri> uploadMsg ) 
    {
        openFileChooser( uploadMsg, "" );
    }
}

Google Geocoding API - REQUEST_DENIED

Until the end of 2014, a common source of this error was omitting the mandatory sensor parameter from the request, as below. However since then this is no longer required:

The sensor Parameter

The Google Maps API previously required that you include the sensor parameter to indicate whether your application used a sensor to determine the user's location. This parameter is no longer required.


Did you specify the sensor parameter on the request?

"REQUEST_DENIED" indicates that your request was denied, generally because of lack of a sensor parameter.

sensor (required) — Indicates whether or not the geocoding request comes from a device with a location sensor. This value must be either true or false

How to list branches that contain a given commit?

You may run:

git log <SHA1>..HEAD --ancestry-path --merges

From comment of last commit in the output you may find original branch name

Example:

       c---e---g--- feature
      /         \
-a---b---d---f---h---j--- master

git log e..master --ancestry-path --merges

commit h
Merge: g f
Author: Eugen Konkov <>
Date:   Sat Oct 1 00:54:18 2016 +0300

    Merge branch 'feature' into master

How to change theme for AlertDialog

You can override the default theme used by DialogFragments spawned by an activity by modifying the activity's theme's attributes....

set the activity's theme in AndroidManifest.xml.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.helloworld">

    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">     <!-- set all Activity themes to your custom theme -->

        .....

    </application>

</manifest>

in the values/styles.xml, override the item used to determine what theme to use for spawned DialogFragments

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="AppTheme" parent="Theme.AppCompat">

        <!-- override the default theme for DialogFragments -->
        <item name="android:dialogTheme">@style/AppTheme.Dialog</item>

    </style>

    .....

</resources>

in the values/styles.xml, define and configure the theme you want to use for DialogFragments

<?xml version="1.0" encoding="utf-8"?>
<resources>

    .....

    <!--
        configure your custom theme for DialogFragments...
    -->
    <style name="AppTheme.Dialog" parent="Theme.AppCompat.Dialog.MinWidth">

        <!-- override the default theme for DialogFragments spawned by this DialogFragment -->
        <item name="android:dialogTheme">@style/AppTheme.Dialog</item>

        <!--
            OPTIONAL: override the background for the dialog...i am using a dark theme,
            and for some reason, there is no themes for dialogs with dark backgrounds,
            so, i made my own.
        -->
        <item name="android:windowBackground">@drawable/dialog__window_background</item>

        <!--
            add the title to the dialog's theme. you can remove it later by using
            DialogFragment.setStyle()
        -->
        <item name="android:windowNoTitle">false</item>
        <item name="windowNoTitle">?android:windowNoTitle</item>

    </style>

    .....

</resources>

OPTIONAL: if you use a dark theme, and overrode android:windowBackground like i did in AppTheme.Dialog, then add a drawable/dialog__window_background.xml file with the contents:

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetLeft="16dp"
    android:insetTop="16dp"
    android:insetRight="16dp"
    android:insetBottom="16dp">
    <shape android:shape="rectangle">
        <corners android:radius="?dialogCornerRadius" />
        <solid android:color="?android:colorBackground" />
    </shape>
</inset>

How to run docker-compose up -d at system start up?

When we use crontab or the deprecated /etc/rc.local file, we need a delay (e.g. sleep 10, depending on the machine) to make sure that system services are available. Usually, systemd (or upstart) is used to manage which services start when the system boots. You can try use the similar configuration for this:

# /etc/systemd/system/docker-compose-app.service

[Unit]
Description=Docker Compose Application Service
Requires=docker.service
After=docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/srv/docker
ExecStart=/usr/local/bin/docker-compose up -d
ExecStop=/usr/local/bin/docker-compose down
TimeoutStartSec=0

[Install]
WantedBy=multi-user.target

Or, if you want run without the -d flag:

# /etc/systemd/system/docker-compose-app.service

[Unit]
Description=Docker Compose Application Service
Requires=docker.service
After=docker.service

[Service]
WorkingDirectory=/srv/docker
ExecStart=/usr/local/bin/docker-compose up
ExecStop=/usr/local/bin/docker-compose down
TimeoutStartSec=0
Restart=on-failure
StartLimitIntervalSec=60
StartLimitBurst=3

[Install]
WantedBy=multi-user.target

Change the WorkingDirectory parameter with your dockerized project path. And enable the service to start automatically:

systemctl enable docker-compose-app

Compare dates in MySQL

this is what it worked for me:

select * from table
where column
BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
 AND STR_TO_DATE('07/10/15', '%d/%m/%Y')

Please, note that I had to change STR_TO_DATE(column, '%d/%m/%Y') from previous solutions, as it was taking ages to load

bash: npm: command not found?

If you already installed npm globally on your system, and you are still getting the above error message by using VSCode terminal. Just close your VSCode application and reopen again, that should resolve the issue.

Unable to auto-detect email address

Make sure that you opened git as admin or root.

How to allocate aligned memory only using the standard library?

Perhaps they would have been satisfied with a knowledge of memalign? And as Jonathan Leffler points out, there are two newer preferable functions to know about.

Oops, florin beat me to it. However, if you read the man page I linked to, you'll most likely understand the example supplied by an earlier poster.

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

A foreign key with a cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete.

You are saying in a opposite way, this is not that when you delete from child table then records will be deleted from parent table.

UPDATE 1:

ON DELETE CASCADE option is to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behaviour of the database server prevents you from deleting data in a table if other tables reference it.

If you specify this option, later when you delete a row in the parent table, the database server also deletes any rows associated with that row (foreign keys) in a child table. The principal advantage to the cascading-deletes feature is that it allows you to reduce the quantity of SQL statements you need to perform delete actions.

So it's all about what will happen when you delete rows from Parent table not from child table.

So in your case when user removes entries from CATs table then rows will be deleted from books table. :)

Hope this helps you :)

In Mongoose, how do I sort by date? (node.js)

Been dealing with this issue today using Mongoose 3.5(.2) and none of the answers quite helped me solve this issue. The following code snippet does the trick

Post.find().sort('-posted').find(function (err, posts) {
    // user posts array
});

You can send any standard parameters you need to find() (e.g. where clauses and return fields) but no callback. Without a callback it returns a Query object which you chain sort() on. You need to call find() again (with or without more parameters -- shouldn't need any for efficiency reasons) which will allow you to get the result set in your callback.

Export database schema into SQL file

Have you tried the Generate Scripts (Right click, tasks, generate scripts) option in SQL Management Studio? Does that produce what you mean by a "SQL File"?

How to get the PID of a process by giving the process name in Mac OS X ?

This is the shortest command I could find that does the job:

ps -ax | awk '/[t]he_app_name/{print $1}'

Putting brackets around the first letter stops awk from finding the awk process itself.

Remove spacing between table cells and rows

Put display:block on the css for the cell, and valign="top" that should do the trick

Java; String replace (using regular expressions)?

Take a look at antlr4. It will get you much farther along in creating a tree structure than regular expressions alone.

https://github.com/antlr/grammars-v4/tree/master/calculator (calculator.g4 contains the grammar you need)

In a nutshell, you define the grammar to parse an expression, use antlr to generate java code, and add callbacks to handle evaluation when the tree is being built.

How to parse a JSON and turn its values into an Array?

You can prefer quick-json parser to meet your requirement...

quick-json parser is very straight forward, flexible, very fast and customizable. Try this out

[quick-json parser] (https://code.google.com/p/quick-json/) - quick-json features -

  • Compliant with JSON specification (RFC4627)

  • High-Performance JSON parser

  • Supports Flexible/Configurable parsing approach

  • Configurable validation of key/value pairs of any JSON Heirarchy

  • Easy to use # Very Less foot print

  • Raises developer friendly and easy to trace exceptions

  • Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when encountered

  • Validating and Non-Validating parser support

  • Support for two types of configuration (JSON/XML) for using quick-json validating parser

  • Require JDK 1.5 # No dependency on external libraries

  • Support for Json Generation through object serialization

  • Support for collection type selection during parsing process

For e.g.

JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);

How can I view the shared preferences file using Android Studio?

You could simply create a special Activity for debugging purpose:

@SuppressWarnings("unchecked")
public void loadPreferences() {
// create a textview with id (tv_pref) in Layout.
TextView prefTextView;
prefTextView = (TextView) findViewById(R.id.tv_pref);
    Map<String, ?> prefs = PreferenceManager.getDefaultSharedPreferences(
            context).getAll();
    for (String key : prefs.keySet()) {
        Object pref = prefs.get(key);
        String printVal = "";
        if (pref instanceof Boolean) {
            printVal =  key + " : " + (Boolean) pref;
        }
        if (pref instanceof Float) {
            printVal =  key + " : " + (Float) pref;
        }
        if (pref instanceof Integer) {
            printVal =  key + " : " + (Integer) pref;
        }
        if (pref instanceof Long) {
            printVal =  key + " : " + (Long) pref;
        }
        if (pref instanceof String) {
            printVal =  key + " : " + (String) pref;
        }
        if (pref instanceof Set<?>) {
            printVal =  key + " : " + (Set<String>) pref;
        }
        // Every new preference goes to a new line
        prefTextView.append(printVal + "\n\n");     
    }
}
// call loadPreferences() in the onCreate of your Activity.

Persist javascript variables across pages?

You can use http://rhaboo.org as a wrapper around localStorage. It stores complex objects but doesn't merely stringify and parse the whole thing like most such libraries do. That's really inefficient if you want to store a lot of data and add to it or change it in small chunks. Also, JSON discards a lot of important stuff like non-numerical properties of arrays.

In rhaboo you can write things like this:

var store = Rhaboo.persistent('Some name');

store.write('count', store.count ? store.count+1 : 1);

var laststamp = store.stamp ? store.stamp.toString() : "never";
store.write('stamp', new Date());

store.write('somethingfancy', {
  one: ['man', 'went'],
  2: 'mow',
  went: [  2, { mow: ['a', 'meadow' ] }, {}  ]
});

store.somethingfancy.went[1].mow.write(1, 'lawn');
console.log( store.somethingfancy.went[1].mow[1] ); //says lawn

BTW, I wrote rhaboo

How can I count the number of children?

Try to get using:

var count = $("ul > li").size();
alert(count);

WorksheetFunction.CountA - not working post upgrade to Office 2010

It may be obvious but, by stating the Range and not including which workbook or worksheet then it may be trying to CountA() on a different sheet entirely. I find to fully address these things saves a lot of headaches.

How to know what the 'errno' means?

Error code 2 means "File/Directory not found". In general, you could use the perror function to print a human readable string.

How do I get the current username in .NET using C#?

I totally second the other answers, but I would like to highlight one more method which says

String UserName = Request.LogonUserIdentity.Name;

The above method returned me the username in the format: DomainName\UserName. For example, EUROPE\UserName

Which is different from:

String UserName = Environment.UserName;

Which displayed in the format: UserName

And finally:

String UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

which gave: NT AUTHORITY\IUSR (while running the application on IIS server) and DomainName\UserName (while running the application on a local server).

batch script - run command on each file in directory

you can run something like this (paste the code bellow in a .bat, or if you want it to run interractively replace the %% by % :

for %%i in (c:\directory\*.xls) do ssconvert %%i %%i.xlsx

If you can run powershell it will be :

Get-ChildItem -Path c:\directory -filter *.xls | foreach {ssconvert $($_.FullName) $($_.baseName).xlsx }

When do I need to use a semicolon vs a slash in Oracle SQL?

I know this is an old thread, but I just stumbled upon it and I feel this has not been explained completely.

There is a huge difference in SQL*Plus between the meaning of a / and a ; because they work differently.

The ; ends a SQL statement, whereas the / executes whatever is in the current "buffer". So when you use a ; and a / the statement is actually executed twice.

You can easily see that using a / after running a statement:

SQL*Plus: Release 11.2.0.1.0 Production on Wed Apr 18 12:37:20 2012

Copyright (c) 1982, 2010, Oracle.  All rights reserved.

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning and OLAP options

SQL> drop table foo;

Table dropped.

SQL> /
drop table foo
           *
ERROR at line 1:
ORA-00942: table or view does not exist

In this case one actually notices the error.


But assuming there is a SQL script like this:

drop table foo;
/

And this is run from within SQL*Plus then this will be very confusing:

SQL*Plus: Release 11.2.0.1.0 Production on Wed Apr 18 12:38:05 2012

Copyright (c) 1982, 2010, Oracle.  All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning and OLAP options

SQL> @drop

Table dropped.

drop table foo
           *
ERROR at line 1:
ORA-00942: table or view does not exist

The / is mainly required in order to run statements that have embedded ; like a CREATE PROCEDURE statement.

Why do people say that Ruby is slow?

Performance is almost always about good design and optimized database interactions. Ruby does what most web sites need quite fast, especially more recent versions; and the speed of development and ease of maintenance provides a large payoff in costs and in keeping customers happy. I find JAVA to have slow execution performance for some tasks, and given the difficulty of developing in JAVA, many developers create slow applications regardless of the theoretical speed capability as demonstrated in benchmarks (benchmarks are generally contrived to show a specific and narrow capability). When I need intensive processing that isn't well suited to my database's capabilities, I choose C or Objective-C or some other truly high performance compiled language for those tasks depending on the platform. If I need to create a databased web application, I use RoR or sometimes C# ASP.NET depending on other requirements; because all platforms have strengths and weaknesses. Execution speed of the things your application does is important, but after all, if execution performance of one narrow aspect of a language is all that counts; then I might still be using Assembler language for everything.

SLF4J: Class path contains multiple SLF4J bindings

Just use only required dependency, not all :))). For me, for normal work of logging process you need this dependency exclude others from pom.xml

<dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.5</version>
    </dependency>

    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.1.8</version>
    </dependency>

    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-core</artifactId>
        <version>1.1.8</version>
    </dependency>

How to install libusb in Ubuntu

First,

sudo apt-get install libusb-1.0-0-dev

updatedb && locate libusb.h.

Second, replace <libusb.h> with <libusb-1.0/libusb.h>.

update:

don't need to change any file.just add this to your Makefile.

`pkg-config libusb-1.0 --libs --cflags`

its result is that -I/usr/include/libusb-1.0 -lusb-1.0

Comparing two maps

Quick Answer

You should use the equals method since this is implemented to perform the comparison you want. toString() itself uses an iterator just like equals but it is a more inefficient approach. Additionally, as @Teepeemm pointed out, toString is affected by order of elements (basically iterator return order) hence is not guaranteed to provide the same output for 2 different maps (especially if we compare two different maps).

Note/Warning: Your question and my answer assume that classes implementing the map interface respect expected toString and equals behavior. The default java classes do so, but a custom map class needs to be examined to verify expected behavior.

See: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

boolean equals(Object o)

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.

Implementation in Java Source (java.util.AbstractMap)

Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap which is used by classes such as HashMap:

 // Comparison and hashing

    /**
     * Compares the specified object with this map for equality.  Returns
     * <tt>true</tt> if the given object is also a map and the two maps
     * represent the same mappings.  More formally, two maps <tt>m1</tt> and
     * <tt>m2</tt> represent the same mappings if
     * <tt>m1.entrySet().equals(m2.entrySet())</tt>.  This ensures that the
     * <tt>equals</tt> method works properly across different implementations
     * of the <tt>Map</tt> interface.
     *
     * <p>This implementation first checks if the specified object is this map;
     * if so it returns <tt>true</tt>.  Then, it checks if the specified
     * object is a map whose size is identical to the size of this map; if
     * not, it returns <tt>false</tt>.  If so, it iterates over this map's
     * <tt>entrySet</tt> collection, and checks that the specified map
     * contains each mapping that this map contains.  If the specified map
     * fails to contain such a mapping, <tt>false</tt> is returned.  If the
     * iteration completes, <tt>true</tt> is returned.
     *
     * @param o object to be compared for equality with this map
     * @return <tt>true</tt> if the specified object is equal to this map
     */
    public boolean equals(Object o) {
        if (o == this)
            return true;

        if (!(o instanceof Map))
            return false;
        Map<K,V> m = (Map<K,V>) o;
        if (m.size() != size())
            return false;

        try {
            Iterator<Entry<K,V>> i = entrySet().iterator();
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                K key = e.getKey();
                V value = e.getValue();
                if (value == null) {
                    if (!(m.get(key)==null && m.containsKey(key)))
                        return false;
                } else {
                    if (!value.equals(m.get(key)))
                        return false;
                }
            }
        } catch (ClassCastException unused) {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }

        return true;
    }

Comparing two different types of Maps

toString fails miserably when comparing a TreeMap and HashMap though equals does compare contents correctly.

Code:

public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");

System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
        + map.toString().equals(map2.toString()));

System.out.println("Map1:"+map.toString());
System.out.println("Map2:"+map2.toString());
}

Output:

Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}

Better way to get type of a Javascript variable?

My 2¢! Really, part of the reason I'm throwing this up here, despite the long list of answers, is to provide a little more all in one type solution and get some feed back in the future on how to expand it to include more real types.

With the following solution, as aforementioned, I combined a couple of solutions found here, as well as incorporate a fix for returning a value of jQuery on jQuery defined object if available. I also append the method to the native Object prototype. I know that is often taboo, as it could interfere with other such extensions, but I leave that to user beware. If you don't like this way of doing it, simply copy the base function anywhere you like and replace all variables of this with an argument parameter to pass in (such as arguments[0]).

;(function() {  //  Object.realType
    function realType(toLower) {
        var r = typeof this;
        try {
            if (window.hasOwnProperty('jQuery') && this.constructor && this.constructor == jQuery) r = 'jQuery';
            else r = this.constructor && this.constructor.name ? this.constructor.name : Object.prototype.toString.call(this).slice(8, -1);
        }
        catch(e) { if (this['toString']) r = this.toString().slice(8, -1); }
        return !toLower ? r : r.toLowerCase();
    }
    Object['defineProperty'] && !Object.prototype.hasOwnProperty('realType')
        ? Object.defineProperty(Object.prototype, 'realType', { value: realType }) : Object.prototype['realType'] = realType;
})();

Then simply use with ease, like so:

obj.realType()  //  would return 'Object'
obj.realType(true)  //  would return 'object'

Note: There is 1 argument passable. If is bool of true, then the return will always be in lowercase.

More Examples:

true.realType();                            //  "Boolean"
var a = 4; a.realType();                    //  "Number"
$('div:first').realType();                   // "jQuery"
document.createElement('div').realType()    //  "HTMLDivElement"

If you have anything to add that maybe helpful, such as defining when an object was created with another library (Moo, Proto, Yui, Dojo, etc...) please feel free to comment or edit this and keep it going to be more accurate and precise. OR roll on over to the GitHub I made for it and let me know. You'll also find a quick link to a cdn min file there.

Sorting a vector of custom objects

In the interest of coverage. I put forward an implementation using lambda expressions.

C++11

#include <vector>
#include <algorithm>

using namespace std;

vector< MyStruct > values;

sort( values.begin( ), values.end( ), [ ]( const MyStruct& lhs, const MyStruct& rhs )
{
   return lhs.key < rhs.key;
});

C++14

#include <vector>
#include <algorithm>

using namespace std;

vector< MyStruct > values;

sort( values.begin( ), values.end( ), [ ]( const auto& lhs, const auto& rhs )
{
   return lhs.key < rhs.key;
});

php resize image on upload

Here is another nice and easy solution:

$maxDim = 800;
$file_name = $_FILES['myFile']['tmp_name'];
list($width, $height, $type, $attr) = getimagesize( $file_name );
if ( $width > $maxDim || $height > $maxDim ) {
    $target_filename = $file_name;
    $ratio = $width/$height;
    if( $ratio > 1) {
        $new_width = $maxDim;
        $new_height = $maxDim/$ratio;
    } else {
        $new_width = $maxDim*$ratio;
        $new_height = $maxDim;
    }
    $src = imagecreatefromstring( file_get_contents( $file_name ) );
    $dst = imagecreatetruecolor( $new_width, $new_height );
    imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
    imagedestroy( $src );
    imagepng( $dst, $target_filename ); // adjust format as needed
    imagedestroy( $dst );
}

Reference: PHP resize image proportionally with max width or weight

Edit: Cleaned up and simplified the code a bit. Thanks @jan-mirus for your comment.

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

Just another possibility: Spring initializes bean by type not by name if you don't define bean with a name, which is ok if you use it by its type:

Producer:

@Service
public void FooServiceImpl implements FooService{}

Consumer:

@Autowired
private FooService fooService;

or

@Autowired
private void setFooService(FooService fooService) {}

but not ok if you use it by name:

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.getBean("fooService");

It would complain: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'fooService' is defined In this case, assigning name to @Service("fooService") would make it work.

How to edit .csproj file

You can right click the project file, select "Unload project" then you can open the file directly for editing by selecting "Edit project name.csproj".

You will have to load the project back after you have saved your changes in order for it to compile.

See How to: Unload and Reload Projects on MSDN.


Since project files are XML files, you can also simply edit them using any text editor that supports Unicode (notepad, notepad++ etc...)

However, I would be very reluctant to edit these files by hand - use the Solution explorer for this if at all possible. If you have errors and you know how to fix them manually, go ahead, but be aware that you can completely ruin the project file if you don't know exactly what you are doing.

Logarithmic returns in pandas dataframe

Here is one way to calculate log return using .shift(). And the result is similar to but not the same as the gross return calculated by pct_change(). Can you upload a copy of your sample data (dropbox share link) to reproduce the inconsistency you saw?

import pandas as pd
import numpy as np

np.random.seed(0)
df = pd.DataFrame(100 + np.random.randn(100).cumsum(), columns=['price'])
df['pct_change'] = df.price.pct_change()
df['log_ret'] = np.log(df.price) - np.log(df.price.shift(1))

Out[56]: 
       price  pct_change  log_ret
0   101.7641         NaN      NaN
1   102.1642      0.0039   0.0039
2   103.1429      0.0096   0.0095
3   105.3838      0.0217   0.0215
4   107.2514      0.0177   0.0176
5   106.2741     -0.0091  -0.0092
6   107.2242      0.0089   0.0089
7   107.0729     -0.0014  -0.0014
..       ...         ...      ...
92  101.6160      0.0021   0.0021
93  102.5926      0.0096   0.0096
94  102.9490      0.0035   0.0035
95  103.6555      0.0069   0.0068
96  103.6660      0.0001   0.0001
97  105.4519      0.0172   0.0171
98  105.5788      0.0012   0.0012
99  105.9808      0.0038   0.0038

[100 rows x 3 columns]

Why catch and rethrow an exception in C#?

Rethrowing exceptions via throw is useful when you don't have a particular code to handle current exceptions, or in cases when you have a logic to handle specific error cases but want to skip all others.

Example:

string numberText = "";
try
{
    Console.Write("Enter an integer: ");
    numberText = Console.ReadLine();
    var result = int.Parse(numberText);

    Console.WriteLine("You entered {0}", result);
}
catch (FormatException)
{
    if (numberText.ToLowerInvariant() == "nothing")
    {
        Console.WriteLine("Please, please don't be lazy and enter a valid number next time.");
    }
    else
    {
        throw;
    }
}    
finally
{
    Console.WriteLine("Freed some resources.");
}
Console.ReadKey();

However, there is also another way of doing this, using conditional clauses in catch blocks:

string numberText = "";
try
{
    Console.Write("Enter an integer: ");
    numberText = Console.ReadLine();
    var result = int.Parse(numberText);

    Console.WriteLine("You entered {0}", result);
}
catch (FormatException) when (numberText.ToLowerInvariant() == "nothing")
{
    Console.WriteLine("Please, please don't be lazy and enter a valid number next time.");
}    
finally
{
    Console.WriteLine("Freed some resources.");
}
Console.ReadKey();

This mechanism is more efficient than re-throwing an exception because of the .NET runtime doesn’t have to rebuild the exception object before re-throwing it.

What is wrong with this code that uses the mysql extension to fetch data from a database in PHP?

Variables in php are case sensitive. Please replace your while loop with following:

while ($rows = mysql_fetch_array($query)):

           $name = $rows['Name'];
           $address = $rows['Address'];
           $email = $rows['Email'];
           $subject = $rows['Subject'];
           $comment = $rows['Comment']

           echo "$name<br>$address<br>$email<br>$subject<br>$comment<br><br>";

           endwhile;

Understanding `scale` in R

It provides nothing else but a standardization of the data. The values it creates are known under several different names, one of them being z-scores ("Z" because the normal distribution is also known as the "Z distribution").

More can be found here:

http://en.wikipedia.org/wiki/Standard_score

kill a process in bash

To interrupt it, you can try pressing ctrl c to send a SIGINT. If it doesn't stop it, you may try to kill it using kill -9 <pid>, which sends a SIGKILL. The latter can't be ignored/intercepted by the process itself (the one being killed).

To move the active process to background, you can press ctrl z. The process is sent to background and you get back to the shell prompt. Use the fg command to do the opposite.

How to disable textbox from editing?

        textBox1.Enabled = false;

"false" property will make the text box disable. and "true" will make it in regular form. Thanks.

Force table column widths to always be fixed regardless of contents

This works for me

td::after { 
content: ''; 
display: block; 
width: 30px;
}

PyCharm shows unresolved references error for valid code

I have a project where one file in src/ imports another file in the same directory. To get PyCharm to recognize I had to to go to File > Settings > Project > Project Structure > select src folder and click "Mark as: Sources"

From https://www.jetbrains.com/help/pycharm/configuring-folders-within-a-content-root.html

Source roots contain the actual source files and resources. PyCharm uses the source roots as the starting point for resolving imports

C# 30 Days From Todays Date

A better solution might be to introduce a license file with a counter. Write into the license file the install date of the application (during installation). Then everytime the application is run you can edit the license file and increment the count by 1. Each time the application starts up you just do a quick check to see if the 30 uses of the application has been reached i.e.

if (LicenseFile.Counter == 30)
    // go into expired mode

Also this will solve the issue if the user has put the system clock back as you can do a simple check to say

if (LicenseFile.InstallationDate < SystemDate)
    // go into expired mode (as punishment for trying to trick the app!) 

The problem with your current setup is the user will have to use the application every day for 30 days to get their full 30 day trial.

Is it possible to create a temporary table in a View and drop it after select?

Try creating another SQL view instead of a temporary table and then referencing it in the main SQL view. In other words, a view within a view. You can then drop the first view once you are done creating the main view.

Draw text in OpenGL ES

I looked at the sprite text example and it looks awfully complicated for such a task, I considered rendering to a texture too, but I'm worried about the performance hit that might cause. I might just have to go with a view instead and worry about porting when it's time to cross that bridge :)

Detect whether there is an Internet connection available on Android

Step 1: Create a class AppStatus in your project(you can give any other name also). Then please paste the given below lines into your code:

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;


public class AppStatus {

    private static AppStatus instance = new AppStatus();
    static Context context;
    ConnectivityManager connectivityManager;
    NetworkInfo wifiInfo, mobileInfo;
    boolean connected = false;

    public static AppStatus getInstance(Context ctx) {
        context = ctx.getApplicationContext();
        return instance;
    }

    public boolean isOnline() {
        try {
            connectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        connected = networkInfo != null && networkInfo.isAvailable() &&
                networkInfo.isConnected();
        return connected;


        } catch (Exception e) {
            System.out.println("CheckConnectivity Exception: " + e.getMessage());
            Log.v("connectivity", e.toString());
        }
        return connected;
    }
}

Step 2: Now to check if the your device has network connectivity then just add this code snippet where ever you want to check ...

if (AppStatus.getInstance(this).isOnline()) {

    Toast.makeText(this,"You are online!!!!",8000).show();

} else {

    Toast.makeText(this,"You are not online!!!!",8000).show();
    Log.v("Home", "############################You are not online!!!!");    
}

Symfony 2 EntityManager injection in service

Note as of Symfony 3.3 EntityManager is depreciated. Use EntityManagerInterface instead.

namespace AppBundle\Service;

use Doctrine\ORM\EntityManagerInterface;

class Someclass {
    protected $em;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->em = $entityManager;
    }

    public function somefunction() {
        $em = $this->em;
        ...
    }
}

..The underlying connection was closed: An unexpected error occurred on a receive

The underlying connection was closed: An unexpected error occurred on a receive.

This problem occurs when the server or another network device unexpectedly closes an existing Transmission Control Protocol (TCP) connection. This problem may occur when a time-out value on the server or on the network device is set too low. To resolve this problem, see resolutions A, D, E, F, and O. The problem can also occur if the server resets the connection unexpectedly, such as if an unhandled exception crashes the server process. Analyze the server logs to see if this may be the issue.

Resolution

To resolve this problem, make sure that you are using the most recent version of the .NET Framework.

Add a method to the class to override the GetWebRequest method. This change lets you access the HttpWebRequest object. If you are using Microsoft Visual C#, the new method must be similar to the following.

class MyTestService:TestService.TestService
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
        HttpWebRequest webRequest = (HttpWebRequest) base.GetWebRequest(uri);
        //Setting KeepAlive to false
        webRequest.KeepAlive = false;
        return webRequest;
    }
}

Excerpt from KB915599: You receive one or more error messages when you try to make an HTTP request in an application that is built on the .NET Framework 1.1 Service Pack 1.

How to declare array of zeros in python (or an array of a certain size)

If you need more columns:

buckets = [[0., 0., 0., 0., 0.] for x in range(0)]

How to make a vertical SeekBar in Android?

This worked for me, just put it into any layout you want to.

<FrameLayout
    android:layout_width="32dp"
    android:layout_height="192dp">

    <SeekBar
        android:layout_width="192dp"
        android:layout_height="32dp"
        android:layout_gravity="center"
        android:rotation="270" />

</FrameLayout>

How do I increase memory on Tomcat 7 when running as a Windows Service?

Assuming that you've downloaded and installed Tomcat as Windows Service Installer exe file from the Tomcat homepage, then check the Apache feather icon in the systray (or when absent, run Monitor Tomcat from the start menu). Doubleclick the feather icon and go to the Java tab. There you can configure the memory.

enter image description here

Restart the service to let the changes take effect.

What is mapDispatchToProps?

I feel like none of the answers have crystallized why mapDispatchToProps is useful.

This can really only be answered in the context of the container-component pattern, which I found best understood by first reading:Container Components then Usage with React.

In a nutshell, your components are supposed to be concerned only with displaying stuff. The only place they are supposed to get information from is their props.

Separated from "displaying stuff" (components) is:

  • how you get the stuff to display,
  • and how you handle events.

That is what containers are for.

Therefore, a "well designed" component in the pattern look like this:

class FancyAlerter extends Component {
    sendAlert = () => {
        this.props.sendTheAlert()
    }

    render() {
        <div>
          <h1>Today's Fancy Alert is {this.props.fancyInfo}</h1>
          <Button onClick={sendAlert}/>
        </div>
     }
}

See how this component gets the info it displays from props (which came from the redux store via mapStateToProps) and it also gets its action function from its props: sendTheAlert().

That's where mapDispatchToProps comes in: in the corresponding container

// FancyButtonContainer.js

function mapDispatchToProps(dispatch) {
    return({
        sendTheAlert: () => {dispatch(ALERT_ACTION)}
    })
}

function mapStateToProps(state) {
    return({fancyInfo: "Fancy this:" + state.currentFunnyString})
}

export const FancyButtonContainer = connect(
    mapStateToProps, mapDispatchToProps)(
    FancyAlerter
)

I wonder if you can see, now that it's the container 1 that knows about redux and dispatch and store and state and ... stuff.

The component in the pattern, FancyAlerter, which does the rendering doesn't need to know about any of that stuff: it gets its method to call at onClick of the button, via its props.

And ... mapDispatchToProps was the useful means that redux provides to let the container easily pass that function into the wrapped component on its props.

All this looks very like the todo example in docs, and another answer here, but I have tried to cast it in the light of the pattern to emphasize why.

(Note: you can't use mapStateToProps for the same purpose as mapDispatchToProps for the basic reason that you don't have access to dispatch inside mapStateToProp. So you couldn't use mapStateToProps to give the wrapped component a method that uses dispatch.

I don't know why they chose to break it into two mapping functions - it might have been tidier to have mapToProps(state, dispatch, props) IE one function to do both!


1 Note that I deliberately explicitly named the container FancyButtonContainer, to highlight that it is a "thing" - the identity (and hence existence!) of the container as "a thing" is sometimes lost in the shorthand

export default connect(...) ????????????

syntax that is shown in most examples

How to increase scrollback buffer size in tmux?

The history limit is a pane attribute that is fixed at the time of pane creation and cannot be changed for existing panes. The value is taken from the history-limit session option (the default value is 2000).

To create a pane with a different value you will need to set the appropriate history-limit option before creating the pane.

To establish a different default, you can put a line like the following in your .tmux.conf file:

set-option -g history-limit 3000

Note: Be careful setting a very large default value, it can easily consume lots of RAM if you create many panes.

For a new pane (or the initial pane in a new window) in an existing session, you can set that session’s history-limit. You might use a command like this (from a shell):

tmux set-option history-limit 5000 \; new-window

For (the initial pane of the initial window in) a new session you will need to set the “global” history-limit before creating the session:

tmux set-option -g history-limit 5000 \; new-session

Note: If you do not re-set the history-limit value, then the new value will be also used for other panes/windows/sessions created in the future; there is currently no direct way to create a single new pane/window/session with its own specific limit without (at least temporarily) changing history-limit (though show-option (especially in 1.7 and later) can help with retrieving the current value so that you restore it later).

How to refer to relative paths of resources when working with a code repository

If you are using setup tools or distribute (a setup.py install) then the "right" way to access these packaged resources seem to be using package_resources.

In your case the example would be

import pkg_resources
my_data = pkg_resources.resource_string(__name__, "foo.dat")

Which of course reads the resource and the read binary data would be the value of my_data

If you just need the filename you could also use

resource_filename(package_or_requirement, resource_name)

Example:

resource_filename("MyPackage","foo.dat")

The advantage is that its guaranteed to work even if it is an archive distribution like an egg.

See http://packages.python.org/distribute/pkg_resources.html#resourcemanager-api

Determine installed PowerShell version

The below cmdlet will return the PowerShell version.

$PSVersionTable.PSVersion.Major

What is the most efficient way to concatenate N arrays?

If you have array of arrays and want to concat the elements into a single array, try the following code (Requires ES2015):

let arrOfArr = [[1,2,3,4],[5,6,7,8]];
let newArr = [];
for (let arr of arrOfArr) {
    newArr.push(...arr);
}

console.log(newArr);
//Output: [1,2,3,4,5,6,7,8];

Or if you're into functional programming

let arrOfArr = [[1,2,3,4],[5,6,7,8]];
let newArr = arrOfArr.reduce((result,current)=>{
    result.push(...current);
    return result;
});

console.log(newArr);
//Output: [1,2,3,4,5,6,7,8];

Or even better with ES5 syntax, without the spread operator

var arrOfArr = [[1,2,3,4],[5,6,7,8]];
var newArr = arrOfArr.reduce((result,current)=>{
    return result.concat(current);
});
console.log(newArr);
//Output: [1,2,3,4,5,6,7,8];

This way is handy if you do not know the no. of arrays at the code time.

Refresh page after form submitting

If you want the form to be submitted on the same page then remove the action from the form attributes.

<form method="POST" name="myform">
 <!-- Your HTML code Here -->
</form>

However, If you want to reload the page or redirect the page after submitting the form from another file then you call this function in php and it will redirect the page in 0 seconds. Also, You can use the header if you want to, just make sure you don't have any content before using the header

 function page_redirect($location)
 {
   echo '<META HTTP-EQUIV="Refresh" Content="0; URL='.$location.'">';
   exit; 
 }

 // I want the page to go to google.
 // page_redirect("http://www.google.com")

JavaScript naming conventions

I think that besides some syntax limitations; the naming conventions reasoning are very much language independent. I mean, the arguments in favor of c_style_functions and JavaLikeCamelCase could equally well be used the opposite way, it's just that language users tend to follow the language authors.

having said that, i think most libraries tend to roughly follow a simplification of Java's CamelCase. I find Douglas Crockford advices tasteful enough for me.

Why AVD Manager options are not showing in Android Studio

I found it from the icon. Please see the device icon.

enter image description here

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

consistency and readability (self-documenting code) are important. some clues (such as case) can and should be used to avoid collisions, and to indicate whether an instance is required.

one of the best practices i got into was the use of code formatters (astyle and uncrustify are 2 examples). code formatters can destroy your code formatting - configure the formatter, and let it do its job. seriously, forget about manual formatting and get into the practice of using them. they will save a ton of time.

as mentioned, be very descriptive with naming. also, be very specific with scoping (class types/data/namespaces/anonymous namespaces). in general, i really like much of java's common written form - that is a good reference and similar to c++.

as for specific appearance/naming, this is a small sample similar to what i use (variables/arguments are lowerCamel and this only demonstrates a portion of the language's features):

/** MYC_BEGIN_FILE_ID::FD_Directory_nanotimer_FN_nanotimer_hpp_::MYC_BEGIN_FILE_DIR::Directory/nanotimer::MYC_BEGIN_FILE_FILE::nanotimer.hpp::Copyright... */
#ifndef FD_Directory_nanotimer_FN_nanotimer_hpp_
#define FD_Directory_nanotimer_FN_nanotimer_hpp_

/* typical commentary omitted -- comments detail notations/conventions. also, no defines/macros other than header guards */

namespace NamespaceName {

/* types prefixed with 't_' */
class t_nanotimer : public t_base_timer {
    /* private types */
    class t_thing {
        /*...*/
    };
public:
    /* public types */
    typedef uint64_t t_nanosecond;

    /* factory initializers -- UpperCamel */
    t_nanotimer* WithFloat(const float& arg);
    /* public/protected class interface -- UpperCamel */
    static float Uptime();
protected:
    /* static class data -- UpperCamel -- accessors, if needed, use Get/Set prefix */
    static const t_spoke Spoke;
public:
    /* enums in interface are labeled as static class data */
    enum { Granularity = 4 };
public:
    /* construction/destruction -- always use proper initialization list */
    explicit t_nanotimer(t_init);
    explicit t_nanotimer(const float& arg);

    virtual ~t_nanotimer();

    /*
       public and protected instance methods -- lowercaseCamel()
       - booleans prefer is/has
       - accessors use the form: getVariable() setVariable().
       const-correctness is important
     */
    const void* address() const;
    virtual uint64_t hashCode() const;
protected:
    /* interfaces/implementation of base pure virtuals (assume this was pure virtual in t_base_timer) */
    virtual bool hasExpired() const;
private:
    /* private methods and private static data */
    void invalidate();
private:
    /*
       instance variables
       - i tend to use underscore suffix, but d_ (for example) is another good alternative
       - note redundancy in visibility
     */
    t_thing ivar_;
private:
    /* prohibited stuff */
    explicit t_nanotimer();
    explicit t_nanotimer(const int&);
};
} /* << NamespaceName */
/* i often add a multiple include else block here, preferring package-style inclusions */    
#endif /* MYC_END_FILE::FD_Directory_nanotimer_FN_nanotimer_hpp_ */

How to increase IDE memory limit in IntelliJ IDEA on Mac?

It looks like IDEA solves this for you (like everything else). When loading a large project and letting it thrash, it will open a dialog to up the memory settings. Entering 2048 for Xmx and clicking "Shutdown", then restarting IDEA makes IDEA start up with more memory. This seems to work well for Mac OS, though it never seems to persist for me on Windows (not sure about IDEA 12).

Why doesn't catching Exception catch RuntimeException?

Catching Exception will catch a RuntimeException

Where is debug.keystore in Android Studio

You can use this command and will fetch all your key-stores, go to your terminal and in your android root directory run this:

./gradlew signingReport

it will give you something like this a list of key-store and their information:

enter image description here

Basic HTTP and Bearer Token Authentication

I had a similar problem - authenticate device and user at device. I used a Cookie header alongside an Authorization: Bearer... header. One header authenticated the device, the other authenticated the user. I used a Cookie header because these are commonly used for authentication.

.gitignore all the .DS_Store files in every folder and subfolder

Add**/.DS_Store into .gitignore for the sub directory


If .DS_Store already committed:

find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch

To ignore them in all repository: (sometimes it named ._.DS_Store)

echo ".DS_Store" >> ~/.gitignore_global
echo "._.DS_Store" >> ~/.gitignore_global
echo "**/.DS_Store" >> ~/.gitignore_global
echo "**/._.DS_Store" >> ~/.gitignore_global
git config --global core.excludesfile ~/.gitignore_global

200 PORT command successful. Consider using PASV. 425 Failed to establish connection

Actually your Windows firewall is blocking the connection. You need to enter these commands into cmd.exe from Administrator.

netsh advfirewall firewall add rule name="FTP" dir=in action=allow program=%SystemRoot%\System32\ftp.exe enable=yes protocol=tcp
netsh advfirewall firewall add rule name="FTP" dir=in action=allow program=%SystemRoot%\System32\ftp.exe enable=yes protocol=udp

In case something goes wrong then you can revert by this:

netsh advfirewall firewall delete rule name="FTP" program=%SystemRoot%\System32\ftp.exe

What is the equivalent of Java's final in C#?

Java class final and method final -> sealed. Java member variable final -> readonly for runtime constant, const for compile time constant.

No equivalent for Local Variable final and method argument final

Dockerfile if else condition with external arguments

You can use the conditional system that best fits your needs.

Dockerfile

ARG ENV

FROM foo as base

ARG ENV

# run common
RUN ...

# For long running tasks that would slow down deployments
RUN if [[ "$ENV" == "dev" ]] ; then \
        yum install -y lots of big dev packages ; \
    fi

# Build dev image
FROM base as image-dev

RUN ...
COPY ...

# Build prod image
FROM base as image-prod

RUN ...
COPY ...

FROM image-$ENV AS final

Note that we define ENV twice - you need to define ENV globally, and in each image where it is used.

Use docker:

docker build -t my_docker . --build-arg ENV="dev"

Use docker-compose:

version: '3'

services:

  dev:
    container_name: dev
    ports:
      - 3000:8080
    volumes:
      - ./:/var/task
    tty: true
    build:
      context: .
      dockerfile: Dockerfile
      args:
        ENV: dev
docker-compose build --no-cache dev && docker-compose up dev

Include of non-modular header inside framework module

Try going Build Settings under "Target" and set "Allow Non-modular Includes in Framework Modules" to YES.

The real answer is that the location of the imports needs to be changed by the library owner. Those files ifaddrs.h, arpa/inet.h, sys/types.h are getting imported in a .h file in a framework, which Xcode doesn't like. The library maintainer should move them to a .m file. See for example this issue on GitHub, where AFNetworking fixed the same problem: https://github.com/AFNetworking/AFNetworking/issues/2205

What are the sizes used for the iOS application splash screen?

For Xcode 9 and latest devices

Portrait

iPhone 4/4S 640 x 960

iPhone 5/5C/5S iPod touch 5th generation 640 x 1136

iPhone 6/7/8 750 x 1334

iPhone 6/7/8 Plus 1242 x 2208

iPhone X 1125 x 2436

iPad non-retina 768 x 1024

iPad retina 1536 x 2048

Landscape

iPhone 6, 7 and 8 plus 2208 x 1242

iPhone X 2436 x 1125

iPad non-retina 1024 x 768

iPad retina 2048 x 1536

How to send an email from JavaScript

There is a combination service. You can combine the above listed solutions like mandrill with a service EmailJS, which can make the system more secure. They have not yet started the service though.

C++ delete vector, objects, free memory

Move semantics allows for a straightforward way to release memory, by simply applying the assignment (=) operator from an empty rvalue:

std::vector<uint32_t> vec(100, 0);
std::cout << vec.capacity(); // 100

vec = vector<uint32_t>();    // Same as "vector<uint32_t>().swap(vec)";    
std::cout << vec.capacity(); // 0

It is as much efficient as the "swap()"-based method described in other answers (indeed, both are conceptually doing the same thing). When it comes to readability, however, the assignment version makes a better job at expressing the programmer's intention while being more concise.

How to send a html email with the bash command "sendmail"?

This page should help - http://www.zedwood.com/article/103/bash-send-mail-with-an-attachment

It includes a script to send e-mail with a MIME attachment, ie with a HTML page and images included.

Change the mouse pointer using JavaScript

With regards to @CrazyJugglerDrummer second method it would be:

elementsToChange.style.cursor = "http://wiki-devel.sugarlabs.org/images/e/e2/Arrow.cur";

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

This typed error-message also shows while an if-statement comparison is done where there is an array and for example a bool or int. See for example:

... code snippet ...

if dataset == bool:
    ....

... code snippet ...

This clause has dataset as array and bool is euhm the "open door"... True or False.

In case the function is wrapped within a try-statement you will receive with except Exception as error: the message without its error-type:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

How to change the status bar background color and text color on iOS 7?

Just to add to Shahid's answer - you can account for orientation changes or different devices using this (iOS7+):

- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  ...

  //Create the background
  UIView* statusBg = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.window.frame.size.width, 20)];
  statusBg.backgroundColor = [UIColor colorWithWhite:1 alpha:.7];

  //Add the view behind the status bar
  [self.window.rootViewController.view addSubview:statusBg];

  //set the constraints to auto-resize
  statusBg.translatesAutoresizingMaskIntoConstraints = NO;
  [statusBg.superview addConstraint:[NSLayoutConstraint constraintWithItem:statusBg attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:statusBg.superview attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]];
  [statusBg.superview addConstraint:[NSLayoutConstraint constraintWithItem:statusBg attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:statusBg.superview attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0]];
  [statusBg.superview addConstraint:[NSLayoutConstraint constraintWithItem:statusBg attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:statusBg.superview attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.0]];
  [statusBg.superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[statusBg(==20)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(statusBg)]];
  [statusBg.superview setNeedsUpdateConstraints];
  ...
}

Codesign error: Provisioning profile cannot be found after deleting expired profile

In my case the problem was solved by opening Window -> Organizer, selecting my device and removing the old Provisioning Profile under the "Provisioning" panel on the right. The old one was already marked with a red "x" symbol but the iPhone was still using it.

Besides that profile, also the new one was showing up (with the same name) and after simply relaunching the application I had it running smoothly.

How to implement a binary search tree in Python?

Here is a quick example of a binary insert:

class Node:
    def __init__(self, val):
        self.l_child = None
        self.r_child = None
        self.data = val

def binary_insert(root, node):
    if root is None:
        root = node
    else:
        if root.data > node.data:
            if root.l_child is None:
                root.l_child = node
            else:
                binary_insert(root.l_child, node)
        else:
            if root.r_child is None:
                root.r_child = node
            else:
                binary_insert(root.r_child, node)

def in_order_print(root):
    if not root:
        return
    in_order_print(root.l_child)
    print root.data
    in_order_print(root.r_child)

def pre_order_print(root):
    if not root:
        return        
    print root.data
    pre_order_print(root.l_child)
    pre_order_print(root.r_child)    

r = Node(3)
binary_insert(r, Node(7))
binary_insert(r, Node(1))
binary_insert(r, Node(5))

     3
    / \
   1   7
      /
     5

print "in order:"
in_order_print(r)

print "pre order"
pre_order_print(r)

in order:
1
3
5
7
pre order
3
1
7
5

How to make a Java thread wait for another thread's output?

Try CountDownLatch class out of the java.util.concurrent package, which provides higher level synchronization mechanisms, that are far less error prone than any of the low level stuff.

How do I access refs of a child component in the parent component

  1. Inside the child component add a ref to the node you need
  2. Inside the parent component add a ref to the child component.
/*
* Child component
*/
class Child extends React.Component {
  render() {
    return (
      <div id="child">
        <h1 ref={(node) => { this.heading = node; }}>
          Child
        </h1>
      </div>
    );
  }
}

/*
 * Parent component
 */
class Parent extends React.Component {
  componentDidMount() {
    // Access child component refs via parent component instance like this
    console.log(this.child.heading.getDOMNode());
  }

  render() {
    return (
      <div>
        <Child
          ref={(node) => { this.child = node; }}
        />
      </div>
    );
  }
}

Demo: https://codepen.io/itsfadnis/pen/aLWVVx?editors=0011

SELECT INTO USING UNION QUERY

You have to define a table alias for a derived table in SQL Server:

SELECT x.* 
  INTO [NEW_TABLE]
  FROM (SELECT * FROM TABLE1
        UNION
        SELECT * FROM TABLE2) x

"x" is the table alias in this example.

javascript how to create a validation error message without using alert

I would strongly suggest you start using jQuery. Your code would look like:

$(function() {
    $('form[name="myform"]').submit(function(e) {
        var username = $('form[name="myform"] input[name="username"]').val();
        if ( username == '') {
            e.preventDefault();
            $('#errors').text('*Please enter a username*');
        }
    });
});

issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

Error message looks like this

Error message => ORA-00001: unique constraint (schema.unique_constraint_name) violated

ORA-00001 occurs when: "a query tries to insert a "duplicate" row in a table". It makes an unique constraint to fail, consequently query fails and row is NOT added to the table."

Solution:

Find all columns used in unique_constraint, for instance column a, column b, column c, column d collectively creates unique_constraint and then find the record from source data which is duplicate, using following queries:

-- to find <<owner of the table>> and <<name of the table>> for unique_constraint

select *
from DBA_CONSTRAINTS
where CONSTRAINT_NAME = '<unique_constraint_name>';

Then use Justin Cave's query (pasted below) to find all columns used in unique_constraint:

  SELECT column_name, position
  FROM all_cons_columns
  WHERE constraint_name = <<name of constraint from the error message>>
   AND owner           = <<owner of the table>>
   AND table_name      = <<name of the table>>

    -- to find duplicates

    select column a, column b, column c, column d
    from table
    group by column a, column b, column c, column d
    having count (<any one column used in constraint > ) > 1;

you can either delete that duplicate record from your source data (which was a select query in my particular case, as I experienced it with "Insert into select") or modify to make it unique or change the constraint.

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

Your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary POST.

That is: Modern browsers will only allow Ajax calls to services in the same domain as the HTML page.

Example: A page in http://www.example.com/myPage.html can only directly request services that are in http://www.example.com, like http://www.example.com/testservice/etc. If the service is in other domain, the browser won't make the direct call (as you'd expect). Instead, it will try to make a CORS request.

To put it shortly, to perform a CORS request, your browser:

  • Will first send an OPTION request to the target URL
  • And then only if the server response to that OPTION contains the adequate headers (Access-Control-Allow-Origin is one of them) to allow the CORS request, the browse will perform the call (almost exactly the way it would if the HTML page was at the same domain).
    • If the expected headers don't come, the browser simply gives up (like it did to you).

How to solve it? The simplest way is to enable CORS (enable the necessary headers) on the server.

If you don't have server-side access to it, you can mirror the web service from somewhere else, and then enable CORS there.

document.all vs. document.getElementById

Specifically, document.all was introduced for IE4 BEFORE document.getElementById had been introduced.

So, the presence of document.all means that the code is intended to support IE4, or is trying to identify the browser as IE4 (though it could have been Opera), or the person who wrote (or copied and pasted) the code wasn't up on the latest.

In the highly unlikely event that you need to support IE4, then, you do need document.all (or a library that handles these ancient IE specs).

how to count length of the JSON array element

First, there is no such thing as a JSON object. JSON is a string format that can be used as a representation of a Javascript object literal.

Since JSON is a string, Javascript will treat it like a string, and not like an object (or array or whatever you are trying to use it as.)

Here is a good JSON reference to clarify this difference:

http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/

So if you need accomplish the task mentioned in your question, you must convert the JSON string to an object or deal with it as a string, and not as a JSON array. There are several libraries to accomplish this. Look at http://www.json.org/js.html for a reference.

What does %s mean in a python format string?

%s indicates a conversion type of string when using python's string formatting capabilities. More specifically, %s converts a specified value to a string using the str() function. Compare this with the %r conversion type that uses the repr() function for value conversion.

Take a look at the docs for string formatting.

Why does Firebug say toFixed() is not a function?

toFixed isn't a method of non-numeric variable types. In other words, Low and High can't be fixed because when you get the value of something in Javascript, it automatically is set to a string type. Using parseFloat() (or parseInt() with a radix, if it's an integer) will allow you to convert different variable types to numbers which will enable the toFixed() function to work.

var Low  = parseFloat($SliderValFrom.val()),
    High = parseFloat($SliderValTo.val());

Parsing boolean values with argparse

As an improvement to @Akash Desarda 's answer, you could do

import argparse
from distutils.util import strtobool

parser = argparse.ArgumentParser()
parser.add_argument("--foo", 
    type=lambda x:bool(strtobool(x)),
    nargs='?', const=True, default=False)
args = parser.parse_args()
print(args.foo)

And it supports python test.py --foo

(base) [costa@costa-pc code]$ python test.py
False
(base) [costa@costa-pc code]$ python test.py --foo 
True
(base) [costa@costa-pc code]$ python test.py --foo True
True
(base) [costa@costa-pc code]$ python test.py --foo False
False

DateTime.MinValue and SqlDateTime overflow

Very simple avoid using DateTime.MinValue use System.Data.SqlTypes.SqlDateTime.MinValue instead.

Trying to get property of non-object in

Your error

Notice: Trying to get property of non-object in C:\wamp\www\phone\pages\init.php on line 22

Your comment

@22 is <?php echo $sidemenu->mname."<br />";?>

$sidemenu is not an object, and you are trying to access one of its properties.

That is the reason for your error.

Convert a object into JSON in REST service by Spring MVC

Spring framework itself handles json conversion when controller is annotated properly.

For eg:

   @PutMapping(produces = {"application/json"})
        @ResponseBody
        public UpdateResponse someMethod(){ //do something
return UpdateResponseInstance;
}

Here spring internally converts the UpdateResponse object to corresponding json string and returns it. In order to do it spring internally uses Jackson library.

If you require a json representation of a model object anywhere apart from controller then you can use objectMapper provided by jackson. Model should be properly annotated for this to work.

Eg:

ObjectMapper mapper = new ObjectMapper();
SomeModelClass someModelObject = someModelRepository.findById(idValue).get();
mapper.writeValueAsString(someModelObject);

Color picker utility (color pipette) in Ubuntu

You can install the package gcolor2 for this:

sudo apt-get install gcolor2

Then:

Applications -> Graphics -> GColor2

How do I call a function twice or more times consecutively?

I would:

for _ in range(3):
    do()

The _ is convention for a variable whose value you don't care about.

You might also see some people write:

[do() for _ in range(3)]

however that is slightly more expensive because it creates a list containing the return values of each invocation of do() (even if it's None), and then throws away the resulting list. I wouldn't suggest using this unless you are using the list of return values.

How can I build a recursive function in python?

Let's say you want to build: u(n+1)=f(u(n)) with u(0)=u0

One solution is to define a simple recursive function:

u0 = ...

def f(x):
  ...

def u(n):
  if n==0: return u0
  return f(u(n-1))

Unfortunately, if you want to calculate high values of u, you will run into a stack overflow error.

Another solution is a simple loop:

def u(n):
  ux = u0
  for i in xrange(n):
    ux=f(ux)
  return ux

But if you want multiple values of u for different values of n, this is suboptimal. You could cache all values in an array, but you may run into an out of memory error. You may want to use generators instead:

def u(n):
  ux = u0
  for i in xrange(n):
    ux=f(ux)
  yield ux

for val in u(1000):
  print val

There are many other options, but I guess these are the main ones.

Insert all data of a datagridview to database at once

I think the best way is by using TableAdapters rather than using Commands objects, its Update method sends all changes mades (Updates,Inserts and Deletes) inside a Dataset or DataTable straight TO the database. Usually when using a DataGridView you bind to a BindingSource which lets you interact with a DataSource such as Datatables or Datasets.

If you work like this, then on your bounded DataGridView you can just do:

this.customersBindingSource.EndEdit();
this.myTableAdapter.Update(this.myDataSet.Customers);

The 'customersBindingSource' is the DataSource of the DataGridView.

The adapter's Update method will update a single data table and execute the correct command (INSERT, UPDATE, or DELETE) based on the RowState of each data row in the table.

From: https://msdn.microsoft.com/en-us/library/ms171933.aspx

So any changes made inside the DatagridView will be reflected on the Database when using the Update method.

More about TableAdapters: https://msdn.microsoft.com/en-us/library/bz9tthwx.aspx

Is it possible to animate scrollTop with jQuery?

Like Kita mentioned there is a problem with multiple callbacks firing when you animate on both 'html' and 'body'. Instead of animating both and blocking subsequent callbacks I prefer to use some basic feature detection and only animate the scrollTop property of a single object.

The accepted answer on this other thread gives some insight as to which object's scrollTop property we should try to animate: pageYOffset Scrolling and Animation in IE8

// UPDATE: don't use this... see below
// only use 'body' for IE8 and below
var scrollTopElement = (window.pageYOffset != null) ? 'html' : 'body';

// only animate on one element so our callback only fires once!
$(scrollTopElement).animate({ 
        scrollTop: '400px' // vertical position on the page
    },
    500, // the duration of the animation 
    function() {       
        // callback goes here...
    })
});

UPDATE - - -

The above attempt at feature detection fails. Seems like there's not a one-line way of doing it as webkit type browsers pageYOffset property always returns zero when there's a doctype. Instead, I found a way to use a promise to do a single callback for every time the animation executes.

$('html, body')
    .animate({ scrollTop: 100 })
    .promise()
    .then(function(){
        // callback code here
    })
});

Case insensitive string compare in LINQ-to-SQL

If you pass a string that is case-insensitive into LINQ-to-SQL it will get passed into the SQL unchanged and the comparison will happen in the database. If you want to do case-insensitive string comparisons in the database all you need to to do is create a lambda expression that does the comparison and the LINQ-to-SQL provider will translate that expression into a SQL query with your string intact.

For example this LINQ query:

from user in Users
where user.Email == "[email protected]"
select user

gets translated to the following SQL by the LINQ-to-SQL provider:

SELECT [t0].[Email]
FROM [User] AS [t0]
WHERE [t0].[Email] = @p0
-- note that "@p0" is defined as nvarchar(11)
-- and is passed my value of "[email protected]"

As you can see, the string parameter will be compared in SQL which means things ought to work just the way you would expect them to.

Show and hide divs at a specific time interval using jQuery

Loop through divs every 10 seconds.

$(function () {

    var counter = 0,
        divs = $('#div1, #div2, #div3');

    function showDiv () {
        divs.hide() // hide all divs
            .filter(function (index) { return index == counter % 3; }) // figure out correct div to show
            .show('fast'); // and show it

        counter++;
    }; // function to loop through divs and show correct div

    showDiv(); // show first div    

    setInterval(function () {
        showDiv(); // show next div
    }, 10 * 1000); // do this every 10 seconds    

});

How to activate virtualenv?

Here is my workflow after creating a folder and cd'ing into it:

$ virtualenv venv --distribute
New python executable in venv/bin/python
Installing distribute.........done.
Installing pip................done.
$ source venv/bin/activate
(venv)$ python

Make a dictionary with duplicate keys in Python

You can change the behavior of the built in types in Python. For your case it's really easy to create a dict subclass that will store duplicated values in lists under the same key automatically:

class Dictlist(dict):
    def __setitem__(self, key, value):
        try:
            self[key]
        except KeyError:
            super(Dictlist, self).__setitem__(key, [])
        self[key].append(value)

Output example:

>>> d = dictlist.Dictlist()
>>> d['test'] = 1
>>> d['test'] = 2
>>> d['test'] = 3
>>> d
{'test': [1, 2, 3]}
>>> d['other'] = 100
>>> d
{'test': [1, 2, 3], 'other': [100]}

Linux shell sort file according to the second column?

To sort by second field only (thus where second fields match, those lines with matches remain in the order they are in the original without sorting on other fields) :

sort -k 2,2 -s orig_file > sorted_file

How can I select the row with the highest ID in MySQL?

For MySQL:

SELECT *
FROM permlog
ORDER BY id DESC
LIMIT 1

You want to sort the rows from highest to lowest id, hence the ORDER BY id DESC. Then you just want the first one so LIMIT 1:

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement.
[...]
With one argument, the value specifies the number of rows to return from the beginning of the result set

SQL Server - INNER JOIN WITH DISTINCT

It's not the same doing a select distinct at the beginning because you are wasting all the calculated rows from the result.

select a.FirstName, a.LastName, v.District
from AddTbl a order by Firstname
natural join (select distinct LastName from
            ValTbl v  where a.LastName = v.LastName)

try that.

Looping through all the properties of object php

If this is just for debugging output, you can use the following to see all the types and values as well.

var_dump($obj);

If you want more control over the output you can use this:

foreach ($obj as $key => $value) {
    echo "$key => $value\n";
}

Calculating distance between two points, using latitude longitude?

package distanceAlgorithm;

public class CalDistance {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    CalDistance obj=new CalDistance();
    /*obj.distance(38.898556, -77.037852, 38.897147, -77.043934);*/
        System.out.println(obj.distance(38.898556, -77.037852, 38.897147, -77.043934, "M") + " Miles\n");
        System.out.println(obj.distance(38.898556, -77.037852, 38.897147, -77.043934, "K") + " Kilometers\n");
        System.out.println(obj.distance(32.9697, -96.80322, 29.46786, -98.53506, "N") + " Nautical Miles\n");       
    }   
    public double distance(double lat1, double lon1, double lat2, double lon2, String sr) {


          double theta = lon1 - lon2;
          double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
          dist = Math.acos(dist);
          dist = rad2deg(dist);
          dist = dist * 60 * 1.1515;
          if (sr.equals("K")) {
            dist = dist * 1.609344;
          } else if (sr.equals("N")) {
            dist = dist * 0.8684;
            }
          return (dist);
        }
    public double deg2rad(double deg) {
          return (deg * Math.PI / 180.0);
        }
    public double rad2deg(double rad) {
          return (rad * 180.0 / Math.PI);
        }


    }

Checking if an input field is required using jQuery

$('form#register input[required]')

It will only return inputs which have required attribute.

What port number does SOAP use?

SOAP (communication protocol) for communication between applications. Uses HTTP (port 80) or SMTP ( port 25 or 2525 ), for message negotiation and transmission.

How to get query params from url in Angular 2?

Even though the question specifies version beta 7, this question also comes up as top search result on Google for common phrases like angular 2 query parameters. For that reason here's an answer for the newest router (currently in alpha.7).

The way the params are read has changed dramatically. First you need to inject dependency called Router in your constructor parameters like:

constructor(private router: Router) { }

and after that we can subscribe for the query parameters on our ngOnInit method (constructor is okay too, but ngOnInit should be used for testability) like

this.router
  .routerState
  .queryParams
  .subscribe(params => {
    this.selectedId = +params['id'];
  });

In this example we read the query param id from URL like example.com?id=41.

There are still few things to notice:

  1. Accessing property of params like params['id'] always returns a string, and this can be converted to number by prefixing it with +.
  2. The reason why the query params are fetched with observable is that it allows re-using the same component instance instead of loading a new one. Each time query param is changed, it will cause a new event that we have subscribed for and thus we can react on changes accordingly.

Regular expression for letters, numbers and - _

Something like this should work

$code = "screen new file.css";
if (!preg_match("/^[-_a-zA-Z0-9.]+$/", $code))
{
    echo "not valid";
}

This will echo "not valid"

Detect enter press in JTextField

Just use this code:

SwingUtilities.getRootPane(myButton).setDefaultButton(myButton);

How to use EOF to run through a text file in C?

You should check the EOF after reading from file.

fscanf_s                   // read from file
while(condition)           // check EOF
{
   fscanf_s               // read from file
}

Changing image size in Markdown

If you are using kramdown, you can do this:

{:.foo}
![drawing](drawing.jpg)

Then add this to your Custom CSS:

.foo {
  text-align: center;
  width: 100px;
}

how to create a logfile in php?

Use below function

// Enable error reporting
ini_set('display_errors', 1);
//Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
//error_reporting(E_ALL & ~E_NOTICE);
// Tell php where your custom php error log is
ini_set('error_log', 'php_error.log');

$dateTime=date("Y-m-d H:i:s");
$ip= $_SERVER['REMOTE_ADDR'];
$errorString="Error occured on time $dateTime by ip $ip";
$php_error_msg.=$errorString;
// Append the error message to the php-error log
//error_log($php_error_msg);
error_log("A custom error has been triggered",1,"email_address","From: email_address");

Above function will create a log in file php_error with proper description and email will be sent.

What is an unhandled promise rejection?

I had faced a similar issue with NodeJS, where the culprit was a forEach loop. Note that forEach is a synchronous function (NOT Asynchronous). Therefore it just ignores the promise returned. The solution was to use a for-of loop instead: Code where I got the error:

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()

is as follows:

permissionOrders.forEach( async(order) => {
        const requestPermissionOrder = new RequestPermissionOrderSchema({
            item: order.item,
            item_desc: order.item_desc,
            quantity: order.quantity,
            unit_price: order.unit_price,
            total_cost: order.total_cost,
            status: order.status,
            priority: order.priority,
            directOrder: order.directOrder
        });

        try {
            const dat_order = await requestPermissionOrder.save();
            res.json(dat_order);
        } catch(err){
            res.json({ message : err});
        }
    });

Solution for the above issue is as follows:

for (let order of permissionOrders){
        const requestPermissionOrder = new RequestPermissionOrderSchema({
            item: order.item,
            item_desc: order.item_desc,
            quantity: order.quantity,
            unit_price: order.unit_price,
            total_cost: order.total_cost,
            status: order.status,
            priority: order.priority,
            directOrder: order.directOrder
        });

        try {
            const dat_order = await requestPermissionOrder.save();
            res.json(dat_order);
        } catch(err){
            res.json({ message : err});
        }
    };

Angular2, what is the correct way to disable an anchor element?

My answer might be late for this post. It can be achieved through inline css within anchor tag only.

<a [routerLink]="['/user']" [style.pointer-events]="isDisabled ?'none':'auto'">click-label</a>

Considering isDisabled is a property in component which can be true or false.

Plunker for it: https://embed.plnkr.co/TOh8LM/

How to quickly and conveniently create a one element arraylist

The other answers all use Arrays.asList(), which returns an unmodifiable list (an UnsupportedOperationException is thrown if you try to add or remove an element). To get a mutable list you can wrap the returned list in a new ArrayList as a couple of answers point out, but a cleaner solution is to use Guava's Lists.newArrayList() (available since at least Guava 10, released in 2011).

For example:

Lists.newArrayList("Blargle!");

Handling onchange event in HTML.DropDownList Razor MVC

The way of dknaack does not work for me, I found this solution as well:

@Html.DropDownList("Chapters", ViewBag.Chapters as SelectList, 
                    "Select chapter", new { @onchange = "location = this.value;" })

where

@Html.DropDownList(controlName, ViewBag.property + cast, "Default value", @onchange event)

In the controller you can add:

DbModel db = new DbModel();    //entity model of Entity Framework

ViewBag.Chapters = new SelectList(db.T_Chapter, "Id", "Name");

How to drop a unique constraint from table column?

I would like to refer a previous question, Because I have faced same problem and solved by this solution. First of all a constraint is always built with a Hash value in it's name. So problem is this HASH is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4 here 6AB17FE4 is the hash value(8 bit). So I am referring a single script which will be fruitful to all

DECLARE @Command NVARCHAR(MAX)
     declare @table_name nvarchar(256)
     declare @col_name nvarchar(256)
     set @table_name = N'ProcedureAlerts'
     set @col_name = N'EmailSent'

     select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
     from 
         sys.tables t
         join sys.default_constraints d on d.parent_object_id = t.object_id
         join sys.columns c on c.object_id = t.object_id
                               and c.column_id = d.parent_column_id
     where 
         t.name = @table_name
         and c.name = @col_name) + ']'

    --print @Command
    exec sp_executesql @Command

It will drop your default constraint. However if you want to create it again you can simply try this

ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]

Finally, just simply run a DROP command to drop the column.

How do I suspend painting for a control and its children?

This is even simpler, and perhaps hacky - as I can see a lot of GDI muscle on this thread, and is obviously only a good fit for certain scenarios. YMMV

In my scenario, I use what I'll refer to as a "Parent" UserControl - and during the Load event, I simply remove the control-to-be-manipulated from the Parent's .Controls collection, and the Parent's OnPaint takes care of completely painting the child control in whatever special way.. fully taking the child's paint capabilities offline.

Now, I hand off my child paint routine to an extension method based off this concept from Mike Gold for printing windows forms.

Here I'm needing a sub-set of labels to render perpendicular to the layout:

simple diagram of your Visual Studio IDE

Then, I exempt the child control from being painted, with this code in the ParentUserControl.Load event handler:

Private Sub ParentUserControl_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    SetStyle(ControlStyles.UserPaint, True)
    SetStyle(ControlStyles.AllPaintingInWmPaint, True)

    'exempt this control from standard painting: 
    Me.Controls.Remove(Me.HostedControlToBeRotated) 
End Sub

Then, in the same ParentUserControl, we paint the control-to-be-manipulated from the ground up:

Protected Overrides Sub OnPaint(e As PaintEventArgs)
    'here, we will custom paint the HostedControlToBeRotated instance...

    'twist rendering mode 90 counter clockwise, and shift rendering over to right-most end 
    e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
    e.Graphics.TranslateTransform(Me.Width - Me.HostedControlToBeRotated.Height, Me.Height)
    e.Graphics.RotateTransform(-90)
    MyCompany.Forms.CustomGDI.DrawControlAndChildren(Me.HostedControlToBeRotated, e.Graphics)

    e.Graphics.ResetTransform()
    e.Graphics.Dispose()

    GC.Collect()
End Sub

Once you host the ParentUserControl somewhere, e.g. a Windows Form - I'm finding that my Visual Studio 2015 renders the form correctly at Design Time as well as runtime: ParentUserControl hosted in a Windows Form or perhaps other user control

Now, since my particular manipulation rotates the child control 90 degrees, I'm sure all the hot spots and interactivity has been destroyed in that region - but, the problem I was solving was all for a package label that needed to preview and print, which worked out fine for me.

If there are ways to reintroduce the hot spots and control-ness to my purposely orphaned control - I'd love to learn about that someday (not for this scenario, of course, but.. just to learn). Of course, WPF supports such craziness OOTB.. but.. hey.. WinForms is so much fun still, amiright?

Javascript | Set all values of an array

Found this while working with Epicycles - clearly works - where 'p' is invisible to my eyes.

/** Convert a set of picture points to a set of Cartesian coordinates */
function toCartesian(points, scale) {
  const x_max = Math.max(...points.map(p=>p[0])),
  y_max = Math.max(...points.map(p=>p[1])),
  x_min = Math.min(...points.map(p=>p[0])),
  y_min = Math.min(...points.map(p=>p[1])),
  signed_x_max = Math.floor((x_max - x_min + 1) / 2),
  signed_y_max = Math.floor((y_max - y_min + 1) / 2);

  return points.map(p=>
  [ -scale * (signed_x_max - p[0] + x_min),
  scale * (signed_y_max - p[1] + y_min) ] );
}

Converting URL to String and back again

Swift 3 version code:

let urlString = "file:///Users/Documents/Book/Note.txt"
let pathURL = URL(string: urlString)!
print("the url = " + pathURL.path)

Set android shape color programmatically

this is the solution that works for me...wrote it in another question as well: How to change shape color dynamically?

//get the image button by id
ImageButton myImg = (ImageButton) findViewById(R.id.some_id);

//get drawable from image button
GradientDrawable drawable = (GradientDrawable) myImg.getDrawable();

//set color as integer
//can use Color.parseColor(color) if color is a string
drawable.setColor(color)

Android ListView headers

What I did to make the Date (e.g December 01, 2016) as header. I used the StickyHeaderListView library

https://github.com/emilsjolander/StickyListHeaders

Convert the date to long in millis [do not include the time] and make it as the header Id.

@Override
public long getHeaderId(int position) {
    return <date in millis>;
}

Adding a css class to select using @Html.DropDownList()

Try below code:

@Html.DropDownList("ProductTypeID",null,"",new { @class = "form-control"})

rails generate model

The error shows you either didn't create the rails project yet or you're not in the rails project directory.

Suppose if you're working on myapp project. You've to move to that project directory on your command line and then generate the model. Here are some steps you can refer.

Example: Assuming you didn't create the Rails app yet:

$> rails new myapp
$> cd myapp

Now generate the model from your commandline.

$> rails generate model your_model_name 

git: How to diff changed files versus previous versions after a pull?

If you do a straight git pull then you will either be 'fast-forwarded' or merge an unknown number of commits from the remote repository. This happens as one action though, so the last commit that you were at immediately before the pull will be the last entry in the reflog and can be accessed as HEAD@{1}. This means that you can do:

git diff HEAD@{1}

However, I would strongly recommend that if this is something you find yourself doing a lot then you should consider just doing a git fetch and examining the fetched branch before manually merging or rebasing onto it. E.g. if you're on master and were going to pull in origin/master:

git fetch

git log HEAD..origin/master

 # looks good, lets merge

git merge origin/master

Is SMTP based on TCP or UDP?

Seems the SMTP as internet standard uses only reliable Transport protocol. RFC821 has TCP, NCP, NITS as examples!

Java 8 Iterable.forEach() vs foreach loop

The advantage of Java 1.8 forEach method over 1.7 Enhanced for loop is that while writing code you can focus on business logic only.

forEach method takes java.util.function.Consumer object as an argument, so It helps in having our business logic at a separate location that you can reuse it anytime.

Have look at below snippet,

  • Here I have created new Class that will override accept class method from Consumer Class, where you can add additional functionility, More than Iteration..!!!!!!

    class MyConsumer implements Consumer<Integer>{
    
        @Override
        public void accept(Integer o) {
            System.out.println("Here you can also add your business logic that will work with Iteration and you can reuse it."+o);
        }
    }
    
    public class ForEachConsumer {
    
        public static void main(String[] args) {
    
            // Creating simple ArrayList.
            ArrayList<Integer> aList = new ArrayList<>();
            for(int i=1;i<=10;i++) aList.add(i);
    
            //Calling forEach with customized Iterator.
            MyConsumer consumer = new MyConsumer();
            aList.forEach(consumer);
    
    
            // Using Lambda Expression for Consumer. (Functional Interface) 
            Consumer<Integer> lambda = (Integer o) ->{
                System.out.println("Using Lambda Expression to iterate and do something else(BI).. "+o);
            };
            aList.forEach(lambda);
    
            // Using Anonymous Inner Class.
            aList.forEach(new Consumer<Integer>(){
                @Override
                public void accept(Integer o) {
                    System.out.println("Calling with Anonymous Inner Class "+o);
                }
            });
        }
    }
    

How to install all required PHP extensions for Laravel?

Laravel Server Requirements mention that BCMath, Ctype, JSON, Mbstring, OpenSSL, PDO, Tokenizer, and XML extensions are required. Most of the extensions are installed and enabled by default.

You can run the following command in Ubuntu to make sure the extensions are installed.

sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip

PHP version specific installation (if PHP 7.4 installed)

sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring

You may need other PHP extensions for your composer packages. Find from links below.

PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)

PHP extensions for Ubuntu 18.04 LTS (Bionic)

PHP extensions for Ubuntu 16.04 LTS (Xenial)

How to display PDF file in HTML?

I understand you want to display using HTMl but you can also open the PDF file using php by pointing out the path and the browser will render it in a few simple steps

<?php
$your_file_name = "url_here";

//Content type and this case its a PDF
header("Content-type: application/pdf");

header("Content-Length: " . filesize($your_file_name )); 

//Display the file
readfile($your_file_name );
?>

C++ Singleton design pattern

This is about object life-time management. Suppose you have more than singletons in your software. And they depend on Logger singleton. During application destruction, suppose another singleton object uses Logger to log its destruction steps. You have to guarantee that Logger should be cleaned up last. Therefore, please also check out this paper: http://www.cs.wustl.edu/~schmidt/PDF/ObjMan.pdf

What is the difference between encrypting and signing in asymmetric encryption?

Signing indicates you really are the source or vouch for of the object signed. Everyone can read the object, though.

Encrypting means only those with the corresponding private key can read it, but without signing there is no guarantee you are behind the encrypted object.

TypeError: Can't convert 'int' object to str implicitly

You cannot concatenate a string with an int. You would need to convert your int to a string using the str function, or use formatting to format your output.

Change: -

print("Ok. Your balance is now at " + balanceAfterStrength + " skill points.")

to: -

print("Ok. Your balance is now at {} skill points.".format(balanceAfterStrength))

or: -

print("Ok. Your balance is now at " + str(balanceAfterStrength) + " skill points.")

or as per the comment, use , to pass different strings to your print function, rather than concatenating using +: -

print("Ok. Your balance is now at ", balanceAfterStrength, " skill points.")

Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?

To add to the above: If interrupt is not working, you can restart the kernel.

Go to the kernel dropdown >> restart >> restart and clear output. This usually does the trick. If this still doesn't work, kill the kernel in the terminal (or task manager) and then restart.

Interrupt doesn't work well for all processes. I especially have this problem using the R kernel.

How to write connection string in web.config file and read from it?

Are you sure that your configuration file (web.config) is at the right place and the connection string is really in the (generated) file? If you publish your file, the content of web.release.config might be copied.

The configuration and the access to the Connection string looks all right to me. I would always add a providername

<connectionStrings>
  <add name="Dbconnection" 
       connectionString="Server=localhost; Database=OnlineShopping; 
       Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

mysql update column with value from another table

Store your data in temp table

Select * into tempTable from table1

Now update the column

 UPDATE table1
    SET table1.FileName = (select FileName from tempTable where tempTable.id = table1.ID);

java.lang.OutOfMemoryError: Java heap space in Maven

In order to resolve java.lang.OutOfMemoryError: Java heap space in Maven, try to configure below configuration in pom

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>${maven-surefire-plugin.version}</version>
     <configuration>
        <verbose>true</verbose>
        <fork>true</fork>
        <argLine>-XX:MaxPermSize=500M</argLine>
    </configuration>
</plugin>

Python's "in" set operator

Sets behave different than dicts, you need to use set operations like issubset():

>>> k
{'ip': '123.123.123.123', 'pw': 'test1234', 'port': 1234, 'debug': True}
>>> set('ip,port,pw'.split(',')).issubset(set(k.keys()))
True
>>> set('ip,port,pw'.split(',')) in set(k.keys())
False

Draw a connecting line between two elements

jsPlumb is an option available that supports drag and drop, as seen by its numerous demos, including the Flowchart demo.

It is available in a free Community edition, and a paid Toolkit edition.

The Toolkit edition wraps the Community edition with a comprehensive data binding layer, as well as several UI widgets for building applications and integrations for popular libraries, and is commercially licensed.

Tomcat Server Error - Port 8080 already in use

To get rid of this error just click on server tab on eclipse . You will get list of servers as below image (In my case it was tomcat 8 only)

enter image description here

Double click on the respective server. You will get screen as shown below :-

enter image description here

Now change Conflicting port number. In my case I changed 8080 to 8081 (highlighted portion). Save it (ctrl+s) and hence you can start your server now.

How to create empty constructor for data class in Kotlin Android

Along with @miensol answer, let me add some details:

If you want a Java-visible empty constructor using data classes, you need to define it explicitely.

Using default values + constructor specifier is quite easy:

data class Activity(
    var updated_on: String = "",
    var tags: List<String> = emptyList(),
    var description: String = "",
    var user_id: List<Int> = emptyList(),
    var status_id: Int = -1,
    var title: String = "",
    var created_at: String = "",
    var data: HashMap<*, *> = hashMapOf<Any, Any>(),
    var id: Int = -1,
    var counts: LinkedTreeMap<*, *> = LinkedTreeMap<Any, Any>()
) {
    constructor() : this(title = "") // this constructor is an explicit
                                     // "empty" constructor, as seen by Java.
}

This means that with this trick you can now serialize/deserialize this object with the standard Java serializers (Jackson, Gson etc).

React Native Border Radius with background color

Try moving the button styling to the TouchableHighlight itself:

Styles:

  submit:{
    marginRight:40,
    marginLeft:40,
    marginTop:10,
    paddingTop:20,
    paddingBottom:20,
    backgroundColor:'#68a0cf',
    borderRadius:10,
    borderWidth: 1,
    borderColor: '#fff'
  },
  submitText:{
      color:'#fff',
      textAlign:'center',
  }

Button (same):

<TouchableHighlight
  style={styles.submit}
  onPress={() => this.submitSuggestion(this.props)}
  underlayColor='#fff'>
    <Text style={[this.getFontSize(),styles.submitText]}>Submit</Text>
</TouchableHighlight>

enter image description here

HTML5 LocalStorage: Checking if a key exists

Update:

if (localStorage.hasOwnProperty("username")) {
    //
}

Another way, relevant when value is not expected to be empty string, null or any other falsy value:

if (localStorage["username"]) {
    //
}

Find the division remainder of a number

If you want to avoid modulo, you can also use a combination of the four basic operations :)

26 - (26 // 7 * 7) = 5

C Linking Error: undefined reference to 'main'

You should provide output file name after -o option. In your case runexp.o is treated as output file name, not input object file and thus your main function is undefined.

C++ template constructor

Here's a workaround.

Make a template subclass B of A. Do the template-argument-independent part of the construction in A's constructor. Do the template-argument-dependent part in B's constructor.

Jquery - How to get the style display attribute "none / block"

this is the correct answer

$('#theid').css('display') == 'none'

You can also use following line to find if it is display block or none

$('.deal_details').is(':visible')

Lazy Loading vs Eager Loading

Lazy loading - is good when handling with pagination like on page load list of users appear which contains 10 users and as the user scrolls down the page an api call brings next 10 users.Its good when you don't want to load enitire data at once as it would take more time and would give bad user experience.

Eager loading - is good as other people suggested when there are not much relations and fetch entire data at once in single call to database

What's the difference between Docker Compose vs. Dockerfile

"better" is relative. It all depends on what your needs are. Docker compose is for orchestrating multiple containers. If these images already exist in the docker registry, then it's better to list them in the compose file. If these images or some other images have to be built from files on your computer, then you can describe the processes of building those images in a Dockerfile.

I understand that Dockerfiles are used in Docker Compose, but I am not sure if it is good practice to put everything in one large Dockerfile with multiple FROM commands for the different images?

Using multiple FROM in a single dockerfile is not a very good idea because there is a proposal to remove the feature. 13026

If for instance, you want to dockerize an application which uses a database and have the application files on your computer, you can use a compose file together with a dockerfile as follows

docker-compose.yml

mysql:
  image: mysql:5.7
  volumes:
    - ./db-data:/var/lib/mysql
  environment:
    - "MYSQL_ROOT_PASSWORD=secret"
    - "MYSQL_DATABASE=homestead"
    - "MYSQL_USER=homestead"
  ports:
    - "3307:3306"
app:
  build:
    context: ./path/to/Dockerfile
    dockerfile: Dockerfile
  volumes:
    - ./:/app
  working_dir: /app
      

Dockerfile

FROM php:7.1-fpm 
RUN apt-get update && apt-get install -y libmcrypt-dev \
  mysql-client libmagickwand-dev --no-install-recommends \
  && pecl install imagick \
  && docker-php-ext-enable imagick \
  && docker-php-ext-install pdo_mysql \
  && curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

How do I split a string with multiple separators in JavaScript?

Tricky method:

var s = "dasdnk asd, (naks) :d skldma";
var a = s.replace('(',' ').replace(')',' ').replace(',',' ').split(' ');
console.log(a);//["dasdnk", "asd", "naks", ":d", "skldma"]

Opening A Specific File With A Batch File?

That program would need to have a specific API that you can use from the command line.

For example the following command uses 7Zip to extract a zip file. This only works as 7Zip has an API to do this specific task (using the x switch).

"C:\Program Files\7-Zip\CommandLine\7za.exe" x C:\docs\base-file-structure.zip 

How to replace special characters in a string?

string Output = Regex.Replace(Input, @"([ a-zA-Z0-9&, _]|^\s)", "");

Here all the special characters except space, comma, and ampersand are replaced. You can also omit space, comma and ampersand by the following regular expression.

string Output = Regex.Replace(Input, @"([ a-zA-Z0-9_]|^\s)", "");

Where Input is the string which we need to replace the characters.

How to recover just deleted rows in mysql?

I'm sorry, bu it's not posible, unless you made a backup file earlier.

EDIT: Actually it is possible, but it gets very tricky and you shouldn't think about it if data wasn't really, really important. You see: when data get's deleted from a computer it still remains in the same place on the disk, only its sectors are marked as empty. So data remains intact, except if it gets overwritten by new data. There are several programs designed for this purpose and there are companies who specialize in data recovery, though they are rather expensive.

file_get_contents() Breaks Up UTF-8 Characters

I had similar problem with polish language

I tried:

$fileEndEnd = mb_convert_encoding($fileEndEnd, 'UTF-8', mb_detect_encoding($fileEndEnd, 'UTF-8', true));

I tried:

$fileEndEnd = utf8_encode ( $fileEndEnd );

I tried:

$fileEndEnd = iconv( "UTF-8", "UTF-8", $fileEndEnd );

And then -

$fileEndEnd = mb_convert_encoding($fileEndEnd, 'HTML-ENTITIES', "UTF-8");

This last worked perfectly !!!!!!

How to pip or easy_install tkinter on Windows

In python, Tkinter was a default package, you can repair the installation and select Tcl/Tk. repair When you run this, DDL should be installed like so: enter image description here

PHP Converting Integer to Date, reverse of strtotime

I guess you are asking why is 1388516401 equal to 2014-01-01...?

There is an historical reason for that. There is a 32-bit integer variable, called time_t, that keeps the count of the time elapsed since 1970-01-01 00:00:00. Its value expresses time in seconds. This means that in 2014-01-01 00:00:01 time_t will be equal to 1388516401.

This leads us for sure to another interesting fact... In 2038-01-19 03:14:07 time_t will reach 2147485547, the maximum value for a 32-bit number. Ever heard about John Titor and the Year 2038 problem? :D

Validating parameters to a Bash script

The man page for test (man test) provides all available operators you can use as boolean operators in bash. Use those flags in the beginning of your script (or functions) for input validation just like you would in any other programming language. For example:

if [ -z $1 ] ; then
  echo "First parameter needed!" && exit 1;
fi

if [ -z $2 ] ; then
  echo "Second parameter needed!" && exit 2;
fi

How to delete duplicates on a MySQL table?

This work for me to remove old records:

delete from table where id in 
(select min(e.id)
    from (select * from table) e 
    group by column1, column2
    having count(*) > 1
); 

You can replace min(e.id) to max(e.id) to remove newest records.

how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application?

I found it working for me by setting this variable directly on Azure platorm (if you use it). Just select your web app -> configuration -> application settings and add the variable and its value, then press Save button.

how to call an ASP.NET c# method using javascript

I'm going to go right ahead and offer a solution using jQuery, which means you will need to import the library if you haven't already...

Import the jQuery library in your page mark-up:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>

Then create another *.js script file (I call mine ExecutePageMethod, since that is the only method it is going to expose) and import it:

<script type="text/javascript" src="/ExecutePageMethod.js" ></script>

Within the newly added file, add the following code (I remember pulling this from elsewhere, so someone else deserves credit for it really):

function ExecutePageMethod(page, fn, paramArray, successFn, errorFn) {
    var paramList = '';
    if (paramArray.length > 0) {
        for (var i = 0; i < paramArray.length; i += 2) {
            if (paramList.length > 0) paramList += ',';
            paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
        }
    }
    paramList = '{' + paramList + '}';
    $.ajax({
        type: "POST",
        url: page + "/" + fn,
        contentType: "application/json; charset=utf-8",
        data: paramList,
        dataType: "json",
        success: successFn,
        error: errorFn
    });
}

You will then need to augment your .NET page method with the appropriate attributes, as such:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string MyMethod()
{
    return "Yay!";
}

Now, within your page mark-up, within a script block or from another script file, you can call the method, like so:

ExecutePageMethod("PageName.aspx", "MyMethod", [], OnSuccess, OnFailure);

Obviously you will need to implement the OnSuccess and OnFailure methods.

To consume the results, say in the OnSuccess method, you can use the parseJSON method, which, if the results become more complex (in the case or returning an array of types, for instance) this method will parse it into objects:

function OnSuccess(result) {
    var parsedResult = jQuery.parseJSON(result.d);
}

This ExecutePageMethod code is particularly useful since it it reusable, so rather than having to manage an $.ajax call for each page method you might want to execute, you just need to pass the page, method name and arguments to this method.

How to count objects in PowerShell?

@($output).Count does not always produce correct results. I used the ($output | Measure).Count method.

I found this with VMware Get-VmQuestion cmdlet:

$output = Get-VmQuestion -VM vm1
@($output).Count

The answer it gave is one, whereas

$output

produced no output (the correct answer was 0 as produced with the Measure method).

This only seemed to be the case with 0 and 1. Anything above 1 was correct with limited testing.

ArrayList - How to modify a member of an object?

If you need fast lookup (basically constant time) of a object stored in your collection you should use Map instead of List.

If you need fast iteration of the objects you should use List.

So in your case...

Map<String,Customer> customers = new HashMap<String,Customer>();

//somewhere in the code you fill up the Map, assuming customer names are unique
customers.put(customer.getName(), customer)

// at some later point you retrieve it like this; 
// this is fast, given a good hash
// been calculated for the "keys" in your map, in this case the keys are unique 
// String objects so the default hash algorithm should be fine
Customer theCustomerYouLookFor = customers.get("Doe");

// modify it
theCustomerYouLookFor.setEmail("[email protected]")

How to implement private method in ES6 class with Traceur

As Marcelo Lazaroni has already said,

Although currently there is no way to declare a method or property as private, ES6 modules are not in the global namespace. Therefore, anything that you declare in your module and do not export will not be available to any other part of your program, but will still be available to your module during run time.

But his example didn't show how the private method could access members of the instance of the class. Max shows us some good examples of how access instance members through binding or the alternative of using a lambda method in the constructor, but I would like to add one more simple way of doing it: passing the instance as a parameter to the private method. Doing it this way would lead Max's MyClass to look like this:

function myPrivateFunction(myClass) {
  console.log("My property: " + myClass.prop);
}

class MyClass() {
  constructor() {
    this.prop = "myProp";
  }
  testMethod() {
    myPrivateFunction(this);
  }
}
module.exports = MyClass;

Which way you do it really comes down to personal preference.

How can I do time/hours arithmetic in Google Spreadsheet?

Google Sheets now have a duration formatting option. Select: Format -> Number -> Duration.

String.Format alternative in C++

As already mentioned the C++ way is using stringstreams.

#include <sstream>

string a = "test";
string b = "text.txt";
string c = "text1.txt";

std::stringstream ostr;
ostr << a << " " << b << " > " << c;

Note that you can get the C string from the string stream object like so.

std::string formatted_string = ostr.str();
const char* c_str = formatted_string.c_str();