Programs & Examples On #Dial up

Network tools that simulate slow network connection

try Traffic Shaper XP you can easily limit speed of IE or other browser with this App and its also freeware

Can you force Visual Studio to always run as an Administrator in Windows 8?

VSCommands didn't work for me and caused a problem when I installed Visual Studio 2010 aside of Visual Studio 2012.

After some experimentations I found the trick:

Go to HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers and add an entry with the name "C:\Program Files (x86)\Common Files\Microsoft Shared\MSEnv\VSLauncher.exe" and the value "RUNASADMIN".

This should solve your issue. I've also blogged about that.

How do I create dynamic variable names inside a loop?

You can use eval() method to declare dynamic variables. But better to use an Array.

for (var i = 0; i < coords.length; ++i) {
    var str ="marker"+ i+" = undefined";
    eval(str);
}

show/hide a div on hover and hover out

<script type="text/javascript">
    var IdAry=['reports1'];
    window.onload=function() {
     for (var zxc0=0;zxc0<IdAry.length;zxc0++){
      var el=document.getElementById(IdAry[zxc0]);
      if (el){
       el.onmouseover=function() {
         changeText(this,'hide','show')
        }
       el.onmouseout=function() {
         changeText(this,'show','hide');
        }
      }
     }
    }
    function changeText(obj,cl1,cl2) {
       obj.getElementsByTagName('SPAN')[0].className=cl1;
       obj.getElementsByTagName('SPAN')[1].className=cl2;
    }
</script>

ur html should look like this

<p id="reports1">
                <span id="span1">Test Content</span>
                <span class="hide">

                    <br /> <br /> This is the content that appears when u hover on the it
                </span>
            </p>

Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org

If you're running on a Mac you could just search for Install Certificates.command on the spotlight and hit enter.

How do I find the install time and date of Windows?

Another question elligeable for a 'code-challenge': here are some source code executables to answer the problem, but they are not complete.
Will you find a vb script that anyone can execute on his/her computer, with the expected result ?


systeminfo|find /i "original" 

would give you the actual date... not the number of seconds ;)
As Sammy comments, find /i "install" gives more than you need.
And this only works if the locale is English: It needs to match the language.
For Swedish this would be "ursprungligt" and "ursprüngliches" for German.


In Windows PowerShell script, you could just type:

PS > $os = get-wmiobject win32_operatingsystem
PS > $os.ConvertToDateTime($os.InstallDate) -f "MM/dd/yyyy" 

By using WMI (Windows Management Instrumentation)

If you do not use WMI, you must read then convert the registry value:

PS > $path = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
PS > $id = get-itemproperty -path $path -name InstallDate
PS > $d = get-date -year 1970 -month 1 -day 1 -hour 0 -minute 0 -second 0
## add to hours (GMT offset)
## to get the timezone offset programatically:
## get-date -f zz
PS > ($d.AddSeconds($id.InstallDate)).ToLocalTime().AddHours((get-date -f zz)) -f "MM/dd/yyyy"

The rest of this post gives you other ways to access that same information. Pick your poison ;)


In VB.Net that would give something like:

Dim dtmInstallDate As DateTime
Dim oSearcher As New ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem")
For Each oMgmtObj As ManagementObject In oSearcher.Get
    dtmInstallDate =
        ManagementDateTimeConverter.ToDateTime(CStr(oMgmtO bj("InstallDate")))
Next

In Autoit (a Windows scripting language), that would be:

;Windows Install Date
;
$readreg = RegRead("HKLM\SOFTWARE\MICROSOFT\WINDOWS NT\CURRENTVERSION\", "InstallDate")
$sNewDate = _DateAdd( 's',$readreg, "1970/01/01 00:00:00")
MsgBox( 4096, "", "Date: " & $sNewDate )
Exit

In Delphy 7, that would go as:

Function GetInstallDate: String;
Var
  di: longint;
  buf: Array [ 0..3 ] Of byte;
Begin
  Result := 'Unknown';
  With TRegistry.Create Do
  Begin
    RootKey := HKEY_LOCAL_MACHINE;
    LazyWrite := True;
    OpenKey ( '\SOFTWARE\Microsoft\Windows NT\CurrentVersion', False );
    di := readbinarydata ( 'InstallDate', buf, sizeof ( buf ) );
//    Result := DateTimeToStr ( FileDateToDateTime ( buf [ 0 ] + buf [ 1 ] * 256 + buf [ 2 ] * 65535 + buf [ 3 ] * 16777216 ) );
showMessage(inttostr(di));
    Free;
  End;
End;

As an alternative, CoastN proposes in the comments:

As the system.ini-file stays untouched in a typical windows deployment, you can actually get the install-date by using the following oneliner:

(PowerShell): (Get-Item "C:\Windows\system.ini").CreationTime

Objective-C - Remove last character from string

In your controller class, create an action method you will hook the button up to in Interface Builder. Inside that method you can trim your string like this:


if ([string length] > 0) {
    string = [string substringToIndex:[string length] - 1];
} else {
    //no characters to delete... attempting to do so will result in a crash
}






If you want a fancy way of doing this in just one line of code you could write it as:

string = [string substringToIndex:string.length-(string.length>0)];

*Explanation of fancy one-line code snippet:

If there is a character to delete (i.e. the length of the string is greater than 0)
     (string.length>0) returns 1 thus making the code return:
          string = [string substringToIndex:string.length-1];

If there is NOT a character to delete (i.e. the length of the string is NOT greater than 0)
     (string.length>0) returns 0 thus making the code return:
          string = [string substringToIndex:string.length-0];
     Which prevents crashes.

How to get only numeric column values?

SELECT column1 FROM table WHERE ISNUMERIC(column1) = 1

Note, as Damien_The_Unbeliever has pointed out, this will include any valid numeric type.

To filter out columns containing non-digit characters (and empty strings), you could use

SELECT column1 FROM table WHERE column1 not like '%[^0-9]%' and column1 != ''

Regular expression to match a line that doesn't contain a word

Since the introduction of ruby-2.4.1, we can use the new Absent Operator in Ruby’s Regular Expressions

from the official doc

(?~abc) matches: "", "ab", "aab", "cccc", etc.
It doesn't match: "abc", "aabc", "ccccabc", etc.

Thus, in your case ^(?~hede)$ does the job for you

2.4.1 :016 > ["hoho", "hihi", "haha", "hede"].select{|s| /^(?~hede)$/.match(s)}
 => ["hoho", "hihi", "haha"]

Psql list all tables

Connect to the database, then list the tables:

\c liferay
\dt

That's how I do it anyway.

You can combine those two commands onto a single line, if you prefer:

\c liferay \dt

Change user-agent for Selenium web-driver

To build on Louis's helpful answer...

Setting the User Agent in PhantomJS

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
...
caps = DesiredCapabilities.PHANTOMJS
caps["phantomjs.page.settings.userAgent"] = "whatever you want"
driver = webdriver.PhantomJS(desired_capabilities=caps)

The only minor issue is that, unlike for Firefox and Chrome, this does not return your custom setting:

driver.execute_script("return navigator.userAgent")

So, if anyone figures out how to do that in PhantomJS, please edit my answer or add a comment below! Cheers.

The best node module for XML parsing

You can try xml2js. It's a simple XML to JavaScript object converter. It gets your XML converted to a JS object so that you can access its content with ease.

Here are some other options:

  1. libxmljs
  2. xml-stream
  3. xmldoc
  4. cheerio – implements a subset of core jQuery for XML (and HTML)

I have used xml2js and it has worked fine for me. The rest you might have to try out for yourself.

Could not open ServletContext resource [/WEB-INF/applicationContext.xml]

ContextLoaderListener has its own context which is shared by all servlets and filters. By default it will search /WEB-INF/applicationContext.xml

You can customize this by using

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/somewhere-else/root-context.xml</param-value>
</context-param>

on web.xml, or remove this listener if you don't need one.

Multiple definition of ... linker error

Don't define variables in headers. Put declarations in header and definitions in one of the .c files.

In config.h

extern const char *names[];

In some .c file:

const char *names[] =
    {
        "brian", "stefan", "steve"
    };

If you put a definition of a global variable in a header file, then this definition will go to every .c file that includes this header, and you will get multiple definition error because a varible may be declared multiple times but can be defined only once.

How to set image width to be 100% and height to be auto in react native?

"resizeMode" isn't style property. Should move to Image component's Props like below code.

const win = Dimensions.get('window');

const styles = StyleSheet.create({
    image: {
        flex: 1,
        alignSelf: 'stretch',
        width: win.width,
        height: win.height,
    }
});

...
    <Image 
       style={styles.image}
       resizeMode={'contain'}   /* <= changed  */
       source={require('../../../images/collection-imag2.png')} /> 
...

Image's height won't become automatically because Image component is required both width and height in style props. So you can calculate by using getSize() method for remote images like this answer and you can also calculate image ratio for static images like this answer.

There are a lot of useful open source libraries -

How to display loading message when an iFrame is loading?

I have followed the following approach

First, add sibling div

$('<div class="loading"></div>').insertBefore("#Iframe");

and then when the iframe completed loading

$("#Iframe").load(function(){
   $(this).siblings(".loading-fetching-content").remove(); 
  });

What is Activity.finish() method doing exactly?

In addition to @rommex answer above, I have also noticed that finish() does queue the destruction of the Activity and that it depends on Activity priority.

If I call finish() after onPause(), I see onStop(), and onDestroy() immediately called.

If I call finish() after onStop(), I don't see onDestroy() until 5 minutes later.

From my observation, it looks like finish is queued up and when I looked at the adb shell dumpsys activity activities it was set to finishing=true, but since it is no longer in the foreground, it wasn't prioritized for destruction.

In summary, onDestroy() is never guaranteed to be called, but even in the case it is called, it could be delayed.

Return the most recent record from ElasticSearch index

Get the Last ID using by date (with out time stamp)

Sample URL : http://localhost:9200/deal/dealsdetails/
Method : POST

Query :

{
  "fields": ["_id"],
  "sort": [{
      "created_date": {
        "order": "desc"
      }
    },
    {
      "_score": {
        "order": "desc"
      }
    }
  ],
  "size": 1
}

result:

{
  "took": 4,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 9,
    "max_score": null,
    "hits": [{
      "_index": "deal",
      "_type": "dealsdetails",
      "_id": "10",
      "_score": 1,
      "sort": [
        1478266145174,
        1
      ]
    }]
  }
}

Python: Converting from ISO-8859-1/latin1 to UTF-8

Try decoding it first, then encoding:

apple.decode('iso-8859-1').encode('utf8')

Git Bash won't run my python files?

This works great on win7

$ PATH=$PATH:/c/Python27/ $ python -V Python 2.7.12

Screenshot

Linq to Entities join vs groupjoin

According to eduLINQ:

The best way to get to grips with what GroupJoin does is to think of Join. There, the overall idea was that we looked through the "outer" input sequence, found all the matching items from the "inner" sequence (based on a key projection on each sequence) and then yielded pairs of matching elements. GroupJoin is similar, except that instead of yielding pairs of elements, it yields a single result for each "outer" item based on that item and the sequence of matching "inner" items.

The only difference is in return statement:

Join:

var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
{ 
    var key = outerKeySelector(outerElement); 
    foreach (var innerElement in lookup[key]) 
    { 
        yield return resultSelector(outerElement, innerElement); 
    } 
} 

GroupJoin:

var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
{ 
    var key = outerKeySelector(outerElement); 
    yield return resultSelector(outerElement, lookup[key]); 
} 

Read more here:

Register 32 bit COM DLL to 64 bit Windows 7

I was getting the error "The module may compatible with this version of windows" for both version of RegSvr32 (32 bit and 64 bit). I was trying to register a DLL that was built for XP (32 bit) in Server 2008 R2 (x64) and none of the Regsr32 resolutions worked for me. However, registering the assembly in the appropriate .Net worked perfect for me. C:\Windows\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe

How do I change the background color of the ActionBar of an ActionBarActivity using XML?

Its very simple for those who are using API 21 or greater Use this code below

for Dark ActionBar

<resources>
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="android:background">@color/colorDarkGrey</item>
</style>

for_LightActionBar

<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.ActionBar">
    <item name="android:background">@color/colorDarkGrey</item>
</style>

Windows equivalent of the 'tail' command

Here is a fast native head command that gives you the first 9 lines in DOS.

findstr /n "." myfile.txt | findstr "^.:"

The first 2 characters on each line will be the line number.

ASP.NET MVC Global Variables

Technically any static variable or Property on a class, anywhere in your project, will be a Global variable e.g.

public static class MyGlobalVariables
{
    public static string MyGlobalString { get; set; }
}

But as @SLaks says, they can 'potentially' be bad practice and dangerous, if not handled correctly. For instance, in that above example, you would have multiple requests (threads) trying to access the same Property, which could be an issue if it was a complex type or a collection, you would have to implement some form of locking.

How can I merge the columns from two tables into one output?

SELECT col1,
  col2
FROM
  (SELECT rownum X,col_table1 FROM table1) T1
INNER JOIN
  (SELECT rownum Y, col_table2 FROM table2) T2
ON T1.X=T2.Y;

Get the full URL in PHP

I've made this function to handle the URL:

 <?php
     function curPageURL()
     {
         $pageURL = 'http';
         if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
         $pageURL .= "://";
         if ($_SERVER["SERVER_PORT"] != "80") {
             $pageURL .=
             $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
         }
         else {
             $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
         }
         return $pageURL;
     }
 ?>

The value violated the integrity constraints for the column

Teradata table or view stores NULL as "?" and SQL considers it as a character or string. This is the main reason for the error "The value violated the integrity constraints for the column." when data is ported from Teradata source to SQL destination. Solution 1: Allow the destination table to hold NULL Solution 2: Convert the '?' character to be stored as some value in the destination table.

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

Simply just do in this way.

string yourFormat = DateTime.Now.ToString("yyyyMMdd");

Happy coding :)

Scanner only reads first word instead of line

The javadocs for Scanner answer your question

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

You might change the default whitespace pattern the Scanner is using by doing something like

Scanner s = new Scanner();
s.useDelimiter("\n");

How to watch for array changes?

Not sure if this covers absolutely everything, but I use something like this (especially when debugging) to detect when an array has an element added:

var array = [1,2,3,4];
array = new Proxy(array, {
    set: function(target, key, value) {
        if (Number.isInteger(Number(key)) || key === 'length') {
            debugger; //or other code
        }
        target[key] = value;
        return true;
    }
});

"VT-x is not available" when I start my Virtual machine

You might try reducing your base memory under settings to around 3175MB and reduce your cores to 1. That should work given that your BIOS is set for virtualization. Use the f12 key, security, virtualization to make sure that it is enabled. If it doesn't say VT-x that is ok, it should say VT-d or the like.

No connection could be made because the target machine actively refused it (PHP / WAMP)

Just Go to your Control-panel and start Apache & MySQL Services.

WAITING at sun.misc.Unsafe.park(Native Method)

From the stack trace it's clear that, the ThreadPoolExecutor > Worker thread started and it's waiting for the task to be available on the BlockingQueue(DelayedWorkQueue) to pick the task and execute.So this thread will be in WAIT status only as long as get a SIGNAL from the publisher thread.

How do I create sql query for searching partial matches?

This may work as well.

SELECT * 
FROM myTable
WHERE CHARINDEX('mall', name) > 0
  OR CHARINDEX('mall', description) > 0

How to use apply a custom drawable to RadioButton?

Give your radiobutton a custom style:

<style name="MyRadioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton">
    <item name="android:button">@drawable/custom_btn_radio</item>
</style>

custom_btn_radio.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_window_focused="false"
          android:drawable="@drawable/btn_radio_on" />
    <item android:state_checked="false" android:state_window_focused="false"
          android:drawable="@drawable/btn_radio_off" />

    <item android:state_checked="true" android:state_pressed="true"
          android:drawable="@drawable/btn_radio_on_pressed" />
    <item android:state_checked="false" android:state_pressed="true"
          android:drawable="@drawable/btn_radio_off_pressed" />

    <item android:state_checked="true" android:state_focused="true"
          android:drawable="@drawable/btn_radio_on_selected" />
    <item android:state_checked="false" android:state_focused="true"
          android:drawable="@drawable/btn_radio_off_selected" />

    <item android:state_checked="false" android:drawable="@drawable/btn_radio_off" />
    <item android:state_checked="true" android:drawable="@drawable/btn_radio_on" />
</selector>

Replace the drawables with your own.

How to install Python package from GitHub?

You need to use the proper git URL:

pip install git+https://github.com/jkbr/httpie.git#egg=httpie

Also see the VCS Support section of the pip documentation.

Don’t forget to include the egg=<projectname> part to explicitly name the project; this way pip can track metadata for it without having to have run the setup.py script.

In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?

Boundary Control Entity pattern have two versions:
- old structural, described at 127 (entity as an data model elements, control as an functions, boundary as an application interface)
- new object pattern


As an object pattern:
- Boundary is an interface for "other world"
- Control in an any internal logic (like a service in DDD pattern)
- Entity is an an persistence serwis for objects (like a repository in DDD pattern).
All classes have operations (see Fowler anemic domain model anti-pattern)
All of them is an Model component in MVC pattern. The rules:
- Only Boundary provide services for the "other world"
- Boundary can call only to Controll
- Control can call anybody
- Entity can't call anybody (!), only be called.

jz

Convert a Unicode string to a string in Python (containing extra symbols)

Here is an example code

import unicodedata    
raw_text = u"here $%6757 dfgdfg"
convert_text = unicodedata.normalize('NFKD', raw_text).encode('ascii','ignore')

What is the inclusive range of float and double in Java?

Of course you can use floats or doubles for "critical" things ... Many applications do nothing but crunch numbers using these datatypes.

You might have misunderstood some of the various caveats regarding floating-point numbers, such as the recommendation to never compare for exact equality, and so on.

Format an Integer using Java String Format

String.format("%03d", 1)  // => "001"
//              ¦¦¦   +-- print the number one
//              ¦¦+------ ... as a decimal integer
//              ¦+------- ... minimum of 3 characters wide
//              +-------- ... pad with zeroes instead of spaces

See java.util.Formatter for more information.

Unlocking tables if thread is lost

With Sequel Pro:

Restarting the app unlocked my tables. It resets the session connection.

NOTE: I was doing this for a site on my local machine.

Replace CRLF using powershell

You have not specified the version, I'm assuming you are using Powershell v3.

Try this:

$path = "C:\Users\abc\Desktop\File\abc.txt"
(Get-Content $path -Raw).Replace("`r`n","`n") | Set-Content $path -Force

Editor's note: As mike z points out in the comments, Set-Content appends a trailing CRLF, which is undesired. Verify with: 'hi' > t.txt; (Get-Content -Raw t.txt).Replace("`r`n","`n") | Set-Content t.txt; (Get-Content -Raw t.txt).EndsWith("`r`n"), which yields $True.

Note this loads the whole file in memory, so you might want a different solution if you want to process huge files.

UPDATE

This might work for v2 (sorry nowhere to test):

$in = "C:\Users\abc\Desktop\File\abc.txt"
$out = "C:\Users\abc\Desktop\File\abc-out.txt"
(Get-Content $in) -join "`n" > $out

Editor's note: Note that this solution (now) writes to a different file and is therefore not equivalent to the (still flawed) v3 solution. (A different file is targeted to avoid the pitfall Ansgar Wiechers points out in the comments: using > truncates the target file before execution begins). More importantly, though: this solution too appends a trailing CRLF, which may be undesired. Verify with 'hi' > t.txt; (Get-Content t.txt) -join "`n" > t.NEW.txt; [io.file]::ReadAllText((Convert-Path t.NEW.txt)).endswith("`r`n"), which yields $True.

Same reservation about being loaded to memory though.

What are FTL files

An ftl file could just have a series of html tags just as a JSP page or it can have freemarker template coding for representing the objects passed on from a controller java file.
But, its actual ability is to combine the contents of a java class and view/client side stuff(html/ JQuery/ javascript etc). It is quite similar to velocity. You could map a method or object of a class to a freemarker (.ftl) page and use it as if it is a variable or a functionality created in the very page.

How to enter a multi-line command

  1. Use a semi-colon ; to separate command
  2. Replace double backslash \\ on any backslashes \.
  3. Use "' for passing safe address to switch command like "'PATH'".

This ps1 command install locale pfx certificate.

powershell -Command "$pfxPassword = ConvertTo-SecureString -String "12345678" -Force -AsPlainText ; Import-PfxCertificate -FilePath "'C:\\Program Files\\VpnManagement\\resources\\assets\\cert\\localhost.pfx'" Cert:\\LocalMachine\\My -Password $pfxPassword ; Import-PfxCertificate -FilePath "'C:\\Program Files\\VpnManagement\\resources\\assets\\cert\\localhost.pfx'" Cert:\\LocalMachine\\Root -Password $pfxPassword"

Button that refreshes the page on click

Use this its work fine for me to reload the same page:

<button onClick="window.location.reload();">

Append key/value pair to hash with << in Ruby

Since hashes aren't inherently ordered, there isn't a notion of appending. Ruby hashes since 1.9 maintain insertion order, however. Here are the ways to add new key/value pairs.

The simplest solution is

h[:key] = "bar"

If you want a method, use store:

h.store(:key, "bar")

If you really, really want to use a "shovel" operator (<<), it is actually appending to the value of the hash as an array, and you must specify the key:

h[:key] << "bar"

The above only works when the key exists. To append a new key, you have to initialize the hash with a default value, which you can do like this:

h = Hash.new {|h, k| h[k] = ''}
h[:key] << "bar"

You may be tempted to monkey patch Hash to include a shovel operator that works in the way you've written:

class Hash
  def <<(k,v)
    self.store(k,v)
  end
end

However, this doesn't inherit the "syntactic sugar" applied to the shovel operator in other contexts:

h << :key, "bar" #doesn't work
h.<< :key, "bar" #works

ng-change get new value and original value

With an angular {{expression}} you can add the old user or user.id value to the ng-change attribute as a literal string:

<select ng-change="updateValue(user, '{{user.id}}')" 
        ng-model="user.id" ng-options="user.id as user.name for user in users">
</select>

On ngChange, the 1st argument to updateValue will be the new user value, the 2nd argument will be the literal that was formed when the select-tag was last updated by angular, with the old user.id value.

How to switch to another domain and get-aduser

get-aduser -Server "servername" -Identity %username% -Properties *

get-aduser -Server "testdomain.test.net" -Identity testuser -Properties *

These work when you have the username. Also less to type than using the -filter property.

EDIT: Formatting.

How can I create a dynamic button click event on a dynamic button?

Button button = new Button();
button.Click += (s,e) => { your code; };
//button.Click += new EventHandler(button_Click);
container.Controls.Add(button);

//protected void button_Click (object sender, EventArgs e) { }

How to load property file from classpath?

final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("foo.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}

How can I select all rows with sqlalchemy?

You can easily import your model and run this:

from models import User

# User is the name of table that has a column name
users = User.query.all()

for user in users:
    print user.name

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

Would not creating a UserJsonResponse class and populating with the wanted fields be a cleaner solution?

Returning directly a JSON seems a great solution when you want to give all the model back. Otherwise it just gets messy.

In the future, for example you might want to have a JSON field that does not match any Model field and then you're in a bigger trouble.

Select all text inside EditText when it gets focus

You can try in your main.xml file:

android:selectAllOnFocus="true"

Or, in Java, use

editText.setSelectAllOnFocus(true);

Do copyright dates need to be updated?

There is no reason at all for an individual to update the copyright year, because in the U.S. and Europe the life of copyright is the life of the author plus 70 years (50 years in some other countries like Canada and Australia). Extending the date does not extend the copyright. This also applies when a page has multiple contributors none of which are corporations.

As for corporations, Google doesn't update their copyright dates because they don't care whether some page they started in 1999 and updated this year falls into the public domain in 2094 or 2109. And if they don't, why should you? (As a Googler, now an ex-Googler, I was told this was the policy for internal source code as well.)

Override body style for content in an iframe

I have a blog and I had a lot of trouble finding out how to resize my embedded gist. Post manager only allows you to write text, place images and embed HTML code. Blog layout is responsive itself. It's built with Wix. However, embedded HTML is not. I read a lot about how it's impossible to resize components inside body of generated iFrames. So, here is my suggestion:

If you only have one component inside your iFrame, i.e. your gist, you can resize only the gist. Forget about the iFrame.

I had problems with viewport, specific layouts to different user agents and this is what solved my problem:

<script language="javascript" type="text/javascript" src="https://gist.github.com/roliveiravictor/447f994a82238247f83919e75e391c6f.js"></script>

<script language="javascript" type="text/javascript">

function windowSize() {
  let gist = document.querySelector('#gist92442763');

  let isMobile = {
    Android: function() {
        return /Android/i.test(navigator.userAgent)
    },
    BlackBerry: function() {
        return /BlackBerry/i.test(navigator.userAgent)
    },
    iOS: function() {
        return /iPhone|iPod/i.test(navigator.userAgent)
    },
    Opera: function() {
        return /Opera Mini/i.test(navigator.userAgent)
    },
    Windows: function() {
        return /IEMobile/i.test(navigator.userAgent) || /WPDesktop/i.test(navigator.userAgent)
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};

  if(isMobile.any()) {
    gist.style.width = "36%";
    gist.style.WebkitOverflowScrolling = "touch"
    gist.style.position = "absolute"
  } else {
    gist.style.width = "auto !important";
  }
}

windowSize();

window.addEventListener('onresize', function() {
    windowSize();
});

</script>

<style type="text/css">

.gist-data {
  max-height: 300px;
}

.gist-meta {
  display: none;
}

</style>

The logic is to set gist (or your component) css based on user agent. Make sure to identify your component first, before applying to query selector. Feel free to take a look how responsiveness is working.

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

Formatting your data that may be the problem. Try either of these:

data: '{ "things":' + JSON.stringify(things) + '}',

Or (from How can I post an array of string to ASP.NET MVC Controller without a form?)

var postData = { things: things };
...
data = postData

ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

"HTTP 415 Unsupported Media Type response" stems from Content-Type in header of your request. for example in javascript by axios:

Axios({
            method: 'post',
            headers: { 'Content-Type': 'application/json'},
            url: '/',
            data: data,  // an object u want to send
          }).then(function (response) {
            console.log(response);
          });

What is use of c_str function In c++

Oh must add my own pick here, you will use this when you encode/decode some string obj you transfer between two programs.

Lets say you use base64encode some array in python, and then you want to decode that into c++. Once you have the string you decode from base64decode in c++. In order to get it back to array of float, all you need to do here is

float arr[1024];
memcpy(arr, ur_string.c_str(), sizeof(float) * 1024);

This is pretty common use I suppose.

Compiling with g++ using multiple cores

People have mentioned make but bjam also supports a similar concept. Using bjam -jx instructs bjam to build up to x concurrent commands.

We use the same build scripts on Windows and Linux and using this option halves our build times on both platforms. Nice.

Empty brackets '[]' appearing when using .where

You can use the lower function:

Guide.where("lower(title)='attack'") 

As a comment: Work on your question. The title isn't terribly informative, and you drop a big chunk of code at the end that is irrelevant to your question.

Git push requires username and password

What worked for me was to edit .git/config and use

[remote "origin"]
        url = https://<login>:<password>@gitlab.com(...).git

It goes without saying that this is an insecure way of storing your password but there are environments/cases where this may not be a problem.

Eclipse and Windows newlines

You could give it a try. The problem is that Windows inserts a carriage return as well as a line feed when given a new line. Unix-systems just insert a line feed. So the extra carriage return character could be the reason why your eclipse messes up with the newlines.

Grab one or two files from your project and convert them. You could use Notepad++ to do so. Just open the file, go to Format->Convert to Unix (when you are using windows).

In Linux just try this on a command line:

sed 's/$'"/`echo \\\r`/" yourfile.java > output.java

500 internal server error at GetResponse()

Finally I get rid of internal server error message with the following code. Not sure if there is another way to achieve it.


string uri = "Path.asmx";
string soap = "soap xml string";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Headers.Add("SOAPAction", "\"http://xxxxxx"");
request.ContentType = "text/xml;charset=\"utf-8\"";
request.Accept = "text/xml";
request.Method = "POST";

using (Stream stm = request.GetRequestStream())
{
    using (StreamWriter stmw = new StreamWriter(stm))
    {
        stmw.Write(soap);
    }
}

using (WebResponse webResponse = request.GetResponse())
{
}

How do the major C# DI/IoC frameworks compare?

I came across another performance comparison(latest update 10 April 2014). It compares the following:

Here is a quick summary from the post:

Conclusion

Ninject is definitely the slowest container.

MEF, LinFu and Spring.NET are faster than Ninject, but still pretty slow. AutoFac, Catel and Windsor come next, followed by StructureMap, Unity and LightCore. A disadvantage of Spring.NET is, that can only be configured with XML.

SimpleInjector, Hiro, Funq, Munq and Dynamo offer the best performance, they are extremely fast. Give them a try!

Especially Simple Injector seems to be a good choice. It's very fast, has a good documentation and also supports advanced scenarios like interception and generic decorators.

You can also try using the Common Service Selector Library and hopefully try multiple options and see what works best for you.

Some informtion about Common Service Selector Library from the site:

The library provides an abstraction over IoC containers and service locators. Using the library allows an application to indirectly access the capabilities without relying on hard references. The hope is that using this library, third-party applications and frameworks can begin to leverage IoC/Service Location without tying themselves down to a specific implementation.

Update

13.09.2011: Funq and Munq were added to the list of contestants. The charts were also updated, and Spring.NET was removed due to it's poor performance.

04.11.2011: "added Simple Injector, the performance is the best of all contestants".

Curl error: Operation timed out

Some time this error in Joomla appear because some thing incorrect with SESSION or coockie. That may because incorrect HTTPd server setting or because some before CURL or Server http requests

so PHP code like:

  curl_setopt($ch, CURLOPT_URL, $url_page);
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30); 
  curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
  curl_setopt($ch, CURLOPT_REFERER, $url_page);
  curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
  curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
  curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
  curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());

  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);

will need replace to PHP code

  curl_setopt($ch, CURLOPT_URL, $url_page);
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30); 
//curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
  curl_setopt($ch, CURLOPT_REFERER, $url_page);
  curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
//curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // !!!!!!!!!!!!!
  //if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);

May be some body reply how this options connected with "Curl error: Operation timed out after .."

List of foreign keys and the tables they reference in Oracle DB

I used below code and it served my purpose-

SELECT fk.owner, fk.table_name, col.column_name
FROM dba_constraints pk, dba_constraints fk, dba_cons_columns col
WHERE pk.constraint_name = fk.r_constraint_name
AND fk.constraint_name = col.constraint_name
AND pk.owner = col.owner
AND pk.owner = fk.owner
AND fk.constraint_type = 'R'   
AND pk.owner = sys_context('USERENV', 'CURRENT_SCHEMA') 
AND pk.table_name = :my_table
AND pk.constraint_type = 'P';

List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?

Few lines solution without redundant pairs of variables:

corr_matrix = df.corr().abs()

#the matrix is symmetric so we need to extract upper triangle matrix without diagonal (k = 1)

sol = (corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))
                  .stack()
                  .sort_values(ascending=False))

#first element of sol series is the pair with the biggest correlation

Then you can iterate through names of variables pairs (which are pandas.Series multi-indexes) and theirs values like this:

for index, value in sol.items():
  # do some staff

How to convert text column to datetime in SQL

In SQL Server , cast text as datetime

select cast('5/21/2013 9:45:48' as datetime)

'uint32_t' identifier not found error

I have the same error and it fixed it including in the file the following

#include <stdint.h>

at the beginning of your file.

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

There are a few things you need to do to create a multiple file upload, its pretty basic actually. You don't need to use Java, Ajax, Flash. Just build a normal file upload form starting off with:

<form enctype="multipart/form-data" action="post_upload.php" method="POST">

Then the key to success;

<input type="file" name="file[]" multiple />

do NOT forget those brackets! In the post_upload.php try the following:

<?php print_r($_FILES['file']['tmp_name']); ?>

Notice you get an array with tmp_name data, which will mean you can access each file with an third pair of brackets with the file 'number' example:

$_FILES['file']['tmp_name'][0]

You can use php count() to count the number of files that was selected. Goodluck widdit!

SQL join: selecting the last records in a one-to-many relationship

Please try this,

SELECT 
c.Id,
c.name,
(SELECT pi.price FROM purchase pi WHERE pi.Id = MAX(p.Id)) AS [LastPurchasePrice]
FROM customer c INNER JOIN purchase p 
ON c.Id = p.customerId 
GROUP BY c.Id,c.name;

ES6 Map in Typescript

How do I declare an ES6 Map type in typescript?

You need to target --module es6. This is misfortunate and you can raise your concern here : https://github.com/Microsoft/TypeScript/issues/2953#issuecomment-98514111

How to increment an iterator by 2?

You could use the 'assignment by addition' operator

iter += 2;

Python/Django: log to console under runserver, log to file under Apache

Here's a Django logging-based solution. It uses the DEBUG setting rather than actually checking whether or not you're running the development server, but if you find a better way to check for that it should be easy to adapt.

LOGGING = {
    'version': 1,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/path/to/your/file.log',
            'formatter': 'simple'
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    }
}

if DEBUG:
    # make all loggers use the console.
    for logger in LOGGING['loggers']:
        LOGGING['loggers'][logger]['handlers'] = ['console']

see https://docs.djangoproject.com/en/dev/topics/logging/ for details.

Why can't C# interfaces contain fields?

Eric Lippert nailed it, I'll use a different way to say what he said. All of the members of an interface are virtual and they all need to be overridden by a class that inherits the interface. You don't explicitly write the virtual keyword in the interface declaration, nor use the override keyword in the class, they are implied.

The virtual keyword is implemented in .NET with methods and a so-called v-table, an array of method pointers. The override keyword fills the v-table slot with a different method pointer, overwriting the one produced by the base class. Properties, events and indexers are implemented as methods under the hood. But fields are not. Interfaces can therefore not contain fields.

Change the spacing of tick marks on the axis of a plot?

There are at least two ways for achieving this in base graph (my examples are for the x-axis, but work the same for the y-axis):

  1. Use par(xaxp = c(x1, x2, n)) or plot(..., xaxp = c(x1, x2, n)) to define the position (x1 & x2) of the extreme tick marks and the number of intervals between the tick marks (n). Accordingly, n+1 is the number of tick marks drawn. (This works only if you use no logarithmic scale, for the behavior with logarithmic scales see ?par.)

  2. You can suppress the drawing of the axis altogether and add the tick marks later with axis().
    To suppress the drawing of the axis use plot(... , xaxt = "n").
    Then call axis() with side, at, and labels: axis(side = 1, at = v1, labels = v2). With side referring to the side of the axis (1 = x-axis, 2 = y-axis), v1 being a vector containing the position of the ticks (e.g., c(1, 3, 5) if your axis ranges from 0 to 6 and you want three marks), and v2 a vector containing the labels for the specified tick marks (must be of same length as v1, e.g., c("group a", "group b", "group c")). See ?axis and my updated answer to a post on stats.stackexchange for an example of this method.

How to change the style of alert box?

One option is to use altertify, this gives a nice looking alert box.

Simply include the required libraries from here, and use the following piece of code to display the alert box.

alertify.confirm("This is a confirm dialog.",
  function(){
    alertify.success('Ok');
  },
  function(){
    alertify.error('Cancel');
  });

The output will look like this. To see it in action here is the demo

enter image description here

Why doesn't CSS ellipsis work in table cell?

As said before, you can use td { display: block; } but this defeats the purpose of using a table.

You can use table { table-layout: fixed; } but maybe you want it to behave differently for some colums.

So the best way to achieve what you want would be to wrap your text in a <div> and apply your CSS to the <div> (not to the <td>) like this :

td {
  border: 1px solid black;
}
td > div {
  width: 50px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

Cause of a process being a deadlock victim

The answers here are worth a try, but you should also review your code. Specifically have a read of Polyfun's answer here: How to get rid of deadlock in a SQL Server 2005 and C# application?

It explains the concurrency issue, and how the usage of "with (updlock)" in your queries might correct your deadlock situation - depending really on exactly what your code is doing. If your code does follow this pattern, this is likely a better fix to make, before resorting to dirty reads, etc.

How to git reset --hard a subdirectory?

Ajedi32's answer is what I was looking for but for some commits I ran into this error:

error: cannot apply binary patch to 'path/to/directory' without full index line

May be because some files of the directory are binary files. Adding '--binary' option to the git diff command fixed it:

git diff --binary --cached commit -- path/to/directory | git apply -R --index

TERM environment variable not set

You can see if it's really not set. Run the command set | grep TERM.

If not, you can set it like that: export TERM=xterm

PHP-FPM and Nginx: 502 Bad Gateway

I'm very late to this game, but my problem started when I upgraded php on my server. I was able to just remove the .socket file and restart my services. Then, everything worked. Not sure why it made a difference, since the file is size 0 and the ownership and permissions are the same, but it worked.

DNS caching in linux

On Linux (and probably most Unix), there is no OS-level DNS caching unless nscd is installed and running. Even then, the DNS caching feature of nscd is disabled by default at least in Debian because it's broken. The practical upshot is that your linux system very very probably does not do any OS-level DNS caching.

You could implement your own cache in your application (like they did for Squid, according to diegows's comment), but I would recommend against it. It's a lot of work, it's easy to get it wrong (nscd got it wrong!!!), it likely won't be as easily tunable as a dedicated DNS cache, and it duplicates functionality that already exists outside your application.

If an end user using your software needs to have DNS caching because the DNS query load is large enough to be a problem or the RTT to the external DNS server is long enough to be a problem, they can install a caching DNS server such as Unbound on the same machine as your application, configured to cache responses and forward misses to the regular DNS resolvers.

How to remove specific value from array using jQuery

A working JSFIDDLE

You can do something like this:

var y = [1, 2, 2, 3, 2]
var removeItem = 2;

y = jQuery.grep(y, function(value) {
  return value != removeItem;
});

Result:

[1, 3]

http://snipplr.com/view/14381/remove-item-from-array-with-jquery/

Can't connect to docker from docker-compose

Anyone checked log ?

In my case error message in /var/log/upstart/docker.log was:

Listening for HTTP on unix (/var/run/docker.sock) 
[graphdriver] using prior storage driver "aufs" 
Running modprobe bridge nf_nat failed with message: , error: exit status 1 
Error starting daemon: Error initializing network controller: Error creating default "bridge" network: can't find an address range for interface "docker0" 

Worth to mentioned I had vpn turned on, so: $ sudo service openvpn stop $ sudo service docker restart $ docker-compose up|start $ sudo service openvpn start was the solution.

How to send HTTP request in java?

From Oracle's java tutorial

import java.net.*;
import java.io.*;

public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL yahoo = new URL("http://www.yahoo.com/");
        URLConnection yc = yahoo.openConnection();
        BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                yc.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();
    }
}

How to use jQuery to show/hide divs based on radio button selection?

The simple jquery source for the same -

$("input:radio[name='group1']").click(function() {      
    $('.desc').hide();
    $('#' + $("input:radio[name='group1']:checked").val()).show();
});

In order to make it little more appropriate just add checked to first option --

<div><label><input type="radio" name="group1" value="opt1" checked>opt1</label></div>  

remove .desc class from styling and modify divs like --

<div id="opt1" class="desc">lorem ipsum dolor</div>
<div id="opt2" class="desc" style="display: none;">consectetur adipisicing</div>
<div id="opt3" class="desc" style="display: none;">sed do eiusmod tempor</div>

it will really look good any-ways.

req.query and req.param in ExpressJS

I would suggest using following

req.param('<param_name>')

req.param("") works as following

Lookup is performed in the following order:

req.params
req.body
req.query

Direct access to req.body, req.params, and req.query should be favoured for clarity - unless you truly accept input from each object.

Ref:http://expressjs.com/4x/api.html#req.param

Python, creating objects

Create a class and give it an __init__ method:

class Student:
    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major

    def is_old(self):
        return self.age > 100

Now, you can initialize an instance of the Student class:

>>> s = Student('John', 88, None)
>>> s.name
    'John'
>>> s.age
    88

Although I'm not sure why you need a make_student student function if it does the same thing as Student.__init__.

Missing Authentication Token while accessing API Gateway?

I had the same problem which I solved the following way:

GET Method test

https://54wtstq8d2.execute-api.ap-southeast-2.amazonaws.com/dev/echo/hello
Authorization tab -> 
•   select type(AWS signature)
•   Add AccessKey and SecretKey

How do I return multiple values from a function in C?

Two different approaches:

  1. Pass in your return values by pointer, and modify them inside the function. You declare your function as void, but it's returning via the values passed in as pointers.
  2. Define a struct that aggregates your return values.

I think that #1 is a little more obvious about what's going on, although it can get tedious if you have too many return values. In that case, option #2 works fairly well, although there's some mental overhead involved in making specialized structs for this purpose.

Gradient of n colors ranging from color 1 and color 2

The above answer is useful but in graphs, it is difficult to distinguish between darker gradients of black. One alternative I found is to use gradients of gray colors as follows

palette(gray.colors(10, 0.9, 0.4))
plot(rep(1,10),col=1:10,pch=19,cex=3))

More info on gray scale here.

Added

When I used the code above for different colours like blue and black, the gradients were not that clear. heat.colors() seems more useful.

This document has more detailed information and options. pdf

How to convert time milliseconds to hours, min, sec format in JavaScript?

Here is my solution

let h,m,s;
h = Math.floor(timeInMiliseconds/1000/60/60);
m = Math.floor((timeInMiliseconds/1000/60/60 - h)*60);
s = Math.floor(((timeInMiliseconds/1000/60/60 - h)*60 - m)*60);

// to get time format 00:00:00

s < 10 ? s = `0${s}`: s = `${s}`
m < 10 ? m = `0${m}`: m = `${m}`
h < 10 ? h = `0${h}`: h = `${h}`


console.log(`${s}:${m}:${h}`);

Display unescaped HTML in Vue.js

Vue by default ships with the v-html directive to show it, you bind it onto the element itself rather than using the normal moustache binding for string variables.

So for your specific example you would need:

<div id="logapp">    
    <table>
        <tbody>
            <tr v-repeat="logs">
                <td v-html="fail"></td>
                <td v-html="type"></td>
                <td v-html="description"></td>
                <td v-html="stamp"></td>
                <td v-html="id"></td>
            </tr>
        </tbody>
    </table>
</div>

How can I run MongoDB as a Windows service?

I just had to restart the MongoDB (v4.4) service after editing the config file on a Windows box. Here's what I did:

  1. Press Win+R to open the Run panel
  2. Type in "services.msc" and press Enter
  3. Search for "MongoDB" - you can press "m" to jump to it.
  4. Right click - select "Restart"

Thats it!

How to compare two tables column by column in oracle

Try to use 3rd party tool, such as SQL Data Examiner which compares Oracle databases and shows you differences.

pgadmin4 : postgresql application server could not be contacted.

I had the same issue on the macosx and I renamed .pgadmin (in /users/costa) to .pgadminx and I was able to start pgAdmin4.

How to check for null in Twig?

How to set default values in twig: http://twig.sensiolabs.org/doc/filters/default.html

{{ my_var | default("my_var doesn't exist") }}

Or if you don't want it to display when null:

{{ my_var | default("") }}

Modifying the "Path to executable" of a windows service

There is also this approach seen on SuperUser which uses the sc command line instead of modifying the registry:

sc config <service name> binPath= <binary path>

Note: the space after binPath= is important. You can also query the current configuration using:

sc qc <service name>

This displays output similar to:

[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: ServiceName

    TYPE               : 10  WIN32_OWN_PROCESS
    START_TYPE         : 2   AUTO_START
    ERROR_CONTROL      : 1   NORMAL
    BINARY_PATH_NAME   : C:\Services\ServiceName
    LOAD_ORDER_GROUP   :
    TAG                : 0
    DISPLAY_NAME       : <Display name>
    DEPENDENCIES       :
    SERVICE_START_NAME : user-name@domain-name

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

It's interesting things with IDE (IntelliJ in this case):

  • if you leave default, i.e. don't declare spring-boot-starter-tomcat as provided, a spring-boot-maven-plugin (SBMP) put tomcat's jars to your war -> and you'll probably get errors deploying this war to container (there could be a versions conflict)

  • else you'll get classpath with no compile dependency on tomcat-embed (SBMP will build executable war/jar with provided deps included anyway)

    • intelliJ honestly doesn't see provided deps at runtime (they are not in classpath) when you run its Spring Boot run configuration.
    • and with no tomcat-embed you can't run Spring-Boot with embedded servlet container.

There is some tricky workaround: put Tomcat's jars to classpath of your idea-module via UI: File->Project Structure->(Libraries or Modules/Dependencies tab) .

  • tomcat-embed-core
  • tomcat-embed-el
  • tomcat-embed-websocket
  • tomcat-embed-logging-juli

Better solution for maven case

Instead of adding module dependencies in Idea, it is better to declare maven profile with compile scope of spring-boot-starter-tomcat library.

<profiles>
    <profile>
        <id>embed-tomcat</id>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>compile</scope>
            </dependency>
        </dependencies>
    </profile>
</profiles>

while spring-boot-starter-tomcat was declared provided in <dependencies/>, making this profile active in IDE or CLI (mvn -Pembed-tomcat ...) allow you to launch build with embedded tomcat.

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

Empty refers to a variable being at its default value. So if you check if a cell with a value of 0 = Empty then it would return true.

IsEmpty refers to no value being initialized.

In a nutshell, if you want to see if a cell is empty (as in nothing exists in its value) then use IsEmpty. If you want to see if something is currently in its default value then use Empty.

When should I use a trailing slash in my URL?

The trailing slash does not matter for your root domain or subdomain. Google sees the two as equivalent.

But trailing slashes do matter for everything else because Google sees the two versions (one with a trailing slash and one without) as being different URLs. Conventionally, a trailing slash (/) at the end of a URL meant that the URL was a folder or directory.

A URL without a trailing slash at the end used to mean that the URL was a file.

Read more

Google recommendation

How can I combine two commits into one commit?

Lazy simple version for forgetfuls like me:

git rebase -i HEAD~3 or however many commits instead of 3.

Turn this

pick YourCommitMessageWhatever
pick YouGetThePoint
pick IdkManItsACommitMessage

into this

pick YourCommitMessageWhatever
s YouGetThePoint
s IdkManItsACommitMessage

and do some action where you hit esc then enter to save the changes. [1]

When the next screen comes up, get rid of those garbage # lines [2] and create a new commit message or something, and do the same escape enter action. [1]

Wowee, you have fewer commits. Or you just broke everything.


[1] - or whatever works with your git configuration. This is just a sequence that's efficient given my setup.

[2] - you'll see some stuff like # this is your n'th commit a few times, with your original commits right below these message. You want to remove these lines, and create a commit message to reflect the intentions of the n commits that you're combining into 1.

Download file using libcurl in C/C++

Just for those interested you can avoid writing custom function by passing NULL as last parameter (if you do not intend to do extra processing of returned data).
In this case default internal function is used.

Details
http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTWRITEDATA

Example

#include <stdio.h>
#include <curl/curl.h>

int main(void)
{
    CURL *curl;
    FILE *fp;
    CURLcode res;
    char *url = "http://stackoverflow.com";
    char outfilename[FILENAME_MAX] = "page.html";
    curl = curl_easy_init();                                                                                                                                                                                                                                                           
    if (curl)
    {   
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);
    }   
    return 0;
}

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

Problem solved.

Just drop down status bar, touch Choose input method, then change to another input method, type the password again. And everything is OK.

So weird...

Solution from a Chinese BBS. Thanks for the answer's author and all above who try to provide a solution, thanks!

How to have an auto incrementing version number (Visual Studio)?

You could use the T4 templating mechanism in Visual Studio to generate the required source code from a simple text file :

I wanted to configure version information generation for some .NET projects. It’s been a long time since I investigated available options, so I searched around hoping to find some simple way of doing this. What I’ve found didn’t look very encouraging: people write Visual Studio add-ins and custom MsBuild tasks just to obtain one integer number (okay, maybe two). This felt overkill for a small personal project.

The inspiration came from one of the StackOverflow discussions where somebody suggested that T4 templates could do the job. And of course they can. The solution requires a minimal effort and no Visual Studio or build process customization. Here what should be done:

  1. Create a file with extension ".tt" and place there T4 template that will generate AssemblyVersion and AssemblyFileVersion attributes:
<#@ template language="C#" #>
// 
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
// 

using System.Reflection;

[assembly: AssemblyVersion("1.0.1.<#= this.RevisionNumber #>")]
[assembly: AssemblyFileVersion("1.0.1.<#= this.RevisionNumber #>")]
<#+
    int RevisionNumber = (int)(DateTime.UtcNow - new DateTime(2010,1,1)).TotalDays;
#>

You will have to decide about version number generation algorithm. For me it was sufficient to auto-generate a revision number that is set to the number of days since January 1st, 2010. As you can see, the version generation rule is written in plain C#, so you can easily adjust it to your needs.

  1. The file above should be placed in one of the projects. I created a new project with just this single file to make version management technique clear. When I build this project (actually I don’t even need to build it: saving the file is enough to trigger a Visual Studio action), the following C# is generated:
// 
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
// 

using System.Reflection;

[assembly: AssemblyVersion("1.0.1.113")]
[assembly: AssemblyFileVersion("1.0.1.113")]

Yes, today it’s 113 days since January 1st, 2010. Tomorrow the revision number will change.

  1. Next step is to remove AssemblyVersion and AssemblyFileVersion attributes from AssemblyInfo.cs files in all projects that should share the same auto-generated version information. Instead choose “Add existing item” for each projects, navigate to the folder with T4 template file, select corresponding “.cs” file and add it as a link. That will do!

What I like about this approach is that it is lightweight (no custom MsBuild tasks), and auto-generated version information is not added to source control. And of course using C# for version generation algorithm opens for algorithms of any complexity.

Best way to reset an Oracle sequence to the next value in an existing column?

You can temporarily increase the cache size and do one dummy select and then reset the cache size back to 1. So for example

ALTER SEQUENCE mysequence INCREMENT BY 100;

select mysequence.nextval from dual;

ALTER SEQUENCE mysequence INCREMENT BY 1;

Git push rejected "non-fast-forward"

Well I used the advice here and it screwed me as it merged my local code directly to master. .... so take it all with a grain of salt. My coworker said the following helped resolve the issue, needed to repoint my branch.

 git branch --set-upstream-to=origin/feature/my-current-branch feature/my-current-branch

What is the syntax meaning of RAISERROR()

The severity level 16 in your example code is typically used for user-defined (user-detected) errors. The SQL Server DBMS itself emits severity levels (and error messages) for problems it detects, both more severe (higher numbers) and less so (lower numbers).

The state should be an integer between 0 and 255 (negative values will give an error), but the choice is basically the programmer's. It is useful to put different state values if the same error message for user-defined error will be raised in different locations, e.g. if the debugging/troubleshooting of problems will be assisted by having an extra indication of where the error occurred.

How to find out the MySQL root password

one thing that tripped me up on a new install of mySQL and wonder why I couldn't get the default password to work and why even the reset methods where not working. well turns out that on Ubuntu 18 the most recent version of mysql server does not use password auth at all for the root user by default. So this means it doesn't matter what you set it to, it won't let you use it. it's expecting you to login from a privileged socket. so

mysql -u root -p

will not work at all, even if you are using the correct password!!! it will deny access no matter what you put in.

Instead you need to use

sudo mysql

that will work with out any password. then once you in you need type in

 ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'Password you want to use';

then log out and now the bloody thing will finally accept your password

Eliminating NAs from a ggplot

Not sure if you have solved the problem. For this issue, you can use the "filter" function in the dplyr package. The idea is to filter the observations/rows whose values of the variable of your interest is not NA. Next, you make the graph with these filtered observations. You can find my codes below, and note that all the name of the data frame and variable is copied from the prompt of your question. Also, I assume you know the pipe operators.

library(tidyverse) 

MyDate %>%
   filter(!is.na(the_variable)) %>%
     ggplot(aes(x= the_variable, fill=the_variable)) + 
        geom_bar(stat="bin") 

You should be able to remove the annoying NAs on your plot. Hope this works :)

Jenkins Slave port number for firewall

A slave isn't a server, it's a client type application. Network clients (almost) never use a specific port. Instead, they ask the OS for a random free port. This works much better since you usually run clients on many machines where the current configuration isn't known in advance. This prevents thousands of "client wouldn't start because port is already in use" bug reports every day.

You need to tell the security department that the slave isn't a server but a client which connects to the server and you absolutely need to have a rule which says client:ANY -> server:FIXED. The client port number should be >= 1024 (ports 1 to 1023 need special permissions) but I'm not sure if you actually gain anything by adding a rule for this - if an attacker can open privileged ports, they basically already own the machine.

If they argue, then ask them why they don't require the same rule for all the web browsers which people use in your company.

How do I replace a character at a particular index in JavaScript?

This works similar to Array.splice:

String.prototype.splice = function (i, j, str) {
    return this.substr(0, i) + str + this.substr(j, this.length);
};

Android ADB device offline, can't issue commands

I had the same problem, while trying to install CyanogenMod on Galaxy S III from Ubuntu. In the end, I simply copied the ZIP file to the external SD card, by attaching the SD card directly to the PC. Then I moved the card back to the phone, and when I rebooted the phone, I could install CyanogenMod from the SD card.

How to set div width using ng-style

ngStyle accepts a map:

$scope.myStyle = {
    "width" : "900px",
    "background" : "red"
};

Fiddle

What is the Angular equivalent to an AngularJS $watch?

You can use getter function or get accessor to act as watch on angular 2.

See demo here.

import {Component} from 'angular2/core';

@Component({
  // Declare the tag name in index.html to where the component attaches
  selector: 'hello-world',

  // Location of the template for this component
  template: `
  <button (click)="OnPushArray1()">Push 1</button>
  <div>
    I'm array 1 {{ array1 | json }}
  </div>
  <button (click)="OnPushArray2()">Push 2</button>
  <div>
    I'm array 2 {{ array2 | json }}
  </div>
  I'm concatenated {{ concatenatedArray | json }}
  <div>
    I'm length of two arrays {{ arrayLength | json }}
  </div>`
})
export class HelloWorld {
    array1: any[] = [];
    array2: any[] = [];

    get concatenatedArray(): any[] {
      return this.array1.concat(this.array2);
    }

    get arrayLength(): number {
      return this.concatenatedArray.length;
    }

    OnPushArray1() {
        this.array1.push(this.array1.length);
    }

    OnPushArray2() {
        this.array2.push(this.array2.length);
    }
}

copy all files and folders from one drive to another drive using DOS (command prompt)

try this command, xcopy c:\ (file or directory path) F:\ /e. If you want more details refer this site [[http://www.computerhope.com/xcopyhlp.htm]]

Reactive forms - disabled attribute

in Angular-9 if you want to disable/enable on button click here is a simple solution if you are using reactive forms.

define a function in component.ts file

//enable example you can use the same approach for disable with .disable()

toggleEnable() {
  this.yourFormName.controls.formFieldName.enable();
  console.log("Clicked")
} 

Call it from your component.html

e.g

<button type="button" data-toggle="form-control" class="bg-primary text-white btn- 
                reset" style="width:100%"(click)="toggleEnable()">

URL string format for connecting to Oracle database with JDBC

if you are using oracle 10g expree Edition then:
1. for loading class use DriverManager.registerDriver (new oracle.jdbc.OracleDriver()); 2. for connecting to database use Connection conn = DriverManager.getConnection("jdbc:oracle:thin:username/password@localhost:1521:xe");

"Press Any Key to Continue" function in C

You don't say what system you're using, but as you already have some answers that may or may not work for Windows, I'll answer for POSIX systems.

In POSIX, keyboard input comes through something called a terminal interface, which by default buffers lines of input until Return/Enter is hit, so as to deal properly with backspace. You can change that with the tcsetattr call:

#include <termios.h>

struct termios info;
tcgetattr(0, &info);          /* get current terminal attirbutes; 0 is the file descriptor for stdin */
info.c_lflag &= ~ICANON;      /* disable canonical mode */
info.c_cc[VMIN] = 1;          /* wait until at least one keystroke available */
info.c_cc[VTIME] = 0;         /* no timeout */
tcsetattr(0, TCSANOW, &info); /* set immediately */

Now when you read from stdin (with getchar(), or any other way), it will return characters immediately, without waiting for a Return/Enter. In addition, backspace will no longer 'work' -- instead of erasing the last character, you'll read an actual backspace character in the input.

Also, you'll want to make sure to restore canonical mode before your program exits, or the non-canonical handling may cause odd effects with your shell or whoever invoked your program.

Get list of Excel files in a folder using VBA

Sub test()
    Dim FSO As Object
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set folder1 = FSO.GetFolder(FromPath).Files
    FolderPath_1 = "D:\Arun\Macro Files\UK Marco\External Sales Tool for Au\Example Files\"
    Workbooks.Add
    Set Movenamelist = ActiveWorkbook
    For Each fil In folder1
        Movenamelist.Activate
        Range("A100000").End(xlUp).Offset(1, 0).Value = fil
        ActiveCell.Offset(1, 0).Select
    Next
End Sub

HTTP Error 503, the service is unavailable

Check your application's respective Application Framework Pool - it could be stopped. If it is, start it and check again.

If you're still experiencing issues you can also check out Event Viewer to find the cause of that error in order to troubleshoot more.

Set the text in a span

Try it.. It will first look for anchor tag that contain span with class "ui-icon-circle-triangle-w", then it set the text of span to "<<".

$('a span.ui-icon-circle-triangle-w').text('<<');

Reloading the page gives wrong GET request with AngularJS HTML5 mode

I am using apache (xampp) on my dev environment and apache on the production, add:

errorDocument 404 /index.html

to the .htaccess solve for me this issue.

How to replace multiple strings in a file using PowerShell

With version 3 of PowerShell you can chain the replace calls together:

 (Get-Content $sourceFile) | ForEach-Object {
    $_.replace('something1', 'something1').replace('somethingElse1', 'somethingElse2')
 } | Set-Content $destinationFile

Maven Unable to locate the Javac Compiler in:

In Eclipse, actions like importing Maven projects or invoking "Update Sources" runs in the same JVM in which Eclipse is running. If that JVM comes from JRE that isn’t part of JDK, there would be no Java compiler (the tools.jar).

So to launch Maven from within Eclipse, JRE used for launch also need to come from JDK. By default Eclipse registers JRE it is started in, but this can be configured on "Window / Preferences… / Java / Installed JREs" preference page as mentioned above by Parthasarathy

Alternatively you can specify compilerId in the pom.xml, so Maven won’t be looking for JDK when compiling Java code:

 <plugin>
  <artifactid>maven-compiler-plugin</artifactid>
  <configuration>
    <compilerid>eclipse</compilerid>
  </configuration>
  <dependencies>
    <dependency>
      <groupid>org.codehaus.plexus</groupid>
      <artifactid>plexus-compiler-eclipse</artifactid>
      <version>xxxx</version>
    </dependency>
  </dependencies>
</plugin>

Stretch image to fit full container width bootstrap

container class has 15px left & right padding, so if you want to remove this padding, use following, because row class has -15px left & right margin.

<div class="container">
  <div class="row">
     <img class='img-responsive' src="#" alt="" />
  </div>
</div>

Codepen: http://codepen.io/m-dehghani/pen/jqeKgv

How to prevent form from being submitted?

The following works as of now (tested in chrome and firefox):

<form onsubmit="event.preventDefault(); return validateMyForm();">

where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault()

What are major differences between C# and Java?

Comparing Java 7 and C# 3

(Some features of Java 7 aren't mentioned here, but the using statement advantage of all versions of C# over Java 1-6 has been removed.)

Not all of your summary is correct:

  • In Java methods are virtual by default but you can make them final. (In C# they're sealed by default, but you can make them virtual.)
  • There are plenty of IDEs for Java, both free (e.g. Eclipse, Netbeans) and commercial (e.g. IntelliJ IDEA)

Beyond that (and what's in your summary already):

  • Generics are completely different between the two; Java generics are just a compile-time "trick" (but a useful one at that). In C# and .NET generics are maintained at execution time too, and work for value types as well as reference types, keeping the appropriate efficiency (e.g. a List<byte> as a byte[] backing it, rather than an array of boxed bytes.)
  • C# doesn't have checked exceptions
  • Java doesn't allow the creation of user-defined value types
  • Java doesn't have operator and conversion overloading
  • Java doesn't have iterator blocks for simple implemetation of iterators
  • Java doesn't have anything like LINQ
  • Partly due to not having delegates, Java doesn't have anything quite like anonymous methods and lambda expressions. Anonymous inner classes usually fill these roles, but clunkily.
  • Java doesn't have expression trees
  • C# doesn't have anonymous inner classes
  • C# doesn't have Java's inner classes at all, in fact - all nested classes in C# are like Java's static nested classes
  • Java doesn't have static classes (which don't have any instance constructors, and can't be used for variables, parameters etc)
  • Java doesn't have any equivalent to the C# 3.0 anonymous types
  • Java doesn't have implicitly typed local variables
  • Java doesn't have extension methods
  • Java doesn't have object and collection initializer expressions
  • The access modifiers are somewhat different - in Java there's (currently) no direct equivalent of an assembly, so no idea of "internal" visibility; in C# there's no equivalent to the "default" visibility in Java which takes account of namespace (and inheritance)
  • The order of initialization in Java and C# is subtly different (C# executes variable initializers before the chained call to the base type's constructor)
  • Java doesn't have properties as part of the language; they're a convention of get/set/is methods
  • Java doesn't have the equivalent of "unsafe" code
  • Interop is easier in C# (and .NET in general) than Java's JNI
  • Java and C# have somewhat different ideas of enums. Java's are much more object-oriented.
  • Java has no preprocessor directives (#define, #if etc in C#).
  • Java has no equivalent of C#'s ref and out for passing parameters by reference
  • Java has no equivalent of partial types
  • C# interfaces cannot declare fields
  • Java has no unsigned integer types
  • Java has no language support for a decimal type. (java.math.BigDecimal provides something like System.Decimal - with differences - but there's no language support)
  • Java has no equivalent of nullable value types
  • Boxing in Java uses predefined (but "normal") reference types with particular operations on them. Boxing in C# and .NET is a more transparent affair, with a reference type being created for boxing by the CLR for any value type.

This is not exhaustive, but it covers everything I can think of off-hand.

Laravel Carbon subtract days from current date

You can always use strtotime to minus the number of days from the current date:

$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', date('Y-m-d', strtotime("-30 days"))
           ->get();

How to time Java program execution speed

final long startTime = System.currentTimeMillis();
for (int i = 0; i < length; i++) {
  // Do something
}
final long endTime = System.currentTimeMillis();

System.out.println("Total execution time: " + (endTime - startTime));

How do I concatenate text in a query in sql server?

You have to explicitly cast the string types to the same in order to concatenate them, In your case you may solve the issue by simply addig an 'N' in front of 'SomeText' (N'SomeText'). If that doesn't work, try Cast('SomeText' as nvarchar(8)).

Style input element to fill remaining width of its container

I suggest using Flexbox:

Be sure to add the proper vendor prefixes though!

_x000D_
_x000D_
form {_x000D_
  width: 400px;_x000D_
  border: 1px solid black;_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
input {_x000D_
  flex: 2;_x000D_
}_x000D_
_x000D_
input, label {_x000D_
  margin: 5px;_x000D_
}
_x000D_
<form method="post">_x000D_
  <label for="myInput">Sample label</label>_x000D_
  <input type="text" id="myInput" placeholder="Sample Input"/>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Difference between ${} and $() in Bash

The syntax is token-level, so the meaning of the dollar sign depends on the token it's in. The expression $(command) is a modern synonym for `command` which stands for command substitution; it means run command and put its output here. So

echo "Today is $(date). A fine day."

will run the date command and include its output in the argument to echo. The parentheses are unrelated to the syntax for running a command in a subshell, although they have something in common (the command substitution also runs in a separate subshell).

By contrast, ${variable} is just a disambiguation mechanism, so you can say ${var}text when you mean the contents of the variable var, followed by text (as opposed to $vartext which means the contents of the variable vartext).

The while loop expects a single argument which should evaluate to true or false (or actually multiple, where the last one's truth value is examined -- thanks Jonathan Leffler for pointing this out); when it's false, the loop is no longer executed. The for loop iterates over a list of items and binds each to a loop variable in turn; the syntax you refer to is one (rather generalized) way to express a loop over a range of arithmetic values.

A for loop like that can be rephrased as a while loop. The expression

for ((init; check; step)); do
    body
done

is equivalent to

init
while check; do
    body
    step
done

It makes sense to keep all the loop control in one place for legibility; but as you can see when it's expressed like this, the for loop does quite a bit more than the while loop.

Of course, this syntax is Bash-specific; classic Bourne shell only has

for variable in token1 token2 ...; do

(Somewhat more elegantly, you could avoid the echo in the first example as long as you are sure that your argument string doesn't contain any % format codes:

date +'Today is %c. A fine day.'

Avoiding a process where you can is an important consideration, even though it doesn't make a lot of difference in this isolated example.)

Add a prefix string to beginning of each line

While I don't think pierr had this concern, I needed a solution that would not delay output from the live "tail" of a file, since I wanted to monitor several alert logs simultaneously, prefixing each line with the name of its respective log.

Unfortunately, sed, cut, etc. introduced too much buffering and kept me from seeing the most current lines. Steven Penny's suggestion to use the -s option of nl was intriguing, and testing proved that it did not introduce the unwanted buffering that concerned me.

There were a couple of problems with using nl, though, related to the desire to strip out the unwanted line numbers (even if you don't care about the aesthetics of it, there may be cases where using the extra columns would be undesirable). First, using "cut" to strip out the numbers re-introduces the buffering problem, so it wrecks the solution. Second, using "-w1" doesn't help, since this does NOT restrict the line number to a single column - it just gets wider as more digits are needed.

It isn't pretty if you want to capture this elsewhere, but since that's exactly what I didn't need to do (everything was being written to log files already, I just wanted to watch several at once in real time), the best way to lose the line numbers and have only my prefix was to start the -s string with a carriage return (CR or ^M or Ctrl-M). So for example:

#!/bin/ksh

# Monitor the widget, framas, and dweezil
# log files until the operator hits <enter>
# to end monitoring.

PGRP=$$

for LOGFILE in widget framas dweezil
do
(
    tail -f $LOGFILE 2>&1 |
    nl -s"^M${LOGFILE}>  "
) &
sleep 1
done

read KILLEM

kill -- -${PGRP}

Clearing NSUserDefaults

I love extensions when they make the code cleaner:

extension NSUserDefaults {
    func clear() {
        guard let domainName = NSBundle.mainBundle().bundleIdentifier else {
            return
        }

        self.removePersistentDomainForName(domainName)
    }
}

Swift 5

extension UserDefaults {
    func clear() {
        guard let domainName = Bundle.main.bundleIdentifier else {
            return
        }
        removePersistentDomain(forName: domainName)
        synchronize()
    }
}

OSError: [Errno 8] Exec format error

OSError: [Errno 8] Exec format error can happen if there is no shebang line at the top of the shell script and you are trying to execute the script directly. Here's an example that reproduces the issue:

>>> with open('a','w') as f: f.write('exit 0') # create the script
... 
>>> import os
>>> os.chmod('a', 0b111101101) # rwxr-xr-x make it executable                       
>>> os.execl('./a', './a')     # execute it                                            
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/os.py", line 312, in execl
    execv(file, args)
OSError: [Errno 8] Exec format error

To fix it, just add the shebang e.g., if it is a shell script; prepend #!/bin/sh at the top of your script:

>>> with open('a','w') as f: f.write('#!/bin/sh\nexit 0')
... 
>>> os.execl('./a', './a')

It executes exit 0 without any errors.


On POSIX systems, shell parses the command line i.e., your script won't see spaces around = e.g., if script is:

#!/usr/bin/env python
import sys
print(sys.argv)

then running it in the shell:

$ /usr/local/bin/script hostname = '<hostname>' -p LONGLIST

produces:

['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']

Note: no spaces around '='. I've added quotes around <hostname> to escape the redirection metacharacters <>.

To emulate the shell command in Python, run:

from subprocess import check_call

cmd = ['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']
check_call(cmd)

Note: no shell=True. And you don't need to escape <> because no shell is run.

"Exec format error" might indicate that your script has invalid format, run:

$ file /usr/local/bin/script

to find out what it is. Compare the architecture with the output of:

$ uname -m

Formatting DataBinder.Eval data

You can use a function into a repeater like you said, but notice that the DataBinder.Eval returns an object and you have to cast it to a DateTime.

You also can format your field inline:

<%# ((DateTime)DataBinder.Eval(Container.DataItem,"publishedDate")).ToString("yyyy-MMM-dd") %>

If you use ASP.NET 2.0 or newer you can write this as below:

<%# ((DateTime)Eval("publishedDate")).ToString("yyyy-MMM-dd") %>

Another option is to bind the value to label at OnItemDataBound event.

Get yesterday's date using Date

changed from your code :

private String toDate(long timestamp) {
    Date date = new Date (timestamp * 1000 -  24 * 60 * 60 * 1000);
   return new SimpleDateFormat("yyyy-MM-dd").format(date).toString();

}

but you do better using calendar.

How can I convert a std::string to int?

In Windows, you could use:

const std::wstring hex = L"0x13";
const std::wstring dec = L"19";

int ret;
if (StrToIntEx(hex.c_str(), STIF_SUPPORT_HEX, &ret)) {
    std::cout << ret << "\n";
}
if (StrToIntEx(dec.c_str(), STIF_SUPPORT_HEX, &ret)) {
    std::cout << ret << "\n";
}

strtol,stringstream need to specify the base if you need to interpret hexdecimal.

Fastest way to write huge data in text file Java

For those who want to improve the time for retrieval of records and dump into the file (i.e no processing on records), instead of putting them into an ArrayList, append those records into a StringBuffer. Apply toSring() function to get a single String and write it into the file at once.

For me, the retrieval time reduced from 22 seconds to 17 seconds.

List and kill at jobs on UNIX

at -l to list jobs, which gives return like this:

age2%> at -l
11      2014-10-21 10:11 a hoppent
10      2014-10-19 13:28 a hoppent

atrm 10 kills job 10

Or so my sysadmin told me, and it

Compare a string using sh shell

-eq is used to compare integers. Use = instead.

How to remove unique key from mysql table

First you need to know the exact name of the INDEX (Unique key in this case) to delete or update it.
INDEX names are usually same as column names. In case of more than one INDEX applied on a column, MySQL automatically suffixes numbering to the column names to create unique INDEX names.

For example if 2 indexes are applied on a column named customer_id

  1. The first index will be named as customer_id itself.
  2. The second index will be names as customer_id_2 and so on.

To know the name of the index you want to delete or update

SHOW INDEX FROM <table_name>

as suggested by @Amr

To delete an index

ALTER TABLE <table_name> DROP INDEX <index_name>;

Reverse Singly Linked List Java

A more elegant solution would be to use recursion

void ReverseList(ListNode current, ListNode previous) {
            if(current.Next != null) 
            {
                ReverseList(current.Next, current);
                ListNode temp = current.Next;
                temp.Next = current;
                current.Next = previous;
            }
        }

$ is not a function - jQuery error

<script type="text/javascript">
    $("ol li:nth-child(1)").addClass('olli1');
    $("ol li:nth-child(2)").addClass("olli2");
    $("ol li:nth-child(3)").addClass("olli3");
    $("ol li:nth-child(4)").addClass("olli4");
    $("ol li:nth-child(5)").addClass("olli5");
    $("ol li:nth-child(6)").addClass("olli6");
    $("ol li:nth-child(7)").addClass("olli7");
    $("ol li:nth-child(8)").addClass("olli8");
    $("ol li:nth-child(9)").addClass("olli9");
    $("ol li:nth-child(10)").addClass("olli10");
    $("ol li:nth-child(11)").addClass("olli11");
    $("ol li:nth-child(12)").addClass("olli12");
    $("ol li:nth-child(13)").addClass("olli13");
    $("ol li:nth-child(14)").addClass("olli14");
    $("ol li:nth-child(15)").addClass("olli15");
    $("ol li:nth-child(16)").addClass("olli16");
    $("ol li:nth-child(17)").addClass("olli17");
    $("ol li:nth-child(18)").addClass("olli18");
    $("ol li:nth-child(19)").addClass("olli19");
    $("ol li:nth-child(20)").addClass("olli20"); 
</script>

change this to

    <script type="text/javascript">
        jQuery(document).ready(function ($) {
        $("ol li:nth-child(1)").addClass('olli1');
        $("ol li:nth-child(2)").addClass("olli2");
        $("ol li:nth-child(3)").addClass("olli3");
        $("ol li:nth-child(4)").addClass("olli4");
        $("ol li:nth-child(5)").addClass("olli5");
        $("ol li:nth-child(6)").addClass("olli6");
        $("ol li:nth-child(7)").addClass("olli7");
        $("ol li:nth-child(8)").addClass("olli8");
        $("ol li:nth-child(9)").addClass("olli9");
        $("ol li:nth-child(10)").addClass("olli10");
        $("ol li:nth-child(11)").addClass("olli11");
        $("ol li:nth-child(12)").addClass("olli12");
        $("ol li:nth-child(13)").addClass("olli13");
        $("ol li:nth-child(14)").addClass("olli14");
        $("ol li:nth-child(15)").addClass("olli15");
        $("ol li:nth-child(16)").addClass("olli16");
        $("ol li:nth-child(17)").addClass("olli17");
        $("ol li:nth-child(18)").addClass("olli18");
        $("ol li:nth-child(19)").addClass("olli19");
        $("ol li:nth-child(20)").addClass("olli20"); 
     });
    </script>

How to use onClick event on react Link component?

You should use this:

<Link to={this.props.myroute} onClick={hello}>Here</Link>

Or (if method hello lays at this class):

<Link to={this.props.myroute} onClick={this.hello}>Here</Link>

Update: For ES6 and latest if you want to bind some param with click method, you can use this:

    const someValue = 'some';  
....  
    <Link to={this.props.myroute} onClick={() => hello(someValue)}>Here</Link>

sum two columns in R

tablename$column3=rowSums(cbind(tablename$column1,tablename$column2),na.rm=TRUE)

This can be used to ignore blank values in the excel sheet.
I have used for Euro stat dataset.

This example works in R:

crime_stat_data$All_theft <-rowSums(cbind(crime_stat_data$Theft,crime_stat_data$Theft_of_a_motorised_land_vehicle, crime_stat_data$Burglary, crime_stat_data$Burglary_of_private_residential_premises), na.rm=TRUE)  

In Visual Basic how do you create a block comment

There's not a way as of 11/2012, HOWEVER

Highlight Text (In visual Studio.net)

ctrl + k + c, ctrl + k + u

Will comment / uncomment, respectively

Is System.nanoTime() completely useless?

This answer was written in 2011 from the point of view of what the Sun JDK of the time running on operating systems of the time actually did. That was a long time ago! leventov's answer offers a more up-to-date perspective.

That post is wrong, and nanoTime is safe. There's a comment on the post which links to a blog post by David Holmes, a realtime and concurrency guy at Sun. It says:

System.nanoTime() is implemented using the QueryPerformanceCounter/QueryPerformanceFrequency API [...] The default mechanism used by QPC is determined by the Hardware Abstraction layer(HAL) [...] This default changes not only across hardware but also across OS versions. For example Windows XP Service Pack 2 changed things to use the power management timer (PMTimer) rather than the processor timestamp-counter (TSC) due to problems with the TSC not being synchronized on different processors in SMP systems, and due the fact its frequency can vary (and hence its relationship to elapsed time) based on power-management settings.

So, on Windows, this was a problem up until WinXP SP2, but it isn't now.

I can't find a part II (or more) that talks about other platforms, but that article does include a remark that Linux has encountered and solved the same problem in the same way, with a link to the FAQ for clock_gettime(CLOCK_REALTIME), which says:

  1. Is clock_gettime(CLOCK_REALTIME) consistent across all processors/cores? (Does arch matter? e.g. ppc, arm, x86, amd64, sparc).

It should or it's considered buggy.

However, on x86/x86_64, it is possible to see unsynced or variable freq TSCs cause time inconsistencies. 2.4 kernels really had no protection against this, and early 2.6 kernels didn't do too well here either. As of 2.6.18 and up the logic for detecting this is better and we'll usually fall back to a safe clocksource.

ppc always has a synced timebase, so that shouldn't be an issue.

So, if Holmes's link can be read as implying that nanoTime calls clock_gettime(CLOCK_REALTIME), then it's safe-ish as of kernel 2.6.18 on x86, and always on PowerPC (because IBM and Motorola, unlike Intel, actually know how to design microprocessors).

There's no mention of SPARC or Solaris, sadly. And of course, we have no idea what IBM JVMs do. But Sun JVMs on modern Windows and Linux get this right.

EDIT: This answer is based on the sources it cites. But i still worry that it might actually be completely wrong. Some more up-to-date information would be really valuable. I just came across to a link to a four year newer article about Linux's clocks which could be useful.

How Many Seconds Between Two Dates?

I'm taking YYYY & ZZZZ to mean integer values which mean the year, MM & NN to mean integer values meaning the month of the year and DD & EE as integer values meaning the day of the month.

var t1 = new Date(YYYY, MM, DD, 0, 0, 0, 0);
var t2 = new Date(ZZZZ, NN, EE, 0, 0, 0, 0);
var dif = t1.getTime() - t2.getTime();

var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);

A handy source for future reference is the MDN site

Alternatively, if your dates come in a format javascript can parse

var dif = Date.parse(MM + " " + DD + ", " + YYYY) - Date.parse(NN + " " + EE + ", " + ZZZZ);

and then you can use that value as the difference in milliseconds (dif in both my examples has the same meaning)

Running javascript in Selenium using Python

Use execute_script, here's a python example:

from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/questions/7794087/running-javascript-in-selenium-using-python") 
driver.execute_script("document.getElementsByClassName('comment-user')[0].click()")

How to modify a global variable within a function in bash?

Maybe you can use a file, write to file inside function, read from file after it. I have changed e to an array. In this example blanks are used as separator when reading back the array.

#!/bin/bash

declare -a e
e[0]="first"
e[1]="secondddd"

function test1 () {
 e[2]="third"
 e[1]="second"
 echo "${e[@]}" > /tmp/tempout
 echo hi
}

ret=$(test1)

echo "$ret"

read -r -a e < /tmp/tempout
echo "${e[@]}"
echo "${e[0]}"
echo "${e[1]}"
echo "${e[2]}"

Output:

hi
first second third
first
second
third

Deleting multiple columns based on column names in Pandas

You can do this in one line and one go:

df.drop([col for col in df.columns if "Unnamed" in col], axis=1, inplace=True)

This involves less moving around/copying of the object than the solutions above.

multiple packages in context:component-scan, spring config

For Example you have the package "com.abc" and you have multiple packages inside it, You can use like

@ComponentScan("com.abc")

How to run or debug php on Visual Studio Code (VSCode)

XDebug changed some configuration settings.

Old settings:

xdebug.remote_enable = 1
xdebug.remote_autostart = 1
xdebug.remote_port = 9000

New settings:

xdebug.mode=debug
xdebug.start_with_request=yes
xdebug.client_port=9000

So you should paste the latter in php.ini file. More info: XDebug Changed Configuration Settings

How to solve npm install throwing fsevents warning on non-MAC OS?

npm i -f

I'd like to repost some comments from this thread, where you can read up on the issue and the issue was solved.

This is exactly Angular's issue. Current package.json requires fsevent as not optionalDependencies but devDependencies. This may be a problem for non-OSX users.

Sometimes

Even if you remove it from package.json npm i still fails because another module has it as a peer dep.

So

if npm-shrinkwrap.json is still there, please remove it or try npm i -f

document.createElement("script") synchronously

Ironically, I have what you want, but want something closer to what you had.

I am loading things in dynamically and asynchronously, but with an load callback like so (using dojo and xmlhtpprequest)

  dojo.xhrGet({
    url: 'getCode.php',
    handleAs: "javascript",
    content : {
    module : 'my.js'
  },
  load: function() {
    myFunc1('blarg');
  },
  error: function(errorMessage) {
    console.error(errorMessage);
  }
});

For a more detailed explanation, see here

The problem is that somewhere along the line the code gets evaled, and if there's anything wrong with your code, the console.error(errorMessage); statement will indicate the line where eval() is, not the actual error. This is SUCH a big problem that I am actually trying to convert back to <script> statements (see here.

Regex to get NUMBER only from String

\d+

\d represents any digit, + for one or more. If you want to catch negative numbers as well you can use -?\d+.

Note that as a string, it should be represented in C# as "\\d+", or @"\d+"

How to receive JSON as an MVC 5 action method parameter

Unfortunately, Dictionary has problems with Model Binding in MVC. Read the full story here. Instead, create a custom model binder to get the Dictionary as a parameter for the controller action.

To solve your requirement, here is the working solution -

First create your ViewModels in following way. PersonModel can have list of RoleModels.

public class PersonModel
{
    public List<RoleModel> Roles { get; set; }
    public string Name { get; set; }
}

public class RoleModel
{
    public string RoleName { get; set;}
    public string Description { get; set;}
}

Then have a index action which will be serving basic index view -

public ActionResult Index()
{
    return View();
}

Index view will be having following JQuery AJAX POST operation -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(function () {
        $('#click1').click(function (e) {

            var jsonObject = {
                "Name" : "Rami",
                "Roles": [{ "RoleName": "Admin", "Description" : "Admin Role"}, { "RoleName": "User", "Description" : "User Role"}]
            };

            $.ajax({
                url: "@Url.Action("AddUser")",
                type: "POST",
                data: JSON.stringify(jsonObject),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function (response) {
                    alert(response.responseText);
            },
                success: function (response) {
                    alert(response);
                }
            });

        });
    });
</script>

<input type="button" value="click1" id="click1" />

Index action posts to AddUser action -

[HttpPost]
public ActionResult AddUser(PersonModel model)
{
    if (model != null)
    {
        return Json("Success");
    }
    else
    {
        return Json("An Error Has occoured");
    }
}

So now when the post happens you can get all the posted data in the model parameter of action.

Update:

For asp.net core, to get JSON data as your action parameter you should add the [FromBody] attribute before your param name in your controller action. Note: if you're using ASP.NET Core 2.1, you can also use the [ApiController] attribute to automatically infer the [FromBody] binding source for your complex action method parameters. (Doc)

enter image description here

Select where count of one field is greater than one

I give an example up on Group By between two table in Sql:

Select cn.name,ct.name,count(ct.id) totalcity from city ct left join country cn on ct.countryid = cn.id Group By cn.name,ct.name Having totalcity > 2


Get full query string in C# ASP.NET

Request.QueryString returns you a collection of Key/Value pairs representing the Query String. Not a String. Don't think that would cause a Object Reference error though. The reason your getting that is because as Mauro pointed out in the comments. It's QueryString and not Querystring.

Try:

Request.QueryString.ToString();

or

<%                                 
    string URL = Request.Url.AbsoluteUri 
    System.Net.WebClient wc = new System.Net.WebClient();
    string data = wc.DownloadString(URL);
    Response.Output.Write(data);
%>

Same as your code but Request.Url.AbsoluteUri will return the full path, including the query string.

How can I put an icon inside a TextInput in React Native?

You can wrap your TextInput in View.

_x000D_
_x000D_
<View>_x000D_
  <TextInput/>_x000D_
  <Icon/>_x000D_
<View>
_x000D_
_x000D_
_x000D_

and dynamically calculate width, if you want add an icon,

iconWidth = 0.05*viewWidth 
textInputWidth = 0.95*viewWidth

otherwise textInputwWidth = viewWidth.

View and TextInput background color are both white. (Small hack)

'str' object does not support item assignment in Python

The other answers are correct, but you can, of course, do something like:

>>> str1 = "mystring"
>>> list1 = list(str1)
>>> list1[5] = 'u'
>>> str1 = ''.join(list1)
>>> print(str1)
mystrung
>>> type(str1)
<type 'str'>

if you really want to.

Split string using a newline delimiter with Python

Here you go:

>>> data = """a,b,c
d,e,f
g,h,i
j,k,l"""
>>> data.split()  # split automatically splits through \n and space
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
>>> 

Choose File Dialog

I have implemented the Samsung File Selector Dialog, it provides the ability to open, save file, file extension filter, and create new directory in the same dialog I think it worth trying Here is the Link you have to log in to Samsung developer site to view the solution

Add a Progress Bar in WebView

The best approch which worked for me is

webView.setWebViewClient(new WebViewClient() {

    @Override public void onPageStarted(WebView view, String url, Bitmap favicon) {
          super.onPageStarted(view, url, favicon);
          mProgressBar.setVisibility(ProgressBar.VISIBLE);
          webView.setVisibility(View.INVISIBLE);
        }

    @Override public void onPageCommitVisible(WebView view, String url) {
      super.onPageCommitVisible(view, url);
      mProgressBar.setVisibility(ProgressBar.GONE);
      webView.setVisibility(View.VISIBLE);
      isWebViewLoadingFirstPage=false;
    }
}

MatPlotLib: Multiple datasets on the same scatter plot

I came across this question as I had exact same problem. Although accepted answer works good but with matplotlib version 2.1.0, it is pretty straight forward to have two scatter plots in one plot without using a reference to Axes

import matplotlib.pyplot as plt

plt.scatter(x,y, c='b', marker='x', label='1')
plt.scatter(x, y, c='r', marker='s', label='-1')
plt.legend(loc='upper left')
plt.show()

MassAssignmentException in Laravel

I used this and have no problem:

protected $guarded=[];

Install specific version using laravel installer

You can use composer method like

composer create-project laravel/laravel blog "5.1"

Or here is the composer file

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "pre-update-cmd": [
            "php artisan clear-compiled"
        ],
        "post-update-cmd": [
            "php artisan optimize"
        ],
        "post-root-package-install": [
            "php -r \"copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    }
}

Use of True, False, and None as return values in Python functions

In the case of your fictional getattr function, if the requested attribute always should be available but isn't then throw an error. If the attribute is optional then return None.

SQL Server Error : String or binary data would be truncated

This error is usually encountered when inserting a record in a table where one of the columns is a VARCHAR or CHAR data type and the length of the value being inserted is longer than the length of the column.

I am not satisfied how Microsoft decided to inform with this "dry" response message, without any point of where to look for the answer.

How to insert spaces/tabs in text using HTML/CSS

To insert tab space between two words/sentences I usually use

&emsp; and &ensp;

Restoring MySQL database from physical files

I have the same problem but was not able to successfully recover the database, based on the instructions above.

I was only able to recover mysql database folders from my Ubuntu OS. My problem is how to recover my database with those unreadable mysql data folders. So I switched back to win7 OS for development environment.

*NOTE I have an existing database server running in win7 and I only need few database files to retrieve from the recovered files. To successfully recover the database files from Ubuntu OS I need to freshly install mysql database server (same version from Ubuntu OS in my win7 OS) to recover everything in that old database server.

  1. Make another new mysql database server same version from the recovered files.

  2. Stop the mysql server

  3. copy the recovered folder and paste in the (C:\ProgramData\MySQL\MySQL Server 5.5\data) mysql database is stored.

  4. copy the ibdata1 file located in linux mysql installed folder and paste it in (C:\ProgramData\MySQL\MySQL Server 5.5\data). Just overwrite the existing or make backup before replacing.

  5. start the mysql server and check if you have successfully recovered the database files.

  6. To use the recovered database in my currently used mysql server simply export the recovered database and import it my existing mysql server.

Hope these will help, because nothing else worked for me.

How to identify unused CSS definitions from multiple CSS files in a project

Chrome Developer Tools has an Audits tab which can show unused CSS selectors.

Run an audit, then, under Web Page Performance see Remove unused CSS rules

enter image description here

Update multiple tables in SQL Server using INNER JOIN

You can update with a join if you only affect one table like this:

UPDATE table1 
SET table1.name = table2.name 
FROM table1, table2 
WHERE table1.id = table2.id 
AND table2.foobar ='stuff'

But you are trying to affect multiple tables with an update statement that joins on multiple tables. That is not possible.

However, updating two tables in one statement is actually possible but will need to create a View using a UNION that contains both the tables you want to update. You can then update the View which will then update the underlying tables.

SQL JOINS

But this is a really hacky parlor trick, use the transaction and multiple updates, it's much more intuitive.

Maximum concurrent connections to MySQL

As per the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_max_user_connections

 maximum range: 4,294,967,295  (e.g. 2**32 - 1)

You'd probably run out of memory, file handles, and network sockets, on your server long before you got anywhere close to that limit.

ASP.NET Button to redirect to another page

You can either do a Response.Redirect("YourPage.aspx"); or a Server.Transfer("YourPage.aspx"); on your button click event. So it's gonna be like the following:

protected void btnConfirm_Click(object sender, EventArgs e)
{
    Response.Redirect("YourPage.aspx");
    //or
    Server.Transfer("YourPage.aspx");
}

Assigning multiple styles on an HTML element

In HTML the style tag has the following syntax:

style="property1:value1;property2:value2"

so in your case:

<h2 style="text-align:center;font-family:tahoma">TITLE</h2>

Hope this helps.

jQuery "blinking highlight" effect on div?

You may want to look into jQuery UI. Specifically, the highlight effect:

http://jqueryui.com/demos/effect/

Concatenating variables in Bash

Try doing this, there's no special character to concatenate in bash :

mystring="${arg1}12${arg2}endoffile"

explanations

If you don't put brackets, you will ask to concatenate $arg112 + $argendoffile (I guess that's not what you asked) like in the following example :

mystring="$arg112$arg2endoffile"

The brackets are delimiters for the variables when needed. When not needed, you can use it or not.

another solution

(less portable : require bash > 3.1)

$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile

See http://mywiki.wooledge.org/BashFAQ/013

Deserializing JSON array into strongly typed .NET object

This worked for me for deserializing JSON into an array of objects:

List<TheUser> friends = JsonConvert.DeserializeObject<List<TheUser>>(response);

How to implement band-pass Butterworth filter with Scipy.signal.butter

For a bandpass filter, ws is a tuple containing the lower and upper corner frequencies. These represent the digital frequency where the filter response is 3 dB less than the passband.

wp is a tuple containing the stop band digital frequencies. They represent the location where the maximum attenuation begins.

gpass is the maximum attenutation in the passband in dB while gstop is the attentuation in the stopbands.

Say, for example, you wanted to design a filter for a sampling rate of 8000 samples/sec having corner frequencies of 300 and 3100 Hz. The Nyquist frequency is the sample rate divided by two, or in this example, 4000 Hz. The equivalent digital frequency is 1.0. The two corner frequencies are then 300/4000 and 3100/4000.

Now lets say you wanted the stopbands to be down 30 dB +/- 100 Hz from the corner frequencies. Thus, your stopbands would start at 200 and 3200 Hz resulting in the digital frequencies of 200/4000 and 3200/4000.

To create your filter, you'd call buttord as

fs = 8000.0
fso2 = fs/2
N,wn = scipy.signal.buttord(ws=[300/fso2,3100/fso2], wp=[200/fs02,3200/fs02],
   gpass=0.0, gstop=30.0)

The length of the resulting filter will be dependent upon the depth of the stop bands and the steepness of the response curve which is determined by the difference between the corner frequency and stopband frequency.

How do I force "git pull" to overwrite local files?

? Important: If you have any local changes, they will be lost. With or without --hard option, any local commits that haven't been pushed will be lost.[*]

If you have any files that are not tracked by Git (e.g. uploaded user content), these files will not be affected.


First, run a fetch to update all origin/<branch> refs to latest:

git fetch --all

Backup your current branch:

git checkout -b backup-master

Then, you have two options:

git reset --hard origin/master

OR If you are on some other branch:

git reset --hard origin/<branch_name>

Explanation:

git fetch downloads the latest from remote without trying to merge or rebase anything.

Then the git reset resets the master branch to what you just fetched. The --hard option changes all the files in your working tree to match the files in origin/master


Maintain current local commits

[*]: It's worth noting that it is possible to maintain current local commits by creating a branch from master before resetting:

git checkout master
git branch new-branch-to-save-current-commits
git fetch --all
git reset --hard origin/master

After this, all of the old commits will be kept in new-branch-to-save-current-commits.

Uncommitted changes

Uncommitted changes, however (even staged), will be lost. Make sure to stash and commit anything you need. For that you can run the following:

git stash

And then to reapply these uncommitted changes:

git stash pop

How to use variables in a command in sed?

This may also can help

input="inputtext"
output="outputtext"
sed "s/$input/${output}/" inputfile > outputfile

Return content with IHttpActionResult for non-OK response

For exceptions, I usually do

 catch (Exception ex)
        {
            return InternalServerError(new ApplicationException("Something went wrong in this request. internal exception: " + ex.Message));
        }

Calling stored procedure from another stored procedure SQL Server

You could add an OUTPUT parameter to test2, and set it to the new id straight after the INSERT using:

SELECT @NewIdOutputParam = SCOPE_IDENTITY()

Then in test1, retrieve it like so:

DECLARE @NewId INTEGER
EXECUTE test2 @NewId OUTPUT
-- Now use @NewId as needed

ldconfig error: is not a symbolic link

simple run in shell : sudo apt-get install --reinstall libexpat1
got same problem with libxcb - solved in this way - very fast :)

Scala check if element is present in a list

this should work also with different predicate

myFunction(strings.find( _ == mystring ).isDefined)

How do you get the current text contents of a QComboBox?

Getting the Text of ComboBox when the item is changed

     self.ui.comboBox.activated.connect(self.pass_Net_Adap)

  def pass_Net_Adap(self):
      print str(self.ui.comboBox.currentText())

Storing Python dictionaries

If save to a JSON file, the best and easiest way of doing this is:

import json
with open("file.json", "wb") as f:
    f.write(json.dumps(dict).encode("utf-8"))

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

You dont have to configure your project properties platform target X86. You can also configure the iis options to work with x86 like that

  • Select Application pool
  • Select the pool which your app uses
  • Advanced settings
  • Enable 32 bit applications true

What is the most efficient way to check if a value exists in a NumPy array?

How about

if value in my_array[:, col_num]:
    do_whatever

Edit: I think __contains__ is implemented in such a way that this is the same as @detly's version

Simplest way to detect a mobile device in PHP

I found mobile detect to be really simple and you can just use the isMobile() function :)

Access parent URL from iframe

I couldnt get previous solution to work but I found out that if I set the iframe scr with for example http:otherdomain.com/page.htm?from=thisdomain.com/thisfolder then I could, in the iframe extract thisdomain.com/thisfolder by using following javascript:

var myString = document.location.toString();
var mySplitResult = myString.split("=");
fromString = mySplitResult[1];

Your project contains error(s), please fix it before running it

I come across this error often when I import a new project in my workspace.

Reason: Some necessary files (Like R.Java) is not generated in its respective packages.

Cure: Clean and build projects, All the files that needs to be auto generated will be there on place after building the project.

Best Luck.

How can I use the HTML5 canvas element in IE?

The page is using excanvas - a JS library that simulates the canvas element using IE's VML renderer.

Note that in Internet Explorer 9, the canvas tag is supported natively! See MSDN docs for details...

Convert Current date to integer

If you need only an integer representing elapsed days since Jan. 1, 1970, you can try these:

// magic number=
// millisec * sec * min * hours
// 1000 * 60 * 60 * 24 = 86400000
public static final long MAGIC=86400000L;

public int DateToDays (Date date){
    //  convert a date to an integer and back again
    long currentTime=date.getTime();
    currentTime=currentTime/MAGIC;
    return (int) currentTime; 
}

public Date DaysToDate(int days) {
    //  convert integer back again to a date
    long currentTime=(long) days*MAGIC;
    return new Date(currentTime);
}

Shorter but less readable (slightly faster?):

public static final long MAGIC=86400000L;

public int DateToDays (Date date){
    return (int) (date.getTime()/MAGIC);
}

public Date DaysToDate(int days) {
    return new Date((long) days*MAGIC);
}

Hope this helps.

EDIT: This could work until Fri Jul 11 01:00:00 CET 5881580

ASP.NET DateTime Picker

In the textbox add this:

textmode="Date"

It gives you nice looking Datepicker like this:

DatePicker

Other variations of this are:

textmode="DateTime"

It gives you this look:

Date Time Picker

textmode="DateTimeLocal"