Programs & Examples On #Ora 04091

table name is mutating, trigger/function may not see it

Column/Vertical selection with Keyboard in SublimeText 3

The SublimeText 3 Column-Select plugin should be all you need. Install that, then make sure you have something like the following in your 'Default (OSX).sublime-keymap' file:

    // Column mode
    { "keys": ["ctrl+alt+up"], "command": "column_select", "args": {"by": "lines", "forward": false}},
    { "keys": ["ctrl+alt+down"], "command": "column_select", "args": {"by": "lines", "forward": true}},
    { "keys": ["ctrl+alt+pageup"], "command": "column_select", "args": {"by": "pages", "forward": false}},
    { "keys": ["ctrl+alt+pagedown"], "command": "column_select", "args": {"by": "pages", "forward": true}},
    { "keys": ["ctrl+alt+home"], "command": "column_select", "args": {"by": "all", "forward": false}},
    { "keys": ["ctrl+alt+end"], "command": "column_select", "args": {"by": "all", "forward": true}}

What exactly about it did not work for you?

MySQL "between" clause not inclusive?

Hi this query works for me,

select * from person where dob between '2011-01-01' and '2011-01-31 23:59:59'

How to "comment-out" (add comment) in a batch/cmd?

You can use :: or rem for comments.

When commenting, use :: as it's 3 times faster. An example is shown here

Only if comments are in if, use rem, as the colons could make errors, because they are a label.

how to set imageview src?

To set image cource in imageview you can use any of the following ways. First confirm your image is present in which format.

If you have image in the form of bitmap then use

imageview.setImageBitmap(bm);

If you have image in the form of drawable then use

imageview.setImageDrawable(drawable);

If you have image in your resource example if image is present in drawable folder then use

imageview.setImageResource(R.drawable.image);

If you have path of image then use

imageview.setImageURI(Uri.parse("pathofimage"));

Get all photos from Instagram which have a specific hashtag with PHP

There is the instagram public API's tags section that can help you do this.

Can't find SDK folder inside Android studio path, and SDK manager not opening

I faced the same issue. And I am able to resolve it by uninstalling the previous version I had, and removing the Android studio projects and reinstalling it.

And then go to Settings-> Android Studio -> Click on edit, to specify studio location, it will recognize the requask you if you would like to download sdk,

How to use radio on change event?

Use onchage function

<input type="radio" name="bedStatus" id="allot" checked="checked" value="allot" onchange="my_function('allot')">Allot
<input type="radio" name="bedStatus" id="transfer" value="transfer" onchange="my_function('transfer')">Transfer

<script>
 function my_function(val){
    alert(val);
 }
</script>

Detecting when Iframe content has loaded (Cross browser)

to detect when the iframe has loaded and its document is ready?

It's ideal if you can get the iframe to tell you itself from a script inside the frame. For example it could call a parent function directly to tell it it's ready. Care is always required with cross-frame code execution as things can happen in an order you don't expect. Another alternative is to set ‘var isready= true;’ in its own scope, and have the parent script sniff for ‘contentWindow.isready’ (and add the onload handler if not).

If for some reason it's not practical to have the iframe document co-operate, you've got the traditional load-race problem, namely that even if the elements are right next to each other:

<img id="x" ... />
<script type="text/javascript">
    document.getElementById('x').onload= function() {
        ...
    };
</script>

there is no guarantee that the item won't already have loaded by the time the script executes.

The ways out of load-races are:

  1. on IE, you can use the ‘readyState’ property to see if something's already loaded;

  2. if having the item available only with JavaScript enabled is acceptable, you can create it dynamically, setting the ‘onload’ event function before setting source and appending to the page. In this case it cannot be loaded before the callback is set;

  3. the old-school way of including it in the markup:

    <img onload="callback(this)" ... />

Inline ‘onsomething’ handlers in HTML are almost always the wrong thing and to be avoided, but in this case sometimes it's the least bad option.

How to pass parameters on onChange of html select

Simply:

_x000D_
_x000D_
function retrieve(){
alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
< script type = "text/javascript> {

function retrieve_other() {
  alert(myForm.SMS_recipient.options[document.getElementById('SMS_recipient').selectedIndex].text);
}

function retrieve() {
  alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}
} 
</script>
_x000D_
<HTML>
<BODY>
  <p>RETRIEVING TEXT IN OPTION OF SELECT </p>
  <form name="myForm" action="">
    <P>Select:
      <select id="SMS_recipient">
        <options value='+15121234567'>Andrew</option>
          <options value='+15121234568'>Klaus</option>
      </select>
    </p>
    <p>
      <!-- Note: Despite the script engine complaining about it the code works!-->
      <input type="button" onclick="retrieve()" value="Try it" />
      <input type="button" onclick="retrieve_other()" value="Try Form" />
    </p>
  </form>
</HTML>
</BODY>
_x000D_
_x000D_
_x000D_

Output: Klaus or Andrew depending on what the selectedIndex is. If you are after the value just replace .text with value. However if it is just the value you are after (not the text in the option) then use document.getElementById('SMS_recipient').value

How to convert string to integer in PowerShell

Use:

$filelist = @("11", "1", "2")
$filelist | sort @{expression={[int]$_}} | % {$newName = [string]([int]$_ + 1)}
New-Item $newName -ItemType Directory

Update row with data from another row in the same table

Try this:

UPDATE data_table t, (SELECT DISTINCT ID, NAME, VALUE
                        FROM data_table
                       WHERE VALUE IS NOT NULL AND VALUE != '') t1
   SET t.VALUE = t1.VALUE
 WHERE t.ID = t1.ID
   AND t.NAME = t1.NAME

html script src="" triggering redirection with button

First you are linking the file that is here:

<script src="../Script/login.js"> 

Which would lead the website to a file in the Folder Script, but then in the second paragraph you are saying that the folder name is

and also i have onother folder named scripts that contains the the following login.js file

So, this won't work! Because you are not accessing the correct file. To do that please write the code as

<script src="/script/login.js"></script>

Try removing the .. from the beginning of the code too.

This way, you'll reach the js file where the function would run!

Just to make sure:

Just to make sure that the files are attached the HTML DOM, then please open Developer Tools (F12) and in the network workspace note each request that the browser makes to the server. This way you will learn which files were loaded and which weren't, and also why they were not!

Good luck.

How to add a WiX custom action that happens only on uninstall (via MSI)?

You can do this with a custom action. You can add a refrence to your custom action under <InstallExecuteSequence>:

<InstallExecuteSequence>
...
  <Custom Action="FileCleaner" After='InstallFinalize'>
          Installed AND NOT UPGRADINGPRODUCTCODE</Custom>

Then you will also have to define your Action under <Product>:

<Product> 
...
  <CustomAction Id='FileCleaner' BinaryKey='FileCleanerEXE' 
                ExeCommand='' Return='asyncNoWait'  />

Where FileCleanerEXE is a binary (in my case a little c++ program that does the custom action) which is also defined under <Product>:

<Product> 
...
  <Binary Id="FileCleanerEXE" SourceFile="path\to\fileCleaner.exe" />

The real trick to this is the Installed AND NOT UPGRADINGPRODUCTCODE condition on the Custom Action, with out that your action will get run on every upgrade (since an upgrade is really an uninstall then reinstall). Which if you are deleting files is probably not want you want during upgrading.

On a side note: I recommend going through the trouble of using something like C++ program to do the action, instead of a batch script because of the power and control it provides -- and you can prevent the "cmd prompt" window from flashing while your installer runs.

Why do I get an error instantiating an interface?

The error message seems self-explanatory. You can't instantiate an instance of an interface, and you've declared IUser as an interface. (The same rule applies to abstract classes.) The whole point of an interface is that it doesn't do anything—there is no implementation provided for its methods.

However, you can instantiate an instance of a class that implements that interface (provides an implementation for its methods), which in your case is the User class.

Thus, your code needs to look like this:

IUser user = new User();

This instantiates an instance of the User class (which provides the implementation), and assigns it to an object variable for the interface type (IUser, which provides the interface, the way in which you as the programmer can interact with the object).

Of course, you could also write:

User user = new User();

which creates an instance of the User class and assigns it to an object variable of the same type, but that sort of defeats the purpose of a defining a separate interface in the first place.

How to compile c# in Microsoft's new Visual Studio Code?

Intellisense does work for C# 6, and it's great.

For running console apps you should set up some additional tools:

  • ASP.NET 5; in Powershell: &{$Branch='dev';iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.ps1'))}
  • Node.js including package manager npm.
  • The rest of required tools including Yeoman yo: npm install -g yo grunt-cli generator-aspnet bower
  • You should also invoke .NET Version Manager: c:\Users\Username\.dnx\bin\dnvm.cmd upgrade -u

Then you can use yo as wizard for Console Application: yo aspnet Choose name and project type. After that go to created folder cd ./MyNewConsoleApp/ and run dnu restore

To execute your program just type >run in Command Palette (Ctrl+Shift+P), or execute dnx . run in shell from the directory of your project.

"git rm --cached x" vs "git reset head --? x"?

Perhaps an example will help:

git rm --cached asd
git commit -m "the file asd is gone from the repository"

versus

git reset HEAD -- asd
git commit -m "the file asd remains in the repository"

Note that if you haven't changed anything else, the second commit won't actually do anything.

Inner join vs Where

They should be exactly the same. However, as a coding practice, I would rather see the Join. It clearly articulates your intent,

Sqlite or MySql? How to decide?

Their feature sets are not at all the same. Sqlite is an embedded database which has no network capabilities (unless you add them). So you can't use it on a network.

If you need

  • Network access - for example accessing from another machine;
  • Any real degree of concurrency - for example, if you think you are likely to want to run several queries at once, or run a workload that has lots of selects and a few updates, and want them to go smoothly etc.
  • a lot of memory usage, for example, to buffer parts of your 1Tb database in your 32G of memory.

You need to use mysql or some other server-based RDBMS.

Note that MySQL is not the only choice and there are plenty of others which might be better for new applications (for example pgSQL).

Sqlite is a very, very nice piece of software, but it has never made claims to do any of these things that RDBMS servers do. It's a small library which runs SQL on local files (using locking to ensure that multiple processes don't screw the file up). It's really well tested and I like it a lot.

Also, if you aren't able to choose this correctly by yourself, you probably need to hire someone on your team who can.

ESLint not working in VS Code?

In my case ESLint was disabled in my workspace. I had to enable it in vscode extensions settings.

How to animate RecyclerView items when they appear

I animated fading in of Recyclerview items when they first appear as shown in the code below. Perhaps this will be of use to someone.

private final static int FADE_DURATION = 1000; //FADE_DURATION in milliseconds

@Override
public void onBindViewHolder(ViewHolder holder, int position) {

    holder.getTextView().setText("some text");

    // Set the view to fade in
    setFadeAnimation(holder.itemView);            
}

private void setFadeAnimation(View view) {
    AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f);
    anim.setDuration(FADE_DURATION);
    view.startAnimation(anim);
}

You can also replace setFadeAnimation() with the following setScaleAnimation() to animate appearance of items by scaling them from a point:

private void setScaleAnimation(View view) {
    ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
    anim.setDuration(FADE_DURATION);
    view.startAnimation(anim);
}

The code above has some warts in so far as when you scroll the RecyclerView items always fade or scale. If you wish you can add code to just allow the animation to happen when the fragment or activity containing the RecyclerView is first created (e.g. get the system time on creation and only allow animation for the first FADE_DURATION milliseconds).

HashMap with multiple values under the same key

If you use Spring Framework. There is: org.springframework.util.MultiValueMap.

To create unmodifiable multi value map:

Map<String,List<String>> map = ...
MultiValueMap<String, String> multiValueMap = CollectionUtils.toMultiValueMap(map);

Or use org.springframework.util.LinkedMultiValueMap

Start service in Android

Java code for start service:

Start service from Activity:

startService(new Intent(MyActivity.this, MyService.class));

Start service from Fragment:

getActivity().startService(new Intent(getActivity(), MyService.class));

MyService.java:

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {

    private static String TAG = "MyService";
    private Handler handler;
    private Runnable runnable;
    private final int runTime = 5000;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate");

        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {

                handler.postDelayed(runnable, runTime);
            }
        };
        handler.post(runnable);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        if (handler != null) {
            handler.removeCallbacks(runnable);
        }
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.i(TAG, "onStart");
    }

}

Define this Service into Project's Manifest File:

Add below tag in Manifest file:

<service android:enabled="true" android:name="com.my.packagename.MyService" />

Done

MongoDB query multiple collections at once

Here is answer for your question.

db.getCollection('users').aggregate([
    {$match : {admin : 1}},
    {$lookup: {from: "posts",localField: "_id",foreignField: "owner_id",as: "posts"}},
    {$project : {
            posts : { $filter : {input : "$posts"  , as : "post", cond : { $eq : ['$$post.via' , 'facebook'] } } },
            admin : 1

        }}

])

Or either you can go with mongodb group option.

db.getCollection('users').aggregate([
    {$match : {admin : 1}},
    {$lookup: {from: "posts",localField: "_id",foreignField: "owner_id",as: "posts"}},
    {$unwind : "$posts"},
    {$match : {"posts.via":"facebook"}},
    { $group : {
            _id : "$_id",
            posts : {$push : "$posts"}
    }}
])

What is default color for text in textview?

I found that android:textColor="@android:color/secondary_text_dark" provides a closer result to the default TextView color than android:textColor="@android:color/tab_indicator_text". I suppose you have to switch between secondary_text_dark/light depending on the Theme you are using

What is bootstrapping?

IMHO there is not a better explanation than the fact about How was the first compiler written?

These days the Operating System loading is the most common process referred as Bootstrapping

SQL: Two select statements in one query

If you like to keep records separate and not do the union.
Try query below

SELECT (SELECT name,
               games,
               goals
        FROM   tblMadrid
        WHERE  name = 'ronaldo') AS table_a,
       (SELECT name,
               games,
               goals
        FROM   tblBarcelona
        WHERE  name = 'messi')   AS table_b
FROM DUAL

Stop Visual Studio from launching a new browser window when starting debug?

Open your startup project's properties (Project ? {ProjectName} Properties... from the main menu or right click your project in the Solution Explorer and choose Properties), then navigate to the Web tab and under Start Action choose Don't open a page. Wait for a request from an external application.

You will still be able to use any browser (or Fiddler, whatever) to access the running application, but it won't open the browser window automatically, it'll just start in the background and wait for any requests.

Should I add the Visual Studio .suo and .user files to source control?

.user is the user settings, and I think .suo is the solution user options. You don't want these files under source control; they will be re-created for each user.

python: iterate a specific range in a list

By using iter builtin:

l = [1, 2, 3]
# i is the first item.
i = iter(l)
next(i)
for d in i:
    print(d)

How to change a PG column to NULLABLE TRUE?

From the fine manual:

ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;

There's no need to specify the type when you're just changing the nullability.

How to search for string in an array

If it's a list of constants then you can use Select Case as follows:

Dim Item$: Item = "A"

Select Case Item
  Case "A", "B", "C"
    ' If 'Item' is in the list then do something.
  Case Else
    ' Otherwise do something else.
End Select

Python 3.1.1 string to hex

The hex codec has been chucked in 3.x. Use binascii instead:

>>> binascii.hexlify(b'hello')
b'68656c6c6f'

How do I tell CMake to link in a static library in the source directory?

I found this helpful...

http://www.cmake.org/pipermail/cmake/2011-June/045222.html

From their example:

ADD_LIBRARY(boost_unit_test_framework STATIC IMPORTED)
SET_TARGET_PROPERTIES(boost_unit_test_framework PROPERTIES IMPORTED_LOCATION /usr/lib/libboost_unit_test_framework.a)
TARGET_LINK_LIBRARIES(mytarget A boost_unit_test_framework C)

How can I send and receive WebSocket messages on the server side?

In addition to the PHP frame encoding function, here follows a decode function:

function Decode($M){
    $M = array_map("ord", str_split($M));
    $L = $M[1] AND 127;

    if ($L == 126)
        $iFM = 4;
    else if ($L == 127)
        $iFM = 10;
    else
        $iFM = 2;

    $Masks = array_slice($M, $iFM, 4);

    $Out = "";
    for ($i = $iFM + 4, $j = 0; $i < count($M); $i++, $j++ ) {
        $Out .= chr($M[$i] ^ $Masks[$j % 4]);
    }
    return $Out;
}

I've implemented this and also other functions in an easy-to-use WebSocket PHP class here.

Play a Sound with Python

For Windows, you can use winsound. It's built in

import winsound

winsound.PlaySound('sound.wav', winsound.SND_FILENAME)

You should be able to use ossaudiodev for linux:

from wave import open as waveOpen
from ossaudiodev import open as ossOpen
s = waveOpen('tada.wav','rb')
(nc,sw,fr,nf,comptype, compname) = s.getparams( )
dsp = ossOpen('/dev/dsp','w')
try:
  from ossaudiodev import AFMT_S16_NE
except ImportError:
  from sys import byteorder
  if byteorder == "little":
    AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
  else:
    AFMT_S16_NE = ossaudiodev.AFMT_S16_BE
dsp.setparameters(AFMT_S16_NE, nc, fr)
data = s.readframes(nf)
s.close()
dsp.write(data)
dsp.close()

(Credit for ossaudiodev: Bill Dandreta http://mail.python.org/pipermail/python-list/2004-October/288905.html)

Fetching distinct values on a column using Spark DataFrame

This solution demonstrates how to transform data with Spark native functions which are better than UDFs. It also demonstrates how dropDuplicates which is more suitable than distinct for certain queries.

Suppose you have this DataFrame:

+-------+-------------+
|country|    continent|
+-------+-------------+
|  china|         asia|
| brazil|south america|
| france|       europe|
|  china|         asia|
+-------+-------------+

Here's how to take all the distinct countries and run a transformation:

df
  .select("country")
  .distinct
  .withColumn("country", concat(col("country"), lit(" is fun!")))
  .show()
+--------------+
|       country|
+--------------+
|brazil is fun!|
|france is fun!|
| china is fun!|
+--------------+

You can use dropDuplicates instead of distinct if you don't want to lose the continent information:

df
  .dropDuplicates("country")
  .withColumn("description", concat(col("country"), lit(" is a country in "), col("continent")))
  .show(false)
+-------+-------------+------------------------------------+
|country|continent    |description                         |
+-------+-------------+------------------------------------+
|brazil |south america|brazil is a country in south america|
|france |europe       |france is a country in europe       |
|china  |asia         |china is a country in asia          |
+-------+-------------+------------------------------------+

See here for more information about filtering DataFrames and here for more information on dropping duplicates.

Ultimately, you'll want to wrap your transformation logic in custom transformations that can be chained with the Dataset#transform method.

C++ cout hex values?

I understand this isn't what OP asked for, but I still think it is worth to point out how to do it with printf. I almost always prefer using it over std::cout (even with no previous C background).

printf("%.2X", a);

'2' defines the precision, 'X' or 'x' defines case.

Query grants for a table in postgres

\z mytable from psql gives you all the grants from a table, but you'd then have to split it up by individual user.

Using the Underscore module with Node.js

Or :

    var _ = require('underscore')._;

Display html text in uitextview

Answer has fitted to me that from BHUPI.

The code transfer to swift as below:

Pay attention "allowLossyConversion: false"

if you set the value to true, it will show pure text.

let theString = "<h1>H1 title</h1><b>Logo</b><img src='http://www.aver.com/Images/Shared/logo-color.png'><br>~end~"

        let theAttributedString = try! NSAttributedString(data: theString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil)

        UITextView_Message.attributedText = theAttributedString

Can I call jQuery's click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

Interesting, this is probably a "feature request" (ie bug) for jQuery. The jQuery click event only triggers the click action (called onClick event on the DOM) on the element if you bind a jQuery event to the element. You should go to jQuery mailing lists ( http://forum.jquery.com/ ) and report this. This might be the wanted behavior, but I don't think so.

EDIT:

I did some testing and what you said is wrong, even if you bind a function to an 'a' tag it still doesn't take you to the website specified by the href attribute. Try the following code:

<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
 <script>
  $(document).ready(function() {
   /* Try to dis-comment this:
   $('#a').click(function () {
    alert('jQuery.click()');
    return true;
   });
   */
  });
  function button_onClick() {
   $('#a').click();
  }
  function a_onClick() {
   alert('a_onClick');
  }
 </script>

</head>
<body>
 <input type="button" onclick="button_onClick()">
 <br>
 <a id='a' href='http://www.google.com' onClick="a_onClick()"> aaa </a>

</body>
</html> 

It never goes to google.com unless you directly click on the link (with or without the commented code). Also notice that even if you bind the click event to the link it still doesn't go purple once you click the button. It only goes purple if you click the link directly.

I did some research and it seems that the .click is not suppose to work with 'a' tags because the browser does not suport "fake clicking" with javascript. I mean, you can't "click" an element with javascript. With 'a' tags you can trigger its onClick event but the link won't change colors (to the visited link color, the default is purple in most browsers). So it wouldn't make sense to make the $().click event work with 'a' tags since the act of going to the href attribute is not a part of the onClick event, but hardcoded in the browser.

How can I write maven build to add resources to classpath?

By default maven does not include any files from "src/main/java".

You have two possible way to that.

  1. put all your resource files (different than java files) to "src/main/resources" - this is highly recommended

  2. Add to your pom (resource plugin):

?

 <resources>
       <resource>
           <directory>src/main/resources</directory>
        </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
  </resources>

Make div scrollable

Place this into your DIV style

overflow:scroll;

Pytorch tensor to numpy array

There are 4 dimensions of the tensor you want to convert.

[:, ::-1, :, :] 

: means that the first dimension should be copied as it is and converted, same goes for the third and fourth dimension.

::-1 means that for the second axes it reverses the the axes

Angularjs loading screen on ajax request

Here simple interceptor example, I set mouse on wait when ajax starts and set it to auto when ajax ends.

$httpProvider.interceptors.push(function($document) {
return {
 'request': function(config) {
     // here ajax start
     // here we can for example add some class or show somethin
     $document.find("body").css("cursor","wait");

     return config;
  },

  'response': function(response) {
     // here ajax ends
     //here we should remove classes added on request start

     $document.find("body").css("cursor","auto");

     return response;
  }
};
});

Code has to be added in application config app.config. I showed how to change mouse on loading state but in there it is possible to show/hide any loader content, or add, remove some css classes which are showing the loader.

Interceptor will run on every ajax call, so no need to create special boolean variables ( $scope.loading=true/false etc. ) on every http call.

Interceptor is using builded in angular jqLite https://docs.angularjs.org/api/ng/function/angular.element so no Jquery needed.

align right in a table cell with CSS

What worked for me now is:

CSS:

.right {
  text-align: right;
  margin-right: 1em;
}

.left {
  text-align: left;
  margin-left: 1em;
}

HTML:

<table width="100%">
  <tbody>
    <tr>
      <td class="left">
        <input id="abort" type="submit" name="abort" value="Back">
        <input id="save" type="submit" name="save" value="Save">
      </td>
      <td class="right">
        <input id="delegate" type="submit" name="delegate" value="Delegate">
        <input id="unassign" type="submit" name="unassign" value="Unassign">
        <input id="complete" type="submit" name="complete" value="Complete">
      </td>
    </tr>
  </tbody>
</table>

See the following fiddle:

http://jsfiddle.net/Joysn/3u3SD/

How to add checkboxes to JTABLE swing

1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,

2) AbstractTableModel should be useful, where is in the JTable required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel,

3) consider using DefaultTableModel, (if you are not sure about how to works) instead of AbstractTableModel,

table_with_BooleanType_column

could be generated from simple code:

import javax.swing.*;
import javax.swing.table.*;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        };
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            /*@Override
            public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
            }*/
            @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Integer.class;
                    case 3:
                        return Double.class;
                    default:
                        return Boolean.class;
                }
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocation(150, 150);
                frame.setVisible(true);
            }
        });
    }
}

How to push objects in AngularJS between ngRepeat arrays

You'd be much better off using the same array with both lists, and creating angular filters to achieve your goal.

http://docs.angularjs.org/guide/dev_guide.templates.filters.creating_filters

Rough, untested code follows:

appModule.filter('checked', function() {
    return function(input, checked) {
        if(!input)return input;
        var output = []
        for (i in input){
            var item = input[i];
            if(item.checked == checked)output.push(item);
        }
        return output
    }
});

and the view (i added an "uncheck" button too)

<div id="AddItem">
     <h3>Add Item</h3>

    <input value="1" type="number" placeholder="1" ng-model="itemAmount">
    <input value="" type="text" placeholder="Name of Item" ng-model="itemName">
    <br/>
    <button ng-click="addItem()">Add to list</button>
</div>
<!-- begin: LIST OF CHECKED ITEMS -->
<div id="CheckedList">
     <h3>Checked Items: {{getTotalCheckedItems()}}</h3>

     <h4>Checked:</h4>

    <table>
        <tr ng-repeat="item in items | checked:true" class="item-checked">
            <td><b>amount:</b> {{item.amount}} -</td>
            <td><b>name:</b> {{item.name}} -</td>
            <td> 
               <i>this item is checked!</i>
               <button ng-click="item.checked = false">uncheck item</button>

            </td>
        </tr>
    </table>
</div>
<!-- end: LIST OF CHECKED ITEMS -->
<!-- begin: LIST OF UNCHECKED ITEMS -->
<div id="UncheckedList">
     <h3>Unchecked Items: {{getTotalItems()}}</h3>

     <h4>Unchecked:</h4>

    <table>
        <tr ng-repeat="item in items | checked:false" class="item-unchecked">
            <td><b>amount:</b> {{item.amount}} -</td>
            <td><b>name:</b> {{item.name}} -</td>
            <td>
                <button ng-click="item.checked = true">check item</button>
            </td>
        </tr>
    </table>
</div>
<!-- end: LIST OF ITEMS -->

Then you dont need the toggle methods etc in your controller

Requests -- how to tell if you're getting a 404

Look at the r.status_code attribute:

if r.status_code == 404:
    # A 404 was issued.

Demo:

>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404

If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 664, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

if r:
    # successful response

If you want to be more explicit, use if r.ok:.

Unexpected end of file error

I also got this error, but for a .h file. The fix was to go into the file Properties (via Solution Explorer's file popup menu) and set the file type correctly. It was set to C/C++ Compiler instead of the correct C/C++ header.

TypeError: unhashable type: 'numpy.ndarray'

Your variable energies probably has the wrong shape:

>>> from numpy import array
>>> set([1,2,3]) & set(range(2, 10))
set([2, 3])
>>> set(array([1,2,3])) & set(range(2,10))
set([2, 3])
>>> set(array([[1,2,3],])) & set(range(2,10))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'

And that's what happens if you read columnar data using your approach:

>>> data
array([[  1.,   2.,   3.],
       [  3.,   4.,   5.],
       [  5.,   6.,   7.],
       [  8.,   9.,  10.]])
>>> hsplit(data,3)[0]
array([[ 1.],
       [ 3.],
       [ 5.],
       [ 8.]])

Probably you can simply use

>>> data[:,0]
array([ 1.,  3.,  5.,  8.])

instead.

(P.S. Your code looks like it's undecided about whether it's data or elementdata. I've assumed it's simply a typo.)

How do I verify that an Android apk is signed with a release certificate?

    1. unzip apk
    1. keytool -printcert -file ANDROID_.RSA or keytool -list -printcert -jarfile app.apk to obtain the hash md5
  • keytool -list -v -keystore clave-release.jks
  • compare the md5

https://www.eovao.com/en/a/signature%20apk%20android/3/how-to-verify-signature-of-.apk-android-archive

Why is document.write considered a "bad practice"?

It can block your page

document.write only works while the page is loading; If you call it after the page is done loading, it will overwrite the whole page.

This effectively means you have to call it from an inline script block - And that will prevent the browser from processing parts of the page that follow. Scripts and Images will not be downloaded until the writing block is finished.

Nginx subdomain configuration

You could move the common parts to another configuration file and include from both server contexts. This should work:

server {
  listen 80;
  server_name server1.example;
  ...
  include /etc/nginx/include.d/your-common-stuff.conf;
}

server {
  listen 80;
  server_name another-one.example;
  ...
  include /etc/nginx/include.d/your-common-stuff.conf;
}

Edit: Here's an example that's actually copied from my running server. I configure my basic server settings in /etc/nginx/sites-enabled (normal stuff for nginx on Ubuntu/Debian). For example, my main server bunkus.org's configuration file is /etc/nginx/sites-enabled and it looks like this:

server {
  listen   80 default_server;
  listen   [2a01:4f8:120:3105::101:1]:80 default_server;

  include /etc/nginx/include.d/all-common;
  include /etc/nginx/include.d/bunkus.org-common;
  include /etc/nginx/include.d/bunkus.org-80;
}

server {
  listen   443 default_server;
  listen   [2a01:4f8:120:3105::101:1]:443 default_server;

  include /etc/nginx/include.d/all-common;
  include /etc/nginx/include.d/ssl-common;
  include /etc/nginx/include.d/bunkus.org-common;
  include /etc/nginx/include.d/bunkus.org-443;
}

As an example here's the /etc/nginx/include.d/all-common file that's included from both server contexts:

index index.html index.htm index.php .dirindex.php;
try_files $uri $uri/ =404;

location ~ /\.ht {
  deny all;
}

location = /favicon.ico {
  log_not_found off;
  access_log off;
}

location ~ /(README|ChangeLog)$ {
  types { }
  default_type text/plain;
}

Android Dialog: Removing title bar

if you are using a custom view then remeber to request window feature before adding content view like this

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(view);
dialog.show();

How to connect Bitbucket to Jenkins properly

I am not familiar with this plugin, but we quite successfully use Bitbucket and Jenkins together, however we poll for changes instead of having them pushed from BitBucket (due to the fact our build server is hidden behind a company firewall). This approach may work for you if you are still having problems with the current approach.

This document on Setting up SSH for Git & Mercurial on Linux covers the details of what you need to do to be able to communicate between your build server and Bitbucket over SSH. Once this is done, with the Git Plugin installed, go to your build configuration and select 'Git' under Source Code Management, and enter the ssh URL of your repository as the repository URL. Finally, in the Build Triggers section, select Poll SCM and set the poll frequency to whatever you require.

Complex JSON nesting of objects and arrays

You can try use this function to find any object in nested nested array of arrays of kings.

Example

function findTByKeyValue (element, target){
        var found = true;
        for(var key in target) { 
            if (!element.hasOwnProperty(key) || element[key] !== target[key])   { 
                found = false;
                break;
            }
        }
        if(found) {
            return element;
        }
        if(typeof(element) !== "object") { 
            return false;
        }
        for(var index in element) { 
            var result = findTByKeyValue(element[index],target);
            if(result) { 
                return result; 
            }
        } 
    };

findTByKeyValue(problems,{"name":"somethingElse","strength":"500 mg"}) =====> result equal to object associatedDrug#2

Git Stash vs Shelve in IntelliJ IDEA

I would prefer to shelve changes instead of stashing them if I am not sharing my changes elsewhere.

Stashing is a git feature and doesn't give you the option to select specific files or changes inside a file. Shelving can do that but this is an IDE-specific feature, not a git feature:

enter image description here

As you can see I am able to choose to specify which files/lines to include on my shelve. Note that I can't do that with stashing.

Beware using shelves in the IDE may limit the portability of your patches because those changes are not stored in a .git folder.

Some helpful links:

How do you use "git --bare init" repository?

You can execute the following commands to initialize your local repository

mkdir newProject
cd newProject
touch .gitignore
git init
git add .
git commit -m "Initial Commit"
git remote add origin user@host:~/path_on_server/newProject.git
git push origin master

You should work on your project from your local repository and use the server as the central repository.

You can also follow this article which explains each and every aspect of creating and maintaining a Git repository. Git for Beginners

Cannot lower case button text in android studio

<style name="AppTheme" parent="AppBaseTheme">
    <item name="android:buttonStyle">@style/Button</item>
</style>

<style name="Button" parent="Widget.AppCompat.Button">
    <item name="android:textAllCaps">false</item>
</style>

Can I access a form in the controller?

To be able to access the form in your controller, you have to add it to a dummy scope object.

Something like $scope.dummy = {}

For your situation this would mean something like:

<form name="dummy.customerForm">

In your controller you will be able to access the form by:

$scope.dummy.customerForm

and you will be able to do stuff like

$scope.dummy.customerForm.$setPristine()

WIKI LINK

Having a '.' in your models will ensure that prototypal inheritance is in play. So, use <input type="text" ng-model="someObj.prop1"> rather than <input type="text" ng-model="prop1">

If you really want/need to use a primitive, there are two workarounds:

1.Use $parent.parentScopeProperty in the child scope. This will prevent the child scope from creating its own property. 2.Define a function on the parent scope, and call it from the child, passing the primitive value up to the parent (not always possible)

Objective-C for Windows

Also:

The Cocotron is an open source project which aims to implement a cross-platform Objective-C API similar to that described by Apple Inc.'s Cocoa documentation. This includes the AppKit, Foundation, Objective-C runtime and support APIs such as CoreGraphics and CoreFoundation.

http://www.cocotron.org/

Installed Java 7 on Mac OS X but Terminal is still using version 6

Because you need to enter in Java Preferences pane and flag only the JVM 7 in this way :

Java Preferences

To easily and quickly open the Java Preferences pane in Mac OS X you can simply call spotlight with ?+SPACE and type System Preferences it will show up in the last row of the window.

How to compile or convert sass / scss to css with node-sass (no Ruby)?

In Windows 10 using node v6.11.2 and npm v3.10.10, in order to execute directly in any folder:

> node-sass [options] <input.scss> [output.css]

I only followed the instructions in node-sass Github:

  1. Add node-gyp prerequisites by running as Admin in a Powershell (it takes a while):

    > npm install --global --production windows-build-tools
    
  2. In a normal command-line shell (Win+R+cmd+Enter) run:

    > npm install -g node-gyp
    > npm install -g node-sass
    

    The -g places these packages under %userprofile%\AppData\Roaming\npm\node_modules. You may check that npm\node_modules\node-sass\bin\node-sass now exists.

  3. Check if your local account (not the System) PATH environment variable contains:

    %userprofile%\AppData\Roaming\npm
    

    If this path is not present, npm and node may still run, but the modules bin files will not!

Close the previous shell and reopen a new one and run either > node-gyp or > node-sass.

Note:

  • The windows-build-tools may not be necessary (if no compiling is done? I'd like to read if someone made it without installing these tools), but it did add to the admin account the GYP_MSVS_VERSION environment variable with 2015 as a value.
  • I am also able to run directly other modules with bin files, such as > uglifyjs main.js main.min.js and > mocha

Which data structures and algorithms book should I buy?

I think introduction to Algorithms is the reference books, and a must have for any serious programmer.

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

Other fun book is The algorithm design manual http://www.algorist.com/. It covers more sophisticated algorithms.

I can't not mention The art of computer programming of Knuth http://www-cs-faculty.stanford.edu/~knuth/taocp.html

using "if" and "else" Stored Procedures MySQL

you can use CASE WHEN as follow as achieve the as IF ELSE.

SELECT FROM A a 
LEFT JOIN B b 
ON a.col1 = b.col1 
AND (CASE 
        WHEN a.col2 like '0%' then TRIM(LEADING '0' FROM a.col2)
        ELSE substring(a.col2,1,2)
    END
)=b.col2; 

p.s:just in case somebody needs this way.

T-SQL substring - separating first and last name

validate last name is blank

SELECT  
person.fullName,
(CASE WHEN 0 = CHARINDEX(' ', person.fullName) 
    then  person.fullName 
    ELSE SUBSTRING(person.fullName, 1, CHARINDEX(' ', person.fullName)) end) as first_name,  
(CASE WHEN 0 = CHARINDEX(' ', person.fullName) 
    THEN ''  
    ELSE SUBSTRING(person.fullName,CHARINDEX(' ', person.fullName), LEN(person.fullName) )end) last_name

FROM person

Check if string contains a value in array

$owned_urls= array('website1.com', 'website2.com', 'website3.com');
    $string = 'my domain name is website3.com';
    for($i=0; $i < count($owned_urls); $i++)
    {
        if(strpos($string,$owned_urls[$i]) != false)
            echo 'Found';
    }   

How to iterate through an ArrayList of Objects of ArrayList of Objects?

Edit:

Well, he edited his post.

If an Object inherits Iterable, you are given the ability to use the for-each loop as such:

for(Object object : objectListVar) {
     //code here
}

So in your case, if you wanted to update your Guns and their Bullets:

for(Gun g : guns) {
     //invoke any methods of each gun
     ArrayList<Bullet> bullets = g.getBullets()
     for(Bullet b : bullets) {
          System.out.println("X: " + b.getX() + ", Y: " + b.getY());
          //update, check for collisions, etc
     }
}

First get your third Gun object:

Gun g = gunList.get(2);

Then iterate over the third gun's bullets:

ArrayList<Bullet> bullets = g.getBullets();

for(Bullet b : bullets) {
     //necessary code here
}

How To Convert A Number To an ASCII Character?

C# represents a character in UTF-16 coding rather than ASCII. Therefore converting a integer to character do not make any difference for A-Z and a-z. But I was working with ASCII Codes besides alphabets and number which did not work for me as system uses UTF-16 code. Therefore I browsed UTF-16 code for all UTF-16 character. Here is the module :

void utfchars()
{
 int i, a, b, x;
 ConsoleKeyInfo z;
  do
  {
   a = 0; b = 0; Console.Clear();
    for (i = 1; i <= 10000; i++)
    {
     if (b == 20)
     {
      b = 0;
      a = a + 1;
     }
    Console.SetCursorPosition((a * 15) + 1, b + 1);
    Console.Write("{0} == {1}", i, (char)i);
   b = b+1;
   if (i % 100 == 0)
  {
 Console.Write("\n\t\t\tPress any key to continue {0}", b);
 a = 0; b = 0;
 Console.ReadKey(true); Console.Clear();
 }
}
Console.Write("\n\n\n\n\n\n\n\t\t\tPress any key to Repeat and E to exit");
z = Console.ReadKey();
if (z.KeyChar == 'e' || z.KeyChar == 'E') Environment.Exit(0);
} while (1 == 1);
}

What is the garbage collector in Java?

To put it in the most simple terms that even a non-programmer can understand, when a program processes data it creates intermediate data and storage space (variables, arrays, certain object metadata etc.) for that data.

When these objects are accessed across functions or over a certain size, they are allocated from a central heap. Then when they are no long needed, they need to be cleaned up.

There are some very good articles online about how this works, so I'll just cover the very basic definition.

The GC is basically the function that does this cleanup. To do this is clears table entries that aren't referenced by any active objects, effectively deleting the objects, than copies and compacts the memory. It's a little more complicated than this, but you get the idea.

The big problem is some parts this process often requires the entire Java VM to require to be stopped temporarily to take place, as well as this entire process being very processor and memory bandwidth intensive. The various options as of GCs and tuning options for each one are designed to balance these various issues with the whole GC process.

Linq style "For Each"

The official MS line is "because it's not a functional operation" (ie it's a stateful operation).

Couldn't you do something like:

list.Select( x => x+1 )

or if you really need it in a List:

var someValues = new List<int>( list.Select( x => x+1 ) );

How do I make JavaScript beep?

Note:put this code in your javascript at the point you want the beep to occur. and remember to specify the directory or folder where the beep sound is stored(source).

<script>
//Appending HTML5 Audio Tag in HTML Body
$('<audio id="chatAudio"><source src="sound/notify.ogg" type="audio/ogg"><source src="sound/notify.mp3" type="audio/mpeg"><source src="sound/notify.wav" type="audio/wav"></audio>').appendTo('body');

$('#chatAudio')[0].play();
</script>

Reference:http://www.9lessons.info/2013/04/play-notification-sound-using-jquery.html.

I implemented this in a social media i am developing and it works find, a notification like that of facebook when chatting, notifying you that you have a new chat message

Use sudo with password as parameter

The -S switch makes sudo read the password from STDIN. This means you can do

echo mypassword | sudo -S command

to pass the password to sudo

However, the suggestions by others that do not involve passing the password as part of a command such as checking if the user is root are probably much better ideas for security reasons

How do I find which transaction is causing a "Waiting for table metadata lock" state?

SHOW ENGINE INNODB STATUS \G

Look for the Section -

TRANSACTIONS

We can use INFORMATION_SCHEMA Tables.

Useful Queries

To check about all the locks transactions are waiting for:

USE INFORMATION_SCHEMA;
SELECT * FROM INNODB_LOCK_WAITS;

A list of blocking transactions:

SELECT * 
FROM INNODB_LOCKS 
WHERE LOCK_TRX_ID IN (SELECT BLOCKING_TRX_ID FROM INNODB_LOCK_WAITS);

OR

SELECT INNODB_LOCKS.* 
FROM INNODB_LOCKS
JOIN INNODB_LOCK_WAITS
  ON (INNODB_LOCKS.LOCK_TRX_ID = INNODB_LOCK_WAITS.BLOCKING_TRX_ID);

A List of locks on particular table:

SELECT * FROM INNODB_LOCKS 
WHERE LOCK_TABLE = db_name.table_name;

A list of transactions waiting for locks:

SELECT TRX_ID, TRX_REQUESTED_LOCK_ID, TRX_MYSQL_THREAD_ID, TRX_QUERY
FROM INNODB_TRX
WHERE TRX_STATE = 'LOCK WAIT';

Reference - MySQL Troubleshooting: What To Do When Queries Don't Work, Chapter 6 - Page 96.

android pinch zoom

I have an open source library that does this very well. It's a four gesture library that comes with an out-of-the-box pan zoom setting. You can find it here: https://bitbucket.org/warwick/hacergestov3 Or you can download the demo app here: https://play.google.com/store/apps/details?id=com.WarwickWestonWright.HacerGestoV3Demo This is a pure canvas library so it can be used in pretty any scenario. Hope this helps.

JSLint is suddenly reporting: Use the function form of "use strict"

I think everyone missed the "suddenly" part of this question. Most likely, your .jshintrc has a syntax error, so it's not including the 'browser' line. Run it through a json validator to see where the error is.

Pass Javascript Variable to PHP POST

There is a lot of ways to achieve this. In regards to the way you are asking, with a hidden form element.

create this form element inside your form:

<input type="hidden" name="total" value="">

So your form like this:

<form id="sampleForm" name="sampleForm" method="post" action="phpscript.php">
<input type="hidden" name="total" id="total" value="">
<a href="#" onclick="setValue();">Click to submit</a>
</form>

Then your javascript something like this:

<script>
function setValue(){
    document.sampleForm.total.value = 100;
    document.forms["sampleForm"].submit();
}
</script>

ngrok command not found

Windows:

  1. Extract.
  2. Open folder
  3. Right click Windows Powershell.
  4. ngrock http 5000 {your post number instead of 5000}
  5. Make sure local server is running on another cmd too.

//Do not worry about auth step

jQuery - keydown / keypress /keyup ENTERKEY detection?

JavaScript/jQuery

$("#entersomething").keyup(function(e){ 
    var code = e.key; // recommended to use e.key, it's normalized across devices and languages
    if(code==="Enter") e.preventDefault();
    if(code===" " || code==="Enter" || code===","|| code===";"){
        $("#displaysomething").html($(this).val());
    } // missing closing if brace
});

HTML

<input id="entersomething" type="text" /> <!-- put a type attribute in -->
<div id="displaysomething"></div>

Good NumericUpDown equivalent in WPF?

add a textbox and scrollbar

in VB

Private Sub Textbox1_ValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.RoutedPropertyChangedEventArgs(Of System.Double)) Handles Textbox1.ValueChanged
     If e.OldValue > e.NewValue Then
         Textbox1.Text = (Textbox1.Text + 1)
     Else
         Textbox1.Text = (Textbox1.Text - 1)
     End If
End Sub

Mocha / Chai expect.to.throw not catching thrown errors

One other possible implementation, more cumbersome than the .bind() solution, but one that helps to make the point that expect() requires a function that provides a this context to the covered function, you can use a call(), e.g.,

expect(function() {model.get.call(model, 'z');}).to.throw('...');

Split a vector into chunks

If you don't like split() and you don't like matrix() (with its dangling NAs), there's this:

chunk <- function(x, n) (mapply(function(a, b) (x[a:b]), seq.int(from=1, to=length(x), by=n), pmin(seq.int(from=1, to=length(x), by=n)+(n-1), length(x)), SIMPLIFY=FALSE))

Like split(), it returns a list, but it doesn't waste time or space with labels, so it may be more performant.

The container 'Maven Dependencies' references non existing library - STS

I got the same problem and this is how i solved. :

  1. Right click your Spring MVC project, choose Run As -> Maven install. Observe the output console to see the installation progress. After the installation is finished, you can continue to the next step.

enter image description here

enter image description here

  1. Right click your Spring MVC project, choose Maven -> Update Project.

enter image description here

  1. Choose your project and click OK. Wait until update process is finished.
  2. The error still yet, then do Project->Clean and then be sure you have selected our project directory and then do the follow Project->Build.

1 = false and 0 = true?

There's no good reason for 1 to be true and 0 to be false; that's just the way things have always been notated. So from a logical perspective, the function in your API isn't "wrong", per se.

That said, it's normally not advisable to work against the idioms of whatever language or framework you're using without a damn good reason to do so, so whoever wrote this function was probably pretty bone-headed, assuming it's not simply a bug.

Using ZXing to create an Android barcode scanning app

Using the provided IntentInegrator is better. It allows you to prompt your user to install the barcode scanner if they do not have it. It also allows you to customize the messages. The IntentIntegrator.REQUEST_CODE constant holds the value of the request code for the onActivityResult to check for in the above if block.

IntentIntegrator intentIntegrator = new IntentIntegrator(this); // where this is activity 
intentIntegrator.initiateScan(IntentIntegrator.ALL_CODE_TYPES); // or QR_CODE_TYPES if you need to scan QR

IntentIntegrator.java

SQL Server equivalent of MySQL's NOW()?

getdate() or getutcdate().

What is the correct way of reading from a TCP socket in C/C++?

Without knowing your full application it is hard to say what the best way to approach the problem is, but a common technique is to use a header which starts with a fixed length field, which denotes the length of the rest of your message.

Assume that your header consist only of a 4 byte integer which denotes the length of the rest of your message. Then simply do the following.

// This assumes buffer is at least x bytes long,
// and that the socket is blocking.
void ReadXBytes(int socket, unsigned int x, void* buffer)
{
    int bytesRead = 0;
    int result;
    while (bytesRead < x)
    {
        result = read(socket, buffer + bytesRead, x - bytesRead);
        if (result < 1 )
        {
            // Throw your error.
        }

        bytesRead += result;
    }
}

Then later in the code

unsigned int length = 0;
char* buffer = 0;
// we assume that sizeof(length) will return 4 here.
ReadXBytes(socketFileDescriptor, sizeof(length), (void*)(&length));
buffer = new char[length];
ReadXBytes(socketFileDescriptor, length, (void*)buffer);

// Then process the data as needed.

delete [] buffer;

This makes a few assumptions:

  • ints are the same size on the sender and receiver.
  • Endianess is the same on both the sender and receiver.
  • You have control of the protocol on both sides
  • When you send a message you can calculate the length up front.

Since it is common to want to explicitly know the size of the integer you are sending across the network define them in a header file and use them explicitly such as:

// These typedefs will vary across different platforms
// such as linux, win32, OS/X etc, but the idea
// is that a Int8 is always 8 bits, and a UInt32 is always
// 32 bits regardless of the platform you are on.
// These vary from compiler to compiler, so you have to 
// look them up in the compiler documentation.
typedef char Int8;
typedef short int Int16;
typedef int Int32;

typedef unsigned char UInt8;
typedef unsigned short int UInt16;
typedef unsigned int UInt32;

This would change the above to:

UInt32 length = 0;
char* buffer = 0;

ReadXBytes(socketFileDescriptor, sizeof(length), (void*)(&length));
buffer = new char[length];
ReadXBytes(socketFileDescriptor, length, (void*)buffer);

// process

delete [] buffer;

I hope this helps.

How do I recognize "#VALUE!" in Excel spreadsheets?

This will return TRUE for #VALUE! errors (ERROR.TYPE = 3) and FALSE for anything else.

=IF(ISERROR(A1),ERROR.TYPE(A1)=3)

How do I select text nodes with jQuery?

Jauco posted a good solution in a comment, so I'm copying it here:

$(elem)
  .contents()
  .filter(function() {
    return this.nodeType === 3; //Node.TEXT_NODE
  });

What is the difference between 'git pull' and 'git fetch'?

Git obtains the branch of the latest version from the remote to the local using two commands:

  1. git fetch: Git is going to get the latest version from remote to local, but it do not automatically merge.      git fetch origin master git log -p master..origin/master git merge origin/master

         The commands above mean that download latest version of the main branch from origin from the remote to origin master branch. And then compares the local master branch and origin master branch. Finally, merge.

  2. git pull: Git is going to get the latest version from the remote and merge into the local.

        git pull origin master

         The command above is the equivalent to git fetch and git merge. In practice, git fetch maybe more secure because before the merge we can see the changes and decide whether to merge.

Disable future dates in jQuery UI Datepicker

Yes, indeed. The datepicker has the maxdate property that you can set when you initialize it.

Here's the codez

$("#datepicker").datepicker({ maxDate: new Date, minDate: new Date(2007, 6, 12) });

Convert python datetime to epoch with strftime

import time
from datetime import datetime
now = datetime.now()

# same as above except keeps microseconds
time.mktime(now.timetuple()) + now.microsecond * 1e-6

(Sorry, it wouldn't let me comment on existing answer)

What's is the difference between train, validation and test set, in neural networks?

The training and validation sets are used during training.

for each epoch
    for each training data instance
        propagate error through the network
        adjust the weights
        calculate the accuracy over training data
    for each validation data instance
        calculate the accuracy over the validation data
    if the threshold validation accuracy is met
        exit training
    else
        continue training

Once you're finished training, then you run against your testing set and verify that the accuracy is sufficient.

Training Set: this data set is used to adjust the weights on the neural network.

Validation Set: this data set is used to minimize overfitting. You're not adjusting the weights of the network with this data set, you're just verifying that any increase in accuracy over the training data set actually yields an increase in accuracy over a data set that has not been shown to the network before, or at least the network hasn't trained on it (i.e. validation data set). If the accuracy over the training data set increases, but the accuracy over the validation data set stays the same or decreases, then you're overfitting your neural network and you should stop training.

Testing Set: this data set is used only for testing the final solution in order to confirm the actual predictive power of the network.

C/C++ line number

Checkout __FILE__ and __LINE__ macros

How to make child element higher z-index than parent?

Use non-static position along with greater z-index in child element:

.parent {
    position: absolute
    z-index: 100;
}

.child {
    position: relative;
    z-index: 101;
}

Create a CSS rule / class with jQuery at runtime

Adding custom rules is useful if you create a jQuery widget that requires custom CSS (such as extending the existing jQueryUI CSS framework for your particular widget). This solution builds on Taras's answer (the first one above).

Assuming your HTML markup has a button with an id of "addrule" and a div with an id of "target" containing some text:

jQuery code:

$( "#addrule" ).click(function () { addcssrule($("#target")); });

function addcssrule(target) 
{ 
var cssrules =  $("<style type='text/css'> </style>").appendTo("head");

cssrules.append(".redbold{ color:#f00; font-weight:bold;}"); 
cssrules.append(".newfont {font-family: arial;}"); 
target.addClass("redbold newfont");     
}       

The advantage of this approach is that you can reuse variable cssrules in your code to add or subtract rules at will. If cssrules is embedded in a persistent object such as a jQuery widget you have a persistent local variable to work with.

Hiding the R code in Rmarkdown/knit and just showing the results

Alternatively, you can also parse a standard markdown document (without code blocks per se) on the fly by the markdownreports package.

Should have subtitle controller already set Mediaplayer error Android

Also you can only set mediaPlayer.reset() and in onDestroy set it to release.

in iPhone App How to detect the screen resolution of the device

CGRect screenBounds = [[UIScreen mainScreen] bounds];

That will give you the entire screen's resolution in points, so it would most typically be 320x480 for iPhones. Even though the iPhone4 has a much larger screen size iOS still gives back 320x480 instead of 640x960. This is mostly because of older applications breaking.

CGFloat screenScale = [[UIScreen mainScreen] scale];

This will give you the scale of the screen. For all devices that do not have Retina Displays this will return a 1.0f, while Retina Display devices will give a 2.0f and the iPhone 6 Plus (Retina HD) will give a 3.0f.

Now if you want to get the pixel width & height of the iOS device screen you just need to do one simple thing.

CGSize screenSize = CGSizeMake(screenBounds.size.width * screenScale, screenBounds.size.height * screenScale);

By multiplying by the screen's scale you get the actual pixel resolution.

A good read on the difference between points and pixels in iOS can be read here.

EDIT: (Version for Swift)

let screenBounds = UIScreen.main.bounds
let screenScale = UIScreen.main.scale
let screenSize = CGSize(width: screenBounds.size.width * screenScale, height: screenBounds.size.height * screenScale)

How can I get the length of text entered in a textbox using jQuery?

For me its not text box its a span tag and this worked for me.

var len = $("span").text().length;

Run Command Line & Command From VBS

Set oShell = CreateObject ("WScript.Shell") 
oShell.run "cmd.exe /C copy ""S:Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "

Using C# to read/write Excel files (.xls/.xlsx)

If you are doing simple manipulation and can tie yourself to xlsx then you can look into manipulating the XML yourself. I have done it and found it to be faster than grokking the excel libs.

There are also 3rd party libs that can be easier to use... and can be used on the server which MS's can't.

Avoid printStackTrace(); use a logger call instead

The main reason is that Proguard would remove Log calls from production. Because by logging or printing StackTrace, it is possible to see them (information inside stack trace or Log) inside the Android phone by for example Logcat Reader application. So that it is a bad practice for security. Also, we do not access them during production, it would better to get removed from production. As ProGuard remove all Log calls not stackTrace, so it is better to use Log in catch blocks and let them removed from Production by Proguard.

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

There is no rule. I find CTEs more readable, and use them unless they exhibit some performance problem, in which case I investigate the actual problem rather than guess that the CTE is the problem and try to re-write it using a different approach. There is usually more to the issue than the way I chose to declaratively state my intentions with the query.

There are certainly cases when you can unravel CTEs or remove subqueries and replace them with a #temp table and reduce duration. This can be due to various things, such as stale stats, the inability to even get accurate stats (e.g. joining to a table-valued function), parallelism, or even the inability to generate an optimal plan because of the complexity of the query (in which case breaking it up may give the optimizer a fighting chance). But there are also cases where the I/O involved with creating a #temp table can outweigh the other performance aspects that may make a particular plan shape using a CTE less attractive.

Quite honestly, there are way too many variables to provide a "correct" answer to your question. There is no predictable way to know when a query may tip in favor of one approach or another - just know that, in theory, the same semantics for a CTE or a single subquery should execute the exact same. I think your question would be more valuable if you present some cases where this is not true - it may be that you have discovered a limitation in the optimizer (or discovered a known one), or it may be that your queries are not semantically equivalent or that one contains an element that thwarts optimization.

So I would suggest writing the query in a way that seems most natural to you, and only deviate when you discover an actual performance problem the optimizer is having. Personally I rank them CTE, then subquery, with #temp table being a last resort.

How to make a <div> appear in front of regular text/tables

It moves table down because there is no much space, try to decrease/increase width of certain elements so that it finds some space and does not push the table down. Also you may want to use absolute positioning to position the div at exactly the place you want, for example:

<style>
 #div_id
 {
   position:absolute;
   top:100px; /* set top value */
   left:100px; /* set left value */
   width:100px;  /* set width value */
 }
</style>

If you want to appear it over something, you also need to give it z-index, so it might look like this:

<style>
 #div_id
 {
   position:absolute;
   z-index:999;
   top:100px; /* set top value */
   left:100px; /* set left value */
   width:100px;  /* set width value */
 }
</style>

How can I list the scheduled jobs running in my database?

Because the SCHEDULER_ADMIN role is a powerful role allowing a grantee to execute code as any user, you should consider granting individual Scheduler system privileges instead. Object and system privileges are granted using regular SQL grant syntax. An example is if the database administrator issues the following statement:

GRANT CREATE JOB TO scott;

After this statement is executed, scott can create jobs, schedules, or programs in his schema.

copied from http://docs.oracle.com/cd/B19306_01/server.102/b14231/schedadmin.htm#i1006239

Check if a number is a perfect square

The idea is to run a loop from i = 1 to floor(sqrt(n)) then check if squaring it makes n.

bool isPerfectSquare(int n) 
{ 
    for (int i = 1; i * i <= n; i++) { 

        // If (i * i = n) 
        if ((n % i == 0) && (n / i == i)) { 
            return true; 
        } 
    } 
    return false; 
} 

Intellij Idea: Importing Gradle project - getting JAVA_HOME not defined yet

If you'd like to have your JAVA_HOME recognised by intellij, you can do one of these:

  • Start your intellij from terminal /Applications/IntelliJ IDEA 14.app/Contents/MacOS (this will pick your bash env variables)
  • Add login env variable by executing: launchctl setenv JAVA_HOME "/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home"

As others have answered you can ignore JAVA_HOME by setting up SDK in project structure.

How to use Bootstrap modal using the anchor tag for Register?

Here is a link to W3Schools that answers your question https://www.w3schools.com/bootstrap/bootstrap_ref_js_modal.asp

Note: For anchor tag elements, omit data-target, and use href="#modalID" instead:

I hope that helps

WebSockets and Apache proxy : how to configure mod_proxy_wstunnel?

In addition to the main answer: if you have more than one service on the same server that uses websockets, you might want to do this to separate them, by using a custom path (*):

Node server:

var io = require('socket.io')({ path: '/ws_website1'}).listen(server);

Client HTML:

<script src="/ws_website1/socket.io.js"></script>
...
<script>
var socket = io('', { path: '/ws_website1' });
...

Apache config:

RewriteEngine On

RewriteRule ^/website1(.*)$ http://localhost:3001$1 [P,L]

RewriteCond %{REQUEST_URI}  ^/ws_website1 [NC]
RewriteCond %{QUERY_STRING} transport=websocket [NC]
RewriteRule ^(.*)$ ws://localhost:3001$1 [P,L]

RewriteCond %{REQUEST_URI}  ^/ws_website1 [NC]
RewriteRule ^(.*)$ http://localhost:3001$1 [P,L]

(*) Note: using the default RewriteCond %{REQUEST_URI} ^/socket.io would not be specific to a website, and websockets requests would be mixed up between different websites!

Inconsistent accessibility: property type is less accessible

Your class Delivery has no access modifier, which means it defaults to internal. If you then try to expose a property of that type as public, it won't work. Your type (class) needs to have the same, or higher access as your property.

More about access modifiers: http://msdn.microsoft.com/en-us/library/ms173121.aspx

What is the difference between display: inline and display: inline-block?

A visual answer

Imagine a <span> element inside a <div>. If you give the <span> element a height of 100px and a red border for example, it will look like this with

display: inline

display: inline

display: inline-block

display: inline-block

display: block

enter image description here

Code: http://jsfiddle.net/Mta2b/

Elements with display:inline-block are like display:inline elements, but they can have a width and a height. That means that you can use an inline-block element as a block while flowing it within text or other elements.

Difference of supported styles as summary:

  • inline: only margin-left, margin-right, padding-left, padding-right
  • inline-block: margin, padding, height, width

Java: unparseable date exception

I encountered this error working in Talend. I was able to store S3 CSV files created from Redshift without a problem. The error occurred when I was trying to load the same S3 CSV files into an Amazon RDS MySQL database. I tried the default timestamp Talend timestamp formats but they were throwing exception:unparseable date when loading into MySQL.

This from the accepted answer helped me solve this problem:

By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern

The key to my solution was changing the Talend schema. Talend set the timestamp field to "date" so I changed it to "timestamp" then I inserted "yyyy-MM-dd HH:mm:ss z" into the format string column view a screenshot here talend schema

I had other issues with 12 hour and 24 hour timestamp translations until I added the "z" at the end of the timestamp string.

Align Bootstrap Navigation to Center

.navbar-nav {
   float: left;
   margin: 0;
   margin-left: 40%;
}

.navbar-nav.navbar-right:last-child {
   margin-right: -15px;
   margin-left: 0;
}

Updated Fiddle

Since You Have used the float property we don't have many options except to adjust it manually.

Save attachments to a folder and rename them

Public Sub Extract_Outlook_Email_Attachments()

Dim OutlookOpened As Boolean
Dim outApp As Outlook.Application
Dim outNs As Outlook.Namespace
Dim outFolder As Outlook.MAPIFolder
Dim outAttachment As Outlook.Attachment
Dim outItem As Object
Dim saveFolder As String
Dim outMailItem As Outlook.MailItem
Dim inputDate As String, subjectFilter As String


saveFolder = "Y:\Wingman" ' THIS IS WHERE YOU WANT TO SAVE THE ATTACHMENT TO

If Right(saveFolder, 1) <> "\" Then saveFolder = saveFolder & "\"

subjectFilter = ("Daily Operations Custom All Req Statuses Report") ' THIS IS WHERE YOU PLACE THE EMAIL SUBJECT FOR THE CODE TO FIND

OutlookOpened = False
On Error Resume Next
Set outApp = GetObject(, "Outlook.Application")
If Err.Number <> 0 Then
    Set outApp = New Outlook.Application
    OutlookOpened = True
End If
On Error GoTo 0

If outApp Is Nothing Then
    MsgBox "Cannot start Outlook.", vbExclamation
    Exit Sub
End If

Set outNs = outApp.GetNamespace("MAPI")
Set outFolder = outNs.GetDefaultFolder(olFolderInbox)

If Not outFolder Is Nothing Then
    For Each outItem In outFolder.Items
        If outItem.Class = Outlook.OlObjectClass.olMail Then
            Set outMailItem = outItem
                If InStr(1, outMailItem.Subject, subjectFilter) > 0 Then 'removed the quotes around subjectFilter
                    For Each outAttachment In outMailItem.Attachments
                    outAttachment.SaveAsFile saveFolder & outAttachment.filename

                    Set outAttachment = Nothing

                    Next
                End If
        End If
    Next
End If

If OutlookOpened Then outApp.Quit

Set outApp = Nothing

End Sub

How to echo out the values of this array?

var_dump($value)

it solved my problem, hope yours too.

Placing/Overlapping(z-index) a view above another view in android

RelativeLayout works the same way, the last image in the relative layout wins.

How to create an instance of System.IO.Stream stream

Stream stream = new MemoryStream();

you can use MemoryStream

Reference: MemoryStream

How to execute raw queries with Laravel 5.1?

you can run raw query like this way too.

DB::table('setting_colleges')->first();

Wait for a void async method

You don't really need to do anything manually, await keyword pauses the function execution until blah() returns.

private async void SomeFunction()
{
     var x = await LoadBlahBlah(); <- Function is not paused
     //rest of the code get's executed even if LoadBlahBlah() is still executing
}

private async Task<T> LoadBlahBlah()
{
     await DoStuff();  <- function is paused
     await DoMoreStuff();
}

T is type of object blah() returns

You can't really await a void function so LoadBlahBlah() cannot be void

Select from where field not equal to Mysql Php

Or can also insert the statement inside bracket.

SELECT * FROM tablename WHERE NOT (columnA = 'x')

Skip a submodule during a Maven build

It's possible to decide which reactor projects to build by specifying the -pl command line argument:

$ mvn --help
[...]
 -pl,--projects <arg>                   Build specified reactor projects
                                        instead of all projects
[...]

It accepts a comma separated list of parameters in one of the following forms:

  • relative path of the folder containing the POM
  • [groupId]:artifactId

Thus, given the following structure:

project-root [com.mycorp:parent]
  |
  + --- server [com.mycorp:server]
  |       |
  |       + --- orm [com.mycorp.server:orm]
  |
  + --- client [com.mycorp:client]

You can specify the following command line:

mvn -pl .,server,:client,com.mycorp.server:orm clean install

to build everything. Remove elements in the list to build only the modules you please.


EDIT: as blackbuild pointed out, as of Maven 3.2.1 you have a new -el flag that excludes projects from the reactor, similarly to what -pl does:

How to add a Java Properties file to my Java Project in Eclipse

If you have created a Java Project in eclipse by using the 'from existing source' option then it should work as it did before. To be more precise File > New Java Project. In the Contents section select 'Create project from existing source' and then select your existing project folder. The wizard will take care of the rest.

Selenium -- How to wait until page is completely loaded

3 answers, which you can combine:

  1. Set implicit wait immediately after creating the web driver instance:

    _ = driver.Manage().Timeouts().ImplicitWait;

    This will try to wait until the page is fully loaded on every page navigation or page reload.

  2. After page navigation, call JavaScript return document.readyState until "complete" is returned. The web driver instance can serve as JavaScript executor. Sample code:

    C#

    new WebDriverWait(driver, MyDefaultTimeout).Until(
    d => ((IJavaScriptExecutor) d).ExecuteScript("return document.readyState").Equals("complete"));
    

    Java

    new WebDriverWait(firefoxDriver, pageLoadTimeout).until(
          webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
    
  3. Check if the URL matches the pattern you expect.

Compiler error "archive for required library could not be read" - Spring Tool Suite

Ok, I had the same problem with STS on a mac and solved it by deleting all the files in repository folder and from the STS IDE click on the project and then Maven -> Update project. Give it a couple of minutes to download all the dependencies and the problem is solved.

How can I get a favicon to show up in my django app?

Best practices :

Contrary to what you may think, the favicon can be of any size and of any image type. Follow this link for details.

Not putting a link to your favicon can slow down the page load.

In a django project, suppose the path to your favicon is :

myapp/static/icons/favicon.png

in your django templates (preferably in the base template), add this line to head of the page :

<link rel="shortcut icon" href="{%  static 'icons/favicon.png' %}">

Note :

We suppose, the static settings are well configured in settings.py.

How to avoid annoying error "declared and not used"

As far as I can tell, these lines in the Go compiler look like the ones to comment out. You should be able to build your own toolchain that ignores these counterproductive warnings.

Object of custom type as dictionary key

You need to add 2 methods, note __hash__ and __eq__:

class MyThing:
    def __init__(self,name,location,length):
        self.name = name
        self.location = location
        self.length = length

    def __hash__(self):
        return hash((self.name, self.location))

    def __eq__(self, other):
        return (self.name, self.location) == (other.name, other.location)

    def __ne__(self, other):
        # Not strictly necessary, but to avoid having both x==y and x!=y
        # True at the same time
        return not(self == other)

The Python dict documentation defines these requirements on key objects, i.e. they must be hashable.

#if DEBUG vs. Conditional("DEBUG")

Well, it's worth noting that they don't mean the same thing at all.

If the DEBUG symbol isn't defined, then in the first case the SetPrivateValue itself won't be called... whereas in the second case it will exist, but any callers who are compiled without the DEBUG symbol will have those calls omitted.

If the code and all its callers are in the same assembly this difference is less important - but it means that in the first case you also need to have #if DEBUG around the calling code as well.

Personally I'd recommend the second approach - but you do need to keep the difference between them clear in your head.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)

When you get a UnicodeEncodeError, it means that somewhere in your code you convert directly a byte string to a unicode one. By default in Python 2 it uses ascii encoding, and utf8 encoding in Python3 (both may fail because not every byte is valid in either encoding)

To avoid that, you must use explicit decoding.

If you may have 2 different encoding in your input file, one of them accepts any byte (say UTF8 and Latin1), you can try to first convert a string with first and use the second one if a UnicodeDecodeError occurs.

def robust_decode(bs):
    '''Takes a byte string as param and convert it into a unicode one.
First tries UTF8, and fallback to Latin1 if it fails'''
    cr = None
    try:
        cr = bs.decode('utf8')
    except UnicodeDecodeError:
        cr = bs.decode('latin1')
    return cr

If you do not know original encoding and do not care for non ascii character, you can set the optional errors parameter of the decode method to replace. Any offending byte will be replaced (from the standard library documentation):

Replace with a suitable replacement character; Python will use the official U+FFFD REPLACEMENT CHARACTER for the built-in Unicode codecs on decoding and ‘?’ on encoding.

bs.decode(errors='replace')

Wait until all jQuery Ajax requests are done?

NOTE: The above answers use functionality that didn't exist at the time that this answer was written. I recommend using jQuery.when() instead of these approaches, but I'm leaving the answer for historical purposes.

-

You could probably get by with a simple counting semaphore, although how you implement it would be dependent on your code. A simple example would be something like...

var semaphore  = 0,     // counting semaphore for ajax requests
    all_queued = false; // bool indicator to account for instances where the first request might finish before the second even starts

semaphore++;
$.get('ajax/test1.html', function(data) {
    semaphore--;
    if (all_queued && semaphore === 0) {
        // process your custom stuff here
    }
});

semaphore++;
$.get('ajax/test2.html', function(data) {
    semaphore--;
    if (all_queued && semaphore === 0) {
        // process your custom stuff here
    }
});

semaphore++;
$.get('ajax/test3.html', function(data) {
    semaphore--;
    if (all_queued && semaphore === 0) {
        // process your custom stuff here
    }
});

semaphore++;
$.get('ajax/test4.html', function(data) {
    semaphore--;
    if (all_queued && semaphore === 0) {
        // process your custom stuff here
    }
});

// now that all ajax requests are queued up, switch the bool to indicate it
all_queued = true;

If you wanted this to operate like {async: false} but you didn't want to lock the browser, you could accomplish the same thing with a jQuery queue.

var $queue = $("<div/>");
$queue.queue(function(){
    $.get('ajax/test1.html', function(data) {
        $queue.dequeue();
    });
}).queue(function(){
    $.get('ajax/test2.html', function(data) {
        $queue.dequeue();
    });
}).queue(function(){
    $.get('ajax/test3.html', function(data) {
        $queue.dequeue();
    });
}).queue(function(){
    $.get('ajax/test4.html', function(data) {
        $queue.dequeue();
    });
});

Simple URL GET/POST function in Python

import urllib

def fetch_thing(url, params, method):
    params = urllib.urlencode(params)
    if method=='POST':
        f = urllib.urlopen(url, params)
    else:
        f = urllib.urlopen(url+'?'+params)
    return (f.read(), f.code)


content, response_code = fetch_thing(
                              'http://google.com/', 
                              {'spam': 1, 'eggs': 2, 'bacon': 0}, 
                              'GET'
                         )

[Update]

Some of these answers are old. Today I would use the requests module like the answer by robaple.

Randomize a List<T>

One can use the Shuffle extension methond from morelinq package, it works on IEnumerables

install-package morelinq

using MoreLinq;
...    
var randomized = list.Shuffle();

Is there a constraint that restricts my generic method to numeric types?

The .NET numeric primitive types do not share any common interface that would allow them to be used for calculations. It would be possible to define your own interfaces (e.g. ISignedWholeNumber) which would perform such operations, define structures which contain a single Int16, Int32, etc. and implement those interfaces, and then have methods which accept generic types constrained to ISignedWholeNumber, but having to convert numeric values to your structure types would likely be a nuisance.

An alternative approach would be to define static class Int64Converter<T> with a static property bool Available {get;}; and static delegates for Int64 GetInt64(T value), T FromInt64(Int64 value), bool TryStoreInt64(Int64 value, ref T dest). The class constructor could use be hard-coded to load delegates for known types, and possibly use Reflection to test whether type T implements methods with the proper names and signatures (in case it's something like a struct which contains an Int64 and represents a number, but has a custom ToString() method). This approach would lose the advantages associated with compile-time type-checking, but would still manage to avoid boxing operations and each type would only have to be "checked" once. After that, operations associated with that type would be replaced with a delegate dispatch.

How to prevent Screen Capture in Android

According to this official guide, you can add WindowManager.LayoutParams.FLAG_SECURE to your window layout and it will disallow screenshots.

Location of the mongodb database on mac

I have just installed mongodb 3.4 with homebrew.(brew install mongodb) It looks for /data/db by default.

https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/

Here is the output of mongod execution.

Remove menubar from Electron app

These solutions has bug. When use solutions at below, windows has delay at closing.

Menu.setApplicationMenu(null),
&&
const updateErrorWindow = new BrowserWindow({autoHideMenuBar: true});

I used solution at below. This is better for now.

const window= new BrowserWindow({...});
window.setMenuBarVisibility(false);

Is it possible to change javascript variable values while debugging in Google Chrome?

Why is this answer still getting upvotes?

Per Mikaël Mayer's answer, this is no longer a problem, and my answer is obsolete (go() now returns 30 after mucking with the console). This was fixed in July 2013, according to the bug report linked above in gabrielmaldi's comment. It alarms me that I'm still getting upvotes - makes me think the upvoter doesn't understand either the question or my answer.

I'll leave my original answer here for historical reasons, but go upvote Mikaël's answer instead.


The trick is that you can't change a local variable directly, but you can modify the properties of an object. You can also modify the value of a global variable:

var g_n = 0;
function go()
{
    var n = 0;
    var o = { n: 0 };
    return g_n + n + o.n;  // breakpoint here
}

console:

> g_n = 10
  10
> g_n
  10
> n = 10
  10
> n
  0
> o.n = 10
  10
> o.n
  10

Check the result of go() after setting the breakpoint and running those calls in the console, and you'll find that the result is 20, rather than 0 (but sadly, not 30).

Change priorityQueue to max priorityqueue

You can provide a custom Comparator object that ranks elements in the reverse order:

PriorityQueue<Integer> pq = new PriorityQueue<Integer>(defaultSize, new Comparator<Integer>() {
    public int compare(Integer lhs, Integer rhs) {
        if (lhs < rhs) return +1;
        if (lhs.equals(rhs)) return 0;
        return -1;
    }
});

Now, the priority queue will reverse all its comparisons, so you will get the maximum element rather than the minimum element.

Hope this helps!

Return Type for jdbcTemplate.queryForList(sql, object, classType)

A complete solution for JdbcTemplate, NamedParameterJdbcTemplate with or without RowMapper Example.

// Create a Employee table

create table employee(  
id number(10),  
name varchar2(100),  
salary number(10)  
);

======================================================================= //Employee.java

public class Employee {
private int id;  
private String name;  
private float salary;  

//no-arg and parameterized constructors  

public Employee(){};

public Employee(int  id, String name, float salary){
    this.id=id;
    this.name=name;
    this.salary=salary;
}

//getters and setters  
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public float getSalary() {
    return salary;
}
public void setSalary(float salary) {
    this.salary = salary;
}
public String toString(){  
   return id+" "+name+" "+salary;  
}   

}

========================================================================= //EmployeeDao.java

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

public class EmployeeDao {  
  private JdbcTemplate jdbcTemplate;  
  private NamedParameterJdbcTemplate nameTemplate;  

  public void setnameTemplate(NamedParameterJdbcTemplate template) {  
    this.nameTemplate = template;  
 }   

 public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
  this.jdbcTemplate = jdbcTemplate;  
 }  

 // BY using JdbcTemplate
 public int saveEmployee(Employee e){  
 int id = e.getId();
 String name = e.getName();
 float salary = e.getSalary();
 Object p[] = {id, name, salary};
    String query="insert into employee values(?,?,?)";
      return jdbcTemplate.update(query, p);
    /*String query="insert into employee     values('"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')"; 
      return jdbcTemplate.update(query);
    */

}  

//By using NameParameterTemplate
public void insertEmploye(Employee e) {  
String query="insert into employee values (:id,:name,:salary)";  
Map<String,Object> map=new HashMap<String,Object>();  
map.put("id",e.getId());  
map.put("name",e.getName());  
map.put("salary",e.getSalary());  

nameTemplate.execute(query,map,new MyPreparedStatement());

 }
// Updating Employee
public int updateEmployee(Employee e){  
String query="update employee set  name='"+e.getName()+"',salary='"+e.getSalary()+"' where id='"+e.getId()+"' ";  
  return jdbcTemplate.update(query);  
 }
 // Deleting a Employee row
 public int deleteEmployee(Employee e){  
 String query="delete from employee where id='"+e.getId()+"' ";  
 return jdbcTemplate.update(query);  
 }  
 //Selecting Single row with condition and also all rows
    public int selectEmployee(Employee e){  
     //String query="select * from employee where id='"+e.getId()+"' ";
      String query="select * from employee";
      List<Map<String, Object>> rows = jdbcTemplate.queryForList(query);
       for(Map<String, Object> row : rows){
          String id = row.get("id").toString();
          String name = (String)row.get("name");
          String salary = row.get("salary").toString();
          System.out.println(id + " " + name + " " + salary );
        }

      return 1;
   }  

   // Can use MyrowMapper class an implementation class for RowMapper interface
    public void getAllEmployee()
    {

    String query="select * from employee";
    List<Employee> l = jdbcTemplate.query(query, new MyrowMapper());

    Iterator it=l.iterator();
    while(it.hasNext())
    {
      Employee e=(Employee)it.next();
      System.out.println(e.getId()+" "+e.getName()+" "+e.getSalary());
    }
   }  

  //Can use directly a RowMapper implementation class without an object creation
  public List<Employee> getAllEmployee1(){
    return jdbcTemplate.query("select * from employee",new RowMapper<Employee>(){  
      @Override  
      public Employee mapRow(ResultSet rs, int rownumber) throws  SQLException    {  
            Employee e=new Employee();  
            e.setId(rs.getInt(1));  
            e.setName(rs.getString(2));  
            e.setSalary(rs.getFloat(3));  
            return e;  
          }  
      });  
      }
     // End of all the function

     }

================================================================ //MyrowMapper.java

 import java.sql.ResultSet;
 import java.sql.SQLException;
 import org.springframework.jdbc.core.RowMapper;

 public class MyrowMapper implements RowMapper<Employee> {

  @Override  
  public Employee mapRow(ResultSet rs, int rownumber) throws SQLException 
   {  
    System.out.println("mapRow()====:"+rownumber);
    Employee e=new Employee();  
     e.setId(rs.getInt("id"));  
     e.setName(rs.getString("name"));  
     e.setSalary(rs.getFloat("salary"));  
     return e;  
      }
    } 

========================================================== //MyPreparedStatement.java

import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;


 public class MyPreparedStatement implements  PreparedStatementCallback<Object> {

 @Override
 public Object doInPreparedStatement(PreparedStatement ps)
        throws SQLException, DataAccessException {

     return ps.executeUpdate(); 
  } 

 } 

===================================================================== //Test.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {  

public static void main(String[] args) {  
 ApplicationContext ctx=new     ClassPathXmlApplicationContext("applicationContext.xml");  

 EmployeeDao dao=(EmployeeDao)ctx.getBean("edao"); 

  // By calling constructor for insert
 /* 
    int status=dao.saveEmployee(new Employee(103,"Ajay",35000));  
    System.out.println(status);  
 */
 // By calling PreparedStatement
  dao.insertEmploye(new Employee(103,"Roh",25000));


 // By calling setter-getter for update
 /* 
    Employee e=new Employee(); 
    e.setId(102);
    e.setName("Rohit");
    e.setSalary(8000000);
    int status=dao.updateEmployee(e);
*/
 // By calling constructor for update
 /*
    int status=dao.updateEmployee(new Employee(102,"Sadhan",15000)); 
    System.out.println(status); 
 */ 
 // Deleting a record 
 /*      
    Employee e=new Employee(); 
    e.setId(102); 
    int status=dao.deleteEmployee(e); 
    System.out.println(status);
 */
 // Selecting single or all rows
 /*
    Employee e=new Employee(); 
    e.setId(102);
    int status=dao.selectEmployee(e);
    System.out.println(status);
*/
// Can use MyrowMapper class an implementation class for RowMapper interface

    dao.getAllEmployee();

// Can use directly a RowMapper implementation class without an object creation
 /*
    List<Employee> list=dao.getAllEmployee1();  
    for(Employee e1:list)  
    System.out.println(e1);  
  */   
   }  

 } 

================================================================== //applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans  
 xmlns="http://www.springframework.org/schema/beans"  
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 xmlns:p="http://www.springframework.org/schema/p"  
 xsi:schemaLocation="http://www.springframework.org/schema/beans   
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  

<bean id="ds"        class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
 <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />  
 <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />  
 <property name="username" value="hr" />  
 <property name="password" value="hr" />  
 </bean>  

 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
 <property name="dataSource" ref="ds"></property>  
 </bean>  

<bean id="nameTemplate"   
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">  
<constructor-arg ref="ds"></constructor-arg>  
</bean>  

<bean id="edao" class="EmployeeDao"> 
<!-- Can use both --> 
<property name="nameTemplate" ref="nameTemplate"></property>
<property name="jdbcTemplate" ref="jdbcTemplate"></property> 
</bean>  

===================================================================

Convert DataSet to List

Fill the dataset with data from, say a stored proc command

DbDataAdapter adapter = DbProviderFactories.GetFactory(cmd.Connection).CreateDataAdapter();
adapter.SelectCommand = cmd;
DataSet ds = new DataSet();
adapter.Fill(ds);

Get The Schema,

string s = ds.GetXmlSchema();

save it to a file say: datasetSchema.xsd. Generate the C# classes for the Schema: (at the VS Command Prompt)

xsd datasetSchema.xsd /c

Now, when you need to convert the DataSet data to classes you can deserialize (the default name given to the generated root class is NewDataSet):

public static T Create<T>(string xml)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    using (StringReader reader = new StringReader(xml))
    {
        T t = (T)serializer.Deserialize(reader);

        reader.Close();
        return t;
    }
}

var xml = ds.GetXml();
var dataSetObjects = Create<NewDataSet>(xml);

git remove merge commit from history

There are two ways to tackle this based on what you want:

Solution 1: Remove purple commits, preserving history (incase you want to roll back)

git revert -m 1 <SHA of merge>

-m 1 specifies which parent line to choose

Purple commits will still be there in history but since you have reverted, you will not see code from those commits.


Solution 2: Completely remove purple commits (disruptive change if repo is shared)

git rebase -i <SHA before branching out>

and delete (remove lines) corresponding to purple commits.

This would be less tricky if commits were not made after merge. Additional commits increase the chance of conflicts during revert/rebase.

How to show imageView full screen on imageView click?

use following property of ImageView for full size of image

 android:scaleType="fitXY"

ex :

      <ImageView
        android:id="@+id/tVHeader2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"
        android:gravity="center"
        android:src="@drawable/done_sunheading" />

1)Switch on other activity when click on image.

2)pass url in intent

3)Take imageview on that Activity and set above property of imageview

4)Get the url from intent and set that image.

but using this your image may be starched if it will of small size.

Should URL be case sensitive?

URL characters are converted into hex code (if you've ever noticed spaces in URLs being displayed as %20, etc.), and since lower and upper case have different hex values, it makes perfect sense that URLs are most definitely case sensitive. However the spirit of the question seems to be SHOULD that be the standard and I say no, but they are. Its up to the developer/provider to account for this in their code if they want it to work regardless for an end user.

Disable password authentication for SSH

In file /etc/ssh/sshd_config

# Change to no to disable tunnelled clear text passwords
#PasswordAuthentication no

Uncomment the second line, and, if needed, change yes to no.

Then run

service ssh restart

how to Call super constructor in Lombok

As an option you can use com.fasterxml.jackson.databind.ObjectMapper to initialize a child class from parent

public class A {
    int x;
    int y;
}

public class B extends A {
    int z;
}

ObjectMapper MAPPER = new ObjectMapper(); //it's configurable
MAPPER.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false );
MAPPER.configure( SerializationFeature.FAIL_ON_EMPTY_BEANS, false );

//Then wherever you need to initialize child from parent:
A parent = new A(x, y);
B child = MAPPER.convertValue( parent, B.class);
child.setZ(z);

You can still use any lombok annotations on A and B if you need.

What key in windows registry disables IE connection parameter "Automatically Detect Settings"?

I'm aware that this question is a bit old, but I consider that my small update could help other programmers.

I didn't want to modify WhoIsRich's answer because it's really great, but I adapted it to fulfill my needs:

  1. If the Automatically Detect Settings is checked then uncheck it.
  2. If the Automatically Detect Settings is unchecked then check it.

    On Error Resume Next
    
    Set oReg   = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
    sKeyPath   = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections"
    sValueName = "DefaultConnectionSettings"
    
    ' Get registry value where each byte is a different setting.
    oReg.GetBinaryValue &H80000001, sKeyPath, sValueName, bValue
    
    ' Check byte to see if detect is currently on.
    If (bValue(8) And 8) = 8 Then
        ' To change the value to Off.
        bValue(8) = bValue(8) And Not 8
    ' Check byte to see if detect is currently off.
    ElseIf (bValue(8) And 8) = 0 Then
        ' To change the value to On.
        bValue(8) = bValue(8) Or 8
    End If
    
    'Write back settings value
    oReg.SetBinaryValue &H80000001, sKeyPath, sValueName, bValue
    
    Set oReg = Nothing
    

Finally, you only need to save it in a .VBS file (VBScript) and run it.

vbscript

What is the meaning of the word logits in TensorFlow?

Personal understanding, in TensorFlow domain, logits are the values to be used as input to softmax. I came to this understanding based on this tensorflow tutorial.

https://www.tensorflow.org/tutorials/layers


Although it is true that logit is a function in maths(especially in statistics), I don't think that's the same 'logit' you are looking at. In the book Deep Learning by Ian Goodfellow, he mentioned,

The function s-1(x) is called the logit in statistics, but this term is more rarely used in machine learning. s-1(x) stands for the inverse function of logistic sigmoid function.

In TensorFlow, it is frequently seen as the name of last layer. In Chapter 10 of the book Hands-on Machine Learning with Scikit-learn and TensorFLow by Aurélien Géron, I came across this paragraph, which stated logits layer clearly.

note that logits is the output of the neural network before going through the softmax activation function: for optimization reasons, we will handle the softmax computation later.

That is to say, although we use softmax as the activation function in the last layer in our design, for ease of computation, we take out logits separately. This is because it is more efficient to calculate softmax and cross-entropy loss together. Remember that cross-entropy is a cost function, not used in forward propagation.

wamp server mysql user id and password

Simply goto MySql Console.

If using Wamp:

  1. Click on Wamp icon just beside o'clock.
  2. In MySql section click on MySql Console.
  3. Press enter (means no password) twice.
  4. mysql commands preview like this : mysql>
  5. SET PASSWORD FOR 'root'@'localhost' = PASSWORD('secret');

That's it. This set your root password to secret

In order to set user privilege to default one:

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('');

Works like a charm!

How to check iOS version?

float deviceOSVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
float versionToBeCompared = 3.1.3; //(For Example in your case)

if(deviceOSVersion < versionToBeCompared)
   //Do whatever you need to do. Device version is lesser than 3.1.3(in your case)
else 
   //Device version should be either equal to the version you specified or above

wget: unable to resolve host address `http'

I have this issue too. I suspect there is an issue with DigitalOcean’s nameservers, so this will likely affect a lot of other people too. Here’s what I’ve done to temporarily get around it - but someone else might be able to advise on a better long-term fix:

  1. Make sure your DNS Resolver config file is writable:

    sudo chmod o+r /etc/resolv.conf

  2. Temporarily change your DNS to use Google’s nameservers instead of DigitalOcean’s:

    sudo nano /etc/resolv.conf

Change the IP address in the file to: 8.8.8.8

Press CTRL + X to save the file.

This is only a temporary fix as this file is automatically written/updated by the server, however, I’ve not yet worked out what writes to it so that I can update it permanently.

How do I clear/delete the current line in terminal?

You can use Ctrl+U to clear up to the beginning.

You can use Ctrl+W to delete just a word.

You can also use Ctrl+C to cancel.

If you want to keep the history, you can use Alt+Shift+# to make it a comment.


Bash Emacs Editing Mode Cheat Sheet

Check if process returns 0 with batch file

You can use below command to check if it returns 0 or 1 :

In below example, I am checking for the string in the one particular file which will give you 1 if that particular word "Error" is not present in the file and if present then 0

find /i "| ERROR1 |" C:\myfile.txt
echo %errorlevel%

if %errorlevel% equ 1 goto notfound
goto found
:notfound
exit 1
:found
echo we found the text.

AngularJS - Building a dynamic table based on a json

First off all I would like to thanks @MaximShoustin.

Thanks of you I have really nice table.

I provide some small modification in $scope.range and $scope.setPage.

In this way I have now possibility to go to the last page or come back to the first page. Also when I'm going to next or prev page the navigation is changing when $scope.gap is crossing. And the current page is not always on first position. For me it's looking more nicer.

Here is the new fiddle example: http://jsfiddle.net/qLBRZ/3/

IN Clause with NULL or IS NULL

Null refers to an absence of data. Null is formally defined as a value that is unavailable, unassigned, unknown or inapplicable (OCA Oracle Database 12c, SQL Fundamentals I Exam Guide, p87). So, you may not see records with columns containing null values when said columns are restricted using an "in" or "not in" clauses.

Concatenate a vector of strings/character

Try using an empty collapse argument within the paste function:

paste(sdata, collapse = '')

Thanks to http://twitter.com/onelinetips/status/7491806343

HTTP status code for update and delete?

{
    "VALIDATON_ERROR": {
        "code": 512,
        "message": "Validation error"
    },
    "CONTINUE": {
        "code": 100,
        "message": "Continue"
    },
    "SWITCHING_PROTOCOLS": {
        "code": 101,
        "message": "Switching Protocols"
    },
    "PROCESSING": {
        "code": 102,
        "message": "Processing"
    },
    "OK": {
        "code": 200,
        "message": "OK"
    },
    "CREATED": {
        "code": 201,
        "message": "Created"
    },
    "ACCEPTED": {
        "code": 202,
        "message": "Accepted"
    },
    "NON_AUTHORITATIVE_INFORMATION": {
        "code": 203,
        "message": "Non Authoritative Information"
    },
    "NO_CONTENT": {
        "code": 204,
        "message": "No Content"
    },
    "RESET_CONTENT": {
        "code": 205,
        "message": "Reset Content"
    },
    "PARTIAL_CONTENT": {
        "code": 206,
        "message": "Partial Content"
    },
    "MULTI_STATUS": {
        "code": 207,
        "message": "Multi-Status"
    },
    "MULTIPLE_CHOICES": {
        "code": 300,
        "message": "Multiple Choices"
    },
    "MOVED_PERMANENTLY": {
        "code": 301,
        "message": "Moved Permanently"
    },
    "MOVED_TEMPORARILY": {
        "code": 302,
        "message": "Moved Temporarily"
    },
    "SEE_OTHER": {
        "code": 303,
        "message": "See Other"
    },
    "NOT_MODIFIED": {
        "code": 304,
        "message": "Not Modified"
    },
    "USE_PROXY": {
        "code": 305,
        "message": "Use Proxy"
    },
    "TEMPORARY_REDIRECT": {
        "code": 307,
        "message": "Temporary Redirect"
    },
    "PERMANENT_REDIRECT": {
        "code": 308,
        "message": "Permanent Redirect"
    },
    "BAD_REQUEST": {
        "code": 400,
        "message": "Bad Request"
    },
    "UNAUTHORIZED": {
        "code": 401,
        "message": "Unauthorized"
    },
    "PAYMENT_REQUIRED": {
        "code": 402,
        "message": "Payment Required"
    },
    "FORBIDDEN": {
        "code": 403,
        "message": "Forbidden"
    },
    "NOT_FOUND": {
        "code": 404,
        "message": "Not Found"
    },
    "METHOD_NOT_ALLOWED": {
        "code": 405,
        "message": "Method Not Allowed"
    },
    "NOT_ACCEPTABLE": {
        "code": 406,
        "message": "Not Acceptable"
    },
    "PROXY_AUTHENTICATION_REQUIRED": {
        "code": 407,
        "message": "Proxy Authentication Required"
    },
    "REQUEST_TIMEOUT": {
        "code": 408,
        "message": "Request Timeout"
    },
    "CONFLICT": {
        "code": 409,
        "message": "Conflict"
    },
    "GONE": {
        "code": 410,
        "message": "Gone"
    },
    "LENGTH_REQUIRED": {
        "code": 411,
        "message": "Length Required"
    },
    "PRECONDITION_FAILED": {
        "code": 412,
        "message": "Precondition Failed"
    },
    "REQUEST_TOO_LONG": {
        "code": 413,
        "message": "Request Entity Too Large"
    },
    "REQUEST_URI_TOO_LONG": {
        "code": 414,
        "message": "Request-URI Too Long"
    },
    "UNSUPPORTED_MEDIA_TYPE": {
        "code": 415,
        "message": "Unsupported Media Type"
    },
    "REQUESTED_RANGE_NOT_SATISFIABLE": {
        "code": 416,
        "message": "Requested Range Not Satisfiable"
    },
    "EXPECTATION_FAILED": {
        "code": 417,
        "message": "Expectation Failed"
    },
    "IM_A_TEAPOT": {
        "code": 418,
        "message": "I'm a teapot"
    },
    "INSUFFICIENT_SPACE_ON_RESOURCE": {
        "code": 419,
        "message": "Insufficient Space on Resource"
    },
    "METHOD_FAILURE": {
        "code": 420,
        "message": "Method Failure"
    },
    "UNPROCESSABLE_ENTITY": {
        "code": 422,
        "message": "Unprocessable Entity"
    },
    "LOCKED": {
        "code": 423,
        "message": "Locked"
    },
    "FAILED_DEPENDENCY": {
        "code": 424,
        "message": "Failed Dependency"
    },
    "PRECONDITION_REQUIRED": {
        "code": 428,
        "message": "Precondition Required"
    },
    "TOO_MANY_REQUESTS": {
        "code": 429,
        "message": "Too Many Requests"
    },
    "REQUEST_HEADER_FIELDS_TOO_LARGE": {
        "code": 431,
        "message": "Request Header Fields Too"
    },
    "UNAVAILABLE_FOR_LEGAL_REASONS": {
        "code": 451,
        "message": "Unavailable For Legal Reasons"
    },
    "INTERNAL_SERVER_ERROR": {
        "code": 500,
        "message": "Internal Server Error"
    },
    "NOT_IMPLEMENTED": {
        "code": 501,
        "message": "Not Implemented"
    },
    "BAD_GATEWAY": {
        "code": 502,
        "message": "Bad Gateway"
    },
    "SERVICE_UNAVAILABLE": {
        "code": 503,
        "message": "Service Unavailable"
    },
    "GATEWAY_TIMEOUT": {
        "code": 504,
        "message": "Gateway Timeout"
    },
    "HTTP_VERSION_NOT_SUPPORTED": {
        "code": 505,
        "message": "HTTP Version Not Supported"
    },
    "INSUFFICIENT_STORAGE": {
        "code": 507,
        "message": "Insufficient Storage"
    },
    "NETWORK_AUTHENTICATION_REQUIRED": {
        "code": 511,
        "message": "Network Authentication Required"
    }
}

Giving my function access to outside variable

The one and probably not so good way of achieving your goal would using global variables.

You could achieve that by adding global $myArr; to the beginning of your function. However note that using global variables is in most cases a bad idea and probably avoidable.

The much better way would be passing your array as an argument to your function:

function someFuntion($arr){
    $myVal = //some processing here to determine value of $myVal
    $arr[] = $myVal;
    return $arr;
}

$myArr = someFunction($myArr);

Select element by exact match of its content

I found a way that works for me. It is not 100% exact but it eliminates all strings that contain more than just the word I am looking for because I check for the string not containing individual spaces too. By the way you don't need these " ". jQuery knows you are looking for a string. Make sure you only have one space in the :contains( ) part otherwise it won't work.

<p>hello</p>
<p>hello world</p>
$('p:contains(hello):not(:contains( ))').css('font-weight', 'bold');

And yes I know it won't work if you have stuff like <p>helloworld</p>

Detect Scroll Up & Scroll down in ListView

Those methods cannot be used to detect scrolling directions directly. There are many ways of getting the direction. A simple code(untested) for one such method is explained below :


public class ScrollTrackingListView extends ListView {

    private boolean readyForMeasurement = false;
    private Boolean isScrollable = null;
    private float prevDistanceToEnd = -1.0;
    private ScrollDirectionListener listener = null;

    public ScrollTrackingListView(Context context) {
        super(context);
        init();
    }

    public ScrollTrackingListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ScrollTrackingListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        ViewTreeObserver observer = getViewTreeObserver();
        observer.addOnGlobalLayoutListener(globalLayoutListener);
        setOnScrollListener(scrollListener);
    }

    private ViewTreeObserver.OnGlobalLayoutListener globalLayoutListener
            = new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            readyForMeasurement = true;
            calculateDistanceToEnd();
        }

    };

    public void registerScrollDirectionListener(ScrollDirectionListener listener) {
        scrollDirectionListener = listener;
    }

    public void unregisterScrollDirectionListener() {
        scrollDirectionListener = null;
    }

    private OnScrollListener scrollListener
            = new OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView absListView, int i) {
            calculateDistanceToEnd();
        }

        @Override
        public void onScroll(AbsListView absListView, int i, int i1, int i2) {
            // Do nothing
        }

    };

    private void calculateDistanceToEnd() {

        if (readyForMeasurement) {

            // I'm using the height of the layout, horizontal scrollbar and
            // content along with scroll down offset

            // computeVerticalScrollExtent is used to compute the length of the thumb within the scrollbar's track.
            // The length of the thumb is a function of the view height and the content length.
            int verticalScrollExtent = computeVerticalScrollExtent();
            int verticalScrollOffset = computeVerticalScrollOffset();
            int verticalScrollRange = computeVerticalScrollRange();
            int horizontalScrollBarHeight = getHorizontalScrollbarHeight();

            /**
             * 1. Let "R" represent the range of the vertical scrollbar. This corresponds to the length of the content
             * in the view.
             * 2. Let "E" represent the extent of the vertical scrollbar. The extent is a constant value and is
             * (probably) equal to a value proportional to the height of the view.
             * 3. Offset "o" represents the current position in the range that is visible to the user. It can take
             * values from "0 to E".
             *
             * Now the DistanceToEnd is calculated using these three values as follows :
             *
             * DistanceToEnd = (R - o) / E
             *
             * DistanceToEnd will hold the value in NumberOfScreenToEnd units.
             *
             */

            float distanceToEnd =
                    ((float)(verticalScrollRange - verticalScrollOffset))/((float)(verticalScrollExtent));

            if(prevDistanceToEnd == -1) {
                 prevDistanceToEnd = distanceToEnd;
            } else {
                 if(listener != null) {
                     if(distanceToEnd > prevDistanceToEnd) {
                        // User is scrolling up
                         listener.onScrollingUp();
                     } else {
                        // User is scrolling up
                         listener.onScrollingDown();
                    }
                 }
                 prevDistanceToEnd = distanceToEnd;
            }

            if(isScrollable == null) {
                // Check if the view height is less than a screen (i.e., no scrolling is enabled)
                if((horizontalScrollBarHeight + verticalScrollExtent) >= verticalScrollRange) {
                    isScrollable = Boolean.FALSE;
                } else {
                    isScrollable = Boolean.TRUE;
                }
            }

        }

    }

    public interface ScrollDirectionListener {

        public void onScrollingUp();

        public void onScrollingDown();

    }

}

The idea is to calculate the distanceToEnd. If distanceToEnd increases, the user is scrolling up and if it decreases, the user is scrolling down. That will also give you the exact distance to the end of the list.

If you are just trying to know whether the user is scrolling up or down you can override the onInterceptTouchEvent to detect the scrolling direction like below :

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mInitialX = event.getX();
                mInitialY = event.getY();
                return true;
            case MotionEvent.ACTION_MOVE:
                final float x = event.getX();
                final float y = event.getY();
                final float yDiff = y - mInitialY; // yDiff less than 0.0 implies scrolling down while yDiff greater than 0.0 implies scrolling up. If I try to add the less than or greater than symbols, the preview refuses to display it.
                if(yDiff less than 0.0) listener.onScrollingDown();
                else if(yDiff greater than 0.0) listener.onScrollingUp();
                break;
        }
        return super.onInterceptTouchEvent(event);
    }

How do I exit the Vim editor?

The q command with a number closes the given split in that position.

:q<split position> or :<split position>q will close the split in that position.

Let's say your Vim window layout is as follows:

-------------------------------------------------
|               |               |               |
-------------------------------------------------
|               |               |               |
|               |               |               |
|    Split 1    |    Split 2    |     Split 3   |
|               |               |               |
-------------------------------------------------

If you run the q1 command, it will close the first split. q2 will close the second split and vice versa.

The order of split position in the quit command does not matter. :2q or :q2 will close the second split.

If the split position you pass to the command is greater than the number of current splits, it will simply close the last split.

For example, if you run the q100 on the above window setup where there are only three splits, it will close the last split (Split 3).

The question has been asked here.

Where is Maven Installed on Ubuntu

$ mvn --version

and look for Maven home: in the output , mine is: Maven home: /usr/share/maven

Iterate Multi-Dimensional Array with Nested Foreach Statement

I was looking for a solution to enumerate an array of an unknown at compile time rank with an access to every element indices set. I saw solutions with yield but here is another implementation with no yield. It is in old school minimalistic way. In this example AppendArrayDebug() just prints all the elements into StringBuilder buffer.

public static void AppendArrayDebug ( StringBuilder sb, Array array )
{
    if( array == null || array.Length == 0 )
    {
        sb.Append( "<nothing>" );
        return;
    }

    int i;

    var rank = array.Rank;
    var lastIndex = rank - 1;

    // Initialize indices and their boundaries
    var indices = new int[rank];
    var lower = new int[rank];
    var upper = new int[rank];
    for( i = 0; i < rank; ++i )
    {
        indices[i] = lower[i] = array.GetLowerBound( i );
        upper[i] = array.GetUpperBound( i );
    }

    while( true )
    {
        BeginMainLoop:

        // Begin work with an element

        var element = array.GetValue( indices );

        sb.AppendLine();
        sb.Append( '[' );
        for( i = 0; i < rank; ++i )
        {
            sb.Append( indices[i] );
            sb.Append( ' ' );
        }
        sb.Length -= 1;
        sb.Append( "] = " );
        sb.Append( element );

        // End work with the element

        // Increment index set

        // All indices except the first one are enumerated several times
        for( i = lastIndex; i > 0; )
        {
            if( ++indices[i] <= upper[i] )
                goto BeginMainLoop;
            indices[i] = lower[i];
            --i;
        }

        // Special case for the first index, it must be enumerated only once
        if( ++indices[0] > upper[0] )
            break;
    }
}

For example the following array will produce the following output:

var array = new [,,]
{
    { {  1,  2,  3 }, {  4,  5,  6 }, {  7,  8,  9 }, { 10, 11, 12 } },
    { { 13, 14, 15 }, { 16, 17, 18 }, { 19, 20, 21 }, { 22, 23, 24 } }
};

/*
Output:

[0 0 0] = 1
[0 0 1] = 2
[0 0 2] = 3
[0 1 0] = 4
[0 1 1] = 5
[0 1 2] = 6
[0 2 0] = 7
[0 2 1] = 8
[0 2 2] = 9
[0 3 0] = 10
[0 3 1] = 11
[0 3 2] = 12
[1 0 0] = 13
[1 0 1] = 14
[1 0 2] = 15
[1 1 0] = 16
[1 1 1] = 17
[1 1 2] = 18
[1 2 0] = 19
[1 2 1] = 20
[1 2 2] = 21
[1 3 0] = 22
[1 3 1] = 23
[1 3 2] = 24
*/

How can I make setInterval also work when a tab is inactive in Chrome?

Note: this solution is not suitable if you like your interval works on the background, for example, playing audio or ... but if you are confused for example about your animation not working properly when coming back to your page(tab) this is a good solution.

There are many ways to achieve this goal, maybe the "WebWorkers" is the most standard one but certainly, it's not the easiest and handy one, especially If you don't have enough Time, so you can try this way:

?BASIC CONCEPT:

1- build a name for your interval(or animation) and set your interval(animation), so it would run when user first time open your page : var interval_id = setInterval(your_func, 3000);

2- by $(window).focus(function() {}); and $(window).blur(function() {}); you can clearInterval(interval_id) everytime browser(tab) is deactived and ReRun your interval(animation) everytime browser(tab) would acive again by interval_id = setInterval();

?SAMPLE CODE:

var interval_id = setInterval(your_func, 3000);

$(window).focus(function() {
    interval_id = setInterval(your_func, 3000);
});
$(window).blur(function() {
    clearInterval(interval_id);
    interval_id = 0;
});

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

You can configure logging in your settings.py file.

One example:

if DEBUG:
    # will output to your console
    logging.basicConfig(
        level = logging.DEBUG,
        format = '%(asctime)s %(levelname)s %(message)s',
    )
else:
    # will output to logging file
    logging.basicConfig(
        level = logging.DEBUG,
        format = '%(asctime)s %(levelname)s %(message)s',
        filename = '/my_log_file.log',
        filemode = 'a'
    )

However that's dependent upon setting DEBUG, and maybe you don't want to have to worry about how it's set up. See this answer on How can I tell whether my Django application is running on development server or not? for a better way of writing that conditional. Edit: the example above is from a Django 1.1 project, logging configuration in Django has changed somewhat since that version.

Check if element is in the list (contains)

std::list does not provide a search method. You can iterate over the list and check if the element exists or use std::find. But I think for your situation std::set is more preferable. The former will take O(n) time but later will take O(lg(n)) time to search.

You can simply use:

int my_var = 3;
std::set<int> mySet {1, 2, 3, 4};
if(mySet.find(myVar) != mySet.end()){
      //do whatever
}

Git add all files modified, deleted, and untracked?

I authored the G2 project, a friendly environment for the command line git lover.
Please get the project from github - G2 https://github.com/orefalo/g2

It has a bunch of handy commands, one of them being exactly what your are looking for: freeze

freeze - Freeze all files in the repository (additions, deletions, modifications) to the staging area, thus staging that content for inclusion in the next commit. Also accept a specific path as parameter

Add new attribute (element) to JSON object using JavaScript

Uses $.extend() of jquery, like this:

token = {_token:window.Laravel.csrfToken};
data = {v1:'asdass',v2:'sdfsdf'}
dat = $.extend(token,data); 

I hope you serve them.

Java : Sort integer array without using Arrays.sort()

class Sort 
{
    public static void main(String[] args) 
    {
    System.out.println("Enter the range");
    java.util.Scanner sc=new java.util.Scanner(System.in);
    int n=sc.nextInt();
    int arr[]=new int[n];
    System.out.println("Enter the array values");
    for(int i=0;i<=n-1;i++)
    {
        arr[i]=sc.nextInt();

    }
    System.out.println("Before sorting array values are");
     for(int i=0;i<=n-1;i++)
    {
     System.out.println(arr[i]);
       }
    System.out.println();
    for(int pass=1;pass<=n;pass++)
    {
    for(int i=0;i<=n-1;i++)
    {
        if(i==n-1)
        {
            break;
        }
        int temp;
        if(arr[i]>arr[i+1])
        {

            temp=arr[i];
            arr[i]=arr[i+1];
            arr[i+1]=temp;
        }
    }
    }

    System.out.println("After sorting array values are");
       for(int i=0;i<=n-1;i++)
    {
     System.out.println(arr[i]);
       }

}
}    

Calculating number of full months between two dates in SQL

I know this is an old question, but as long as the dates are >= 01-Jan-1753 I use:

DATEDIFF(MONTH, DATEADD(DAY,-DAY(@Start)+1,@Start),DATEADD(DAY,-DAY(@Start)+1,@End))

Fastest way to get the first n elements of a List into an Array

Option 1 Faster Than Option 2

Because Option 2 creates a new List reference, and then creates an n element array from the List (option 1 perfectly sizes the output array). However, first you need to fix the off by one bug. Use < (not <=). Like,

String[] out = new String[n];
for(int i = 0; i < n; i++) {
    out[i] = in.get(i);
}

How to format a floating number to fixed width in Python

In python3 the following works:

>>> v=10.4
>>> print('% 6.2f' % v)
  10.40
>>> print('% 12.1f' % v)
        10.4
>>> print('%012.1f' % v)
0000000010.4

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

In your configurations, specify the port number your database is on. You can find the port number at the top left corner of phpMyAdmin. It would look something like this

const DB_HOST = 'localhost:3308';

How to recover the deleted files using "rm -R" command in linux server?

Not possible with standard unix commands. You might have luck with a file recovery utility. Also, be aware, using rm changes the table of contents to mark those blocks as available to be overwritten, so simply using your computer right now risks those blocks being overwritten permanently. If it's critical data, you should turn off the computer before the file sectors gets overwritten. Good luck!

Some restore utility: http://www.ubuntugeek.com/recover-deleted-files-with-foremostscalpel-in-ubuntu.html

Forum where this was previously answered: http://webcache.googleusercontent.com/search?q=cache:m4hiPw-_GekJ:ubuntuforums.org/archive/index.php/t-1134955.html+&cd=1&hl=en&ct=clnk&gl=us

Scala best way of turning a Collection into a Map-by-key?

For what it's worth, here are two pointless ways of doing it:

scala> case class Foo(bar: Int)
defined class Foo

scala> import scalaz._, Scalaz._
import scalaz._
import Scalaz._

scala> val c = Vector(Foo(9), Foo(11))
c: scala.collection.immutable.Vector[Foo] = Vector(Foo(9), Foo(11))

scala> c.map(((_: Foo).bar) &&& identity).toMap
res30: scala.collection.immutable.Map[Int,Foo] = Map(9 -> Foo(9), 11 -> Foo(11))

scala> c.map(((_: Foo).bar) >>= (Pair.apply[Int, Foo] _).curried).toMap
res31: scala.collection.immutable.Map[Int,Foo] = Map(9 -> Foo(9), 11 -> Foo(11))

How can I make git accept a self signed certificate?

It’s not a good practice to set http.sslVerify false. Instead we can use SSL certificate.

So, build agent will use https with SSL certificate and PAT for authentication. enter image description here

enter image description here

enter image description here

Copy the content of cer file including –begin—and –end--.

git bash on build agent => git config –global http.sslcainfo “C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt” Go to this file and append the .cer content.

Thus, build agent can access the SSL certificate

How to add http:// if it doesn't exist in the URL

nickf's solution modified:

function addhttp($url) {
    if (!preg_match("@^https?://@i", $url) && !preg_match("@^ftps?://@i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

"Permission Denied" trying to run Python on Windows 10

The simplest thing to do would be to modify your PATH and PYTHONPATH environmental variables to make sure that the folder containing the proper python binaries are searched befor the local WindowsApp folder. You can access the environmental variables by opening up the control panel and searching for "env"

Counting in a FOR loop using Windows Batch script

for a = 1 to 100 step 1

Command line in Windows . Please use %%a if running in Batch file.

    for /L %a in (1,1,100) Do echo %a 

How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

You cannot do so - the browser will not allow this because of security concerns.

When a file is selected by using the input type=file object, the value of the value property depends on the value of the "Include local directory path when uploading files to a server" security setting for the security zone used to display the Web page containing the input object.

The fully qualified filename of the selected file is returned only when this setting is enabled. When the setting is disabled, Internet Explorer 8 replaces the local drive and directory path with the string C:\fakepath\ in order to prevent inappropriate information disclosure.

And other

You missed ); this at the end of the change event function.

Also do not create function for change event instead just use it as below,

<script type="text/javascript">

    $(function()
    {
        $('#fileUpload').on('change',function ()
        {
            var filePath = $(this).val();
            console.log(filePath);
        });
    });

</script>

How do I test if a recordSet is empty? isNull?

If Not temp_rst1 Is Nothing Then ...

How to get the Touch position in android?

@Override
public boolean onTouchEvent(MotionEvent event)
{
    int x = (int)event.getX();
    int y = (int)event.getY();

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
        case MotionEvent.ACTION_UP:
    }

    return false;
}

The three cases are so that you can react to different types of events, in this example tapping or dragging or lifting the finger again.

ERROR 1067 (42000): Invalid default value for 'created_at'

You can do it like this:

 CREATE TABLE `ttt` (
  `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `t1` TIMESTAMP  NULL DEFAULT '0000-00-00 00:00:00',
  `t2` TIMESTAMP  NULL DEFAULT '0000-00-00 00:00:00',
  `t3` TIMESTAMP  NULL DEFAULT '0000-00-00 00:00:00',
  `t4` TIMESTAMP  NULL DEFAULT 0,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
  • Because the TIMESTAMP value is stored as Epoch Seconds, the timestamp value '1970-01-01 00:00:00' (UTC) is reserved since the second #0 is used to represent '0000-00-00 00:00:00'.
  • In MariaDB 5.5 and before there could only be one TIMESTAMP column per table that had CURRENT_TIMESTAMP defined as its default value. This limit has no longer applied since MariaDB 10.0.

see: https://mariadb.com/kb/en/mariadb/timestamp/

sample

MariaDB []> insert into ttt (id) VALUES (1),(2),(3);
Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0

MariaDB []> select * from ttt;
+----+---------------------+---------------------+---------------------+---------------------+
| id | t1                  | t2                  | t3                  | t4                  |
+----+---------------------+---------------------+---------------------+---------------------+
|  1 | 0000-00-00 00:00:00 | 2000-01-01 12:01:02 | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 |
|  2 | 0000-00-00 00:00:00 | 2000-01-01 12:01:02 | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 |
|  3 | 0000-00-00 00:00:00 | 2000-01-01 12:01:02 | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 |
+----+---------------------+---------------------+---------------------+---------------------+
3 rows in set (0.00 sec)

MariaDB []>

string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

The best practice is selecting the most appropriate one.

.Net Framework 4.0 Beta 2 has a new IsNullOrWhiteSpace() method for strings which generalizes the IsNullOrEmpty() method to also include other white space besides empty string.

The term “white space” includes all characters that are not visible on screen. For example, space, line break, tab and empty string are white space characters*.

Reference : Here

For performance, IsNullOrWhiteSpace is not ideal but is good. The method calls will result in a small performance penalty. Further, the IsWhiteSpace method itself has some indirections that can be removed if you are not using Unicode data. As always, premature optimization may be evil, but it is also fun.

Reference : Here

Check the source code (Reference Source .NET Framework 4.6.2)

IsNullorEmpty

[Pure]
public static bool IsNullOrEmpty(String value) {
    return (value == null || value.Length == 0);
}

IsNullOrWhiteSpace

[Pure]
public static bool IsNullOrWhiteSpace(String value) {
    if (value == null) return true;

    for(int i = 0; i < value.Length; i++) {
        if(!Char.IsWhiteSpace(value[i])) return false;
    }

    return true;
}

Examples

string nullString = null;
string emptyString = "";
string whitespaceString = "    ";
string nonEmptyString = "abc123";

bool result;

result = String.IsNullOrEmpty(nullString);            // true
result = String.IsNullOrEmpty(emptyString);           // true
result = String.IsNullOrEmpty(whitespaceString);      // false
result = String.IsNullOrEmpty(nonEmptyString);        // false

result = String.IsNullOrWhiteSpace(nullString);       // true
result = String.IsNullOrWhiteSpace(emptyString);      // true
result = String.IsNullOrWhiteSpace(whitespaceString); // true
result = String.IsNullOrWhiteSpace(nonEmptyString);   // false

Python pandas insert list into a cell

Since set_value has been deprecated since version 0.21.0, you should now use at. It can insert a list into a cell without raising a ValueError as loc does. I think this is because at always refers to a single value, while loc can refer to values as well as rows and columns.

df = pd.DataFrame(data={'A': [1, 2, 3], 'B': ['x', 'y', 'z']})

df.at[1, 'B'] = ['m', 'n']

df =
    A   B
0   1   x
1   2   [m, n]
2   3   z

You also need to make sure the column you are inserting into has dtype=object. For example

>>> df = pd.DataFrame(data={'A': [1, 2, 3], 'B': [1,2,3]})
>>> df.dtypes
A    int64
B    int64
dtype: object

>>> df.at[1, 'B'] = [1, 2, 3]
ValueError: setting an array element with a sequence

>>> df['B'] = df['B'].astype('object')
>>> df.at[1, 'B'] = [1, 2, 3]
>>> df
   A          B
0  1          1
1  2  [1, 2, 3]
2  3          3

Spring Data JPA and Exists query

Spring Data JPA 1.11 now supports the exists projection in repository query derivation.

See documentation here.

In your case the following will work:

public interface MyEntityRepository extends CrudRepository<MyEntity, String> {  
    boolean existsByFoo(String foo);
}

TypeLoadException says 'no implementation', but it is implemented

I faced almost same issue. I was scratching my head what is causing this error. I cross checked, all the methods were implemented.

On Googling I got this link among other. Based on @Paul McLink comment, This two steps resolved the issue.

  1. Restart Visual Studio
  2. Clean, Build (Rebuild)

and the error gone.

Restart VS Plugin

Thanks Paul :)

Hope this helps someone who come across this error :)

Get the week start date and week end date from week number

I have a way other, It is select day Start and day End of Week Current:

DATEADD(d, -(DATEPART(dw, GETDATE()-2)), GETDATE()) is date time Start

and

DATEADD(day,7-(DATEPART(dw,GETDATE()-1)),GETDATE()) is date time End

Increasing the maximum number of TCP/IP connections in Linux

Maximum number of connections are impacted by certain limits on both client & server sides, albeit a little differently.

On the client side: Increase the ephermal port range, and decrease the tcp_fin_timeout

To find out the default values:

sysctl net.ipv4.ip_local_port_range
sysctl net.ipv4.tcp_fin_timeout

The ephermal port range defines the maximum number of outbound sockets a host can create from a particular I.P. address. The fin_timeout defines the minimum time these sockets will stay in TIME_WAIT state (unusable after being used once). Usual system defaults are:

  • net.ipv4.ip_local_port_range = 32768 61000
  • net.ipv4.tcp_fin_timeout = 60

This basically means your system cannot consistently guarantee more than (61000 - 32768) / 60 = 470 sockets per second. If you are not happy with that, you could begin with increasing the port_range. Setting the range to 15000 61000 is pretty common these days. You could further increase the availability by decreasing the fin_timeout. Suppose you do both, you should see over 1500 outbound connections per second, more readily.

To change the values:

sysctl net.ipv4.ip_local_port_range="15000 61000"
sysctl net.ipv4.tcp_fin_timeout=30

The above should not be interpreted as the factors impacting system capability for making outbound connections per second. But rather these factors affect system's ability to handle concurrent connections in a sustainable manner for large periods of "activity."

Default Sysctl values on a typical Linux box for tcp_tw_recycle & tcp_tw_reuse would be

net.ipv4.tcp_tw_recycle=0
net.ipv4.tcp_tw_reuse=0

These do not allow a connection from a "used" socket (in wait state) and force the sockets to last the complete time_wait cycle. I recommend setting:

sysctl net.ipv4.tcp_tw_recycle=1
sysctl net.ipv4.tcp_tw_reuse=1 

This allows fast cycling of sockets in time_wait state and re-using them. But before you do this change make sure that this does not conflict with the protocols that you would use for the application that needs these sockets. Make sure to read post "Coping with the TCP TIME-WAIT" from Vincent Bernat to understand the implications. The net.ipv4.tcp_tw_recycle option is quite problematic for public-facing servers as it won’t handle connections from two different computers behind the same NAT device, which is a problem hard to detect and waiting to bite you. Note that net.ipv4.tcp_tw_recycle has been removed from Linux 4.12.

On the Server Side: The net.core.somaxconn value has an important role. It limits the maximum number of requests queued to a listen socket. If you are sure of your server application's capability, bump it up from default 128 to something like 128 to 1024. Now you can take advantage of this increase by modifying the listen backlog variable in your application's listen call, to an equal or higher integer.

sysctl net.core.somaxconn=1024

txqueuelen parameter of your ethernet cards also have a role to play. Default values are 1000, so bump them up to 5000 or even more if your system can handle it.

ifconfig eth0 txqueuelen 5000
echo "/sbin/ifconfig eth0 txqueuelen 5000" >> /etc/rc.local

Similarly bump up the values for net.core.netdev_max_backlog and net.ipv4.tcp_max_syn_backlog. Their default values are 1000 and 1024 respectively.

sysctl net.core.netdev_max_backlog=2000
sysctl net.ipv4.tcp_max_syn_backlog=2048

Now remember to start both your client and server side applications by increasing the FD ulimts, in the shell.

Besides the above one more popular technique used by programmers is to reduce the number of tcp write calls. My own preference is to use a buffer wherein I push the data I wish to send to the client, and then at appropriate points I write out the buffered data into the actual socket. This technique allows me to use large data packets, reduce fragmentation, reduces my CPU utilization both in the user land and at kernel-level.

How to trigger click on page load?

You can do the following :-

$(document).ready(function(){
    $("#id").trigger("click");
});

How to declare global variables in Android?

You can do this using two approaches:

  1. Using Application class
  2. Using Shared Preferences

  3. Using Application class

Example:

class SessionManager extends Application{

  String sessionKey;

  setSessionKey(String key){
    this.sessionKey=key;
  }

  String getSessisonKey(){
    return this.sessionKey;
  }
}

You can use above class to implement login in your MainActivity as below. Code will look something like this:

@override 
public void onCreate (Bundle savedInstanceState){
  // you will this key when first time login is successful.
  SessionManager session= (SessionManager)getApplicationContext();
  String key=getSessisonKey.getKey();
  //Use this key to identify whether session is alive or not.
}

This method will work for temporary storage. You really do not any idea when operating system is gonna kill the application, because of low memory. When your application is in background and user is navigating through other application which demands more memory to run, then your application will be killed since operating system given more priority to foreground processes than background. Hence your application object will be null before user logs out. Hence for this I recommend to use second method Specified above.

  1. Using shared preferences.

    String MYPREF="com.your.application.session"
    
    SharedPreferences pref= context.getSharedPreferences(MyPREF,MODE_PRIVATE);
    
    //Insert key as below:
    
    Editot editor= pref.edit();
    
    editor.putString("key","value");
    
    editor.commit();
    
    //Get key as below.
    
    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    
    String key= getResources().getString("key");
    

What is the HTML tabindex attribute?

Controlling the order of tabbing (pressing the tab key to move focus) within the page.

Reference: http://www.w3.org/TR/html401/interact/forms.html#h-17.11.1

Block Comments in a Shell Script

The following should work for sh,bash, ksh and zsh.

The blocks of code to be commented can be put inside BEGINCOMMENT and ENDCOMMENT:

[ -z $BASH ] || shopt -s expand_aliases
alias BEGINCOMMENT="if [ ]; then"
alias ENDCOMMENT="fi"

BEGINCOMMENT
  echo "This line appears in a commented block"
  echo "And this one too!"
ENDCOMMENT

echo "This is outside the commented block"

Executing the above code would result in:

This is outside the commented block

In order to uncomment the code blocks thus commented, say

alias BEGINCOMMENT="if : ; then"

instead of

alias BEGINCOMMENT="if [ ]; then"

in the example above.

"Faceted Project Problem (Java Version Mismatch)" error message

The project facets should be derived automagically by the M2Eclipse plugin from the POM configuration. If you make some changes to the POM and need Eclipse to take them into account, right-click on your project, then go to Maven > Update Project Configuration. You should not set project facets manually.

jQuery .search() to any string

if (str.toLowerCase().indexOf("yes") >= 0)

Or,

if (/yes/i.test(str))