Programs & Examples On #Waithandle

0

How to wait for a JavaScript Promise to resolve before resuming function?

I'm wondering if there is any way to get a value from a Promise or wait (block/sleep) until it has resolved, similar to .NET's IAsyncResult.WaitHandle.WaitOne(). I know JavaScript is single-threaded, but I'm hoping that doesn't mean that a function can't yield.

The current generation of Javascript in browsers does not have a wait() or sleep() that allows other things to run. So, you simply can't do what you're asking. Instead, it has async operations that will do their thing and then call you when they're done (as you've been using promises for).

Part of this is because of Javascript's single threadedness. If the single thread is spinning, then no other Javascript can execute until that spinning thread is done. ES6 introduces yield and generators which will allow some cooperative tricks like that, but we're quite a ways from being able to use those in a wide swatch of installed browsers (they can be used in some server-side development where you control the JS engine that is being used).


Careful management of promise-based code can control the order of execution for many async operations.

I'm not sure I understand exactly what order you're trying to achieve in your code, but you could do something like this using your existing kickOff() function, and then attaching a .then() handler to it after calling it:

function kickOff() {
  return new Promise(function(resolve, reject) {
    $("#output").append("start");

    setTimeout(function() {
      resolve();
    }, 1000);
  }).then(function() {
    $("#output").append(" middle");
    return " end";
  });
}

kickOff().then(function(result) {
    // use the result here
    $("#output").append(result);
});

This will return output in a guaranteed order - like this:

start
middle
end

Update in 2018 (three years after this answer was written):

If you either transpile your code or run your code in an environment that supports ES7 features such as async and await, you can now use await to make your code "appear" to wait for the result of a promise. It is still developing with promises. It does still not block all of Javascript, but it does allow you to write sequential operations in a friendlier syntax.

Instead of the ES6 way of doing things:

someFunc().then(someFunc2).then(result => {
    // process result here
}).catch(err => {
    // process error here
});

You can do this:

// returns a promise
async function wrapperFunc() {
    try {
        let r1 = await someFunc();
        let r2 = await someFunc2(r1);
        // now process r2
        return someValue;     // this will be the resolved value of the returned promise
    } catch(e) {
        console.log(e);
        throw e;      // let caller know the promise was rejected with this reason
    }
}

wrapperFunc().then(result => {
    // got final result
}).catch(err => {
    // got error
});

UTF-8 output from PowerShell

Not an expert on encoding, but after reading these...

... it seems fairly clear that the $OutputEncoding variable only affects data piped to native applications.

If sending to a file from withing PowerShell, the encoding can be controlled by the -encoding parameter on the out-file cmdlet e.g.

write-output "hello" | out-file "enctest.txt" -encoding utf8

Nothing else you can do on the PowerShell front then, but the following post may well help you:.

Visual Studio debugging/loading very slow

One thing that worked for me after doing all the above was:
In the Threads window (Debug->Windows->Threads), set Group by to None. This can only be done while debugging.

This was having an impact even after closing that window.

Why am I getting "Thread was being aborted" in ASP.NET?

If you spawn threads in Application_Start, they will still be executing in the application pool's AppDomain.

If an application is idle for some time (meaning that no requests are coming in), or certain other conditions are met, ASP.NET will recycle the entire AppDomain.

When that happens, any threads that you started from that AppDomain, including those from Application_Start, will be aborted.

Lots more on application pools and recycling in this question: What exactly is Appdomain recycling

If you are trying to run a long-running process within IIS/ASP.NET, the short answer is usually "Don't". That's what Windows Services are for.

How to avoid a System.Runtime.InteropServices.COMException?

I came across System.Runtime.InteropServices.COMException while opening a project solution. Sometimes user doesn't have enough priveleges to run some COM Methods. I ran Visual Studio as Administrator and the exception was gone.

BackgroundWorker vs background Thread

If it ain't broke - fix it till it is...just kidding :)

But seriously BackgroundWorker is probably very similar to what you already have, had you started with it from the beginning maybe you would have saved some time - but at this point I don't see the need. Unless something isn't working, or you think your current code is hard to understand, then I would stick with what you have.

C#: Waiting for all threads to complete

This may not be an option for you, but if you can use the Parallel Extension for .NET then you could use Tasks instead of raw threads and then use Task.WaitAll() to wait for them to complete.

How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?

This works for me:

<?if(isset($_POST['oldPost'])):?>
    <form method="post" id="resetPost"></form>
    <script>$("#resetPost").submit()</script>
<?endif?>

Docker official registry (Docker Hub) URL

I came across this post in search for the dockerhub repo URL when creating a dockerhub kubernetes secret.. figured id share the URL is used with success, hope that's ok.

Live Current: https://index.docker.io/v2/

Dead Orginal: https://index.docker.io/v1/

Postfix is installed but how do I test it?

To check whether postfix is running or not

sudo postfix status

If it is not running, start it.

sudo postfix start

Then telnet to localhost port 25 to test the email id

ehlo localhost
mail from: root@localhost
rcpt to: your_email_id
data
Subject: My first mail on Postfix

Hi,
Are you there?
regards,
Admin
.

Do not forget the . at the end, which indicates end of line

Loop through an array in JavaScript

There are a couple of ways to do it in JavaScript. The first two examples are JavaScript samples. The third one makes use of a JavaScript library, that is, jQuery making use of the .each() function.

_x000D_
_x000D_
var myStringArray = ["hello", "World"];_x000D_
for(var i in myStringArray) {_x000D_
  alert(myStringArray[i]);_x000D_
}
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
var myStringArray = ["hello", "World"];_x000D_
for (var i=0; i < myStringArray.length; i++) {_x000D_
  alert(myStringArray[i]);_x000D_
}
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
var myStringArray = ["hello", "World"];_x000D_
$.each(myStringArray, function(index, value){_x000D_
  alert(value);_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

VBA: activating/selecting a worksheet/row/cell

This is just a sample code, but it may help you get on your way:

Public Sub testIt()
    Workbooks("Workbook2").Activate
    ActiveWorkbook.Sheets("Sheet2").Activate
    ActiveSheet.Range("B3").Select
    ActiveCell.EntireRow.Insert
End Sub

I am assuming that you can open the book (called Workbook2 in the example).


I think (but I'm not sure) you can squash all this in a single line of code:

    Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert

This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.

How to change the length of a column in a SQL Server table via T-SQL

So, let's say you have this table:

CREATE TABLE YourTable(Col1 VARCHAR(10))

And you want to change Col1 to VARCHAR(20). What you need to do is this:

ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)

That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5), then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE will fail.

How to kill a process in MacOS?

in the spotlight, search for Activity Monitor. You can force fully remove any application from here.

enter image description here

Java enum with multiple value types

First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.

Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.

Here's how you should do it with all the suggestions above:

public enum States {
    ...
    MASSACHUSETTS("Massachusetts",  "MA",   true),
    MICHIGAN     ("Michigan",       "MI",   false),
    ...; // all 50 of those

    private final String full;
    private final String abbr;
    private final boolean originalColony;

    private States(String full, String abbr, boolean originalColony) {
        this.full = full;
        this.abbr = abbr;
        this.originalColony = originalColony;
    }

    public String getFullName() {
        return full;
    }

    public String getAbbreviatedName() {
        return abbr;
    }

    public boolean isOriginalColony(){
        return originalColony;
    }
}

What is the difference between compileSdkVersion and targetSdkVersion?

compiledSdkVersion==> which version of SDK should compile your code to bytecode(it uses in development environment) point: it's better use last version of SDK.

minSdkVersion==> these item uses for installation of APK(it uses in production environment). For example:

if(client-sdk-version   <   min-sdk-versoin )
    client-can-not-install-apk;
else
    client-can-install-apk;

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

I wouldn't use StringTokenizer as it is one of classes in the JDK that's legacy.

The javadoc says:

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

How to set conditional breakpoints in Visual Studio?

  1. Set breakpoint on the line
  2. Right clik on RED ball
  3. Chose conditioal breakpoint
  4. Setup condition

Build Eclipse Java Project from Command Line

Just wanted to add my two cents to this. I tried doing as @Kieveli suggested for non win32 (repeated below) but it didn't work for me (on CentOS with Eclipse: Luna):

java -cp startup.jar -noSplash -data "D:\Source\MyProject\workspace" -application org.eclipse.jdt.apt.core.aptBuild

On my particular setup on CentOS using Eclipse (Luna) this worked:

$ECLIPSE_HOME/eclipse -nosplash -application org.eclipse.jdt.apt.core.aptBuild  startup.jar -data ~/workspace

The output should look something like this:

Building workspace
Building '/RemoteSystemsTempFiles'
Building '/test'
Invoking 'Java Builder' on '/test'.
Cleaning output folder for test
Build done
Building workspace
Building '/RemoteSystemsTempFiles'
Building '/test'
Invoking 'Java Builder' on '/test'.
Preparing to build test
Cleaning output folder for test
Copying resources to the output folder
Analyzing sources
Compiling test/src/com/company/test/tool
Build done

Not quite sure why it apparently did it twice, but it seems to work.

Bootstrap col-md-offset-* not working

It works in bootstrap 4, there were some changes in documentation.We don't need prefix col-, just offset-md-3 e.g.

<div class="row">
   <div class="offset-md-3 col-md-6"> Some content...
   </div>
</div>

Here doc.

SQL Server JOIN missing NULL values

you can just map like that

select * from tableA a
join tableB b on isnull(a.colID,'') = isnull(b.colId,'')

How to remove a directory from git repository?

I already had committed the folder before and want to remove the directory in the history as well.

I did the following:

Add folder to .gitignore:

echo Folder_Name/ >> .gitignore

Remove from all commits:

git filter-branch --index-filter 'git rm -rf --cached --ignore-unmatch Folder_Name/' --prune-empty --tag-name-filter cat -- --all

remove the refs from the old commits:

git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d

Ensure all old refs are fully removed

rm -Rf .git/logs .git/refs/original

Perform a garbage collection

git gc --prune=all --aggressive

push you changes to the online repository:

git push

You are done here.

But you can to the following to push all the changes to all branches with: But be careful with this command!

git push origin --all --force
git push origin --tags --force

After that the folder was removed from git, but was not deleted from local disk.

Error # 1045 - Cannot Log in to MySQL server -> phpmyadmin

sudo service mysql stop

sudo mysqld --skip-grant-tables &

mysql -u root mysql

Change MYSECRET with your new root password

UPDATE user SET Password=PASSWORD('MYSECRET') WHERE User='root'; FLUSH PRIVILEGES; exit;

Clear Application's Data Programmatically

If you want a less verbose hack:

void deleteDirectory(String path) {
  Runtime.getRuntime().exec(String.format("rm -rf %s", path));
}

if else condition in blade file (laravel 5.3)

I think you are putting one too many curly brackets. Try this

 @if($user->status=='waiting')
            <td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{!! $user->travel_id !!}" data-toggle="modal" data-target="#myModal">Approve/Reject</a> </td>
            @else
            <td>{!! $user->status !!}</td>
        @endif

Clearing an input text field in Angular2

This is a solution for reactive forms. Then there is no need to use @ViewChild decorator:

  clear() {
    this.myForm.get('someControlName').reset()
  }

React: how to update state.item[1] in state using setState?

You could use the update immutability helper for this:

this.setState({
  items: update(this.state.items, {1: {name: {$set: 'updated field name'}}})
})

Or if you don't care about being able to detect changes to this item in a shouldComponentUpdate() lifecycle method using ===, you could edit the state directly and force the component to re-render - this is effectively the same as @limelights' answer, as it's pulling an object out of state and editing it.

this.state.items[1].name = 'updated field name'
this.forceUpdate()

Post-edit addition:

Check out the Simple Component Communication lesson from react-training for an example of how to pass a callback function from a state-holding parent to a child component which needs to trigger a state change.

How to free memory from char array in C

char arr[3] = "bo";

The arr takes the memory into the stack segment. which will be automatically free, if arr goes out of scope.

Get selected value from combo box in C# WPF

How about these:

string yourstringname = (yourComboBox.SelectedItem as ComboBoxItem).Content.ToString();

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

I had this problem and I'm not entirely sure which step below made it work, but hope this helps somebody else...this is what I did:

  • Install the downloaded certificate (.crt) into certificates (I put it into “personal” store) - right click on .crt file and click Install Certificate.
  • Run certmgr.msc and export the certificate (found in whichever store you used in the 1st step) as a pfx file including private key, and extended properties (probably unnecessary)
  • Use the exported .pfx file when signing your project
  • Example signtool: signtool sign /f "c:\mycert.pfx" /p mypassword /d "description" /t http://timestamp.verisign.com/scripts/timstamp.dll $(TargetPath)
    where the password is the same as provided during Export

Form Google Maps URL that searches for a specific places near specific coordinates

Yeah, I had the same question for a long time and I found the perfect one. Here are some parameters from it.

https://maps.google.com/?parameter=value



q=

Used to specify the search query in Google maps search.
eg :

https://maps.google.com/?q=newyork or
https://maps.google.com/?q=51.03841,-114.01679

near=

Used to specify the location instead of putting it into q. Also has the added effect of allowing you to increase the AddressDetails Accuracy value by being more precise. Mostly only useful if q is a business or suchlike.

z=

Zoom level. Can be set 19 normally, but in certain cases can go up to 23.

ll=

Latitude and longitude of the map centre point. Must be in that order. Requires decimal format. Interestingly, you can use this without q, in which case it doesn’t show a marker.

sll=

Similar to ll, only this sets the lat/long of the centre point for a business search. Requires the same input criteria as ll.

t=

Sets the kind of map shown. Can be set to:

m – normal  map
k – satellite
h – hybrid
p – terrain

saddr=

Sets the starting point for directions searches. You can also add text into this in brackets to bold it in the directions sidebar.

daddr=

Sets the end point for directions searches, and again will bold any text added in brackets.You can also add "+to:" which will set via points. These can be added multiple times.

via=

Allows you to insert via points in directions. Must be in CSV format. For example, via=1,5 addresses 1 and 5 will be via points without entries in the sidebar. The start point (which is set as 0), and 2, 3 and 4 will all show full addresses.

doflg=

Changes the units used to measure distance (will default to the standard unit in country of origin). Change to ptk for metric or ptm for imperial.

msa=

Does stuff with My Maps. Set to 0 show defined My Maps, b to turn the My Maps sidebar on, 1 to show the My Maps tab on its own, or 2 to go to the new My Map creator form.

reference : http://moz.com/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters

How to make spring inject value into a static field

As these answers are old, I found this alternative. It is very clean and works with just java annotations:

To fix it, create a “none static setter” to assign the injected value for the static variable. For example :

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class GlobalValue {

public static String DATABASE;

@Value("${mongodb.db}")
public void setDatabase(String db) {
    DATABASE = db;
}
}

https://www.mkyong.com/spring/spring-inject-a-value-into-static-variables/

Add a user control to a wpf window

You probably need to add the namespace:

<Window x:Class="UserControlTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:UserControlTest"
    Title="User Control Test" Height="300" Width="300">
    <local:UserControl1 />
</Window>

Automatically pass $event with ng-click?

I wouldn't recommend doing this, but you can override the ngClick directive to do what you are looking for. That's not saying, you should.

With the original implementation in mind:

compile: function($element, attr) {
  var fn = $parse(attr[directiveName]);
  return function(scope, element, attr) {
    element.on(lowercase(name), function(event) {
      scope.$apply(function() {
        fn(scope, {$event:event});
      });
    });
  };
}

We can do this to override it:

// Go into your config block and inject $provide.
app.config(function ($provide) {

  // Decorate the ngClick directive.
  $provide.decorator('ngClickDirective', function ($delegate) {

    // Grab the actual directive from the returned $delegate array.
    var directive = $delegate[0];

    // Stow away the original compile function of the ngClick directive.
    var origCompile = directive.compile;

    // Overwrite the original compile function.
    directive.compile = function (el, attrs) {

      // Apply the original compile function. 
      origCompile.apply(this, arguments);

      // Return a new link function with our custom behaviour.
      return function (scope, el, attrs) {

        // Get the name of the passed in function. 
        var fn = attrs.ngClick;

        el.on('click', function (event) {
          scope.$apply(function () {

            // If no property on scope matches the passed in fn, return. 
            if (!scope[fn]) {
              return;
            }

            // Throw an error if we misused the new ngClick directive.
            if (typeof scope[fn] !== 'function') {
              throw new Error('Property ' + fn + ' is not a function on ' + scope);
            }

            // Call the passed in function with the event.
            scope[fn].call(null, event);

          });
        });          
      };
    };    

    return $delegate;
  });
});

Then you'd pass in your functions like this:

<div ng-click="func"></div>

as opposed to:

<div ng-click="func()"></div>

jsBin: http://jsbin.com/piwafeke/3/edit

Like I said, I would not recommend doing this but it's a proof of concept showing you that, yes - you can in fact overwrite/extend/augment the builtin angular behaviour to fit your needs. Without having to dig all that deep into the original implementation.

Do please use it with care, if you were to decide on going down this path (it's a lot of fun though).

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

I have found one solution to this problem.

Please follow below these steps:

  1. Go to File->Settings->Compiler->add To --stacktrace --debug in Command-line-Options box and then apply & ok.
  2. Rebuild a project.
  3. Run a project.

Xcode iOS 8 Keyboard types not supported

If you're getting this bug with Xcode Beta, it's a beta bug and can be ignored (as far as I've been told). If you can build and run on a release build of Xcode without this error, then it is not your app that has the problem.

Not 100% on this, but see if this fixes the problem:

iOS Simulator -> Hardware -> Keyboard -> Toggle Software Keyboard.

Then, everything works

How to run a command in the background and get no output?

Sorry this is a bit late but found the ideal solution for somple commands where you don't want any standard or error output (credit where it's due: http://felixmilea.com/2014/12/running-bash-commands-background-properly/)

This redirects output to null and keeps screen clear:

command &>/dev/null &

Inversion of Control vs Dependency Injection

//ICO , DI ,10 years back , this was they way:

public class  AuditDAOImpl implements Audit{

    //dependency
    AuditDAO auditDAO = null;
        //Control of the AuditDAO is with AuditDAOImpl because its creating the object
    public AuditDAOImpl () {
        this.auditDAO = new AuditDAO ();
    }
}

Now with Spring 3,4 or latest its like below

public class  AuditDAOImpl implements Audit{

    //dependency

     //Now control is shifted to Spring. Container find the object and provide it. 
    @Autowired
    AuditDAO auditDAO = null;

}

Overall the control is inverted from old concept of coupled code to the frameworks like Spring which makes the object available. So that's IOC as far as I know and Dependency injection as you know when we inject the dependent object into another object using Constructor or setters . Inject basically means passing it as an argument. In spring we have XML & annotation based configuration where we define bean object and pass the dependent object with Constructor or setter injection style.

read string from .resx file in C#

The Simplest Way to get value from resource file. Add Resource file in the project. Now get the string where you want to add like in my case it was text block(SilverLight). No need to add any namespace also.Its working fine in my case

txtStatus.Text = Constants.RefractionUpdateMessage;

Constants is my resource file name in the project.Here how my resource file look like

Oracle Not Equals Operator

They are the same (as is the third form, ^=).

Note, though, that they are still considered different from the point of view of the parser, that is a stored outline defined for a != won't match <> or ^=.

This is unlike PostgreSQL where the parser treats != and <> yet on parsing stage, so you cannot overload != and <> to be different operators.

installing requests module in python 2.7 windows

On windows 10 run cmd.exe with admin rights then type :

1) cd \Python27\scripts

2) pip install requests

It should work. My case was with python 2.7

Log4j output not displayed in Eclipse console

Configuring with BasicConfigurator.configure(); sets up a basic console appender set at debug. A project with the setup above and no other code (except for a test) should produce three lines of logging in the console. I cannot say anything else than "it works for me".

Have you tried creating an empty project with just log4j and junit, with only the code above and ran it?

Also, in order to get the @Beforemethod running:

@Test
public void testname() throws Exception {
    assertTrue(true);
}

EDIT:

If you run more than one test at one time, each of them will call init before running.

In this case, if you had two tests, the first would have one logger and the second test would call init again, making it log twice (try it) - you should get 9 lines of logging in console with two tests.

You might want to use a static init method annotated with @BeforeClass to avoid this. Though this also happens across files, you might want to have a look at documentation on TestSuites in JUnit 4. And/or call BasicConfigurator.resetConfiguration(); in an @AfterClass annotated class, to remove all loggers after each test class / test suite.

Also, the root logger is reused, so that if you set the root logger's level in a test method that runs early, it will keep this setting for all other tests that are run later, even if they are in different files. (will not happen when resetting configuration).

Testcase - this will cause 9 lines of logging:

import static org.junit.Assert.assertTrue;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;

public class SampleTest
{
   private static final Logger LOGGER = Logger.getLogger(SampleTest.class);

   @Before
   public void init() throws Exception
   {
       // Log4J junit configuration.
       BasicConfigurator.configure();
   }

   @Test
    public void testOne() throws Exception {
       LOGGER.info("INFO TEST");
       LOGGER.debug("DEBUG TEST");
       LOGGER.error("ERROR TEST");

       assertTrue(true);
    }

   @Test
   public void testTwo() throws Exception {
       LOGGER.info("INFO TEST");
       LOGGER.debug("DEBUG TEST");
       LOGGER.error("ERROR TEST");

       assertTrue(true);
   }
}

Changing the init method reduces to the excepted six lines:

@BeforeClass
public static void init() throws Exception
{
    // Log4J junit configuration.
    BasicConfigurator.configure();
}

Your problem is probably caused in some other test class or test suite where the logging level of the root logger is set to ERROR, and not reset.

You could also test this out by resetting in the @BeforeClass method, before setting logging up.

Be advised that these changes might break expected logging for other test cases until it is fixed at all places. I suggest trying out how this works in a separate workspace/project to get a feel for how it works.

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

This is what I get from console on Windows 10:

C:\>find /?
Searches for a text string in a file or files.

FIND [/V] [/C] [/N] [/I] [/OFF[LINE]] "string" [[drive:][path]filename[ ...]]

  /V         Displays all lines NOT containing the specified string.
  /C         Displays only the count of lines containing the string.
  /N         Displays line numbers with the displayed lines.
  /I         Ignores the case of characters when searching for the string.
  /OFF[LINE] Do not skip files with offline attribute set.
  "string"   Specifies the text string to find.
  [drive:][path]filename
             Specifies a file or files to search.

If a path is not specified, FIND searches the text typed at the prompt
or piped from another command.

How to programmatically tell if a Bluetooth device is connected?

This code is for the headset profiles, probably it will work for other profiles too. First you need to provide profile listener (Kotlin code):

private val mProfileListener = object : BluetoothProfile.ServiceListener {
    override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
        if (profile == BluetoothProfile.HEADSET) 
            mBluetoothHeadset = proxy as BluetoothHeadset            
    }

    override fun onServiceDisconnected(profile: Int) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = null
        }
    }
}

Then while checking bluetooth:

mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET)
if (!mBluetoothAdapter.isEnabled) {
    return Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
}

It takes a bit of time until onSeviceConnected is called. After that you may get the list of the connected headset devices from:

mBluetoothHeadset!!.connectedDevices

How to select multiple rows filled with constants?

The following bare VALUES command works for me in PostgreSQL:

VALUES (1,2,3), (4,5,6), (7,8,9)

Converting DateTime format using razor

I was not able to get this working entirely based on the suggestions above. Including the DataTypeAttribute [DataType(DataType.Date)] seemed to solve my issue, see:

Model

[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime RptDate { get; set; }

View

@Html.EditorFor(m => m.CLPosts.RptDate)

HTH

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

By initializing the min/max values to their extreme opposite, you avoid any edge cases of values in the input: Either one of min/max is in fact one of those values (in the case where the input consists of only one of those values), or the correct min/max will be found.

It should be noted that primitive types must have a value. If you used Objects (ie Integer), you could initialize value to null and handle that special case for the first comparison, but that creates extra (needless) code. However, by using these values, the loop code doesn't need to worry about the edge case of the first comparison.

Another alternative is to set both initial values to the first value of the input array (never a problem - see below) and iterate from the 2nd element onward, since this is the only correct state of min/max after one iteration. You could iterate from the 1st element too - it would make no difference, other than doing one extra (needless) iteration over the first element.

The only sane way of dealing with inout of size zero is simple: throw an IllegalArgumentException, because min/max is undefined in this case.

Swift: Testing optionals for nil

Also you can use Nil-Coalescing Operator

The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

let value = optionalValue ?? defaultValue

If optionalValue is nil, it automatically assigns value to defaultValue

How to get integer values from a string in Python?

def function(string):  
    final = ''  
    for i in string:  
        try:   
            final += str(int(i))   
        except ValueError:  
            return int(final)  
print(function("4983results should get"))  

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

As suggested here you can also inject the HttpServletRequest as a method param, e.g.:

public MyResponseObject myApiMethod(HttpServletRequest request, ...) {
    ...
}

Is there a function to round a float in C or do I need to write my own?

To print a rounded value, @Matt J well answers the question.

float x = 45.592346543;
printf("%0.1f\n", x);  // 45.6

As most floating point (FP) is binary based, exact rounding to one decimal place is not possible when the mathematically correct answer is x.1, x.2, ....

To convert the FP number to the nearest 0.1 is another matter.

Overflow: Approaches that first scale by 10 (or 100, 1000, etc) may overflow for large x.

float round_tenth1(float x) {
  x = x * 10.0f;
  ...
}

Double rounding: Adding 0.5f and then using floorf(x*10.0f + 0.5f)/10.0 returns the wrong result when the intermediate sum x*10.0f + 0.5f rounds up to a new integer.

// Fails to round 838860.4375 correctly, comes up with 838860.5 
// 0.4499999880790710449 fails as it rounds to 0.5
float round_tenth2(float x) {
  if (x < 0.0) {
    return ceilf(x*10.0f + 0.5f)/10.0f;
  }
  return floorf(x*10.0f + 0.5f)/10.0f;
}

Casting to int has the obvious problem when float x is much greater than INT_MAX.


Using roundf() and family, available in <math.h> is the best approach.

float round_tenthA(float x) {
  double x10 = 10.0 * x;
  return (float) (round(x10)/10.0);
}

To avoid using double, simply test if the number needs rounding.

float round_tenthB(float x) {
  const float limit = 1.0/FLT_EPSILON;
  if (fabsf(x) < limit) {
    return roundf(x*10.0f)/10.0f;
  }
  return x;
}

How to make HTML Text unselectable

I altered the jQuery plugin posted above so it would work on live elements.

(function ($) {
$.fn.disableSelection = function () {
    return this.each(function () {
        if (typeof this.onselectstart != 'undefined') {
            this.onselectstart = function() { return false; };
        } else if (typeof this.style.MozUserSelect != 'undefined') {
            this.style.MozUserSelect = 'none';
        } else {
            this.onmousedown = function() { return false; };
        }
    });
};
})(jQuery);

Then you could so something like:

$(document).ready(function() {
    $('label').disableSelection();

    // Or to make everything unselectable
    $('*').disableSelection();
});

Conda: Installing / upgrading directly from github

There's better support for this now through conda-env. You can, for example, now do:

name: sample_env
channels:
dependencies:
   - requests
   - bokeh>=0.10.0
   - pip:
     - "--editable=git+https://github.com/pythonforfacebook/facebook-sdk.git@8c0d34291aaafec00e02eaa71cc2a242790a0fcc#egg=facebook_sdk-master"

It's still calling pip under the covers, but you can now unify your conda and pip package specifications in a single environment.yml file.

If you wanted to update your root environment with this file, you would need to save this to a file (for example, environment.yml), then run the command: conda env update -f environment.yml.

It's more likely that you would want to create a new environment:

conda env create -f environment.yml (changed as supposed in the comments)

Read a file one line at a time in node.js?

I was frustrated by the lack of a comprehensive solution for this, so I put together my own attempt (git / npm). Copy-pasted list of features:

  • Interactive line processing (callback-based, no loading the entire file into RAM)
  • Optionally, return all lines in an array (detailed or raw mode)
  • Interactively interrupt streaming, or perform map/filter like processing
  • Detect any newline convention (PC/Mac/Linux)
  • Correct eof / last line treatment
  • Correct handling of multi-byte UTF-8 characters
  • Retrieve byte offset and byte length information on per-line basis
  • Random access, using line-based or byte-based offsets
  • Automatically map line-offset information, to speed up random access
  • Zero dependencies
  • Tests

NIH? You decide :-)

Creating a batch file, for simple javac and java command execution

The only other thing I would add is to make it a tad more flexible. Most times I'll have a trivial java file I want to run like - Main.java, Simple.java, Example.java, or Playground.java (you get the idea).

I use the following to strike off a javac and corresponding java.

@echo off
javac %~n1.java
java %~n1

The %~n1 gets the filename (sans extension) of the first argument passed to the batch file. So this way I can run it using tab completion and not have to worry about it working with either the .class or .java extension.

So both of the following will have the same result:

run.bat Main.class
and
run.bat Main.java

Doesn't 100% answer the original posters question, but I think it is a good next step/evolution for simple javac/java programs.

How to do sed like text replace with python?

If you are using Python3 the following module will help you: https://github.com/mahmoudadel2/pysed

wget https://raw.githubusercontent.com/mahmoudadel2/pysed/master/pysed.py

Place the module file into your Python3 modules path, then:

import pysed
pysed.replace(<Old string>, <Replacement String>, <Text File>)
pysed.rmlinematch(<Unwanted string>, <Text File>)
pysed.rmlinenumber(<Unwanted Line Number>, <Text File>)

How to send redirect to JSP page in Servlet

Look at the HttpServletResponse#sendRedirect(String location) method.

Use it as:

response.sendRedirect(request.getContextPath() + "/welcome.jsp")

Alternatively, look at HttpServletResponse#setHeader(String name, String value) method.

The redirection is set by adding the location header:

response.setHeader("Location", request.getContextPath() + "/welcome.jsp");

How do I include negative decimal numbers in this regular expression?

I have some experiments about regex in django url, which required from negative to positive numbers

^(?P<pid>(\-\d+|\d+))$

Let's we focused on this (\-\d+|\d+) part and ignoring others, this semicolon | means OR in regex, then the negative value will match with this \-\d+ part, and positive value into this \d+

Ineligible Devices section appeared in Xcode 6.x.x

For most people the cause of the problem is probably mismatch between Xcode, device version and app target version.
If versions are not a problem for you, most likely is that the device (iPhone/iPad) has been used with another Mac to copy apps to. This happens particularly more with a team environment where an iDevice can be used between team members. Xcode knows some other developer's Mac has connected to this device, it will show up as "Ineligible". But the previous Mac that connected to it, it will show up as normal.
The quickest work around is as shown by joshstaiger among others:
Go to Xcode ->Product->Destination
Select the ineligible device as target. It should work.

What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops?

I just had the same happen on me when I tried to run a python script from a shared folder in VirtualBox within the new Ubuntu 20.04 LTS. Python bailed with Killed while loading my own personal library. When I moved the folder to a local directory, the issue went away. It appears that the Killed stop happened during the initial imports of my library as I got messages of missing libraries once I moved the folder over.

The issue went away after I restarted my computer.

Therefore, people may want to try moving the program to a local directory if its over a share of some kind or it could be a transient problem that just requires a reboot of the OS.

What is __declspec and when do I need to use it?

Essentially, it's the way Microsoft introduces its C++ extensions so that they won't conflict with future extensions of standard C++. With __declspec, you can attribute a function or class; the exact meaning varies depending on the nature of __declspec. __declspec(naked), for example, suppresses prolog/epilog generation (for interrupt handlers, embeddable code, etc), __declspec(thread) makes a variable thread-local, and so on.

The full list of __declspec attributes is available on MSDN, and varies by compiler version and platform.

How to fix the Eclipse executable launcher was unable to locate its companion shared library for windows 7?

This worked for me

On the Zipped folder of the ADT you initially downloaded unzip and navigate to:

adt-bundle-windows-x86_64-20140702\eclipse\plugins

Copy all the executable jar files and paste them on the

C:\adt-bundle-windows-x86_64-20140702\adt-bundle-windows-x86_64-20140702\eclipse\plugins

directory (or wherever your adt is located).
Any executable jar files missing in the plugin folder will be added. You should be able to launch eclipse

Creating and playing a sound in swift

import UIKit
import AudioToolbox

class ViewController: UIViewController {

    let toneSound : Array =  ["note1","note2","note3","note4","note5","note6"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

    }

    func playSound(theTone : String) {
        if let soundURL = Bundle.main.url(forResource: theTone, withExtension: "wav") {
            var mySound: SystemSoundID = 0
            do {
                AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
                // Play
                AudioServicesPlaySystemSound(mySound);
            }
            catch {
               print(error)
            }
        }
    }

    @IBAction func anypressed(_ sender: UIButton) {
        playSound(theTone: toneSound[sender.tag-1] )
    }    

}

The result of a query cannot be enumerated more than once

if you getting this type of error so I suggest you used to stored proc data as usual list then binding the other controls because I also get this error so I solved it like this ex:-

repeater.DataSource = data.SPBinsReport().Tolist();
repeater.DataBind();

try like this

ssl.SSLError: tlsv1 alert protocol version

I had the same error and google brought me to this question, so here is what I did, hoping that it helps others in a similar situation.

This is applicable for OS X.

Check in the Terminal which version of OpenSSL I had:

$ python3 -c "import ssl; print(ssl.OPENSSL_VERSION)"
>> OpenSSL 0.9.8zh 14 Jan 2016

As my version of OpenSSL was too old, the accepted answer did not work.

So I had to update OpenSSL. To do this, I updated Python to the latest version (from version 3.5 to version 3.6) with Homebrew, following some of the steps suggested here:

$ brew update
$ brew install openssl
$ brew install python3

Then I was having problems with the PATH and the version of python being used, so I just created a new virtualenv making sure that the newest version of python was taken:

$ virtualenv webapp --python=python3.6

Issue solved.

How to directly move camera to current location in Google Maps Android API v2?

make sure you have these permissions:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Then make some activity and register a LocationListener

package com.example.location;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;

public class LocationActivity extends SherlockFragmentActivity implements LocationListener     {
private GoogleMap map;
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map);
    map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); //You can also use LocationManager.GPS_PROVIDER and LocationManager.PASSIVE_PROVIDER        
}

@Override
public void onLocationChanged(Location location) {
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
    map.animateCamera(cameraUpdate);
    locationManager.removeUpdates(this);
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) { }

@Override
public void onProviderEnabled(String provider) { }

@Override
public void onProviderDisabled(String provider) { }
}

map.xml

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>

When should you NOT use a Rules Engine?

That's certainly a good start. The other thing with rules engines is that some things are well-understood, deterministic, and straight-forward. Payroll withholding is (or use to be) like that. You could express it as rules that would be resolved by a rules engine, but you could express the same rules as a fairly simple table of values.

So, workflow engines are good when you're expressing a longer-term process that will have persistent data. Rules engines can do a similar thing, but you have to do a lot of added complexity.

Rules engines are good when you have complicated knowledge bases and need search. Rules engines can resolve complicated issues, and can be adapted quickly to changing situations, but impose a lot of complexity on the base implementation.

Many decision algorithms are simple enough to express as a simple table-driven program without the complexity implied by a real rules engine.

Resize an Array while keeping current elements in Java?

Standard class java.util.ArrayList is resizable array, growing when new elements added.

css label width not taking effect

Make it a block first, then float left to stop pushing the next block in to a new line.

#report-upload-form label {
                           padding-left:26px;
                           width:125px;
                           text-transform: uppercase;
                           display:block;
                           float:left
}

ERROR: ld.so: object LD_PRELOAD cannot be preloaded: ignored

It means the path you input caused an error. In your LD_PRELOAD command, modify the path like the error tips:

/usr/lib/liblunar-calendar-preload.so

Java getHours(), getMinutes() and getSeconds()

For a time difference, note that the calendar starts at 01.01.1970, 01:00, not at 00:00. If you're using java.util.Date and java.text.SimpleDateFormat, you will have to compensate for 1 hour:

long start = System.currentTimeMillis();
long end = start + (1*3600 + 23*60 + 45) * 1000 + 678; // 1 h 23 min 45.678 s
Date timeDiff = new Date(end - start - 3600000); // compensate for 1h in millis
SimpleDateFormat timeFormat = new SimpleDateFormat("H:mm:ss.SSS");
System.out.println("Duration: " + timeFormat.format(timeDiff));

This will print:

Duration: 1:23:45.678

What's the easiest way to install a missing Perl module?

On Fedora you can use

# yum install foo

as long as Fedora has an existing package for the module.

Strip all non-numeric characters from string in JavaScript

we are in 2017 now you can also use ES2016

var a = 'abc123.8<blah>';
console.log([...a].filter( e => isFinite(e)).join(''));

or

console.log([...'abc123.8<blah>'].filter( e => isFinite(e)).join(''));  

The result is

1238

What does "select count(1) from table_name" on any database tables mean?

The parameter to the COUNT function is an expression that is to be evaluated for each row. The COUNT function returns the number of rows for which the expression evaluates to a non-null value. ( * is a special expression that is not evaluated, it simply returns the number of rows.)

There are two additional modifiers for the expression: ALL and DISTINCT. These determine whether duplicates are discarded. Since ALL is the default, your example is the same as count(ALL 1), which means that duplicates are retained.

Since the expression "1" evaluates to non-null for every row, and since you are not removing duplicates, COUNT(1) should always return the same number as COUNT(*).

Simple pthread! C++

You should declare the thread main as:

void* print_message(void*) // takes one parameter, unnamed if you aren't using it

Format an Excel column (or cell) as Text in C#?

Before your write to Excel need to change the format:

xlApp = New Excel.Application
xlWorkSheet = xlWorkBook.Sheets("Sheet1")

Dim cells As Excel.Range = xlWorkSheet.Cells

'set each cell's format to Text
cells.NumberFormat = "@"

'reset horizontal alignment to the right
cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignRight

How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?

Copy the diff file to the root of your repository, and then do:

git apply yourcoworkers.diff

More information about the apply command is available on its man page.

By the way: A better way to exchange whole commits by file is the combination of the commands git format-patch on the sender and then git am on the receiver, because it also transfers the authorship info and the commit message.

If the patch application fails and if the commits the diff was generated from are actually in your repo, you can use the -3 option of apply that tries to merge in the changes.

It also works with Unix pipe as follows:

git diff d892531 815a3b5 | git apply

How do I get the absolute directory of a file in bash?

Take a look at realpath which is available on GNU/Linux, FreeBSD and NetBSD, but not OpenBSD 6.8. I use something like:

CONTAININGDIR=$(realpath ${FILEPATH%/*})

to do what it sounds like you're trying to do.

Can we execute a java program without a main() method?

Now - no


Prior to Java 7:

Yes, sequence is as follows:

  • jvm loads class
  • executes static blocks
  • looks for main method and invokes it

So, if there's code in a static block, it will be executed. But there's no point in doing that.

How to test that:

public final class Test {
    static {
        System.out.println("FOO");
    }
}

Then if you try to run the class (either form command line with java Test or with an IDE), the result is:

FOO
java.lang.NoSuchMethodError: main

How do I create a multiline Python string with inline variables?

You can use Python 3.6's f-strings for variables inside multi-line or lengthy single-line strings. You can manually specify newline characters using \n.

Variables in a multi-line string

string1 = "go"
string2 = "now"
string3 = "great"

multiline_string = (f"I will {string1} there\n"
                    f"I will go {string2}.\n"
                    f"{string3}.")

print(multiline_string)

I will go there
I will go now
great

Variables in a lengthy single-line string

string1 = "go"
string2 = "now"
string3 = "great"

singleline_string = (f"I will {string1} there. "
                     f"I will go {string2}. "
                     f"{string3}.")

print(singleline_string)

I will go there. I will go now. great.


Alternatively, you can also create a multiline f-string with triple quotes.

multiline_string = f"""I will {string1} there.
I will go {string2}.
{string3}."""

Converting characters to integers in Java

Character.getNumericValue(c)

The java.lang.Character.getNumericValue(char ch) returns the int value that the specified Unicode character represents. For example, the character '\u216C' (the roman numeral fifty) will return an int with a value of 50.

The letters A-Z in their uppercase ('\u0041' through '\u005A'), lowercase ('\u0061' through '\u007A'), and full width variant ('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.

This method returns the numeric value of the character, as a nonnegative int value;

-2 if the character has a numeric value that is not a nonnegative integer;

-1 if the character has no numeric value.

And here is the link.

Make header and footer files to be included in multiple html pages

Aloha from 2018. Unfortunately, I don't have anything cool or futuristic to share with you.

I did however want to point out to those who have commented that the jQuery load() method isn't working in the present are probably trying to use the method with local files without running a local web server. Doing so will throw the above mentioned "cross origin" error, which specifies that cross origin requests such as that made by the load method are only supported for protocol schemes like http, data, or https. (I'm assuming that you're not making an actual cross-origin request, i.e the header.html file is actually on the same domain as the page you're requesting it from)

So, if the accepted answer above isn't working for you, please make sure you're running a web server. The quickest and simplest way to do that if you're in a rush (and using a Mac, which has Python pre-installed) would be to spin up a simple Python http server. You can see how easy it is to do that here.

I hope this helps!

How to detect online/offline event cross-browser?

In HTML5 you can use the navigator.onLine property. Look here:

http://www.w3.org/TR/offline-webapps/#related

Probably your current behavior is random as the javascript only ready the "browser" variable and then knows if you're offline and online, but it doesn't actually check the Network Connection.

Let us know if this is what you're looking for.

Kind Regards,

Uncaught TypeError: Cannot set property 'onclick' of null

Does document.getElementById("blue") exist? if it doesn't then blue_box will be equal to null. you can't set a onclick on something that's null

MS Excel showing the formula in a cell instead of the resulting value

I had the same problem and solved with below:

Range("A").Formula = Trim(CStr("the formula"))

How to $http Synchronous call with AngularJS

Not currently. If you look at the source code (from this point in time Oct 2012), you'll see that the call to XHR open is actually hard-coded to be asynchronous (the third parameter is true):

 xhr.open(method, url, true);

You'd need to write your own service that did synchronous calls. Generally that's not something you'll usually want to do because of the nature of JavaScript execution you'll end up blocking everything else.

... but.. if blocking everything else is actually desired, maybe you should look into promises and the $q service. It allows you to wait until a set of asynchronous actions are done, and then execute something once they're all complete. I don't know what your use case is, but that might be worth a look.

Outside of that, if you're going to roll your own, more information about how to make synchronous and asynchronous ajax calls can be found here.

I hope that is helpful.

PHP CURL DELETE request

To call GET,POST,DELETE,PUT All kind of request, i have created one common function

function CallAPI($method, $api, $data) {
    $url = "http://localhost:82/slimdemo/RESTAPI/" . $api;
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    switch ($method) {
        case "GET":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
            break;
        case "POST":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
            break;
        case "DELETE":
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); 
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            break;
    }
    $response = curl_exec($curl);
    $data = json_decode($response);

    /* Check for 404 (file not found). */
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    // Check the HTTP Status code
    switch ($httpCode) {
        case 200:
            $error_status = "200: Success";
            return ($data);
            break;
        case 404:
            $error_status = "404: API Not found";
            break;
        case 500:
            $error_status = "500: servers replied with an error.";
            break;
        case 502:
            $error_status = "502: servers may be down or being upgraded. Hopefully they'll be OK soon!";
            break;
        case 503:
            $error_status = "503: service unavailable. Hopefully they'll be OK soon!";
            break;
        default:
            $error_status = "Undocumented error: " . $httpCode . " : " . curl_error($curl);
            break;
    }
    curl_close($curl);
    echo $error_status;
    die;
}

CALL Delete Method

$data = array('id'=>$_GET['did']);
$result = CallAPI('DELETE', "DeleteCategory", $data);

CALL Post Method

$data = array('title'=>$_POST['txtcategory'],'description'=>$_POST['txtdesc']);
$result = CallAPI('POST', "InsertCategory", $data);

CALL Get Method

$data = array('id'=>$_GET['eid']);
$result = CallAPI('GET', "GetCategoryById", $data);

CALL Put Method

$data = array('id'=>$_REQUEST['eid'],m'title'=>$_REQUEST['txtcategory'],'description'=>$_REQUEST['txtdesc']);
$result = CallAPI('POST', "UpdateCategory", $data);

Disable time in bootstrap date time picker

Here's the solution for you. It's very easy to just add code like this:

    $('#datetimepicker4').datetimepicker({ 

    pickTime: false 

    minview:2;(Please see here.)

    }); 

Install IPA with iTunes 11

For osX Mavericks Users you can install the ipa-file with the Apple Configurator. (Instead of the iPhone configuration utility, which crashes on OSX 10.9)

Excel doesn't update value unless I hit Enter

Found the problem and couldn't find the solution until tried this.

  1. Open Visual Basic from Developer tab (OR right-click at any sheet and click 'View code')
  2. At upper left panel, select 'ThisWorkbook'
  3. At lower left panel, find 'ForceFullCalculation' attribute
  4. Change it from 'False' to 'True' and save it

I'm not sure if this has any side-effect, but it is work for me now.

Adding header for HttpURLConnection

I have used the following code in the past and it had worked with basic authentication enabled in TomCat:

URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();

String userCredentials = "username:password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));

myURLConnection.setRequestProperty ("Authorization", basicAuth);
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length);
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);

You can try the above code. The code above is for POST, and you can modify it for GET

Convert Text to Date?

You can use DateValue to convert your string to a date in this instance

Dim c As Range
For Each c In ActiveSheet.UsedRange.columns("A").Cells
    c.Value = DateValue(c.Value)
Next c

It can convert yyyy-mm-dd format string directly into a native Excel date value.

(SC) DeleteService FAILED 1072

For some buggy reason both Event Viewer and/or Services.msc won't do a proper refresh when you tell them to!

Close them and restart, and the service would have been deleted anyway.

How to transform array to comma separated words string?

Directly from the docs:

$comma_separated = implode(",", $array);

Using multiple .cpp files in c++ program?

You must use a tool called a "header". In a header you declare the function that you want to use. Then you include it in both files. A header is a separate file included using the #include directive. Then you may call the other function.

other.h

void MyFunc();

main.cpp

#include "other.h"
int main() {
    MyFunc();
}

other.cpp

#include "other.h"
#include <iostream>
void MyFunc() {
    std::cout << "Ohai from another .cpp file!";
    std::cin.get();
}

How to set Linux environment variables with Ansible

Here's a quick local task to permanently set key/values on /etc/environment (which is system-wide, all users):

- name: populate /etc/environment
  lineinfile:
    dest: "/etc/environment"
    state: present
    regexp: "^{{ item.key }}="
    line: "{{ item.key }}={{ item.value}}"
  with_items: "{{ os_environment }}"

and the vars for it:

os_environment:
  - key: DJANGO_SETTINGS_MODULE 
    value : websec.prod_settings  
  - key: DJANGO_SUPER_USER 
    value : admin

and, yes, if you ssh out and back in, env shows the new environment variables.

Responsive timeline UI with Bootstrap3

BootFlat

You can also try BootFlat, which has a section in their documentation specifically for crafting Timelines:

enter image description here

Java String new line

Platform-Independent Line Breaks

finalString = "physical" + System.lineSeparator() + "distancing";
System.out.println(finalString);

Output:

physical
distancing

Notes:
Java 6: System.getProperty("line.separator")
Java 7 & above: System.lineSeparator()

jQuery: Get the cursor position of text in input without browser specific code?

You can't do this without some browser specific code, since they implement text select ranged slightly differently. However, there are plugins that abstract this away. For exactly what you're after, there's the jQuery Caret (jCaret) plugin.

For your code to get the position you could do something like this:

$("#myTextInput").bind("keydown keypress mousemove", function() {
  alert("Current position: " + $(this).caret().start);
});

You can test it here.

How do you obtain a Drawable object from a resource id in android package?

As of API 21, you could also use:

   ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);

Instead of ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)

How do you change the value inside of a textfield flutter?

First Thing

  TextEditingController MyController= new TextEditingController();

Then add it to init State or in any SetState

    MyController.value = TextEditingValue(text: "ANY TEXT");

Initializing C dynamic arrays

You need to allocate a block of memory and use it as an array as:

int *arr = malloc (sizeof (int) * n); /* n is the length of the array */
int i;

for (i=0; i<n; i++)
{
  arr[i] = 0;
}

If you need to initialize the array with zeros you can also use the memset function from C standard library (declared in string.h).

memset (arr, 0, sizeof (int) * n);

Here 0 is the constant with which every locatoin of the array will be set. Note that the last argument is the number of bytes to be set the the constant. Because each location of the array stores an integer therefore we need to pass the total number of bytes as this parameter.

Also if you want to clear the array to zeros, then you may want to use calloc instead of malloc. calloc will return the memory block after setting the allocated byte locations to zero.

After you have finished, free the memory block free (arr).

EDIT1

Note that if you want to assign a particular integer in locations of an integer array using memset then it will be a problem. This is because memset will interpret the array as a byte array and assign the byte you have given, to every byte of the array. So if you want to store say 11243 in each location then it will not be possible.

EDIT2

Also note why every time setting an int array to 0 with memset may not work: Why does "memset(arr, -1, sizeof(arr)/sizeof(int))" not clear an integer array to -1? as pointed out by @Shafik Yaghmour

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

I got this error, while using it on my rocketchat to communicate with my gitlab via enterprise proxy,

Because, was using the https://:8080 but actually, it worked for http://:8080

if statement checks for null but still throws a NullPointerException

The problem is that you are using the bitwise or operator: |. If you use the logical or operator, ||, your code will work fine.

See also:
http://en.wikipedia.org/wiki/Short-circuit_evaluation
Difference between & and && in Java?

JQuery Find #ID, RemoveClass and AddClass

.....

$("#testID #testID2").removeClass("test2").addClass("test3");

Because you have assigned an id to img too, you can simply do this too:

$("#testID2").removeClass("test2").addClass("test3");

And finally, you can do this too:

$("#testID img").removeClass("test2").addClass("test3");

Why can't I use a list as a dict key in python?

There's a good article on the topic in the Python wiki: Why Lists Can't Be Dictionary Keys. As explained there:

What would go wrong if you tried to use lists as keys, with the hash as, say, their memory location?

It can be done without really breaking any of the requirements, but it leads to unexpected behavior. Lists are generally treated as if their value was derived from their content's values, for instance when checking (in-)equality. Many would - understandably - expect that you can use any list [1, 2] to get the same key, where you'd have to keep around exactly the same list object. But lookup by value breaks as soon as a list used as key is modified, and for lookup by identity requires you to keep around exactly the same list - which isn't requires for any other common list operation (at least none I can think of).

Other objects such as modules and object make a much bigger deal out of their object identity anyway (when was the last time you had two distinct module objects called sys?), and are compared by that anyway. Therefore, it's less surprising - or even expected - that they, when used as dict keys, compare by identity in that case as well.

How to change button background image on mouseOver?

You can create a class based on a Button with specific images for MouseHover and MouseDown like this:

public class AdvancedImageButton : Button {

public Image HoverImage { get; set; }
public Image PlainImage { get; set; }
public Image PressedImage { get; set; }

protected override void OnMouseEnter(System.EventArgs e)
{
  base.OnMouseEnter(e);
  if (HoverImage == null) return;
  if (PlainImage == null) PlainImage = base.Image;
  base.Image = HoverImage;
}

protected override void OnMouseLeave(System.EventArgs e)
{
  base.OnMouseLeave(e);
  if (HoverImage == null) return;
  base.Image = PlainImage;
}

protected override void OnMouseDown(MouseEventArgs e)
{
  base.OnMouseDown(e);
  if (PressedImage == null) return;
  if (PlainImage == null) PlainImage = base.Image;
  base.Image = PressedImage;
}

}

This solution has a small drawback that I am sure can be fixed: when you need for some reason change the Image property, you will also have to change the PlainImage property also.

How do I clear a C++ array?

std::fill(a.begin(),a.end(),0);

PHP - remove <img> tag from string

Sean it works fine i've just used this code

$content = preg_replace("/<img[^>]+\>/i", " ", $content); 
echo $content;

//the result it's only the plain text. It works!!!

Unzip All Files In A Directory

To unzip all files in a directory just type this cmd in terminal:

unzip '*.zip'

Don't reload application when orientation changes

I dont know if the a best solution, but i describe it here:

First of all, you need certificate with you class Application of your app is in your manifest of this:

<application
    android:name=".App"
    ...

Second, in my class App i did like this:

public class App extends Application {
    public static boolean isOrientationChanged = false;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onConfigurationChanged(@NotNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ||
                newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            isOrientationChanged = true;
        }
    }

}

Third, you need to set a flag to Orientation Change, in my case, I always set it when the previous activity within the app navigation is called, so only calling once when the later activity is created.

isOrientationChanged = false;

So every time I change the orientation of my screen in that context, I set it every time it changes this setting, it checks if there is a change in orientation, if so, it validates it based on the value of that flag.

Basically, I had to use it whenever I made an asynchronous retrofit request, which he called every moment that changed orientation, constantly crashing the application:

if (!isOrientationChanged) {
    presenter.retrieveAddress(this, idClient, TYPE_ADDRESS);
}

I don't know if it's the most elegant and beautiful solution, but at least here it's functional :)

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

On macos Sierra this work for me, where python is managed by anaconda:

anaconda search -t conda mysql-python

anaconda show CEFCA/mysql-python

conda install --channel https://conda.anaconda.org/CEFCA mysql-python

The to use with SQLAlchemy:

Python 2.7.13 |Continuum Analytics, Inc.| (default, Dec 20 2016, 23:05:08) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. Anaconda is brought to you by Continuum Analytics. Please check out: http://continuum.io/thanks and https://anaconda.org

>>> from sqlalchemy import *

>>>dbengine = create_engine('mysql://....')

Concat a string to SELECT * MySql

If you want to concatenate the fields using / as a separator, you can use concat_ws:

select concat_ws('/', col1, col2, col3) from mytable

You cannot escape listing the columns in the query though. The *-syntax works only in "select * from". You can list the columns and construct the query dynamically though.

Efficient way to return a std::vector in c++

It's time I post an answer about RVO, me too...

If you return an object by value, the compiler often optimizes this so it doesn't get constructed twice, since it's superfluous to construct it in the function as a temporary and then copy it. This is called return value optimization: the created object will be moved instead of being copied.

How to compare two colors for similarity/difference

The best way is deltaE. DeltaE is a number that shows the difference of the colors. If deltae < 1 then the difference can't recognize by human eyes. I wrote a code in canvas and js for converting rgb to lab and then calculating delta e. On this example the code is recognising pixels which have different color with a base color that I saved as LAB1. and then if it is different makes those pixels red. You can increase or reduce the sensitivity of the color difference with increae or decrease the acceptable range of delta e. In this example I assigned 10 for deltaE in the line that I wrote (deltae <= 10):

<script>   
  var constants = {
    canvasWidth: 700, // In pixels.
    canvasHeight: 600, // In pixels.
    colorMap: new Array() 
          };



  // -----------------------------------------------------------------------------------------------------

  function fillcolormap(imageObj1) {


    function rgbtoxyz(red1,green1,blue1){ // a converter for converting rgb model to xyz model
 var red2 = red1/255;
 var green2 = green1/255;
 var blue2 = blue1/255;
 if(red2>0.04045){
      red2 = (red2+0.055)/1.055;
      red2 = Math.pow(red2,2.4);
 }
 else{
      red2 = red2/12.92;
 }
 if(green2>0.04045){
      green2 = (green2+0.055)/1.055;
      green2 = Math.pow(green2,2.4);    
 }
 else{
      green2 = green2/12.92;
 }
 if(blue2>0.04045){
      blue2 = (blue2+0.055)/1.055;
      blue2 = Math.pow(blue2,2.4);    
 }
 else{
      blue2 = blue2/12.92;
 }
 red2 = (red2*100);
 green2 = (green2*100);
 blue2 = (blue2*100);
 var x = (red2 * 0.4124) + (green2 * 0.3576) + (blue2 * 0.1805);
 var y = (red2 * 0.2126) + (green2 * 0.7152) + (blue2 * 0.0722);
 var z = (red2 * 0.0193) + (green2 * 0.1192) + (blue2 * 0.9505);
 var xyzresult = new Array();
 xyzresult[0] = x;
 xyzresult[1] = y;
 xyzresult[2] = z;
 return(xyzresult);
} //end of rgb_to_xyz function
function xyztolab(xyz){ //a convertor from xyz to lab model
 var x = xyz[0];
 var y = xyz[1];
 var z = xyz[2];
 var x2 = x/95.047;
 var y2 = y/100;
 var z2 = z/108.883;
 if(x2>0.008856){
      x2 = Math.pow(x2,1/3);
 }
 else{
      x2 = (7.787*x2) + (16/116);
 }
 if(y2>0.008856){
      y2 = Math.pow(y2,1/3);
 }
 else{
      y2 = (7.787*y2) + (16/116);
 }
 if(z2>0.008856){
      z2 = Math.pow(z2,1/3);
 }
 else{
      z2 = (7.787*z2) + (16/116);
 }
 var l= 116*y2 - 16;
 var a= 500*(x2-y2);
 var b= 200*(y2-z2);
 var labresult = new Array();
 labresult[0] = l;
 labresult[1] = a;
 labresult[2] = b;
 return(labresult);

}

    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    var imageX = 0;
    var imageY = 0;

    context.drawImage(imageObj1, imageX, imageY, 240, 140);
    var imageData = context.getImageData(0, 0, 240, 140);
    var data = imageData.data;
    var n = data.length;
   // iterate over all pixels

    var m = 0;
    for (var i = 0; i < n; i += 4) {
      var red = data[i];
      var green = data[i + 1];
      var blue = data[i + 2];
    var xyzcolor = new Array();
    xyzcolor = rgbtoxyz(red,green,blue);
    var lab = new Array();
    lab = xyztolab(xyzcolor);
    constants.colorMap.push(lab); //fill up the colormap array with lab colors.         
      } 

  }

// -----------------------------------------------------------------------------------------------------

    function colorize(pixqty) {

         function deltae94(lab1,lab2){    //calculating Delta E 1994

         var c1 = Math.sqrt((lab1[1]*lab1[1])+(lab1[2]*lab1[2]));
         var c2 =  Math.sqrt((lab2[1]*lab2[1])+(lab2[2]*lab2[2]));
         var dc = c1-c2;
         var dl = lab1[0]-lab2[0];
         var da = lab1[1]-lab2[1];
         var db = lab1[2]-lab2[2];
         var dh = Math.sqrt((da*da)+(db*db)-(dc*dc));
         var first = dl;
         var second = dc/(1+(0.045*c1));
         var third = dh/(1+(0.015*c1));
         var deresult = Math.sqrt((first*first)+(second*second)+(third*third));
         return(deresult);
          } // end of deltae94 function
    var lab11 =  new Array("80","-4","21");
    var lab12 = new Array();
    var k2=0;
    var canvas = document.getElementById('myCanvas');
                                        var context = canvas.getContext('2d');
                                        var imageData = context.getImageData(0, 0, 240, 140);
                                        var data = imageData.data;

    for (var i=0; i<pixqty; i++) {

    lab12 = constants.colorMap[i];

    var deltae = deltae94(lab11,lab12);     
                                        if (deltae <= 10) {

                                        data[i*4] = 255;
                                        data[(i*4)+1] = 0;
                                        data[(i*4)+2] = 0;  
                                        k2++;
                                        } // end of if 
                                } //end of for loop
    context.clearRect(0,0,240,140);
    alert(k2);
    context.putImageData(imageData,0,0);
} 
// -----------------------------------------------------------------------------------------------------

$(window).load(function () {    
  var imageObj = new Image();
  imageObj.onload = function() {
  fillcolormap(imageObj);    
  }
  imageObj.src = './mixcolor.png';
});

// ---------------------------------------------------------------------------------------------------
 var pixno2 = 240*140; 
 </script>

How to include clean target in Makefile?

By the way it is written, clean rule is invoked only if it is explicitly called:

make clean

I think it is better, than make clean every time. If you want to do this by your way, try this:

CXX = g++ -O2 -Wall

all: clean code1 code2

code1: code1.cc utilities.cc
   $(CXX) $^ -o $@

code2: code2.cc utilities.cc
   $(CXX) $^ -o $@

clean: 
    rm ...
    echo Clean done

React-router urls don't work when refreshing or writing manually

As I am using .Net Core MVC something like this helped me:

    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            var url = Request.Path + Request.QueryString;
            return App(url);
        }

        [Route("App")]
        public IActionResult App(string url)
        {
            return View("/wwwroot/app/build/index.html");
        }
   }

Basically in MVC side, all the routes not matching will fall into to Home/Index as it specified in startup.cs. Inside Index it is possible to get the original request url and pass it wherever needed.

startup.cs

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");

            routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "Home", action = "Index" });
        });

How to escape single quotes within single quoted strings

I'm not specifically addressing the quoting issue because, well, sometimes, it's just reasonable to consider an alternative approach.

rxvt() { urxvt -fg "#${1:-000000}" -bg "#${2:-FFFFFF}"; }

which you can then call as:

rxvt 123456 654321

the idea being that you can now alias this without concern for quotes:

alias rxvt='rxvt 123456 654321'

or, if you need to include the # in all calls for some reason:

rxvt() { urxvt -fg "${1:-#000000}" -bg "${2:-#FFFFFF}"; }

which you can then call as:

rxvt '#123456' '#654321'

then, of course, an alias is:

alias rxvt="rxvt '#123456' '#654321'"

(oops, i guess i kind of did address the quoting :)

Oracle - How to create a readonly user

you can create user and grant privilege

create user read_only identified by read_only; grant create session,select any table to read_only;

What does Maven do, in theory and in practice? When is it worth to use it?

Maven is a build tool. Along with Ant or Gradle are Javas tools for building.
If you are a newbie in Java though just build using your IDE since Maven has a steep learning curve.

What's the difference between django OneToOneField and ForeignKey?

ForeignKey allows you receive subclasses is it definition of another class but OneToOneFields cannot do this and it is not attachable to multiple variables

How to use a findBy method with comparative criteria

$criteria = new \Doctrine\Common\Collections\Criteria();
    $criteria->where($criteria->expr()->gt('id', 'id'))
        ->setMaxResults(1)
        ->orderBy(array("id" => $criteria::DESC));

$results = $articlesRepo->matching($criteria);

Find text string using jQuery?

Take a look at highlight (jQuery plugin).

How do I set ANDROID_SDK_HOME environment variable?

Just set the path to the Android SDK directory

flutter config --android-sdk c:\android\sdk

Why use deflate instead of gzip for text files served by Apache?

GZip is simply deflate plus a checksum and header/footer. Deflate is faster, though, as I learned the hard way.

gzip vs deflate graph

Move div to new line

Try this

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

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

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

.movie_item_content_title {
    display: block;
}

.movie_item_content_year {
    float: right;
}

.movie_item_content_plot {
    display: block;

}

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

In Html

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

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

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

I change position div year.

How do I download code using SVN/Tortoise from Google Code?

Select Tortoise SVN - > Settings - > NetWork

Fill the required proxy if any and then check.

NodeJS - Error installing with NPM

As commented below you may not need to install VS on windows, check this out

https://github.com/nodejs/node-gyp/issues/629#issuecomment-153196245

UPDATED 02/2016

Some npm plugins need node-gyp to be installed.

However, node-gyp has it's own dependencies (from the github page):

enter image description here

UPDATED 09/2016

If you're using Windows you can now install all node-gyp dependencies with single command (NOTE: Run As Admin in Windows PowerShell):

 $ npm install --global --production windows-build-tools

and then install the package

 $ npm install --global node-gyp

UPDATED 06/2018

https://github.com/nodejs/node-gyp/issues/809#issuecomment-155019383

Delete your $HOME/.node-gyp directory and try again.

See full documentation here: node-gyp

Inserting line breaks into PDF

After having so many nightmares, I found a solution.

utf8_decode(chr(10))

I tried \n, <br/> and chr(10) but nothing worked. Then I realized that it was utf-8 and just tried the above one. It works fine with MultiCell but not with Cell.

Repeating a function every few seconds

There are lot of different Timers in the .NET BCL:

When to use which?

  • System.Timers.Timer, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Windows.Forms.Timer (.NET Framework only), a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment; it executes on the UI thread.
  • System.Web.UI.Timer (.NET Framework only), an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.
  • System.Windows.Threading.DispatcherTimer, a timer that's integrated into the Dispatcher queue. This timer is processed with a specified priority at a specified time interval.

Source


Some of them needs explicit Start call to begin ticking (for example System.Timers, System.Windows.Forms). And an explicit Stop to finish ticking.

using TimersTimer = System.Timers.Timer;

static void Main(string[] args)
{
    var timer = new TimersTimer(1000);
    timer.Elapsed += (s, e) => Console.WriteLine("Beep");
    Thread.Sleep(1000); //1 second delay
    timer.Start();
    Console.ReadLine();
    timer.Stop();

}

While on the other hand there are some Timers (like: System.Threading) where you don't need explicit Start and Stop calls. (The provided delegate will run a background thread.) Your timer will tick until you or the runtime dispose it.

So, the following two versions will work in the same way:

using ThreadingTimer = System.Threading.Timer;

static void Main(string[] args)
{
    var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
    Console.ReadLine();
}
using ThreadingTimer = System.Threading.Timer;
static void Main(string[] args)
{
    StartTimer();
    Console.ReadLine();
}

static void StartTimer()
{
    var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}

But if your timer disposed then it will stop ticking obviously.

using ThreadingTimer = System.Threading.Timer; 

static void Main(string[] args)
{
    StartTimer();
    GC.Collect(0);
    Console.ReadLine();
}

static void StartTimer()
{
    var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}

How do I set a Windows scheduled task to run in the background?

As noted by Mattias Nordqvist in the comments below, you can also select the radio button option "Run whether user is logged on or not". When saving the task, you will be prompted once for the user password. bambams noted that this wouldn't grant System permissions to the process, and also seems to hide the command window.


It's not an obvious solution, but to make a Scheduled Task run in the background, change the User running the task to "SYSTEM", and nothing will appear on your screen.

enter image description here

enter image description here

enter image description here

Byte Array and Int conversion in Java

I took a long look at many questions like this, and found this post... I didn't like the fact that the conversion code is duplicated for each type, so I've made a generic method to perform the task:

public static byte[] toByteArray(long value, int n)
{
    byte[] ret = new byte[n];
    ret[n-1] = (byte) ((value >> (0*8) & 0xFF);   
    ret[n-2] = (byte) ((value >> (1*8) & 0xFF);   
    ...
    ret[1] = (byte) ((value >> ((n-2)*8) & 0xFF);   
    ret[0] = (byte) ((value >> ((n-1)*8) & 0xFF);   
    return ret;
}

See full post.

How to elegantly check if a number is within a range?

Regarding elegance, the closest thing to the mathematical notation (a <= x <= b) slightly improves readability:

public static bool IsBetween(this int value, int min, int max)
{
    return min <= value && value <= max;
}

For further illustration:

public static bool IsOutside(this int value, int min, int max)
{
    return value < min || max < value;
}

.NET End vs Form.Close() vs Application.Exit Cleaner way to close one's app

The situation you describe is pretty fishy. Whenever you close your program's startup form, the entire application should quit automatically, including closing all other open forms. Make sure that you're closing the correct form, and you should not experience any problems.

The other possibility is that you've changed your project (using its Properties page) not to close until all open windows have been closed. In this mode, your application will not exit until the last remaining open form has been closed. If you've chosen this setting, you have to make sure that you call the Close method of all forms that you've shown during the course of application, not just the startup/main form.

The first setting is the default for a reason, and if you've changed it, you probably want to go fix it back.
It is by far the most intuitive model for normal applications, and it prevents exactly the situation you describe. For it to work properly, make sure that you have specified your main form as the "Startup form" (rather than a splash screen or log-in form).

The settings I'm talking about are highlighted here:

   Visual Studio Project Properties

But primarily, note that you should never have to call Application.Exit in a properly-designed application. If you find yourself having to do this in order for your program to close completely, then you are doing something wrong. Doing it is not a bad practice in itself, as long as you have a good reason. The other two answers fail to explain that, and thus I feel are incomplete at best.

How do I check out an SVN project into Eclipse as a Java project?

Here are the steps:

  • Install the subclipse plugin (provides svn connectivity in eclipse) and connect to the repository. Instructions here: http://subclipse.tigris.org/install.html
  • Go to File->New->Other->Under the SVN category, select Checkout Projects from SVN.
  • Select your project's root folder and select checkout as a project in the workspace.

It seems you are checking the .project file into the source repository. I would suggest not checking in the .project file so users can have their own version of the file. Also, if you use the subclipse plugin it allows you to check out and configure a source folder as a java project. This process creates the correct .project for you(with the java nature),

How to restrict SSH users to a predefined set of commands after login?

You should acquire `rssh', the restricted shell

You can follow the restriction guides mentioned above, they're all rather self-explanatory, and simple to follow. Understand the terms `chroot jail', and how to effectively implement sshd/terminal configurations, and so on.

Being as most of your users access your terminals via sshd, you should also probably look into sshd_conifg, the SSH daemon configuration file, to apply certain restrictions via SSH. Be careful, however. Understand properly what you try to implement, for the ramifications of incorrect configurations are probably rather dire.

Composer: file_put_contents(./composer.json): failed to open stream: Permission denied

This might be super edge case, but if you are using Travis CI and taking advantage of caching, you might want to clear all cache and retry.

Fixed my issue when I was going from sudo to non sudo builds.

How to parse string into date?

Although the CONVERT thing works, you actually shouldn't use it. You should ask yourself why you are parsing string values in SQL-Server. If this is a one-time job where you are manually fixing some data you won't get that data another time, this is ok, but if any application is using this, you should change something. Best way would be to use the "date" data type. If this is user input, this is even worse. Then you should first do some checking in the client. If you really want to pass string values where SQL-Server expects a date, you can always use ISO format ('YYYYMMDD') and it should convert automatically.

Assign output to variable in Bash

In shell, you don't put a $ in front of a variable you're assigning. You only use $IP when you're referring to the variable.

#!/bin/bash

IP=$(curl automation.whatismyip.com/n09230945.asp)

echo "$IP"

sed "s/IP/$IP/" nsupdate.txt | nsupdate

Creating a system overlay window (always on top)

TYPE_SYSTEM_OVERLAY This constant was deprecated in since API level 26. Use TYPE_APPLICATION_OVERLAY instead. or **for users below and above android 8

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
    LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_PHONE;
}

How do I make a https post in Node Js without any third party module?

For example, like this:

const querystring = require('querystring');
const https = require('https');

var postData = querystring.stringify({
    'msg' : 'Hello World!'
});

var options = {
  hostname: 'posttestserver.com',
  port: 443,
  path: '/post.php',
  method: 'POST',
  headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
       'Content-Length': postData.length
     }
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});

req.write(postData);
req.end();

How can I start an Activity from a non-Activity class?

Your onTap override receives the MapView from which you can obtain the Context:

@Override
public boolean onTap(GeoPoint p, MapView mapView)
{
    // ...

    Intent intent = new Intent();
    intent.setClass(mapView.getContext(), FullscreenView.class);
    startActivity(intent);

    // ...
}

Difference between SelectedItem, SelectedValue and SelectedValuePath

inspired by this question I have written a blog along with the code snippet here. Below are some of the excerpts from the blog

SelectedItem – Selected Item helps to bind the actual value from the DataSource which will be displayed. This is of type object and we can bind any type derived from object type with this property. Since we will be using the MVVM binding for our combo boxes in that case this is the property which we can use to notify VM that item has been selected.

SelectedValue and SelectedValuePath – These are the two most confusing and misinterpreted properties for combobox. But these properties come to rescue when we want to bind our combobox with the value from already created object. Please check my last scenario in the following list to get a brief idea about the properties.

How do we determine the number of days for a given month in python

Use calendar.monthrange:

>>> from calendar import monthrange
>>> monthrange(2011, 2)
(1, 28)

Just to be clear, monthrange supports leap years as well:

>>> from calendar import monthrange
>>> monthrange(2012, 2)
(2, 29)

As @mikhail-pyrev mentions in a comment:

First number is weekday of first day of the month, second number is number of days in said month.

Create table in SQLite only if it doesn't exist already

From http://www.sqlite.org/lang_createtable.html:

CREATE TABLE IF NOT EXISTS some_table (id INTEGER PRIMARY KEY AUTOINCREMENT, ...);

Windows 7, 64 bit, DLL problems

I just resolved the same problem with C++ Qt 5 and Windows 7 64 bits with MSCVC 2012.

In the beginning I thought it was a MSVC/Windows DLL file problem, but as BorisP said, the problem was in my project dependencies. The key is "How to know your project dependencies in Qt 5?".

As I didn't find any clear way to know it (Dependency Walker didn't help me a lot...), I followed next the "inverse procedure" that takes no more than 5 minutes and avoid a lot of headaches with DLL file dependencies:

  1. Compile your project and take the executable file to an empty folder: myproject.exe
  2. Try to execute it, It will retrieve an error (missing DLL files...).
  3. Now, copy all the DLL files from Qt (in my case they were in C:\Qt\Qt5.1.1\5.1.1\msvc2012_64_opengl\bin) to this folder.
  4. Try to execute again, it will probably works fine.
  5. Start to delete progressively and try every time your executable still works, trying to leave the minimum necessary DLL files.

When you have all the DLL files in the same folder it is easier to find which of them are not valid (XML, WebKit, ... whatever..), and consequently this method doesn't take more than five minutes.

Why doesn't file_get_contents work?

If PHP's allow_url_fopen ini directive is set to true, and if curl doesn't work either (see this answer for an example of how to use it instead of file_get_contents), then the problem could be that your server has a firewall preventing scripts from getting the contents of arbitrary urls (which could potentially allow malicious code to fetch things).

I had this problem, and found that the solution for me was to edit the firewall settings to explicitly allow requests to the domain (or IP address) in question.

Safe Area of Xcode 9

I want to mention something that caught me first when I was trying to adapt a SpriteKit-based app to avoid the round edges and "notch" of the new iPhone X, as suggested by the latest Human Interface Guidelines: The new property safeAreaLayoutGuide of UIView needs to be queried after the view has been added to the hierarchy (for example, on -viewDidAppear:) in order to report a meaningful layout frame (otherwise, it just returns the full screen size).

From the property's documentation:

The layout guide representing the portion of your view that is unobscured by bars and other content. When the view is visible onscreen, this guide reflects the portion of the view that is not covered by navigation bars, tab bars, toolbars, and other ancestor views. (In tvOS, the safe area reflects the area not covered the screen's bezel.) If the view is not currently installed in a view hierarchy, or is not yet visible onscreen, the layout guide edges are equal to the edges of the view.

(emphasis mine)

If you read it as early as -viewDidLoad:, the layoutFrame of the guide will be {{0, 0}, {375, 812}} instead of the expected {{0, 44}, {375, 734}}

Trim leading and trailing spaces from a string in awk

just use a regex as a separator:

', *' - for leading spaces

' *,' - for trailing spaces

for both leading and trailing:

awk -F' *,? *' '{print $1","$2}' input.txt

Using Java with Microsoft Visual Studio 2012

theoretically it could be done by defining a custom build step to the VS project. And you can make a file template to create a new java file, don't know if you could have it throw things in the right package or not, so you may end up writing quite a bit of the stuff a java ide would throw in already. it's not impossible, but from experience (I've used xcode on mac, vs in windows, eclipse, netbeans, code::blocks, and ended up compiling from command line for both java and c++ a lot) it's easier just to learn the new ide.

if you are insistent, i found this: http://improve.dk/compiling-java-in-visual-studio/

i plan on following and trying to modify it to create a general template for java

if possible (meaning if i understand enough of what im doing) im goint to implement a custom wizard for java projects and files.

Converting ISO 8601-compliant String to java.util.Date

java.time

Note that in Java 8, you can use the java.time.ZonedDateTime class and its static parse(CharSequence text) method.

Uncaught TypeError: Cannot read property 'length' of undefined

You are not passing the variable correctly. One fast solution is to make a global variable like this:

var global_json_data;
$(document).ready(function() {
    var json_source = "https://spreadsheets.google.com/feeds/list/0ApL1zT2P00q5dG1wOUMzSlNVV3VRV2pwQ2Fnbmt3M0E/od7/public/basic?alt=json";
    var string_data ="";
    var json_data = $.ajax({
        dataType: 'json', // Return JSON
        url: json_source,
        success: function(data){
            var data_obj = [];
            for (i=0; i<data.feed.entry.length; i++){
                var el = {'key': data.feed.entry[i].title['$t'], 'value': '<p><a href="'+data.feed.entry[i].content['$t']+'>'+data.feed.entry[i].title['$t']+'</a></p>'};
                data_obj.push(el)};

            console.log("data grabbed");  
            global_json_data =   data_obj;

            return data_obj;


        },      

        error: function(jqXHR, textStatus, errorThrown){ 
                        $('#results_box').html('<h2>Something went wrong!</h2><p><b>' + textStatus  + '</b> ' + errorThrown  + '</p>');
        }
    }); 

    $(':submit').click(function(event){
        var json_data = global_json_data;
        event.preventDefault();
        console.log(json_data.length);

        //function
        if ($('#place').val() !=''){
            var copy_string = $('#place').val();
            var converted_string = copy_string;
            for (i=0; i<json_data.length; i++){
                //console_log(data.feed.entry[i].title['$t']);
                converted_string = converted_string.replace(json_data.feed.entry[i].title['$t'], 
                    '<a href="'+json_data.feed.entry[i].content['$t']+'>'+json_data.feed.entry[i].title['$t']+'</a>');
            }  
            $('#results_box').text(converted_string).html();
        }
    });

});//document ready end 

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

It's possible that you're creating your controls on the wrong thread. Consider the following documentation from MSDN:

This means that InvokeRequired can return false if Invoke is not required (the call occurs on the same thread), or if the control was created on a different thread but the control's handle has not yet been created.

In the case where the control's handle has not yet been created, you should not simply call properties, methods, or events on the control. This might cause the control's handle to be created on the background thread, isolating the control on a thread without a message pump and making the application unstable.

You can protect against this case by also checking the value of IsHandleCreated when InvokeRequired returns false on a background thread. If the control handle has not yet been created, you must wait until it has been created before calling Invoke or BeginInvoke. Typically, this happens only if a background thread is created in the constructor of the primary form for the application (as in Application.Run(new MainForm()), before the form has been shown or Application.Run has been called.

Let's see what this means for you. (This would be easier to reason about if we saw your implementation of SafeInvoke also)

Assuming your implementation is identical to the referenced one with the exception of the check against IsHandleCreated, let's follow the logic:

public static void SafeInvoke(this Control uiElement, Action updater, bool forceSynchronous)
{
    if (uiElement == null)
    {
        throw new ArgumentNullException("uiElement");
    }

    if (uiElement.InvokeRequired)
    {
        if (forceSynchronous)
        {
            uiElement.Invoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
        }
        else
        {
            uiElement.BeginInvoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
        }
    }
    else
    {    
        if (uiElement.IsDisposed)
        {
            throw new ObjectDisposedException("Control is already disposed.");
        }

        updater();
    }
}

Consider the case where we're calling SafeInvoke from the non-gui thread for a control whose handle has not been created.

uiElement is not null, so we check uiElement.InvokeRequired. Per the MSDN docs (bolded) InvokeRequired will return false because, even though it was created on a different thread, the handle hasn't been created! This sends us to the else condition where we check IsDisposed or immediately proceed to call the submitted action... from the background thread!

At this point, all bets are off re: that control because its handle has been created on a thread that doesn't have a message pump for it, as mentioned in the second paragraph. Perhaps this is the case you're encountering?

How to check if a query string value is present via JavaScript?

one more variant, but almost the same as Gumbos solution:

var isDebug = function(){
    return window.location.href.search("[?&]debug=") != -1;
};

How to pass prepareForSegue: an object

I have a sender class, like this

@class MyEntry;

@interface MySenderEntry : NSObject
@property (strong, nonatomic) MyEntry *entry;
@end

@implementation MySenderEntry
@end

I use this sender class for passing objects to prepareForSeque:sender:

-(void)didSelectItemAtIndexPath:(NSIndexPath*)indexPath
{
    MySenderEntry *sender = [MySenderEntry new];
    sender.entry = [_entries objectAtIndex:indexPath.row];
    [self performSegueWithIdentifier:SEGUE_IDENTIFIER_SHOW_ENTRY sender:sender];
}

-(void)prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:SEGUE_IDENTIFIER_SHOW_ENTRY]) {
        NSAssert([sender isKindOfClass:[MySenderEntry class]], @"MySenderEntry");
        MySenderEntry *senderEntry = (MySenderEntry*)sender;
        MyEntry *entry = senderEntry.entry;
        NSParameterAssert(entry);

        [segue destinationViewController].delegate = self;
        [segue destinationViewController].entry = entry;
        return;
    }

    if ([[segue identifier] isEqualToString:SEGUE_IDENTIFIER_HISTORY]) {
        // ...
        return;
    }

    if ([[segue identifier] isEqualToString:SEGUE_IDENTIFIER_FAVORITE]) {
        // ...
        return;
    }
}

Why is my Git Submodule HEAD detached from master?

Adding a branch option in .gitmodule is NOT related to the detached behavior of submodules at all. The old answer from @mkungla is incorrect, or obsolete.

From git submodule --help, HEAD detached is the default behavior of git submodule update --remote.

First, there's no need to specify a branch to be tracked. origin/master is the default branch to be tracked.

--remote

Instead of using the superproject's recorded SHA-1 to update the submodule, use the status of the submodule's remote-tracking branch. The remote used is branch's remote (branch.<name>.remote), defaulting to origin. The remote branch used defaults to master.

Why

So why is HEAD detached after update? This is caused by the default module update behavior: checkout.

--checkout

Checkout the commit recorded in the superproject on a detached HEAD in the submodule. This is the default behavior, the main use of this option is to override submodule.$name.update when set to a value other than checkout.

To explain this weird update behavior, we need to understand how do submodules work?

Quote from Starting with Submodules in book Pro Git

Although sbmodule DbConnector is a subdirectory in your working directory, Git sees it as a submodule and doesn’t track its contents when you’re not in that directory. Instead, Git sees it as a particular commit from that repository.

The main repo tracks the submodule with its state at a specific point, the commit id. So when you update modules, you're updating the commit id to a new one.

How

If you want the submodule merged with remote branch automatically, use --merge or --rebase.

--merge

This option is only valid for the update command. Merge the commit recorded in the superproject into the current branch of the submodule. If this option is given, the submodule's HEAD will not be detached.

--rebase

Rebase the current branch onto the commit recorded in the superproject. If this option is given, the submodule's HEAD will not be detached.

All you need to do is,

git submodule update --remote --merge
# or
git submodule update --remote --rebase

Recommended alias:

git config alias.supdate 'submodule update --remote --merge'

# do submodule update with
git supdate

There's also an option to make --merge or --rebase as the default behavior of git submodule update, by setting submodule.$name.update to merge or rebase.

Here's an example about how to config the default update behavior of submodule update in .gitmodule.

[submodule "bash/plugins/dircolors-solarized"]
    path = bash/plugins/dircolors-solarized
    url = https://github.com/seebi/dircolors-solarized.git
    update = merge # <-- this is what you need to add

Or configure it in command line,

# replace $name with a real submodule name
git config -f .gitmodules submodule.$name.update merge

References

Upgrading React version and it's dependencies by reading package.json

I highly recommend using yarn upgrade-interactive to update React, or any Node project for that matter. It lists your packages, current version, the latest version, an indication of a Minor, Major, or Patch update compared to what you have, plus a link to the respective project.

You run it with yarn upgrade-interactive --latest, check out release notes if you want, go down the list with your arrow keys, choose which packages you want to upgrade by selecting with the space bar, and hit Enter to complete.

Npm-upgrade is ok but not as slick.

Is there a CSS selector for text nodes?

Text nodes cannot have margins or any other style applied to them, so anything you need style applied to must be in an element. If you want some of the text inside of your element to be styled differently, wrap it in a span or div, for example.

How to differ sessions in browser-tabs?

I see many implementations which have client side changes to manipulate session id cookies. But in general session id cookies should be HttpOnly so java-script cannot access otherwise it may lead to Session Hijack thru XSS

How to do HTTP authentication in android?

For my Android projects I've used the Base64 library from here:

http://iharder.net/base64

It's a very extensive library and so far I've had no problems with it.

Code for printf function in C

Here's the GNU version of printf... you can see it passing in stdout to vfprintf:

__printf (const char *format, ...)
{
   va_list arg;
   int done;

   va_start (arg, format);
   done = vfprintf (stdout, format, arg);
   va_end (arg);

   return done;
}

See here.

Here's a link to vfprintf... all the formatting 'magic' happens here.

The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)

how to set active class to nav menu from twitter bootstrap

You could add a diffrent class onto the BODY tag on each page e.g. on the homepage you could have this:

<body class="nav-1-on">

Then this css:

.nav-1-on .nav-1 a, .nav-2-on .nav-2 a, .nav-3-on .nav-3 a, .nav-4-on .nav-4 a {
     // set your styles here
}

The NAV element:

<ul>
  <li class="nav-1"><a href="#">Home</a></li>
  <li class="nav-2"><a href="#">Services</a></li>
  <li class="nav-3"><a href="#">About</a></li>
  <li class="nav-4"><a href="#">Contact</a></li>
</ul>
#

Alternatively you could place a class on the BODY on each page and then grab that via jQuery and add the .active class to the correct nav item based on that tag.

Appending a line break to an output file in a shell script

Try

echo -en "`date` User `whoami` started the script.\n" >> output.log

Try issuing this multiple times. I hope you are looking for the same output.

How do I set log4j level on the command line?

In my pretty standard setup I've been seeing the following work well when passed in as VM Option (commandline before class in Java, or VM Option in an IDE):

-Droot.log.level=TRACE

How to find if div with specific id exists in jQuery?

if ( $( "#myDiv" ).length ) {
    // if ( "#myDiv" ) is exist this will perform
    $( "#myDiv" ).show();

}

Another shorthand way:

    $( "#myDiv" ).length && $( "#myDiv" ).show();

Excel: Search for a list of strings within a particular string using array formulas?

  1. Arange your word list with delimiter which never occures in the words, f.e. |
  2. swap arguments in find call - we want search if cell value is matching one of the words in pattern string {=FIND("cell I want to search","list of words I want to search for")}
  3. if the patterns are similar, there is a risk of getting more results than wanted, we restrict just correct results via adding &"|" to the cell value tested (works well with array formulas) cell G3 could contain: {=SUM(FIND($A$1:$A$100&"|";A3))} this ensures spreadsheet will compare strings like "cellvlaue|" againts "pattern1|", "pattern2|" etc. which sorts out conflicts like pattern1="newly added", pattern2="added" (sum of all cells matching "added" would be too high, including the target values for cells matching "newly added", which would be a logical error)

Returning http 200 OK with error within response body

Even if I want to return a business logic error as HTTP code there is no such acceptable HTTP error code for that errors rather than using HTTP 200 because it will misrepresent the actual error.

So, HTTP 200 will be good for business logic errors. But all errors which are covered by HTTP error codes should use them.

Basically HTTP 200 means what server correctly processes user request (in case of there is no seats on the plane it is no matter because user request was correctly processed, it can even return just a number of seats available on the plane, so there will be no business logic errors at all or that business logic can be on client side. Business logic error is an abstract meaning, but HTTP error is more definite).

docker mounting volumes on host

Basically VOLUME and -v option are almost equal. These mean 'mount specific directory on your container'. For example, VOLUME /data and -v /data is exactly same meaning. If you run the image that have VOLUME /data or with -v /data option, /data directory is mounted your container. This directory doesn't belong to your container.

Imagine that You add some files to /data on the container, then commit the container into new image. There isn't any files on data directory because mounted /data directory is belong to original container.

$ docker run -it -v /data --name volume ubuntu:14.04 bash
root@2b5e0f2d37cd:/# cd /data
root@2b5e0f2d37cd:/data# touch 1 2 3 4 5 6 7 8 9
root@2b5e0f2d37cd:/data# cd /tmp
root@2b5e0f2d37cd:/tmp# touch 1 2 3 4 5 6 7 8 9
root@2b5e0f2d37cd:/tmp# exit
exit

$ docker commit volume nacyot/volume  
835cfe3d8d159622507ba3256bb1c0b0d6e7c1419ae32751ad0f925c40378945
nacyot $ docker run -it nacyot/volume
root@dbe335c7e64d:/# cd /data
root@dbe335c7e64d:/data# ls
root@dbe335c7e64d:/data# cd /tmp
root@dbe335c7e64d:/tmp# ls
1  2  3  4  5  6  7  8  9
root@dbe335c7e64d:/tmp# 
root@dbe335c7e64d:/tmp# 

This mounted directory like /data is used to store data that is not belong to your application. And you can predefine the data directory that is not belong to the container by using VOLUME.

A difference between Volume and -v option is that you can use -v option dynamically on starting container. It mean you can mount some directory dynamically. And another difference is that you can mount your host directory on your container by using -v

How to set the font size in Emacs?

Press Shift and the first mouse button. You can change the font size in the following way: This website has more detail.

Fatal error: Maximum execution time of 30 seconds exceeded

Increase your script execution time by adding the following line at top of the PHP script.

ini_set('max_execution_time', 120); //120 seconds = 2 minutes

Reference has taken from Increase the PHP Script Execution Time

How can I print the contents of an array horizontally?

foreach(var item in array)
Console.Write(item.ToString() + "\t");

How do I create a constant in Python?

There's no const keyword as in other languages, however it is possible to create a Property that has a "getter function" to read the data, but no "setter function" to re-write the data. This essentially protects the identifier from being changed.

Here is an alternative implementation using class property:

Note that the code is far from easy for a reader wondering about constants. See explanation below

def constant(f):
    def fset(self, value):
        raise TypeError
    def fget(self):
        return f()
    return property(fget, fset)

class _Const(object):
    @constant
    def FOO():
        return 0xBAADFACE
    @constant
    def BAR():
        return 0xDEADBEEF

CONST = _Const()

print CONST.FOO
##3131964110

CONST.FOO = 0
##Traceback (most recent call last):
##    ...
##    CONST.FOO = 0
##TypeError: None

Code Explanation:

  1. Define a function constant that takes an expression, and uses it to construct a "getter" - a function that solely returns the value of the expression.
  2. The setter function raises a TypeError so it's read-only
  3. Use the constant function we just created as a decoration to quickly define read-only properties.

And in some other more old-fashioned way:

(The code is quite tricky, more explanations below)

class _Const(object):
    @apply
    def FOO():
        def fset(self, value):
            raise TypeError
        def fget(self):
            return 0xBAADFACE
        return property(**locals())

CONST = _Const()

print CONST.FOO
##3131964110

CONST.FOO = 0
##Traceback (most recent call last):
##    ...
##    CONST.FOO = 0
##TypeError: None

Note that the @apply decorator seems to be deprecated.

  1. To define the identifier FOO, firs define two functions (fset, fget - the names are at my choice).
  2. Then use the built-in property function to construct an object that can be "set" or "get".
  3. Note hat the property function's first two parameters are named fset and fget.
  4. Use the fact that we chose these very names for our own getter & setter and create a keyword-dictionary using the ** (double asterisk) applied to all the local definitions of that scope to pass parameters to the property function

Count indexes using "for" in Python

If you have an existing list and you want to loop over it and keep track of the indices you can use the enumerate function. For example

l = ["apple", "pear", "banana"]
for i, fruit in enumerate(l):
   print "index", i, "is", fruit

How do I see the current encoding of a file in Sublime Text?

With the EncodingHelper plugin you can view the encoding of the file on the status bar. Also you can convert the encoding of the file and extended another functionalities.

Demo

How to get user's high resolution profile picture on Twitter?

use this URL : "https://twitter.com/(userName)/profile_image?size=original"

If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient, using TWTRAuthSession.

This is the code snipe for iOS:

if let twitterId = session.userID{
   let twitterClient = TWTRAPIClient(userID: twitterId)
   twitterClient.loadUser(withID: twitterId) {(user, error) in
       if let userName = user?.screenName{
          let url = "https://twitter.com/\(userName)/profile_image?size=original")
       }
   }
}

Checking for Undefined In React

What you can do is check whether you props is defined initially or not by checking if nextProps.blog.content is undefined or not since your body is nested inside it like

componentWillReceiveProps(nextProps) {

    if(nextProps.blog.content !== undefined && nextProps.blog.title !== undefined) {
       console.log("new title is", nextProps.blog.title);
       console.log("new body content is", nextProps.blog.content["body"]);
       this.setState({
           title: nextProps.blog.title,
           body: nextProps.blog.content["body"]
       })
    }
}

You need not use type to check for undefined, just the strict operator !== which compares the value by their type as well as value

In order to check for undefined, you can also use the typeof operator like

typeof nextProps.blog.content != "undefined"

Angular 4 img src is not found

Add in angular.json

  "assets": [
              "src/favicon.ico",
              "src/assets"
            ],

And then use it like this: <img src={{imgPath}} alt="img"></div>

And in ts: storyPath = 'assets/images/myImg.png';

Setting environment variables for accessing in PHP when using Apache

You can also do this in a .htaccess file assuming they are enabled on the website.

SetEnv KOHANA_ENV production

Would be all you need to add to a .htaccess to add the environment variable

python: iterate a specific range in a list

listOfStuff =([a,b], [c,d], [e,f], [f,g])

for item in listOfStuff[1:3]:
    print item

You have to iterate over a slice of your tuple. The 1 is the first element you need and 3 (actually 2+1) is the first element you don't need.

Elements in a list are numerated from 0:

listOfStuff =([a,b], [c,d], [e,f], [f,g])
               0      1      2      3

[1:3] takes elements 1 and 2.

What are some ways of accessing Microsoft SQL Server from Linux?

pymssql is a DB-API Python module, based on FreeTDS. It worked for me. Create some helper functions, if you need, and use it from Python shell.

Edit a text file on the console using Powershell

Kinesics Text Editor.

It's super fast and handles large text files, though minimal in features. There's a GUI version and console version (k.exe) included. Should work the same on linux.

Example: In my test it took 7 seconds to open a 500mb disk image.

screenshot

Why do I keep getting Delete 'cr' [prettier/prettier]?

Change file type from tsx -> ts, jsx -> js

You can get this error if you are working on .tsx or .jsx file and you are just exporting styles etc and not jsx. In this case the error is solved by changing the file type to .ts or .js

Rollback one specific migration in Laravel

It's quite easy to roll back just a specific migration.
Since the command php artisan migrate:rollback, undo the last database migration, and the order of the migrations execution is stored in the batch field in the migrations table.

You can edit the batch value of the migration that you want to rollback and set it as the higher. Then you can rollback that migration with a simple:

php artisan migrate:rollback

After editing the same migration you can execute it again with a simple

php artisan migrate

NOTICE: if two or more migrations have the same higher value, they will be all rolled back at the same time.

WCF named pipe minimal example

Try this.

Here is the service part.

[ServiceContract]
public interface IService
{
    [OperationContract]
    void  HelloWorld();
}

public class Service : IService
{
    public void HelloWorld()
    {
        //Hello World
    }
}

Here is the Proxy

public class ServiceProxy : ClientBase<IService>
{
    public ServiceProxy()
        : base(new ServiceEndpoint(ContractDescription.GetContract(typeof(IService)),
            new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/MyAppNameThatNobodyElseWillUse/helloservice")))
    {

    }
    public void InvokeHelloWorld()
    {
        Channel.HelloWorld();
    }
}

And here is the service hosting part.

var serviceHost = new ServiceHost
        (typeof(Service), new Uri[] { new Uri("net.pipe://localhost/MyAppNameThatNobodyElseWillUse") });
    serviceHost.AddServiceEndpoint(typeof(IService), new NetNamedPipeBinding(), "helloservice");
    serviceHost.Open();

    Console.WriteLine("Service started. Available in following endpoints");
    foreach (var serviceEndpoint in serviceHost.Description.Endpoints)
    {
        Console.WriteLine(serviceEndpoint.ListenUri.AbsoluteUri);
    }

Find package name for Android apps to use Intent to launch Market app from web

The following bash script can be used to display the package and activity names in an apk, and launch the application by passing it an APK file.

apk_start.sh

package=`aapt dump badging $* | grep package | awk '{print $2}' | sed s/name=//g | sed s/\'//g`
activity=`aapt dump badging $* | grep Activity | awk '{print $2}' | sed s/name=//g | sed s/\'//g`
echo
echo package : $package
echo activity: $activity
echo
echo Launching application on device....
echo
adb shell am start -n $package/$activity

Then to launch the application in the emulator, simply supply the APK filename like so:

apk_start.sh /tmp/MyApp.apk

Of course if you just want the package and activity name of the apk to be displayed, delete the last line of the script.

You can stop an application in the same way by using this script:

apk_stop.sh

package=`aapt dump badging $* | grep package | awk '{print $2}' | sed s/name=//g | sed s/\'//g`
adb shell am force-stop $package

like so:

apk_stop.sh /tmp/MyApp.apk

Important Note: aapt can be found here:

<android_sdk_home>/build-tools/android-<ver>/aapt

Spring Rest POST Json RequestBody Content type not supported

I met the same problem which i solved by deserializing myself the posted value :

@RequestMapping(value = "/arduinos/commands/{idArduino}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String sendCommandesJson(@PathVariable("idArduino") String idArduino, HttpServletRequest request) throws IOException {
    // getting the posted value
    String body = CharStreams.toString(request.getReader());
    List<ArduinoCommand> commandes = new ObjectMapper().readValue(body, new TypeReference<List<ArduinoCommand>>() {
    });

with theses gradle dependencies :

  compile('org.springframework.boot:spring-boot-starter-web')
  compile('com.google.guava:guava:16.0.1')

Twitter Bootstrap scrollable table rows and fixed header

Just stack two bootstrap tables; one for columns, the other for content. No plugins, just pure bootstrap (and that ain't no bs, haha!)

  <table id="tableHeader" class="table" style="table-layout:fixed">
        <thead>
            <tr>
                <th>Col1</th>
                ...
            </tr>
        </thead>
  </table>
  <div style="overflow-y:auto;">
    <table id="tableData" class="table table-condensed" style="table-layout:fixed">
        <tbody>
            <tr>
                <td>data</td>
                ...
            </tr>
        </tbody>
    </table>
 </div>

Demo JSFiddle

The content table div needs overflow-y:auto, for vertical scroll bars. Had to use table-layout:fixed, otherwise, columns did not line up. Also, had to put the whole thing inside a bootstrap panel to eliminate space between the tables.

Have not tested with custom column widths, but provided you keep the widths consistent between the tables, it should work.

    // ADD THIS JS FUNCTION TO MATCH UP COL WIDTHS
    $(function () {

        //copy width of header cells to match width of cells with data
        //so they line up properly
        var tdHeader = document.getElementById("tableHeader").rows[0].cells;
        var tdData = document.getElementById("tableData").rows[0].cells;

        for (var i = 0; i < tdData.length; i++)
            tdHeader[i].style.width = tdData[i].offsetWidth + 'px';

    });

Getting Django admin url for an object

I had a similar issue where I would try to call reverse('admin_index') and was constantly getting django.core.urlresolvers.NoReverseMatch errors.

Turns out I had the old format admin urls in my urls.py file.

I had this in my urlpatterns:

(r'^admin/(.*)', admin.site.root),

which gets the admin screens working but is the deprecated way of doing it. I needed to change it to this:

(r'^admin/', include(admin.site.urls) ),

Once I did that, all the goodness that was promised in the Reversing Admin URLs docs started working.

How to import component into another root component in Angular 2

above answers In simple words, you have to register under @NgModule's

declarations: [
    AppComponent, YourNewComponentHere
  ] 

of app.module.ts

do not forget to import that component.

CSS Circular Cropping of Rectangle Image

Johnny's solution is good. I found that adding min-width:100%, really helps images fill the entire circle. You could do this with a combination of JavaScript to get optimal results or use ImageMagick - http://www.imagemagick.org/script/index.php if you're really serious about getting it right.

_x000D_
_x000D_
.image-cropper {_x000D_
_x000D_
  width: 35px;_x000D_
_x000D_
  height: 35px;_x000D_
_x000D_
  position: relative;_x000D_
_x000D_
  overflow: hidden;_x000D_
_x000D_
  border-radius: 50%;_x000D_
_x000D_
}_x000D_
_x000D_
.image-cropper__image {_x000D_
_x000D_
  display: inline;_x000D_
_x000D_
  margin: 0 auto;_x000D_
_x000D_
  height: 100%;_x000D_
_x000D_
  min-width: 100%;_x000D_
_x000D_
}
_x000D_
<div class="image-cropper">_x000D_
  <img src="#" class="image-cropper__image">_x000D_
</div>
_x000D_
_x000D_
_x000D_

oracle.jdbc.driver.OracleDriver ClassNotFoundException

You can add a JAR which having above specified class exist e.g.ojdbc jar which supported by installed java version, also make sure that you have added it into classpath.

How to show alert message in mvc 4 controller?

You cannot show an alert from a controller. There is one way communication from the client to the server.The server can therefore not tell the client to do anything. The client requests and the server gives a response.

You therefore need to use javascript when the response returns to show a messagebox of some sort.

OR

using jquery on the button that calls the controller action

<script>
 $(document).ready(function(){
  $("#submitButton").on("click",function()
  {
   alert('Your Message');
  });

});
<script>

Best way to convert list to comma separated string in java

From Apache Commons library:

import org.apache.commons.lang3.StringUtils

Use:

StringUtils.join(slist, ',');

Another similar question and answer here

How do I bottom-align grid elements in bootstrap fluid layout

Based on the other answers here is an even more responsive version. I made changes from Ivan's version to support viewports <768px wide and to better support slow window resizes.

!function ($) { //ensure $ always references jQuery
    $(function () { //when dom has finished loading
        //make top text appear aligned to bottom: http://stackoverflow.com/questions/13841387/how-do-i-bottom-align-grid-elements-in-bootstrap-fluid-layout
        function fixHeader() {
            //for each element that is classed as 'pull-down'
            //reset margin-top for all pull down items
            $('.pull-down').each(function () {
                $(this).css('margin-top', 0);
            });

            //set its margin-top to the difference between its own height and the height of its parent
            $('.pull-down').each(function () {
                if ($(window).innerWidth() >= 768) {
                    $(this).css('margin-top', $(this).parent().height() - $(this).height());
                }
            });
        }

        $(window).resize(function () {
            fixHeader();
        });

        fixHeader();
    });
}(window.jQuery);

Submit form and stay on same page?

99% of the time I would use XMLHttpRequest or fetch for something like this. However, there's an alternative solution which doesn't require javascript...

You could include a hidden iframe on your page and set the target attribute of your form to point to that iframe.

<style>
  .hide { position:absolute; top:-1px; left:-1px; width:1px; height:1px; }
</style>

<iframe name="hiddenFrame" class="hide"></iframe>

<form action="receiver.pl" method="post" target="hiddenFrame">
  <input name="signed" type="checkbox">
  <input value="Save" type="submit">
</form>

There are very few scenarios where I would choose this route. Generally handling it with javascript is better because, with javascript you can...

  • gracefully handle errors (e.g. retry)
  • provide UI indicators (e.g. loading, processing, success, failure)
  • run logic before the request is sent, or run logic after the response is received.

How do I put a variable inside a string?

Oh, the many, many ways...

String concatenation:

plot.savefig('hanning' + str(num) + '.pdf')

Conversion Specifier:

plot.savefig('hanning%s.pdf' % num)

Using local variable names:

plot.savefig('hanning%(num)s.pdf' % locals()) # Neat trick

Using str.format():

plot.savefig('hanning{0}.pdf'.format(num)) # Note: This is the new preferred way

Using f-strings:

plot.savefig(f'hanning{num}.pdf') # added in Python 3.6

Using string.Template:

plot.savefig(string.Template('hanning${num}.pdf').substitute(locals()))

Is it possible to run JavaFX applications on iOS, Android or Windows Phone 8?

Background

Invariant's answer is a good resource for how everything was started and what was the state of JavaFX on embedded and mobile in beginning of 2014. But, a lot has changed since then and the users who stumble on this thread do not get the updated information.

Most of my points are related to Invariant's answer, so I would suggest to go through it first.

Current Status of JavaFX on Mobile / Embedded

UPDATE

JavaFXPorts has been deprecated. Gluon Mobile now uses GraalVM underneath. There are multiple advantages of using GraalVM. Please check this blogpost from Gluon. The IDE plugins have been updated to use Gluon Client plugins which leverages GraalVM to AOT compile applications for Android/iOS.

Old answer with JavaFXPorts

Some bad news first:

Now, some good news:

  • JavaFX still runs on Android, iOS and most of the Embedded devices
  • JavaFXPorts SDK for android, iOS and embedded devices can be downloaded from here
  • JavaFXPorts project is still thriving and it is easier than ever to run JavaFX on mobile devices, all thanks to the IDE plugins that is built on top of these SDKs and gets you started in a few minutes without the hassle of installing any SDK
  • JavaFX 3D is now supported on mobile devices
  • GluonVM to replace RoboVM enabling Java 9 support for mobile developers. Yes, you heard it right.
  • Mobile Project has been launched by Oracle to support JDK on all major mobile platforms. It should support JavaFX as well ;)

How to get started

If you are not the DIY kind, I would suggest to install the IDE plugin on your favourite IDE and get started.

Most of the documentation on how to get started can be found here and some of the samples can be found here.

HTML table with fixed headers and a fixed column?

YUI DataTable

I don't know if YUI DT has this feature but I won't be surprised if it does.

Split string into list in jinja?

You can’t run arbitrary Python code in jinja; it doesn’t work like JSP in that regard (it just looks similar). All the things in jinja are custom syntax.

For your purpose, it would make most sense to define a custom filter, so you could for example do the following:

The grass is {{ variable1 | splitpart(0, ',') }} and the boat is {{  splitpart(1, ',') }}
Or just:
The grass is {{ variable1 | splitpart(0) }} and the boat is {{  splitpart(1) }}

The filter function could then look like this:

def splitpart (value, index, char = ','):
    return value.split(char)[index]

An alternative, which might make even more sense, would be to split it in the controller and pass the splitted list to the view.

PDO error message?

From the manual:

If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).

The prepare statement likely caused an error because the db would be unable to prepare the statement. Try testing for an error immediately after you prepare your query and before you execute it.

$qry = '
    INSERT INTO non-existant-table (id, score) 
    SELECT id, 40 
    FROM another-non-existant-table
    WHERE description LIKE "%:search_string%"
    AND available = "yes"
    ON DUPLICATE KEY UPDATE score = score + 40
';
$sth = $this->pdo->prepare($qry);
print_r($this->pdo->errorInfo());

How to detect browser using angularjs?

There is a library ng-device-detector which makes detecting entities like browser, os easy.

Here is tutorial that explains how to use this library. Detect OS, browser and device in AngularJS

ngDeviceDetector

You need to add re-tree.js and ng-device-detector.js scripts into your html

Inject "ng.deviceDetector" as dependency in your module.

Then inject "deviceDetector" service provided by the library into your controller or factory where ever you want the data.

"deviceDetector" contains all data regarding browser, os and device.

How to change Bootstrap's global default font size?

Add !importent in your css

* {
   font-size: 16px !importent;
   line-height: 2;
}

Start an Activity with a parameter

Just add extra data to the Intent you use to call your activity.

In the caller activity :

Intent i = new Intent(this, TheNextActivity.class);
i.putExtra("id", id);
startActivity(i);

Inside the onCreate() of the activity you call :

Bundle b = getIntent().getExtras();
int id = b.getInt("id");