Programs & Examples On #Oracleforms

Oracle Forms is a software product for creating screens that interact with an Oracle database.

What is the format specifier for unsigned short int?

For scanf, you need to use %hu since you're passing a pointer to an unsigned short. For printf, it's impossible to pass an unsigned short due to default promotions (it will be promoted to int or unsigned int depending on whether int has at least as many value bits as unsigned short or not) so %d or %u is fine. You're free to use %hu if you prefer, though.

How to split a string by spaces in a Windows batch file?

Three possible solutions to iterate through the words of the string:

Version 1:

@echo off & setlocal
set s=AAA BBB CCC DDD EEE FFF
for %%a in (%s%) do echo %%a

Version 2:

@echo off & setlocal
set s=AAA BBB CCC DDD EEE FFF
set t=%s%
:loop
for /f "tokens=1*" %%a in ("%t%") do (
   echo %%a
   set t=%%b
   )
if defined t goto :loop

Version 3:

@echo off & setlocal
set s=AAA BBB CCC DDD EEE FFF
call :sub1 %s%
exit /b
:sub1
if "%1"=="" exit /b
echo %1
shift
goto :sub1

Version 1 does not work when the string contains wildcard characters like '*' or '?'.

Versions 1 and 3 treat characters like '=', ';' or ',' as word separators. These characters have the same effect as the space character.

Change bootstrap datepicker date format on select

As of 2016 I used datetimepicker like this:

$(function () {
    $('#date_box').datetimepicker({
        format: 'YYYY-MM-DD hh:mm'
    });
});

How to change the default charset of a MySQL table?

If you want to change the table default character set and all character columns to a new character set, use a statement like this:

ALTER TABLE tbl_name CONVERT TO CHARACTER SET charset_name;

So query will be:

ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8;

Call parent method from child class c#

To access properties and methods of a parent class use the base keyword. So in your child class LoadData() method you would do this:

public class Child : Parent 
{
    public void LoadData() 
    {
        base.MyMethod(); // call method of parent class
        base.CurrentRow = 1; // set property of parent class
        // other stuff...
    }
}

Note that you would also have to change the access modifier of your parent MyMethod() to at least protected for the child class to access it.

wait() or sleep() function in jquery?

That'd be .delay().

http://api.jquery.com/delay/

If you are doing AJAX stuff tho, you really shouldn't just auto write "done" you should really wait for a response and see if it's actually done.

@Resource vs @Autowired

In spring pre-3.0 it doesn't matter which one.

In spring 3.0 there's support for the standard (JSR-330) annotation @javax.inject.Inject - use it, with a combination of @Qualifier. Note that spring now also supports the @javax.inject.Qualifier meta-annotation:

@Qualifier
@Retention(RUNTIME)
public @interface YourQualifier {}

So you can have

<bean class="com.pkg.SomeBean">
   <qualifier type="YourQualifier"/>
</bean>

or

@YourQualifier
@Component
public class SomeBean implements Foo { .. }

And then:

@Inject @YourQualifier private Foo foo;

This makes less use of String-names, which can be misspelled and are harder to maintain.


As for the original question: both, without specifying any attributes of the annotation, perform injection by type. The difference is:

  • @Resource allows you to specify a name of the injected bean
  • @Autowired allows you to mark it as non-mandatory.

How to check if a socket is connected/disconnected in C#?

I made an extension method based on this MSDN article. This is how you can determine whether a socket is still connected.

public static bool IsConnected(this Socket client)
{
    bool blockingState = client.Blocking;

    try
    {
        byte[] tmp = new byte[1];

        client.Blocking = false;
        client.Send(tmp, 0, 0);
        return true;
    }
    catch (SocketException e)
    {
        // 10035 == WSAEWOULDBLOCK
        if (e.NativeErrorCode.Equals(10035))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    finally
    {
        client.Blocking = blockingState;
    }
}

Why can't I set text to an Android TextView?

I was having a similar problem, however my program would crash when I tried to set the text. I was attempting to set the text value from within a class that extends AsyncTask, and that was what was causing the problem.

To resolve it, I moved my setText to the onPostExecute method

protected void onPostExecute(Void result) {
    super.onPostExecute(result);

    TextView text = (TextView) findViewById(R.id.errorsToday);
    text.setText("new string value");
}

Full screen background image in an activity

What about

android:background="@drawable/your_image"

on the main layout of your activity?

This way you can also have different images for different screen densities by placing them in the appropriate res/drawable-**dpi folders.

IntelliJ how to zoom in / out

I assume that you have a similar view regarding the zoom functionality as I have in this picture:

enter image description here

Now if you mark one of the Zoom In/Zoom Out lines and choose Add Keyboard Shortcut:

enter image description here

You will find that this particular shortcut Numpad + is already occupied so there is a conflict:

enter image description here

So you'll just have assign this Zoom In/Zoom Out to some other keyboard shortcut:

enter image description here

Flatten list of lists

Flatten the list to "remove the brackets" using a nested list comprehension. This will un-nest each list stored in your list of lists!

list_of_lists = [[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
flattened = [val for sublist in list_of_lists for val in sublist]

Nested list comprehensions evaluate in the same manner that they unwrap (i.e. add newline and tab for each new loop. So in this case:

flattened = [val for sublist in list_of_lists for val in sublist]

is equivalent to:

flattened = []
for sublist in list_of_lists:
    for val in sublist:
        flattened.append(val)

The big difference is that the list comp evaluates MUCH faster than the unraveled loop and eliminates the append calls!

If you have multiple items in a sublist the list comp will even flatten that. ie

>>> list_of_lists = [[180.0, 1, 2, 3], [173.8], [164.2], [156.5], [147.2], [138.2]]
>>> flattened  = [val for sublist in list_of_lists for val in sublist]
>>> flattened 
[180.0, 1, 2, 3, 173.8, 164.2, 156.5, 147.2,138.2]

setting content between div tags using javascript

See Creating and modifying HTML at what used to be called the Web Standards Curriculum.

Use the createElement, createTextNode and appendChild methods.

Send multipart/form-data files with angular using $http

In Angular 6, you can do this:

In your service file:

 function_name(data) {
    const url = `the_URL`;
    let input = new FormData();
    input.append('url', data);   // "url" as the key and "data" as value
    return this.http.post(url, input).pipe(map((resp: any) => resp));
  }

In component.ts file: in any function say xyz,

xyz(){
this.Your_service_alias.function_name(data).subscribe(d => {   // "data" can be your file or image in base64 or other encoding
      console.log(d);
    });
}

Display Back Arrow on Toolbar

If you are using DrawerLayout with ActionBarDrawerToggle, then to show Back button instead of Menu button (and viceversa), you need to add this code in your Activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // ...

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.application_name, R.string.application_name);
    mDrawerLayout.addDrawerListener(mDrawerToggle);

    mDrawerToggle.setHomeAsUpIndicator(R.drawable.ic_arrow_back_white_32dp);
    mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onBackPressed(); // Or you can perform some other action here when Back button is clicked.
        }
    });
    mDrawerToggle.syncState();
    // ...
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mDrawerToggle.onOptionsItemSelected(item))
        return true;

    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
        // ...
    }

    return super.onOptionsItemSelected(item);
}

public void showBackInToolbar(boolean isBack) {
    // Remove next line if you still want to be able to swipe to show drawer menu.
    mDrawerLayout.setDrawerLockMode(isBack ? DrawerLayout.LOCK_MODE_LOCKED_CLOSED : DrawerLayout.LOCK_MODE_UNLOCKED);
    mDrawerToggle.setDrawerIndicatorEnabled(!isBack);
    mDrawerToggle.syncState();
}

So when you need to show Back button instead of Menu button, call showBackInToolbar(true), and if you need Menu button, call showBackInToolbar(false).

You can generate back arrow (ic_arrow_back_white_32dp) over here, search arrow_back in Clipart section (use default 32dp with 8dp padding). Just select the color you want.

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

Encapsulation vs Abstraction?

NOTE: I am sharing this. It is not mean that here is not good answer but because I easily understood.

Answer:

When a class is conceptualized, what are the properties we can have in it given the context. If we are designing a class Animal in the context of a zoo, it is important that we have an attribute as animalType to describe domestic or wild. This attribute may not make sense when we design the class in a different context.

Similarly, what are the behaviors we are going to have in the class? Abstraction is also applied here. What is necessary to have here and what will be an overdose? Then we cut off some information from the class. This process is applying abstraction.

When we ask for difference between encapsulation and abstraction, I would say, encapsulation uses abstraction as a concept. So then, is it only encapsulation. No, abstraction is even a concept applied as part of inheritance and polymorphism.

Go here for more explanation about this topic.

How to select and change value of table cell with jQuery?

You can do this :

<table id="table_header">
<tr>
   <td contenteditable="true">a</td>
   <td contenteditable="true">b</td>
   <td contenteditable="true">c</td>
</tr>
</table>

Running script upon login mac

Follow this:

  • start Automator.app
  • select Application
  • click Show library in the toolbar (if hidden)
  • add Run shell script (from the Actions/Utilities)
  • copy & paste your script into the window
  • test it
  • save somewhere (for example you can make an Applications folder in your HOME, you will get an your_name.app)

  • go to System Preferences -> Accounts -> Login items

  • add this app
  • test & done ;)

EDIT:

I've recently earned a "Good answer" badge for this answer. While my solution is simple and working, the cleanest way to run any program or shell script at login time is described in @trisweb's answer, unless, you want interactivity.

With automator solution you can do things like next: automator screenshot login application

so, asking to run a script or quit the app, asking passwords, running other automator workflows at login time, conditionally run applications at login time and so on...

Pass request headers in a jQuery AJAX GET call

Use beforeSend:

$.ajax({
         url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
         data: { signature: authHeader },
         type: "GET",
         beforeSend: function(xhr){xhr.setRequestHeader('X-Test-Header', 'test-value');},
         success: function() { alert('Success!' + authHeader); }
      });

http://api.jquery.com/jQuery.ajax/

http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method

Using ExcelDataReader to read Excel data starting from a particular cell

For ExcelDataReader v3.6.0 and above. I struggled a bit to iterate over the Rows. So here's a little more to the above code. Hope it helps for few atleast.

using (var stream = System.IO.File.Open(copyPath, FileMode.Open, FileAccess.Read))
                    {

                        IExcelDataReader excelDataReader = ExcelDataReader.ExcelReaderFactory.CreateReader(stream);

                        var conf = new ExcelDataSetConfiguration()
                        {
                            ConfigureDataTable = a => new ExcelDataTableConfiguration
                            {
                                UseHeaderRow = true
                            }
                        };

                        DataSet dataSet = excelDataReader.AsDataSet(conf);
                        //DataTable dataTable = dataSet.Tables["Sheet1"];
                        DataRowCollection row = dataSet.Tables["Sheet1"].Rows;
                        //DataColumnCollection col = dataSet.Tables["Sheet1"].Columns;

                        List<object> rowDataList = null;
                        List<object> allRowsList = new List<object>();
                        foreach (DataRow item in row)
                        {
                            rowDataList = item.ItemArray.ToList(); //list of each rows
                            allRowsList.Add(rowDataList); //adding the above list of each row to another list
                        }

                    }

INSERT VALUES WHERE NOT EXISTS

You could do this using an IF statement:

IF NOT EXISTS 
    (   SELECT  1
        FROM    tblSoftwareTitles 
        WHERE   Softwarename = @SoftwareName 
        AND     SoftwareSystemType = @Softwaretype
    )
    BEGIN
        INSERT tblSoftwareTitles (SoftwareName, SoftwareSystemType) 
        VALUES (@SoftwareName, @SoftwareType) 
    END;

You could do it without IF using SELECT

INSERT  tblSoftwareTitles (SoftwareName, SoftwareSystemType) 
SELECT  @SoftwareName,@SoftwareType
WHERE   NOT EXISTS 
        (   SELECT  1
            FROM    tblSoftwareTitles 
            WHERE   Softwarename = @SoftwareName 
            AND     SoftwareSystemType = @Softwaretype
        );

Both methods are susceptible to a race condition, so while I would still use one of the above to insert, but you can safeguard duplicate inserts with a unique constraint:

CREATE UNIQUE NONCLUSTERED INDEX UQ_tblSoftwareTitles_Softwarename_SoftwareSystemType
    ON tblSoftwareTitles (SoftwareName, SoftwareSystemType);

Example on SQL-Fiddle


ADDENDUM

In SQL Server 2008 or later you can use MERGE with HOLDLOCK to remove the chance of a race condition (which is still not a substitute for a unique constraint).

MERGE tblSoftwareTitles WITH (HOLDLOCK) AS t
USING (VALUES (@SoftwareName, @SoftwareType)) AS s (SoftwareName, SoftwareSystemType) 
    ON s.Softwarename = t.SoftwareName 
    AND s.SoftwareSystemType = t.SoftwareSystemType
WHEN NOT MATCHED BY TARGET THEN 
    INSERT (SoftwareName, SoftwareSystemType) 
    VALUES (s.SoftwareName, s.SoftwareSystemType);

Example of Merge on SQL Fiddle

Getting Java version at runtime

Just a note that in Java 9 and above, the naming convention is different. System.getProperty("java.version") returns "9" rather than "1.9".

PHP Session data not being saved

I had session cookie path set to "//" instead of "/". Firebug is awesome. Hope it helps somebody.

How do I create directory if it doesn't exist to create a file?

An elegant way to move your file to an nonexistent directory is to create the following extension to native FileInfo class:

public static class FileInfoExtension
{
    //second parameter is need to avoid collision with native MoveTo
    public static void MoveTo(this FileInfo file, string destination, bool autoCreateDirectory) { 

        if (autoCreateDirectory)
        {
            var destinationDirectory = new DirectoryInfo(Path.GetDirectoryName(destination));

            if (!destinationDirectory.Exists)
                destinationDirectory.Create();
        }

        file.MoveTo(destination);
    }
}

Then use brand new MoveTo extension:

 using <namespace of FileInfoExtension>;
 ...
 new FileInfo("some path")
     .MoveTo("target path",true);

Check Methods extension documentation.

Create a text file for download on-the-fly

Check out this SO question's accepted solution. Substitute your own filename for basename($File) and change filesize($File) to strlen($your_string). (You may want to use mb_strlen just in case the string contains multibyte characters.)

Using File.listFiles with FileNameExtensionFilter

The FileNameExtensionFilter class is intended for Swing to be used in a JFileChooser.

Try using a FilenameFilter instead. For example:

File dir = new File("/users/blah/dirname");
File[] files = dir.listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".txt");
    }
});

Why is Python running my module when I import it, and how do I stop it?

Due to the way Python works, it is necessary for it to run your modules when it imports them.

To prevent code in the module from being executed when imported, but only when run directly, you can guard it with this if:

if __name__ == "__main__":
    # this won't be run when imported

You may want to put this code in a main() method, so that you can either execute the file directly, or import the module and call the main(). For example, assume this is in the file foo.py.

def main():
    print "Hello World"

if __name__ == "__main__":
    main()

This program can be run either by going python foo.py, or from another Python script:

import foo

...

foo.main()

WAMP Server ERROR "Forbidden You don't have permission to access /phpmyadmin/ on this server."

Change httpd.conf file as follows:

from

<Directory />
    AllowOverride none
    Require all denied
</Directory>

to

<Directory />
    AllowOverride none
    Require all granted
</Directory>

How to create a Calendar table for 100 years in Sql

 declare @date int
 WITH CTE_DatesTable
AS
(
  SELECT CAST('20000101' as date) AS [date]
  UNION ALL
  SELECT   DATEADD(dd, 1, [date])
  FROM CTE_DatesTable
  WHERE DATEADD(dd, 1, [date]) <= '21001231'
)
SELECT [DWDateKey]=[date],[DayDate]=datepart(dd,[date]),[DayOfWeekName]=datename(dw,[date]),[WeekNumber]=DATEPART( WEEK , [date]),[MonthNumber]=DATEPART( MONTH , [date]),[MonthName]=DATENAME( MONTH , [date]),[MonthShortName]=substring(LTRIM( DATENAME(MONTH,[date])),0, 4),[Year]=DATEPART(YY,[date]),[QuarterNumber]=DATENAME(quarter, [date]),[QuarterName]=DATENAME(quarter, [date]) into DimDate   FROM CTE_DatesTable

OPTION (MAXRECURSION 0);

Label encoding across multiple columns in scikit-learn

import pandas as pd
from sklearn.preprocessing import LabelEncoder

train=pd.read_csv('.../train.csv')

#X=train.loc[:,['waterpoint_type_group','status','waterpoint_type','source_class']].values
# Create a label encoder object 
def MultiLabelEncoder(columnlist,dataframe):
    for i in columnlist:

        labelencoder_X=LabelEncoder()
        dataframe[i]=labelencoder_X.fit_transform(dataframe[i])
columnlist=['waterpoint_type_group','status','waterpoint_type','source_class','source_type']
MultiLabelEncoder(columnlist,train)

Here i am reading a csv from location and in function i am passing the column list i want to labelencode and the dataframe I want to apply this.

This action could not be completed. Try Again (-22421)

Tested in Xcode 7.3, 04142016

Instead of clicking the blue Upload to App Store… button from the Organizer or while Archiving, Xcode offers a better tool to do this, but it is a little hidden and the process is not clear how to use it.

Here is what I documented while submitting our latest iOS application to the App Store:

First, do NOT use the blue Upload to App Store… button.

From Xcode's Xcode: Developer Tools: menu, select Application Loader.

Sign in with appropriate credentials that allow you to upload to the App Store.

When Application Loader shows you its main screen, select the Choose button on the lower right of the main window and open your IPA that you exported for the App Store.

Proceed with the submission.

Why you want to do this:

  1. Detailed app submission error reporting. Exact explanations of submission errors. It tells you what's incorrect in your app that you are trying to submit.
  2. You don't have to deal with the insipid error that prompted this question in the first place.
  3. It works consistently in my tests where Xcode's Submit App to Store… from the Archive menu does not.

Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

Declare an output cursor variable to the inner sp :

@c CURSOR VARYING OUTPUT

Then declare a cursor c to the select you want to return. Then open the cursor. Then set the reference:

DECLARE c CURSOR LOCAL FAST_FORWARD READ_ONLY FOR 
SELECT ...
OPEN c
SET @c = c 

DO NOT close or reallocate.

Now call the inner sp from the outer one supplying a cursor parameter like:

exec sp_abc a,b,c,, @cOUT OUTPUT

Once the inner sp executes, your @cOUT is ready to fetch. Loop and then close and deallocate.

Which TensorFlow and CUDA version combinations are compatible?

if you are coding in jupyter notebook, and want to check which cuda version tf is using, run the follow command directly into jupyter cell:

!conda list cudatoolkit

!conda list cudnn

and to check if the gpu is visible to tf:

tf.test.is_gpu_available(
    cuda_only=False, min_cuda_compute_capability=None
)

Windows Forms ProgressBar: Easiest way to start/stop marquee?

There's a nice article with code on this topic on MSDN. I'm assuming that setting the Style property to ProgressBarStyle.Marquee is not appropriate (or is that what you are trying to control?? -- I don't think it is possible to stop/start this animation although you can control the speed as @Paul indicates).

AngularJs $http.post() does not send data

Similar to the OP's suggested working format & Denison's answer, except using $http.post instead of just $http and is still dependent on jQuery.

The good thing about using jQuery here is that complex objects get passed properly; against manually converting into URL parameters which may garble the data.

$http.post( 'request-url', jQuery.param( { 'message': message } ), {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});

Replace first occurrence of string in Python

Use re.sub directly, this allows you to specify a count:

regex.sub('', url, 1)

(Note that the order of arguments is replacement, original not the opposite, as might be suspected.)

First Or Create

Previous answer is obsolete. It's possible to achieve in one step since Laravel 5.3, firstOrCreate now has second parameter values, which is being used for new record, but not for search

$user = User::firstOrCreate([
    'email' => '[email protected]'
], [
    'firstName' => 'Taylor',
    'lastName' => 'Otwell'
]);

Disable Copy or Paste action for text box?

You might also need to provide your user with an alert showing that those functions are disabled for the text input fields. This will work

_x000D_
_x000D_
    function showError(){_x000D_
     alert('you are not allowed to cut,copy or paste here');_x000D_
    }_x000D_
    _x000D_
    $('.form-control').bind("cut copy paste",function(e) {_x000D_
     e.preventDefault();_x000D_
    });
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<textarea class="form-control"  oncopy="showError()" onpaste="showError()"></textarea>
_x000D_
_x000D_
_x000D_

Pass Hidden parameters using response.sendRedirect()

To send a variable value through URL in response.sendRedirect(). I have used it for one variable, you can also use it for two variable by proper concatenation.

String value="xyz";

response.sendRedirect("/content/test.jsp?var="+value);

How to convert hex to rgb using Java?

public static void main(String[] args) {
    int hex = 0x123456;
    int r = (hex & 0xFF0000) >> 16;
    int g = (hex & 0xFF00) >> 8;
    int b = (hex & 0xFF);
}

Finding local maxima/minima with Numpy in a 1D numpy array

For curves with not too much noise, I recommend the following small code snippet:

from numpy import *

# example data with some peaks:
x = linspace(0,4,1e3)
data = .2*sin(10*x)+ exp(-abs(2-x)**2)

# that's the line, you need:
a = diff(sign(diff(data))).nonzero()[0] + 1 # local min+max
b = (diff(sign(diff(data))) > 0).nonzero()[0] + 1 # local min
c = (diff(sign(diff(data))) < 0).nonzero()[0] + 1 # local max


# graphical output...
from pylab import *
plot(x,data)
plot(x[b], data[b], "o", label="min")
plot(x[c], data[c], "o", label="max")
legend()
show()

The +1 is important, because diff reduces the original index number.

Calculate difference in keys contained in two Python dictionaries

Not sure if it is still relevant but I came across this problem, my situation i just needed to return a dictionary of the changes for all nested dictionaries etc etc. Could not find a good solution out there but I did end up writing a simple function to do this. Hope this helps,

How can I show current location on a Google Map on Android Marshmallow?

For using FusedLocationProviderClient with Google Play Services 11 and higher:

see here: How to get current Location in GoogleMap using FusedLocationProviderClient

For using (now deprecated) FusedLocationProviderApi:

If your project uses Google Play Services 10 or lower, using the FusedLocationProviderApi is the optimal choice.

The FusedLocationProviderApi offers less battery drain than the old open source LocationManager API. Also, if you're already using Google Play Services for Google Maps, there's no reason not to use it.

Here is a full Activity class that places a Marker at the current location, and also moves the camera to the current position.

It also checks for the Location permission at runtime for Android 6 and later (Marshmallow, Nougat, Oreo). In order to properly handle the Location permission runtime check that is necessary on Android M/Android 6 and later, you need to ensure that the user has granted your app the Location permission before calling mGoogleMap.setMyLocationEnabled(true) and also before requesting location updates.

public class MapLocationActivity extends AppCompatActivity
        implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    GoogleMap mGoogleMap;
    SupportMapFragment mapFrag;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getSupportActionBar().setTitle("Map Location Activity");

        mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);
    }

    @Override
    public void onPause() {
        super.onPause();

        //stop location updates when Activity is no longer active
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap)
    {
        mGoogleMap=googleMap;
        mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                //Location Permission already granted
                buildGoogleApiClient();
                mGoogleMap.setMyLocationEnabled(true);
            } else {
                //Request Location Permission
                checkLocationPermission();
            }
        }
        else {
            buildGoogleApiClient();
            mGoogleMap.setMyLocationEnabled(true);
        }
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnected(Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {}

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {}

    @Override
    public void onLocationChanged(Location location)
    {
        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

        //move map camera
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));

    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    private void checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                new AlertDialog.Builder(this)
                        .setTitle("Location Permission Needed")
                        .setMessage("This app needs the Location permission, please accept to use location functionality")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(MapLocationActivity.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION );
                            }
                        })
                        .create()
                        .show();


            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION );
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mGoogleMap.setMyLocationEnabled(true);
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map"
        tools:context=".MapLocationActivity"
        android:name="com.google.android.gms.maps.SupportMapFragment"/>

</LinearLayout>

Result:

Show permission explanation if needed using an AlertDialog (this happens if the user denies a permission request, or grants the permission and then later revokes it in the settings):

enter image description here

Prompt the user for Location permission by calling ActivityCompat.requestPermissions():

enter image description here

Move camera to current location and place Marker when the Location permission is granted:

enter image description here

Array of char* should end at '\0' or "\0"?

Of these two, the first one is a type mistake: '\0' is a character, not a pointer. The compiler still accepts it because it can convert it to a pointer.

The second one "works" only by coincidence. "\0" is a string literal of two characters. If those occur in multiple places in the source file, the compiler may, but need not, make them identical.

So the proper way to write the first one is

char* array[] = { "abc", "def", NULL };

and you test for array[index]==NULL. The proper way to test for the second one is array[index][0]=='\0'; you may also drop the '\0' in the string (i.e. spell it as "") since that will already include a null byte.

How to connect android emulator to the internet

I had similar problem. I have installed an application that required INTERNET permission (and used it), and all of sudden, worked.

Guys, check also whether if you are not connected through a VPN somewhere, because it also can disturb the Internet connection.

blacharnia

How can I list all foreign keys referencing a given table in SQL Server?

There is how to get count of all responsibilities for selected Id. Just change @dbTableName value, @dbRowId value and its type (if int you need to remove '' in line no 82 (..SET @SQL = ..)). Enjoy.

DECLARE @dbTableName varchar(max) = 'User'
DECLARE @dbRowId uniqueidentifier = '21d34ecd-c1fd-11e2-8545-002219a42e1c'

DECLARE @FK_ROWCOUNT int
DECLARE @SQL nvarchar(max)

DECLARE @PKTABLE_QUALIFIER sysname
DECLARE @PKTABLE_OWNER sysname
DECLARE @PKTABLE_NAME sysname
DECLARE @PKCOLUMN_NAME sysname
DECLARE @FKTABLE_QUALIFIER sysname
DECLARE @FKTABLE_OWNER sysname
DECLARE @FKTABLE_NAME sysname
DECLARE @FKCOLUMN_NAME sysname
DECLARE @UPDATE_RULE smallint
DECLARE @DELETE_RULE smallint
DECLARE @FK_NAME sysname
DECLARE @PK_NAME sysname
DECLARE @DEFERRABILITY sysname

IF OBJECT_ID('tempdb..#Temp1') IS NOT NULL
    DROP TABLE #Temp1;
CREATE TABLE #Temp1 ( 
    PKTABLE_QUALIFIER sysname,
    PKTABLE_OWNER sysname,
    PKTABLE_NAME sysname,
    PKCOLUMN_NAME sysname,
    FKTABLE_QUALIFIER sysname,
    FKTABLE_OWNER sysname,
    FKTABLE_NAME sysname,
    FKCOLUMN_NAME sysname,
    UPDATE_RULE smallint,
    DELETE_RULE smallint,
    FK_NAME sysname,
    PK_NAME sysname,
    DEFERRABILITY sysname,
    FK_ROWCOUNT int
    );
DECLARE FK_Counter_Cursor CURSOR FOR
    SELECT PKTABLE_QUALIFIER = CONVERT(SYSNAME,DB_NAME()),
       PKTABLE_OWNER = CONVERT(SYSNAME,SCHEMA_NAME(O1.SCHEMA_ID)),
       PKTABLE_NAME = CONVERT(SYSNAME,O1.NAME),
       PKCOLUMN_NAME = CONVERT(SYSNAME,C1.NAME),
       FKTABLE_QUALIFIER = CONVERT(SYSNAME,DB_NAME()),
       FKTABLE_OWNER = CONVERT(SYSNAME,SCHEMA_NAME(O2.SCHEMA_ID)),
       FKTABLE_NAME = CONVERT(SYSNAME,O2.NAME),
       FKCOLUMN_NAME = CONVERT(SYSNAME,C2.NAME),
       -- Force the column to be non-nullable (see SQL BU 325751)
       --KEY_SEQ             = isnull(convert(smallint,k.constraint_column_id), sysconv(smallint,0)),
       UPDATE_RULE = CONVERT(SMALLINT,CASE OBJECTPROPERTY(F.OBJECT_ID,'CnstIsUpdateCascade') 
                                        WHEN 1 THEN 0
                                        ELSE 1
                                      END),
       DELETE_RULE = CONVERT(SMALLINT,CASE OBJECTPROPERTY(F.OBJECT_ID,'CnstIsDeleteCascade') 
                                        WHEN 1 THEN 0
                                        ELSE 1
                                      END),
       FK_NAME = CONVERT(SYSNAME,OBJECT_NAME(F.OBJECT_ID)),
       PK_NAME = CONVERT(SYSNAME,I.NAME),
       DEFERRABILITY = CONVERT(SMALLINT,7)   -- SQL_NOT_DEFERRABLE
    FROM   SYS.ALL_OBJECTS O1,
           SYS.ALL_OBJECTS O2,
           SYS.ALL_COLUMNS C1,
           SYS.ALL_COLUMNS C2,
           SYS.FOREIGN_KEYS F
           INNER JOIN SYS.FOREIGN_KEY_COLUMNS K
             ON (K.CONSTRAINT_OBJECT_ID = F.OBJECT_ID)
           INNER JOIN SYS.INDEXES I
             ON (F.REFERENCED_OBJECT_ID = I.OBJECT_ID
                 AND F.KEY_INDEX_ID = I.INDEX_ID)
    WHERE  O1.OBJECT_ID = F.REFERENCED_OBJECT_ID
           AND O2.OBJECT_ID = F.PARENT_OBJECT_ID
           AND C1.OBJECT_ID = F.REFERENCED_OBJECT_ID
           AND C2.OBJECT_ID = F.PARENT_OBJECT_ID
           AND C1.COLUMN_ID = K.REFERENCED_COLUMN_ID
           AND C2.COLUMN_ID = K.PARENT_COLUMN_ID
           AND O1.NAME = @dbTableName
OPEN FK_Counter_Cursor;
FETCH NEXT FROM FK_Counter_Cursor INTO @PKTABLE_QUALIFIER, @PKTABLE_OWNER, @PKTABLE_NAME, @PKCOLUMN_NAME, @FKTABLE_QUALIFIER, @FKTABLE_OWNER, @FKTABLE_NAME, @FKCOLUMN_NAME, @UPDATE_RULE, @DELETE_RULE, @FK_NAME, @PK_NAME, @DEFERRABILITY;
WHILE @@FETCH_STATUS = 0
   BEGIN
        SET @SQL = 'SELECT @dbCountOut = COUNT(*) FROM [' + @FKTABLE_NAME + '] WHERE [' + @FKCOLUMN_NAME + '] = ''' + CAST(@dbRowId AS varchar(max)) + '''';
        EXECUTE sp_executesql @SQL, N'@dbCountOut int OUTPUT', @dbCountOut = @FK_ROWCOUNT OUTPUT;
        INSERT INTO #Temp1 (PKTABLE_QUALIFIER, PKTABLE_OWNER, PKTABLE_NAME, PKCOLUMN_NAME, FKTABLE_QUALIFIER, FKTABLE_OWNER, FKTABLE_NAME, FKCOLUMN_NAME, UPDATE_RULE, DELETE_RULE, FK_NAME, PK_NAME, DEFERRABILITY, FK_ROWCOUNT) VALUES (@FKTABLE_QUALIFIER, @PKTABLE_OWNER, @PKTABLE_NAME, @PKCOLUMN_NAME, @FKTABLE_QUALIFIER, @FKTABLE_OWNER, @FKTABLE_NAME, @FKCOLUMN_NAME, @UPDATE_RULE, @DELETE_RULE, @FK_NAME, @PK_NAME, @DEFERRABILITY, @FK_ROWCOUNT)
      FETCH NEXT FROM FK_Counter_Cursor INTO @PKTABLE_QUALIFIER, @PKTABLE_OWNER, @PKTABLE_NAME, @PKCOLUMN_NAME, @FKTABLE_QUALIFIER, @FKTABLE_OWNER, @FKTABLE_NAME, @FKCOLUMN_NAME, @UPDATE_RULE, @DELETE_RULE, @FK_NAME, @PK_NAME, @DEFERRABILITY;
   END;
CLOSE FK_Counter_Cursor;
DEALLOCATE FK_Counter_Cursor;
GO
SELECT * FROM #Temp1
GO

How to declare strings in C

This link should satisfy your curiosity.

Basically (forgetting your third example which is bad), the different between 1 and 2 is that 1 allocates space for a pointer to the array.

But in the code, you can manipulate them as pointers all the same -- only thing, you cannot reallocate the second.

Can you control how an SVG's stroke-width is drawn?

Here is a work around for inner bordered rect using symbol and use.

Example: https://jsbin.com/yopemiwame/edit?html,output

SVG:

<svg>
  <symbol id="inner-border-rect">
    <rect class="inner-border" width="100%" height="100%" style="fill:rgb(0,255,255);stroke-width:10;stroke:rgb(0,0,0)">
  </symbol>
  ...
  <use xlink:href="#inner-border-rect" x="?" y="?" width="?" height="?">
</svg>

Note: Make sure to replace the ? in use with real values.

Background: The reason why this works is because symbol establishes a new viewport by replacing symbol with svg and creating an element in the shadow DOM. This svg of the shadow DOM is then linked into your current SVG element. Note that svgs can be nested and every svg creates a new viewport, which clips everything that overlaps, including the overlapping border. For a much more detailed overview of whats going on read this fantastic article by Sara Soueidan.

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

Java 8

    System.out.println(LocalDateTime.now().getHour());       // 7
    System.out.println(LocalDateTime.now().getMinute());     // 45
    System.out.println(LocalDateTime.now().getSecond());     // 32

Calendar

System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY));  // 7 
System.out.println(Calendar.getInstance().get(Calendar.MINUTE));       // 45
System.out.println(Calendar.getInstance().get(Calendar.SECOND));       // 32

Joda Time

    System.out.println(new DateTime().getHourOfDay());      // 7
    System.out.println(new DateTime().getMinuteOfHour());   // 45
    System.out.println(new DateTime().getSecondOfMinute()); // 32

Formatted

Java 8

    // 07:48:55.056
    System.out.println(ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME));
    // 7:48:55
    System.out.println(LocalTime.now().getHour() + ":" + LocalTime.now().getMinute() + ":" + LocalTime.now().getSecond());

    // 07:48:55
    System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));

    // 074855
    System.out.println(new SimpleDateFormat("HHmmss").format(Calendar.getInstance().getTime()));

    // 07:48:55 
    System.out.println(new Date().toString().substring(11, 20));

syntaxerror: unexpected character after line continuation character in python

The filename should be a string. In other names it should be within quotes.

f = open("D\\python\\HW\\2_1 - Copy.cp","r")
lines = f.readlines()
for i in lines:
    thisline = i.split(" ");

You can also open the file using with

with open("D\\python\\HW\\2_1 - Copy.cp","r") as f:
    lines = f.readlines()
    for i in lines:
        thisline = i.split(" ");

There is no need to add the semicolon(;) in python. It's ugly.

How to echo out the values of this array?

foreach ($array as $key => $val) {
   echo $val;
}

Where does the .gitignore file belong?

If you want to do it globally, you can use the default path git will search for. Just place it inside a file named "ignore" in the path ~/.config/git

(so full path for your file is: ~/.config/git/ignore)

SQL Server: Difference between PARTITION BY and GROUP BY

Small observation. Automation mechanism to dynamically generate SQL using the 'partition by' it is much simpler to implement in relation to the 'group by'. In the case of 'group by', We must take care of the content of 'select' column.

Sorry for My English.

How to detect if multiple keys are pressed at once using JavaScript?

document.onkeydown = keydown; 

function keydown (evt) { 

    if (!evt) evt = event; 

    if (evt.ctrlKey && evt.altKey && evt.keyCode === 115) {

        alert("CTRL+ALT+F4"); 

    } else if (evt.shiftKey && evt.keyCode === 9) { 

        alert("Shift+TAB");

    } 

}

PHP - regex to allow letters and numbers only

try this way .eregi("[^A-Za-z0-9.]", $value)

Android: how to refresh ListView contents?

In my understanding, if you want to refresh ListView immediately when data has changed, you should call notifyDataSetChanged() in RunOnUiThread().

private void updateData() {
    List<Data> newData = getYourNewData();
    mAdapter.setList(yourNewList);

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
                mAdapter.notifyDataSetChanged();
        }
    });
}

How do you remove a Cookie in a Java Servlet

The proper way to remove a cookie is to set the max age to 0 and add the cookie back to the HttpServletResponse object.

Most people don't realize or forget to add the cookie back onto the response object. By doing that it will expire and remove the cookie immediately.

...retrieve cookie from HttpServletRequest
cookie.setMaxAge(0);
response.addCookie(cookie);

Java ArrayList replace at specific index

Check out the set(int index, E element) method in the List interface

Ansible - read inventory hosts and variables to group_vars/all file

If you want to have your vars in files under group_vars, just move them here. Vars can be in the inventory ([group:vars] section) but also (and foremost) in files under group_vars or hosts_vars.

For instance, with your example above, you can move your vars for group tests in the file group_vars/tests :

Inventory file :

[lb]
10.112.84.122

[tomcat]
10.112.84.124

[jboss5]
10.112.84.122

...

[tests:children]
lb
tomcat
jboss5

[default:children]
tests

group_vars/tests file :

data_base_user=NETWIN-4.3
data_base_password=NETWIN
data_base_encrypted_password=
data_base_host=10.112.69.48
data_base_port=1521
data_base_service=ssdenwdb
data_base_url=jdbc:oracle:thin:@10.112.69.48:1521/ssdenwdb

Calculating time difference between 2 dates in minutes

Try this one:

select * from MyTab T where date_add(T.runTime, INTERVAL 20 MINUTE) < NOW()

NOTE: this should work if you're using MySQL DateTime format. If you're using Unix Timestamp (integer), then it would be even easier:

select * from MyTab T where UNIX_TIMESTAMP() - T.runTime > 20*60

UNIX_TIMESTAMP() function returns you current unix timestamp.

What is the best way to find the users home directory in Java?

The concept of a HOME directory seems to be a bit vague when it comes to Windows. If the environment variables (HOMEDRIVE/HOMEPATH/USERPROFILE) aren't enough, you may have to resort to using native functions via JNI or JNA. SHGetFolderPath allows you to retrieve special folders, like My Documents (CSIDL_PERSONAL) or Local Settings\Application Data (CSIDL_LOCAL_APPDATA).

Sample JNA code:

public class PrintAppDataDir {

    public static void main(String[] args) {
        if (com.sun.jna.Platform.isWindows()) {
            HWND hwndOwner = null;
            int nFolder = Shell32.CSIDL_LOCAL_APPDATA;
            HANDLE hToken = null;
            int dwFlags = Shell32.SHGFP_TYPE_CURRENT;
            char[] pszPath = new char[Shell32.MAX_PATH];
            int hResult = Shell32.INSTANCE.SHGetFolderPath(hwndOwner, nFolder,
                    hToken, dwFlags, pszPath);
            if (Shell32.S_OK == hResult) {
                String path = new String(pszPath);
                int len = path.indexOf('\0');
                path = path.substring(0, len);
                System.out.println(path);
            } else {
                System.err.println("Error: " + hResult);
            }
        }
    }

    private static Map<String, Object> OPTIONS = new HashMap<String, Object>();
    static {
        OPTIONS.put(Library.OPTION_TYPE_MAPPER, W32APITypeMapper.UNICODE);
        OPTIONS.put(Library.OPTION_FUNCTION_MAPPER,
                W32APIFunctionMapper.UNICODE);
    }

    static class HANDLE extends PointerType implements NativeMapped {
    }

    static class HWND extends HANDLE {
    }

    static interface Shell32 extends Library {

        public static final int MAX_PATH = 260;
        public static final int CSIDL_LOCAL_APPDATA = 0x001c;
        public static final int SHGFP_TYPE_CURRENT = 0;
        public static final int SHGFP_TYPE_DEFAULT = 1;
        public static final int S_OK = 0;

        static Shell32 INSTANCE = (Shell32) Native.loadLibrary("shell32",
                Shell32.class, OPTIONS);

        /**
         * see http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx
         * 
         * HRESULT SHGetFolderPath( HWND hwndOwner, int nFolder, HANDLE hToken,
         * DWORD dwFlags, LPTSTR pszPath);
         */
        public int SHGetFolderPath(HWND hwndOwner, int nFolder, HANDLE hToken,
                int dwFlags, char[] pszPath);

    }

}

Get String in YYYYMMDD format from JS date object?

Here is a little improvement to the answer from https://stackoverflow.com/users/318563/o-o

Date.prototype.ddmmyyyy = function(delimiter) {
    var yyyy = this.getFullYear().toString();
    var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
    var dd  = this.getDate().toString();
    return (dd[1]?dd:"0"+dd[0]) + delimiter + (mm[1]?mm:"0"+mm[0]) + delimiter +yyyy  ; // padding
};

Hope to be helpfull for anyone!

:)

How to SHUTDOWN Tomcat in Ubuntu?

if you are run this command

 debian@debian:~$  /usr/share/tomcat7/bin/shutdown.sh
 then your server will not stop and you will get o/p like that you provided if you use in 
 super user mode then effect will appear o/p will come like this

 debian@debian:~$ sudo /usr/share/tomcat7/bin/shutdown.sh
 [sudo] password for debian: 
 Using CATALINA_BASE:   /var/lib/tomcat
 Using CATALINA_HOME:   /var/lib/tomcat
 Using CATALINA_TMPDIR: /var/lib/tomcat/temp
 Using JRE_HOME:        /usr/lib/jvm/java-1.6.0-openjdk
 Using CLASSPATH:   /var/lib/tomcat/bin/bootstrap.jar:/var/lib/tomcat/bin/tomcat-juli.jar

Class Diagrams in VS 2017

I am using VS 2017 Enterprise, you can find an option to install the class diagram extension using he Quick Launch in VS.

In C#, why is String a reference type that behaves like a value type?

Strings aren't value types since they can be huge, and need to be stored on the heap. Value types are (in all implementations of the CLR as of yet) stored on the stack. Stack allocating strings would break all sorts of things: the stack is only 1MB for 32-bit and 4MB for 64-bit, you'd have to box each string, incurring a copy penalty, you couldn't intern strings, and memory usage would balloon, etc...

(Edit: Added clarification about value type storage being an implementation detail, which leads to this situation where we have a type with value sematics not inheriting from System.ValueType. Thanks Ben.)

jQuery deferreds and promises - .then() vs .done()

.done() terminates the promise chain, making sure nothing else can attach further steps. This means that the jQuery promise implementation can throw any unhandled exception, since no one can possible handle it using .fail().

In practical terms, if you do not plan to attach more steps to a promise, you should use .done(). For more details see why promises need to be done

Making custom right-click context menus for my web-app

As Adrian said, the plugins are going to work the same way. There are three basic parts you're going to need:

1: Event handler for 'contextmenu' event:

$(document).bind("contextmenu", function(event) {
    event.preventDefault();
    $("<div class='custom-menu'>Custom menu</div>")
        .appendTo("body")
        .css({top: event.pageY + "px", left: event.pageX + "px"});
});

Here, you could bind the event handler to any selector that you want to show a menu for. I've chosen the entire document.

2: Event handler for 'click' event (to close the custom menu):

$(document).bind("click", function(event) {
    $("div.custom-menu").hide();
});

3: CSS to control the position of the menu:

.custom-menu {
    z-index:1000;
    position: absolute;
    background-color:#C0C0C0;
    border: 1px solid black;
    padding: 2px;
}

The important thing with the CSS is to include the z-index and position: absolute

It wouldn't be too tough to wrap all of this in a slick jQuery plugin.

You can see a simple demo here: http://jsfiddle.net/andrewwhitaker/fELma/

How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

This Error hit me after installing RVM correctly. Solution: re-boot Terminal.

Reference RailsCast's RVM Install tutorial.

How do I move an existing Git submodule within a Git repository?

The given solution did not work for me, however a similar version did...

This is with a cloned repository, hence the submodule git repos are contained in the top repositories .git dir. All cations are from the top repository:

  1. Edit .gitmodules and change the "path =" setting for the submodule in question. (No need to change the label, nor to add this file to index.)

  2. Edit .git/modules/name/config and change the "worktree =" setting for the submodule in question

  3. run:

    mv submodule newpath/submodule
    git add -u
    git add newpath/submodule
    

I wonder if it makes a difference if the repositories are atomic, or relative submodules, in my case it was relative (submodule/.git is a ref back to topproject/.git/modules/submodule)

Javascript Print iframe contents only

document.getElementById("printf").contentWindow.print();

Same origin policy applies.

Source file 'Properties\AssemblyInfo.cs' could not be found

This solved my problem. You should select Properties, Right-Click, Source Control and Get Specific Version.

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices
;

For more information on the format models you can use with TO_CHAR on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.

Function to calculate R2 (R-squared) in R

Why not this:

rsq <- function(x, y) summary(lm(y~x))$r.squared
rsq(obs, mod)
#[1] 0.8560185

How to iterate through two lists in parallel?

You should use 'zip' function. Here is an example how your own zip function can look like

def custom_zip(seq1, seq2):
    it1 = iter(seq1)
    it2 = iter(seq2)
    while True:
        yield next(it1), next(it2)

How to add row of data to Jtable from values received from jtextfield and comboboxes

you can use this code as template please customize it as per your requirement.

DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

Generate a random date between two other dates

Alternative way to create random dates between two dates using np.random.randint(), pd.Timestamp().value and pd.to_datetime() with for loop:

# Import libraries
import pandas as pd

# Initialize
start = '2020-01-01' # Specify start date
end = '2020-03-10' # Specify end date
n = 10 # Specify number of dates needed

# Get random dates
x = np.random.randint(pd.Timestamp(start).value, pd.Timestamp(end).value,n)
random_dates = [pd.to_datetime((i/10**9)/(60*60)/24, unit='D').strftime('%Y-%m-%d')  for i in x]

print(random_dates)

Output

['2020-01-06',
 '2020-03-08',
 '2020-01-23',
 '2020-02-03',
 '2020-01-30',
 '2020-01-05',
 '2020-02-16',
 '2020-03-08',
 '2020-02-09',
 '2020-01-04']

CSS3 Transition not working

A general answer for a general question... Transitions can't animate properties that are auto. If you have a transition not working, check that the starting value of the property is explicitly set. (For example, to make a node collapse, when it's height is auto and must stay that way, put the transition on max-height instead. Give max-height a sensible initial value, then transition it to 0)

How do CSS triangles work?

here is another fiddle:

.container:after {
    position: absolute;
    right: 0;
    content: "";
    margin-right:-50px;
    margin-bottom: -8px;
    border-width: 25px;
    border-style: solid;
    border-color: transparent transparent transparent #000;
    width: 0;
    height: 0;
    z-index: 10;
    -webkit-transition: visibility 50ms ease-in-out,opacity 50ms ease-in-out;
    transition: visibility 50ms ease-in-out,opacity 50ms ease-in-out;
    bottom: 21px;
}
.container {
    float: left;
    margin-top: 100px;
    position: relative;
    width: 150px;
    height: 80px;
    background-color: #000;
}

.containerRed {
    float: left;
    margin-top: 100px;
    position: relative;
    width: 100px;
    height: 80px;
    background-color: red;
}

https://jsfiddle.net/qdhvdb17/

How to sort a data frame by alphabetic order of a character variable in R?

Use order function:

set.seed(1)
DF <- data.frame(ID= sample(letters[1:26], 15, TRUE),
                 num = sample(1:100, 15, TRUE),
                 random = rnorm(15),
                 stringsAsFactors=FALSE)
DF[order(DF[,'ID']), ]
   ID num      random
10  b  27  0.61982575
12  e   2 -0.15579551
5   f  78  0.59390132
11  f  39 -0.05612874
1   g  50 -0.04493361
2   j  72 -0.01619026
14  j  87 -0.47815006
3   o 100  0.94383621
9   q  13 -1.98935170
8   r  66  0.07456498
13  r  39 -1.47075238
15  u  35  0.41794156
4   x  39  0.82122120
6   x  94  0.91897737
7   y  22  0.78213630

Another solution would be using orderByfunction from doBy package:

> library(doBy)
> orderBy(~ID, DF)

Python Matplotlib figure title overlaps axes label when using twiny

Just use plt.tight_layout() before plt.show(). It works well.

AssertionError: View function mapping is overwriting an existing endpoint function: main

I would just like to add to this a more 'template' type solution.

def func_name(f):
    def wrap(*args, **kwargs):
        if condition:
            pass
        else:
            whatever you want
        return f(*args, **kwargs)
    wrap.__name__ = f.__name__
    return wrap

would just like to add a really interesting article "Demystifying Decorators" I found recently: https://sumit-ghosh.com/articles/demystifying-decorators-python/

What does DIM stand for in Visual Basic and BASIC?

Dimension a variable, basically you are telling the compiler that you are going to need a variable of this type at some point.

How to do multiline shell script in Ansible

I prefer this syntax as it allows to set configuration parameters for the shell:

---
- name: an example
  shell:
    cmd: |
      docker build -t current_dir .
      echo "Hello World"
      date

    chdir: /home/vagrant/

Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired

A quick bad approach is that go to app\http\middleware\verifycsrftoken.php and add the route in $except list. The post request will be ignord for CSRF Token verification.

protected $except = [
    //
    'doLogin.aspx',
    'create_coupon',
];

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

A key issue here is that this loop iterates over the rows (1st dimension) of B:

In [258]: B
Out[258]: 
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])
In [259]: for b in B:
     ...:     print(b,'=>',end='')
     ...:     b += 1
     ...:     print(b)
     ...:     
[0 1 2] =>[1 2 3]
[3 4 5] =>[4 5 6]
[6 7 8] =>[7 8 9]
[ 9 10 11] =>[10 11 12]

Thus the += is acting on a mutable object, an array.

This is implied in the other answers, but easily missed if your focus is on the a = a+1 reassignment.

I could also make an in-place change to b with [:] indexing, or even something fancier, b[1:]=0:

In [260]: for b in B:
     ...:     print(b,'=>',end='')
     ...:     b[:] = b * 2

[1 2 3] =>[2 4 6]
[4 5 6] =>[ 8 10 12]
[7 8 9] =>[14 16 18]
[10 11 12] =>[20 22 24]

Of course with a 2d array like B we usually don't need to iterate on the rows. Many operations that work on a single of B also work on the whole thing. B += 1, B[1:] = 0, etc.

How can I provide multiple conditions for data trigger in WPF?

To elaborate on @serine's answer and illustrate working with non-trivial multi-valued condition: I had a need to show a "dim-out" overlay on an item for the boolean condition NOT a AND (b OR NOT c).

For background, this is a "Multiple Choice" question. If the user picks a wrong answer it becomes disabled (dimmed out and cannot be selected again). An automated agent has the ability to focus on any particular choice to give an explanation (border highlighted). When the agent focuses on an item, it should not be dimmed out even if it is disabled. All items that are not in focused are marked de-focused, and should be dimmed out.

The logic for dimming is thus:

NOT IsFocused AND (IsDefocused OR NOT Enabled)

To implement this logic, I made a generic IMultiValueConverter named (awkwardly) to match my logic

// 'P' represents a parenthesis
//     !  a &&  ( b ||  !  c )
class NOT_a_AND_P_b_OR_NOT_c_P : IMultiValueConverter
{
    // redacted [...] for brevity
    public object Convert(object[] values, ...)
    {
        bool a = System.Convert.ToBoolean(values[0]);
        bool b = System.Convert.ToBoolean(values[1]);
        bool c = System.Convert.ToBoolean(values[2]);

        return !a && (b || !c);
    }
    ...
}

In the XAML I use this in a MultiDataTrigger in a <Style><Style.Triggers> resource

<MultiDataTrigger>
    <MultiDataTrigger.Conditions>
        <!-- when the equation is TRUE ... -->
        <Condition Value="True">
            <Condition.Binding>
                <MultiBinding Converter="{StaticResource NOT_a_AND_P_b_OR_NOT_c_P}">
                    <!-- NOT IsFocus AND ( IsDefocused OR NOT Enabled ) -->
                    <Binding Path="IsFocus"/>
                    <Binding Path="IsDefocused" />
                    <Binding Path="Enabled" />
                </MultiBinding>
            </Condition.Binding>
        </Condition>
    </MultiDataTrigger.Conditions>
    <MultiDataTrigger.Setters>
        <!-- ... show the 'dim-out' overlay -->
        <Setter Property="Visibility" Value="Visible" />
    </MultiDataTrigger.Setters>
</MultiDataTrigger>

And for completeness sake, my converter is defined in a ResourceDictionary

<ResourceDictionary xmlns:conv="clr-namespace:My.Converters" ...>
    <conv:NOT_a_AND_P_b_OR_NOT_c_P x:Key="NOT_a_AND_P_b_OR_NOT_c_P" />
</ResourceDictionary>

LINQ Where with AND OR condition

Linq With Or Condition by using Lambda expression you can do as below

DataTable dtEmp = new DataTable();

dtEmp.Columns.Add("EmpID", typeof(int));
dtEmp.Columns.Add("EmpName", typeof(string));
dtEmp.Columns.Add("Sal", typeof(decimal));
dtEmp.Columns.Add("JoinDate", typeof(DateTime));
dtEmp.Columns.Add("DeptNo", typeof(int));

dtEmp.Rows.Add(1, "Rihan", 10000, new DateTime(2001, 2, 1), 10);
dtEmp.Rows.Add(2, "Shafi", 20000, new DateTime(2000, 3, 1), 10);
dtEmp.Rows.Add(3, "Ajaml", 25000, new DateTime(2010, 6, 1), 10);
dtEmp.Rows.Add(4, "Rasool", 45000, new DateTime(2003, 8, 1), 20);
dtEmp.Rows.Add(5, "Masthan", 22000, new DateTime(2001, 3, 1), 20);


var res2 = dtEmp.AsEnumerable().Where(emp => emp.Field<int>("EmpID")
            == 1 || emp.Field<int>("EmpID") == 2);

foreach (DataRow row in res2)
{
    Label2.Text += "Emplyee ID: " + row[0] + "   &   Emplyee Name: " + row[1] + ",  ";
}

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 and when to use ‘async’ and ‘await’

The answers here are useful as a general guidance about await/async. They also contain some detail about how await/async is wired. I would like to share some practical experience with you that you should know before using this design pattern.

The term "await" is literal, so whatever thread you call it on will wait for the result of the method before continuing. On the foreground thread, this is a disaster. The foreground thread carries the burden of constructing your app, including views, view models, initial animations, and whatever else you have boot-strapped with those elements. So when you await the foreground thread, you stop the app. The user waits and waits when nothing appears to happen. This provides a negative user experience.

You can certainly await a background thread using a variety of means:

Device.BeginInvokeOnMainThread(async () => { await AnyAwaitableMethod(); });

// Notice that we do not await the following call, 
// as that would tie it to the foreground thread.
try
{
Task.Run(async () => { await AnyAwaitableMethod(); });
}
catch
{}

The complete code for these remarks is at https://github.com/marcusts/xamarin-forms-annoyances. See the solution called AwaitAsyncAntipattern.sln.

The GitHub site also provides links to a more detailed discussion on this topic.

Cannot send a content-body with this verb-type

Don't get the request stream, quite simply. GET requests don't usually have bodies (even though it's not technically prohibited by HTTP) and WebRequest doesn't support it - but that's what calling GetRequestStream is for, providing body data for the request.

Given that you're trying to read from the stream, it looks to me like you actually want to get the response and read the response stream from that:

WebRequest request = WebRequest.Create(get.AbsoluteUri + args);
request.Method = "GET";
using (WebResponse response = request.GetResponse())
{
    using (Stream stream = response.GetResponseStream())
    {
        XmlTextReader reader = new XmlTextReader(stream);
        ...
    }
}

Eclipse not recognizing JVM 1.8

OK, so I don't really know what the problem was, but I simply fixed it by navigating to here http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html and installing 8u74 instead of 8u73 which is what I was prompted to do when I would go to "download latest version" in Java. So changing the versions is what did it in the end. Eclipse launched fine, now. Thanks for everyone's help!

edit: Apr 2018- Now is 8u161 and 8u162 (Just need one, I used 8u162 and it worked.)

Automatic exit from Bash shell script on error

I think that what you are looking for is the trap command:

trap command signal [signal ...]

For more information, see this page.

Another option is to use the set -e command at the top of your script - it will make the script exit if any program / command returns a non true value.

Remove stubborn underline from link

Put the following HTML code before the <BODY> tag:

<STYLE>A {text-decoration: none;} </STYLE>

How get the base URL via context path in JSF?

URLs are not resolved based on the file structure in the server side. URLs are resolved based on the real public web addresses of the resources in question. It's namely the webbrowser who has got to invoke them, not the webserver.

There are several ways to soften the pain:

JSF EL offers a shorthand to ${pageContext.request} in flavor of #{request}:

<li><a href="#{request.contextPath}/index.xhtml">Home</a></li>
<li><a href="#{request.contextPath}/about_us.xhtml">About us</a></li>

You can if necessary use <c:set> tag to make it yet shorter. Put it somewhere in the master template, it'll be available to all pages:

<c:set var="root" value="#{request.contextPath}/" />
...
<li><a href="#{root}index.xhtml">Home</a></li>
<li><a href="#{root}about_us.xhtml">About us</a></li>

JSF 2.x offers the <h:link> which can take a view ID relative to the context root in outcome and it will append the context path and FacesServlet mapping automatically:

<li><h:link value="Home" outcome="index" /></li>
<li><h:link value="About us" outcome="about_us" /></li>

HTML offers the <base> tag which makes all relative URLs in the document relative to this base. You could make use of it. Put it in the <h:head>.

<base href="#{request.requestURL.substring(0, request.requestURL.length() - request.requestURI.length())}#{request.contextPath}/" />
...
<li><a href="index.xhtml">Home</a></li>
<li><a href="about_us.xhtml">About us</a></li>

(note: this requires EL 2.2, otherwise you'd better use JSTL fn:substring(), see also this answer)

This should end up in the generated HTML something like as

<base href="http://example.com/webname/" />

Note that the <base> tag has a caveat: it makes all jump anchors in the page like <a href="#top"> relative to it as well! See also Is it recommended to use the <base> html tag? In JSF you could solve it like <a href="#{request.requestURI}#top">top</a> or <h:link value="top" fragment="top" />.

How to check that an element is in a std::set?

//general Syntax

       set<int>::iterator ii = find(set1.begin(),set1.end(),"element to be searched");

/* in below code i am trying to find element 4 in and int set if it is present or not*/

set<int>::iterator ii = find(set1.begin(),set1.end(),4);
 if(ii!=set1.end())
 {
    cout<<"element found";
    set1.erase(ii);// in case you want to erase that element from set.
 }

Where can I get a list of Ansible pre-defined variables?

There is lot of variables defined as Facts -- http://docs.ansible.com/ansible/playbooks_variables.html#information-discovered-from-systems-facts

"ansible_all_ipv4_addresses": [
    "REDACTED IP ADDRESS"
],
"ansible_all_ipv6_addresses": [
    "REDACTED IPV6 ADDRESS"
],
"ansible_architecture": "x86_64",
"ansible_bios_date": "09/20/2012",
"ansible_bios_version": "6.00",
"ansible_cmdline": {
    "BOOT_IMAGE": "/boot/vmlinuz-3.5.0-23-generic",
    "quiet": true,
    "ro": true,
    "root": "UUID=4195bff4-e157-4e41-8701-e93f0aec9e22",
    "splash": true
},
"ansible_date_time": {
    "date": "2013-10-02",
    "day": "02",
    "epoch": "1380756810",
    "hour": "19",
    "iso8601": "2013-10-02T23:33:30Z",
    "iso8601_micro": "2013-10-02T23:33:30.036070Z",
    "minute": "33",
    "month": "10",
    "second": "30",
    "time": "19:33:30",
    "tz": "EDT",
    "year": "2013"
},
"ansible_default_ipv4": {
    "address": "REDACTED",
    "alias": "eth0",
    "gateway": "REDACTED",
    "interface": "eth0",
    "macaddress": "REDACTED",
    "mtu": 1500,
    "netmask": "255.255.255.0",
    "network": "REDACTED",
    "type": "ether"
},
"ansible_default_ipv6": {},
"ansible_devices": {
    "fd0": {
        "holders": [],
        "host": "",
        "model": null,
        "partitions": {},
        "removable": "1",
        "rotational": "1",
        "scheduler_mode": "deadline",
        "sectors": "0",
        "sectorsize": "512",
        "size": "0.00 Bytes",
        "support_discard": "0",
        "vendor": null
    },
    "sda": {
        "holders": [],
        "host": "SCSI storage controller: LSI Logic / Symbios Logic 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev 01)",
        "model": "VMware Virtual S",
        "partitions": {
            "sda1": {
                "sectors": "39843840",
                "sectorsize": 512,
                "size": "19.00 GB",
                "start": "2048"
            },
            "sda2": {
                "sectors": "2",
                "sectorsize": 512,
                "size": "1.00 KB",
                "start": "39847934"
            },
            "sda5": {
                "sectors": "2093056",
                "sectorsize": 512,
                "size": "1022.00 MB",
                "start": "39847936"
            }
        },
        "removable": "0",
        "rotational": "1",
        "scheduler_mode": "deadline",
        "sectors": "41943040",
        "sectorsize": "512",
        "size": "20.00 GB",
        "support_discard": "0",
        "vendor": "VMware,"
    },
    "sr0": {
        "holders": [],
        "host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)",
        "model": "VMware IDE CDR10",
        "partitions": {},
        "removable": "1",
        "rotational": "1",
        "scheduler_mode": "deadline",
        "sectors": "2097151",
        "sectorsize": "512",
        "size": "1024.00 MB",
        "support_discard": "0",
        "vendor": "NECVMWar"
    }
},
"ansible_distribution": "Ubuntu",
"ansible_distribution_release": "precise",
"ansible_distribution_version": "12.04",
"ansible_domain": "",
"ansible_env": {
    "COLORTERM": "gnome-terminal",
    "DISPLAY": ":0",
    "HOME": "/home/mdehaan",
    "LANG": "C",
    "LESSCLOSE": "/usr/bin/lesspipe %s %s",
    "LESSOPEN": "| /usr/bin/lesspipe %s",
    "LOGNAME": "root",
    "LS_COLORS": "rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.axa=00;36:*.oga=00;36:*.spx=00;36:*.xspf=00;36:",
    "MAIL": "/var/mail/root",
    "OLDPWD": "/root/ansible/docsite",
    "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
    "PWD": "/root/ansible",
    "SHELL": "/bin/bash",
    "SHLVL": "1",
    "SUDO_COMMAND": "/bin/bash",
    "SUDO_GID": "1000",
    "SUDO_UID": "1000",
    "SUDO_USER": "mdehaan",
    "TERM": "xterm",
    "USER": "root",
    "USERNAME": "root",
    "XAUTHORITY": "/home/mdehaan/.Xauthority",
    "_": "/usr/local/bin/ansible"
},
"ansible_eth0": {
    "active": true,
    "device": "eth0",
    "ipv4": {
        "address": "REDACTED",
        "netmask": "255.255.255.0",
        "network": "REDACTED"
    },
    "ipv6": [
        {
            "address": "REDACTED",
            "prefix": "64",
            "scope": "link"
        }
    ],
    "macaddress": "REDACTED",
    "module": "e1000",
    "mtu": 1500,
    "type": "ether"
},
"ansible_form_factor": "Other",
"ansible_fqdn": "ubuntu2.example.com",
"ansible_hostname": "ubuntu2",
"ansible_interfaces": [
    "lo",
    "eth0"
],
"ansible_kernel": "3.5.0-23-generic",
"ansible_lo": {
    "active": true,
    "device": "lo",
    "ipv4": {
        "address": "127.0.0.1",
        "netmask": "255.0.0.0",
        "network": "127.0.0.0"
    },
    "ipv6": [
        {
            "address": "::1",
            "prefix": "128",
            "scope": "host"
        }
    ],
    "mtu": 16436,
    "type": "loopback"
},
"ansible_lsb": {
    "codename": "precise",
    "description": "Ubuntu 12.04.2 LTS",
    "id": "Ubuntu",
    "major_release": "12",
    "release": "12.04"
},
"ansible_machine": "x86_64",
"ansible_memfree_mb": 74,
"ansible_memtotal_mb": 991,
"ansible_mounts": [
    {
        "device": "/dev/sda1",
        "fstype": "ext4",
        "mount": "/",
        "options": "rw,errors=remount-ro",
        "size_available": 15032406016,
        "size_total": 20079898624
    }
],
"ansible_nodename": "ubuntu2.example.com",
"ansible_os_family": "Debian",
"ansible_pkg_mgr": "apt",
"ansible_processor": [
    "Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz"
],
"ansible_processor_cores": 1,
"ansible_processor_count": 1,
"ansible_processor_threads_per_core": 1,
"ansible_processor_vcpus": 1,
"ansible_product_name": "VMware Virtual Platform",
"ansible_product_serial": "REDACTED",
"ansible_product_uuid": "REDACTED",
"ansible_product_version": "None",
"ansible_python_version": "2.7.3",
"ansible_selinux": false,
"ansible_ssh_host_key_dsa_public": "REDACTED KEY VALUE"
"ansible_ssh_host_key_ecdsa_public": "REDACTED KEY VALUE"
"ansible_ssh_host_key_rsa_public": "REDACTED KEY VALUE"
"ansible_swapfree_mb": 665,
"ansible_swaptotal_mb": 1021,
"ansible_system": "Linux",
"ansible_system_vendor": "VMware, Inc.",
"ansible_user_id": "root",
"ansible_userspace_architecture": "x86_64",
"ansible_userspace_bits": "64",
"ansible_virtualization_role": "guest",
"ansible_virtualization_type": "VMware"

Pass values of checkBox to controller action in asp.net mvc4

If a checkbox is checked, then the postback values will contain a key-value pair of the form [InputName]=[InputValue]

If a checkbox is not checked, then the posted form contains no reference to the checkbox at all.

Knowing this, the following will work:

In the markup code:

 <input id="responsable" name="checkResp" value="true" type="checkbox" />

And your action method signature:

public ActionResult Index( string responsables, bool checkResp = false)

This will work because when the checkbox is checked, the postback will contain checkResp=true, and if the checkbox is not checked the parameter will default to false.

PHP function to build query string from array

As this question is quite old and for PHP, here is a way to do it in the (currently) very popular PHP framework Laravel.

To encode the query string for a path in your application, give your routes names and then use the route() helper function like so:

route('documents.list.', ['foo' => 'bar']);

The result will look something like:

http://localhost/documents/list?foo=bar

Also be aware that if your route has any path segment parameters e.g. /documents/{id}, then make sure you pass an id argument to the route() parameters too, otherwise it will default to using the value of the first parameter.

Dynamically change color to lighter or darker by percentage CSS (Javascript)

I found a PHP class that let me do this server side. I just output an inline CSS color style for whatever I need to be lighter/darker. Works great.

http://www.barelyfitz.com/projects/csscolor/

(note that the class uses PEAR for throwing errors, but I didn't want to include PEAR just to modify colors, so I just removed all the PEAR references)

I turned it into a static class with static methods so I can call "lighten" & "darken" functions directly without creating a new object.

Sample usage:

$original_color = 'E58D8D';  
$lighter_color = Css::lighten($original_color, .7);  
$darker_color = Css::darken($original_color, .7);

numpy max vs amax vs maximum

You've already stated why np.maximum is different - it returns an array that is the element-wise maximum between two arrays.

As for np.amax and np.max: they both call the same function - np.max is just an alias for np.amax, and they compute the maximum of all elements in an array, or along an axis of an array.

In [1]: import numpy as np

In [2]: np.amax
Out[2]: <function numpy.core.fromnumeric.amax>

In [3]: np.max
Out[3]: <function numpy.core.fromnumeric.amax>

lexers vs parsers

To answer the question as asked (without repeating unduly what appears in other answers)

Lexers and parsers are not very different, as suggested by the accepted answer. Both are based on simple language formalisms: regular languages for lexers and, almost always, context-free (CF) languages for parsers. They both are associated with fairly simple computational models, the finite state automaton and the push-down stack automaton. Regular languages are a special case of context-free languages, so that lexers could be produced with the somewhat more complex CF technology. But it is not a good idea for at least two reasons.

A fundamental point in programming is that a system component should be buit with the most appropriate technology, so that it is easy to produce, to understand and to maintain. The technology should not be overkill (using techniques much more complex and costly than needed), nor should it be at the limit of its power, thus requiring technical contortions to achieve the desired goal.

That is why "It seems fashionable to hate regular expressions". Though they can do a lot, they sometimes require very unreadable coding to achieve it, not to mention the fact that various extensions and restrictions in implementation somewhat reduce their theoretical simplicity. Lexers do not usually do that, and are usually a simple, efficient, and appropriate technology to parse token. Using CF parsers for token would be overkill, though it is possible.

Another reason not to use CF formalism for lexers is that it might then be tempting to use the full CF power. But that might raise sructural problems regarding the reading of programs.

Fundamentally, most of the structure of program text, from which meaning is extracted, is a tree structure. It expresses how the parse sentence (program) is generated from syntax rules. Semantics is derived by compositional techniques (homomorphism for the mathematically oriented) from the way syntax rules are composed to build the parse tree. Hence the tree structure is essential. The fact that tokens are identified with a regular set based lexer does not change the situation, because CF composed with regular still gives CF (I am speaking very loosely about regular transducers, that transform a stream of characters into a stream of token).

However, CF composed with CF (via CF transducers ... sorry for the math), does not necessarily give CF, and might makes things more general, but less tractable in practice. So CF is not the appropriate tool for lexers, even though it can be used.

One of the major differences between regular and CF is that regular languages (and transducers) compose very well with almost any formalism in various ways, while CF languages (and transducers) do not, not even with themselves (with a few exceptions).

(Note that regular transducers may have others uses, such as formalization of some syntax error handling techniques.)

BNF is just a specific syntax for presenting CF grammars.

EBNF is a syntactic sugar for BNF, using the facilities of regular notation to give terser version of BNF grammars. It can always be transformed into an equivalent pure BNF.

However, the regular notation is often used in EBNF only to emphasize these parts of the syntax that correspond to the structure of lexical elements, and should be recognized with the lexer, while the rest with be rather presented in straight BNF. But it is not an absolute rule.

To summarize, the simpler structure of token is better analyzed with the simpler technology of regular languages, while the tree oriented structure of the language (of program syntax) is better handled by CF grammars.

I would suggest also looking at AHR's answer.

But this leaves a question open: Why trees?

Trees are a good basis for specifying syntax because

  • they give a simple structure to the text

  • there are very convenient for associating semantics with the text on the basis of that structure, with a mathematically well understood technology (compositionality via homomorphisms), as indicated above. It is a fundamental algebraic tool to define the semantics of mathematical formalisms.

Hence it is a good intermediate representation, as shown by the success of Abstract Syntax Trees (AST). Note that AST are often different from parse tree because the parsing technology used by many professionals (Such as LL or LR) applies only to a subset of CF grammars, thus forcing grammatical distorsions which are later corrected in AST. This can be avoided with more general parsing technology (based on dynamic programming) that accepts any CF grammar.

Statement about the fact that programming languages are context-sensitive (CS) rather than CF are arbitrary and disputable.

The problem is that the separation of syntax and semantics is arbitrary. Checking declarations or type agreement may be seen as either part of syntax, or part of semantics. The same would be true of gender and number agreement in natural languages. But there are natural languages where plural agreement depends on the actual semantic meaning of words, so that it does not fit well with syntax.

Many definitions of programming languages in denotational semantics place declarations and type checking in the semantics. So stating as done by Ira Baxter that CF parsers are being hacked to get a context sensitivity required by syntax is at best an arbitrary view of the situation. It may be organized as a hack in some compilers, but it does not have to be.

Also it is not just that CS parsers (in the sense used in other answers here) are hard to build, and less efficient. They are are also inadequate to express perspicuously the kinf of context-sensitivity that might be needed. And they do not naturally produce a syntactic structure (such as parse-trees) that is convenient to derive the semantics of the program, i.e. to generate the compiled code.

Web scraping with Python

I'd really recommend Scrapy.

Quote from a deleted answer:

  • Scrapy crawling is fastest than mechanize because uses asynchronous operations (on top of Twisted).
  • Scrapy has better and fastest support for parsing (x)html on top of libxml2.
  • Scrapy is a mature framework with full unicode, handles redirections, gzipped responses, odd encodings, integrated http cache, etc.
  • Once you are into Scrapy, you can write a spider in less than 5 minutes that download images, creates thumbnails and export the extracted data directly to csv or json.

The requested operation cannot be performed on a file with a user-mapped section open

The solution for me was to close out of all instances of VS and to kill any hanging devenv.exe processes.

How to return first 5 objects of Array in Swift?

For an array of objects you can create an extension from Sequence.

extension Sequence {
    func limit(_ max: Int) -> [Element] {
        return self.enumerated()
            .filter { $0.offset < max }
            .map { $0.element }
    }
}

Usage:

struct Apple {}

let apples: [Apple] = [Apple(), Apple(), Apple()]
let limitTwoApples = apples.limit(2)

// limitTwoApples: [Apple(), Apple()]

How to disable the parent form when a child form is active?

Have you tried using Form.ShowDialog() instead of Form.Show()?

ShowDialog shows your window as modal, which means you cannot interact with the parent form until it closes.

Set View Width Programmatically

hsThumbList.setLayoutParams(new LayoutParams(100, 400));

Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

If you are going with Custom Static Cells just comment this method:

//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    static NSString *CellIdentifier = @"notificationCell";
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
//    return cell;
//}

and give the cells an identifier at "Attributes Inspector" in storyboard.

Unable to create Genymotion Virtual Device

  1. If you have installed the Genymotion plugin without VirtualBox then make sure the version of VBox is compatible with the plugin, otherwise the plugin will not deploy the virtual device regardless of the OVA file.Install the latest versions of both if you are unsure
  2. Once you verified the versions, you may need to either:

    a: Give administrative privileges for Genymotion via properties

    OR

    b: Change the location for the deployed devices via Settings/VirtualBox to somewhere more accessbile like D:/GenyMotion VMs/

  3. If both step 1 and 2 doesnt work for you, sadly you will have to clear the cache via Settings/Misc and reinstall the OVA file.Hopefully your efforts will be worth it. Good Luck.

open existing java project in eclipse

Simple, you just open klik file -> import -> General -> existing project into workspace -> browse file in your directory.

(I'am used Eclipse Mars)

How to position a Bootstrap popover?

Sure you can. Fortunately there is a clean way to do that and it is in the Bootstrap popover / tooltip documentation as well.

let mySpecialTooltip = $('#mySpecialTooltip); 
mySpecialTooltip.tooltip({
 container: 'body',
 placement: 'bottom',
 html: true,
 template: '<div class="tooltip your-custom-class" role="tooltip"><div class="arrow"></div><div class="tooltip-inner"></div></div>'
}); 

in your css file:-

.your-custom-class {
 bottom: your value;
}

Make sure to add the template in bootstrap's tooltip documentation and add your custom class name and style it using css

And, that's it. You can find more about this on https://getbootstrap.com/docs/4.0/components/tooltips/

pass parameter by link_to ruby on rails

The above did not work for me but this did

<%= link_to "text_to_show_in_url", action_controller_path(:gender => "male", :param2=> "something_else") %>

Access-control-allow-origin with multiple domains

Try this:

<add name="Access-Control-Allow-Origin" value="['URL1','URL2',...]" />

How to kill a while loop with a keystroke?

There is a solution that requires no non-standard modules and is 100% transportable

import thread

def input_thread(a_list):
    raw_input()
    a_list.append(True)

def do_stuff():
    a_list = []
    thread.start_new_thread(input_thread, (a_list,))
    while not a_list:
        stuff()

Activity transition in Android

Yes. You can tell the OS what kind of transition you want to have for your activity.

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    getWindow().setWindowAnimations(ANIMATION);

    ...

}

Where ANIMATION is an integer referring to a built in animation in the OS.

What is [Serializable] and when should I use it?

Since the original question was about the SerializableAttribute, it should be noted that this attribute only applies when using the BinaryFormatter or SoapFormatter.

It is a bit confusing, unless you really pay attention to the details, as to when to use it and what its actual purpose is.

It has NOTHING to do with XML or JSON serialization.

Used with the SerializableAttribute are the ISerializable Interface and SerializationInfo Class. These are also only used with the BinaryFormatter or SoapFormatter.

Unless you intend to serialize your class using Binary or Soap, do not bother marking your class as [Serializable]. XML and JSON serializers are not even aware of its existence.

How to duplicate sys.stdout to a log file?

As per a request by @user5359531 in the comments under @John T's answer, here's a copy of the referenced post to the revised version of the linked discussion in that answer:

Issue of redirecting the stdout to both file and screen
Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon May 28 12:45:51 CEST 2007

    Previous message: Issue of redirecting the stdout to both file and screen
    Next message: Formal interfaces with Python
    Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]

En Mon, 28 May 2007 06:17:39 -0300, ???????,???????
<kelvin.you at gmail.com> escribió:

> I wanna print the log to both the screen and file, so I simulatered a
> 'tee'
>
> class Tee(file):
>
>     def __init__(self, name, mode):
>         file.__init__(self, name, mode)
>         self.stdout = sys.stdout
>         sys.stdout = self
>
>     def __del__(self):
>         sys.stdout = self.stdout
>         self.close()
>
>     def write(self, data):
>         file.write(self, data)
>         self.stdout.write(data)
>
> Tee('logfile', 'w')
> print >>sys.stdout, 'abcdefg'
>
> I found that it only output to the file, nothing to screen. Why?
> It seems the 'write' function was not called when I *print* something.

You create a Tee instance and it is immediately garbage collected. I'd
restore sys.stdout on Tee.close, not __del__ (you forgot to call the
inherited __del__ method, btw).
Mmm, doesn't work. I think there is an optimization somewhere: if it looks
like a real file object, it uses the original file write method, not yours.
The trick would be to use an object that does NOT inherit from file:

import sys
class TeeNoFile(object):
     def __init__(self, name, mode):
         self.file = open(name, mode)
         self.stdout = sys.stdout
         sys.stdout = self
     def close(self):
         if self.stdout is not None:
             sys.stdout = self.stdout
             self.stdout = None
         if self.file is not None:
             self.file.close()
             self.file = None
     def write(self, data):
         self.file.write(data)
         self.stdout.write(data)
     def flush(self):
         self.file.flush()
         self.stdout.flush()
     def __del__(self):
         self.close()

tee=TeeNoFile('logfile', 'w')
print 'abcdefg'
print 'another line'
tee.close()
print 'screen only'
del tee # should do nothing

--
Gabriel Genellina

Replace a string in a file with nodejs

This may help someone:

This is a little different than just a global replace

from the terminal we run
node replace.js

replace.js:

function processFile(inputFile, repString = "../") {
var fs = require('fs'),
    readline = require('readline'),
    instream = fs.createReadStream(inputFile),
    outstream = new (require('stream'))(),
    rl = readline.createInterface(instream, outstream);
    formatted = '';   

const regex = /<xsl:include href="([^"]*)" \/>$/gm;

rl.on('line', function (line) {
    let url = '';
    let m;
    while ((m = regex.exec(line)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
        }
        
        url = m[1];
    }

    let re = new RegExp('^.* <xsl:include href="(.*?)" \/>.*$', 'gm');

    formatted += line.replace(re, `\t<xsl:include href="${repString}${url}" />`);
    formatted += "\n";
});

rl.on('close', function (line) {
    fs.writeFile(inputFile, formatted, 'utf8', function (err) {
        if (err) return console.log(err);
    });

});
}


// path is relative to where your running the command from
processFile('build/some.xslt');

This is what this does. We have several file that have xml:includes

However in development we need the path to move down a level.

From this

<xsl:include href="common/some.xslt" />

to this

<xsl:include href="../common/some.xslt" />

So we end up running two regx patterns one to get the href and the other to write there is probably a better way to do this but it work for now.

Thanks

Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3

This answer is in three parts, see below for the official release (v3 and v4)

I couldn't even find the col-lg-push-x or pull classes in the original files for RC1 i downloaded, so check your bootstrap.css file. hopefully this is something they will sort out in RC2.

anyways, the col-push-* and pull classes did exist and this will suit your needs. Here is a demo

<div class="row">
    <div class="col-sm-5 col-push-5">
        Content B
    </div>
    <div class="col-sm-5 col-pull-5">
        Content A
    </div>
    <div class="col-sm-2">
        Content C
    </div>
</div>

EDIT: BELOW IS THE ANSWER FOR THE OFFICIAL RELEASE v3.0

Also see This blog post on the subject

  • col-vp-push-x = push the column to the right by x number of columns, starting from where the column would normally render -> position: relative, on a vp or larger view-port.

  • col-vp-pull-x = pull the column to the left by x number of columns, starting from where the column would normally render -> position: relative, on a vp or larger view-port.

    vp = xs, sm, md, or lg

    x = 1 thru 12

I think what messes most people up, is that you need to change the order of the columns in your HTML markup (in the example below, B comes before A), and that it only does the pushing or pulling on view-ports that are greater than or equal to what was specified. i.e. col-sm-push-5 will only push 5 columns on sm view-ports or greater. This is because Bootstrap is a "mobile first" framework, so your HTML should reflect the mobile version of your site. The Pushing and Pulling are then done on the larger screens.

  • (Desktop) Larger view-ports get pushed and pulled.
  • (Mobile) Smaller view-ports render in normal order.

DEMO

<div class="row">
    <div class="col-sm-5 col-sm-push-5">
        Content B
    </div>
    <div class="col-sm-5 col-sm-pull-5">
        Content A
    </div>
    <div class="col-sm-2">
        Content C
    </div>
</div>

View-port >= sm

|A|B|C|

View-port < sm

|B|
|A|
|C|

EDIT: BELOW IS THE ANSWER FOR v4.0

With v4 comes flexbox and other changes to the grid system and the push\pull classes have been removed in favor of using flexbox ordering.

  • Use .order-* classes to control visual order (where * = 1 thru 12)
  • This can also be grid tier specific .order-md-*
  • Also .order-first (-1) and .order-last (13) avalable

_x000D_
_x000D_
<div class="row">_x000D_
  <div class="col order-2">1st yet 2nd</div>_x000D_
  <div class="col order-1">2nd yet 1st</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Regular expression: find spaces (tabs/space) but not newlines

Try this character set:

[ \t]

This does only match a space or a tabulator.

Is there a way to make AngularJS load partials in the beginning and not at when needed?

You can pass $state to your controller and then when the page loads and calls the getter in the controller you call $state.go('index') or whatever partial you want to load. Done.

How can I compile and run c# program without using visual studio?

If you have .NET v4 installed (so if you have a newer windows or if you apply the windows updates)

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe somefile.cs

or

C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe nomefile.sln

or

C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe nomefile.csproj

It's highly probable that if you have .NET installed, the %FrameworkDir% variable is set, so:

%FrameworkDir%\v4.0.30319\csc.exe ...

%FrameworkDir%\v4.0.30319\msbuild.exe ...

How to reset Jenkins security settings from the command line?

\.jenkins\secrets\initialAdminPassword

Copy the password from the initialAdminPassword file and paste it into the Jenkins.

How can I debug javascript on Android?

No one mentioned liriliri/eruda which adds its own debugging tools meant for mobile websites/apps

Adding this to your page:

<script src="//cdn.jsdelivr.net/npm/eruda"></script>
<script>eruda.init();</script>

Will add a floating icon to your page which opens the console.

Nuget connection attempt failed "Unable to load the service index for source"

If you are behind a company proxy and on Mac, just make sure your http/https checkboxes are checked and applied.

permission denied - php unlink

You (as in the process that runs b.php, either you through CLI or a webserver) need write access to the directory in which the files are located. You are updating the directory content, so access to the file is not enough.

Note that if you use the PHP chmod() function to set the mode of a file or folder to 777 you should use 0777 to make sure the number is correctly interpreted as an octal number.

how to convert an RGB image to numpy array?

You can get numpy array of rgb image easily by using numpy and Image from PIL

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

im = Image.open('*image_name*') #These two lines
im_arr = np.array(im) #are all you need
plt.imshow(im_arr) #Just to verify that image array has been constructed properly

setImmediate vs. nextTick

Use setImmediate if you want to queue the function behind whatever I/O event callbacks that are already in the event queue. Use process.nextTick to effectively queue the function at the head of the event queue so that it executes immediately after the current function completes.

So in a case where you're trying to break up a long running, CPU-bound job using recursion, you would now want to use setImmediate rather than process.nextTick to queue the next iteration as otherwise any I/O event callbacks wouldn't get the chance to run between iterations.

Docker compose port mapping

If you want to bind to the redis port from your nodejs container you will have to expose that port in the redis container:

version: '2'
services:
  nodejs:
    build:
      context: .
      dockerfile: DockerFile
    ports:
      - "4000:4000"
    links:
      - redis

  redis:
    build:
      context: .
      dockerfile: Dockerfile-redis
    expose:
      - "6379"

The expose tag will let you expose ports without publishing them to the host machine, but they will be exposed to the containers networks.

https://docs.docker.com/compose/compose-file/#expose

The ports tag will be mapping the host port with the container port HOST:CONTAINER

https://docs.docker.com/compose/compose-file/#ports

How to create our own Listener interface in android?

There are 4 steps:

1.create interface class (listener)

2.use interface in view 1 (define variable)

3.implements interface to view 2 (view 1 used in view 2)

4.pass interface in view 1 to view 2

Example:

Step 1: you need create interface and definde function

public interface onAddTextViewCustomListener {
    void onAddText(String text);
}

Step 2: use this interface in view

public class CTextView extends TextView {


    onAddTextViewCustomListener onAddTextViewCustomListener; //listener custom

    public CTextView(Context context, onAddTextViewCustomListener onAddTextViewCustomListener) {
        super(context);
        this.onAddTextViewCustomListener = onAddTextViewCustomListener;
        init(context, null);
    }

    public CTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public CTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public CTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    public void init(Context context, @Nullable AttributeSet attrs) {

        if (isInEditMode())
            return;

        //call listener
        onAddTextViewCustomListener.onAddText("this TextView added");
    }
}

Step 3,4: implements to activity

public class MainActivity extends AppCompatActivity implements onAddTextViewCustomListener {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //get main view from layout
        RelativeLayout mainView = (RelativeLayout)findViewById(R.id.mainView);

        //create new CTextView and set listener
        CTextView cTextView = new CTextView(getApplicationContext(), this);

        //add cTextView to mainView
        mainView.addView(cTextView);
    }

    @Override
    public void onAddText(String text) {
        Log.i("Message ", text);
    }
}

HTML5 LocalStorage: Checking if a key exists

The MDN documentation shows how the getItem method is implementated:

Object.defineProperty(oStorage, "getItem", {
      value: function (sKey) { return sKey ? this[sKey] : null; },
      writable: false,
      configurable: false,
      enumerable: false
    });

If the value isn't set, it returns null. You are testing to see if it is undefined. Check to see if it is null instead.

if(localStorage.getItem("username") === null){

Memory address of variables in Java

It is possible using sun.misc.Unsafe : see this great answer from @Peter Lawrey -> Is there a way to get a reference address?

Using its code for printAddresses() :

    public static void printAddresses(String label, Object... objects) {
    System.out.print(label + ": 0x");
    long last = 0;
    int offset = unsafe.arrayBaseOffset(objects.getClass());
    int scale = unsafe.arrayIndexScale(objects.getClass());
    switch (scale) {
    case 4:
        long factor = is64bit ? 8 : 1;
        final long i1 = (unsafe.getInt(objects, offset) & 0xFFFFFFFFL) * factor;
        System.out.print(Long.toHexString(i1));
        last = i1;
        for (int i = 1; i < objects.length; i++) {
            final long i2 = (unsafe.getInt(objects, offset + i * 4) & 0xFFFFFFFFL) * factor;
            if (i2 > last)
                System.out.print(", +" + Long.toHexString(i2 - last));
            else
                System.out.print(", -" + Long.toHexString( last - i2));
            last = i2;
        }
        break;
    case 8:
        throw new AssertionError("Not supported");
    }
    System.out.println();
}

I set up this test :

    //hashcode
    System.out.println("Hashcode :       "+myObject.hashCode());
    System.out.println("Hashcode :       "+System.identityHashCode(myObject));
    System.out.println("Hashcode (HEX) : "+Integer.toHexString(myObject.hashCode()));

    //toString
    System.out.println("toString :       "+String.valueOf(myObject));

    printAddresses("Address", myObject);

Here is the output :

Hashcode :       125665513
Hashcode :       125665513
Hashcode (HEX) : 77d80e9
toString :       java.lang.Object@77d80e9
Address: 0x7aae62270

Conclusion :

  • hashcode != address
  • toString = class@HEX(hashcode)

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

For me, ASP.NET 5 is not yet required, I removed update, and then reinstalled ASP.NET 4.5. It's a bit tricky:

  1. Removed from control panel "Microsoft ASP.NET 5 RC1 Update1". After that, you will no longer open ASP.NET MVC projects
  2. Then I changed the installation of "Microsoft Visual Studio Professional 2015", clicked "Modify", and selected "Microsoft Web Developer Tools"

No longer follow the notification of update in Visual Studio 2015!!!

Convert pandas DataFrame into list of lists

you can do it like this:

map(list, df.values)

Simple working Example of json.net in VB.net

Imports Newtonsoft.Json.Linq

Dim json As JObject = JObject.Parse(Me.TextBox1.Text)
MsgBox(json.SelectToken("Venue").SelectToken("ID"))

SQL Error with Order By in Subquery

If building a temp table, move the ORDER BY clause from inside the temp table code block to the outside.

Not allowed:

SELECT * FROM (
SELECT A FROM Y
ORDER BY Y.A
) X;

Allowed:

SELECT * FROM (
SELECT A FROM Y
) X
ORDER BY X.A;

How to color the Git console?

Well, if you are not satisfied with the default setting, you can use ANSI escape code to help you set the color, and if you want to modify some text, you can write bash to help you. see as below:

Eaxmplae

# .gitconfig

[alias]
    st-color = "!f() { \
        echo -n -e '\\033[38;2;255;0;01m\\033[4m' ;\
        git status -s | grep ' D' | \
        sed -e 's/^ ./DELETE:/' ; \
        echo -n -e '\\033[m' ;\
        \
        echo -n -e '\\033[48;2;128;128;128m' ;\
        echo -n -e '\\033[38;2;0;255;01m' ;\
        git status -s | grep ' [AM]' | \
        sed -e 's/^ ./NEW OR MODIFY:/' ; \
        echo -n -e '\\033[m' ;\
        \
        echo -n -e '\\033[38;2;255;0;255m' ;\
        echo Rename ;\
        git status -s | grep 'R ' | \
        sed -e 's/^..//' ; \
        echo -n -e '\\033[m' ;\
    }; f"

demo

enter image description here

Explanation

  1. you can write the long script on .gitconfig use the syntax as below:

    [alias]
        your-cmd = !f() { \
            \
        }; f"
    
  2. echo -n -e (see more echo)

    • -n = Do not output a trailing newline.
    • -e Enable interpretation of the following backslash-escaped
  3. \\033[38;2;255;0;0m\\033[4m (see more SGR parameters)

    • \\033[38;2;255;0;0m : 38 mean fore color. 255;0;0 = Red | r;g;b
    • \\033[4m : underline
  4. grep : The grep command is used to search text.

  5. sed -e 's/be_replace_string/new_string/' replace string to new string.

How do I make an HTTP request in Swift?

For XCUITest to stop the test finishing before the async request completes use this (maybe reduce the 100 timeout):

func test_api() {
    let url = URL(string: "https://jsonplaceholder.typicode.com/posts/42")!
    let exp = expectation(description: "Waiting for data")
    let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
        guard let data = data else { return }
        print(String(data: data, encoding: .utf8)!)
        exp.fulfill()
    }
    task.resume()
    XCTWaiter.wait(for: [exp], timeout: 100)
}

Convert a python 'type' object to a string

In case you want to use str() and a custom str method. This also works for repr.

class TypeProxy:
    def __init__(self, _type):
        self._type = _type

    def __call__(self, *args, **kwargs):
        return self._type(*args, **kwargs)

    def __str__(self):
        return self._type.__name__

    def __repr__(self):
        return "TypeProxy(%s)" % (repr(self._type),)

>>> str(TypeProxy(str))
'str'
>>> str(TypeProxy(type("")))
'str'

Angular 6 Material mat-select change method removed

I have this issue today with mat-option-group. The thing which solved me the problem is using in other provided event of mat-select : valueChange

I put here a little code for understanding :

<mat-form-field >
  <mat-label>Filter By</mat-label>
  <mat-select  panelClass="" #choosedValue (valueChange)="doSomething1(choosedValue.value)"> <!-- (valueChange)="doSomething1(choosedValue.value)" instead of (change) or other event-->

    <mat-option >-- None --</mat-option>
      <mat-optgroup  *ngFor="let group of filterData" [label]="group.viewValue"
                    style = "background-color: #0c5460">
        <mat-option *ngFor="let option of group.options" [value]="option.value">
          {{option.viewValue}}
        </mat-option>
      </mat-optgroup>
  </mat-select>
</mat-form-field>

Mat Version:

"@angular/material": "^6.4.7",

Download/Stream file from URL - asp.net

Download url to bytes and convert bytes into stream:

using (var client = new WebClient())
{
    var content = client.DownloadData(url);
    using (var stream = new MemoryStream(content))
    {
        ...
    }
}   

Set selected item in Android BottomNavigationView

Reflection is bad idea.

Head to this gist. There is a method that performs the selection but also invokes the callback:

  @CallSuper
    public void setSelectedItem(int position) {
        if (position >= getMenu().size() || position < 0) return;

        View menuItemView = getMenuItemView(position);
        if (menuItemView == null) return;
        MenuItemImpl itemData = ((MenuView.ItemView) menuItemView).getItemData();


        itemData.setChecked(true);

        boolean previousHapticFeedbackEnabled = menuItemView.isHapticFeedbackEnabled();
        menuItemView.setSoundEffectsEnabled(false);
        menuItemView.setHapticFeedbackEnabled(false); //avoid hearing click sounds, disable haptic and restore settings later of that view
        menuItemView.performClick();
        menuItemView.setHapticFeedbackEnabled(previousHapticFeedbackEnabled);
        menuItemView.setSoundEffectsEnabled(true);


        mLastSelection = position;

    }

Counter in foreach loop in C#

The sequence being iterated in a foreach loop might not support indexing or know such a concept it just needs to implement a method called GetEnumerator that returns an object that as a minimum has the interface of IEnumerator though implmenting it is not required. If you know that what you iterate does support indexing and you need the index then I suggest to use a for loop instead.

An example class that can be used in foreach:

    class Foo {

        public iterator GetEnumerator() {
            return new iterator();
        }

        public class iterator {
            public Bar Current {
                get{magic}
            }

            public bool MoveNext() {
                incantation
            }
        }
    }

String's Maximum length in Java - calling length() method

Considering the String class' length method returns an int, the maximum length that would be returned by the method would be Integer.MAX_VALUE, which is 2^31 - 1 (or approximately 2 billion.)

In terms of lengths and indexing of arrays, (such as char[], which is probably the way the internal data representation is implemented for Strings), Chapter 10: Arrays of The Java Language Specification, Java SE 7 Edition says the following:

The variables contained in an array have no names; instead they are referenced by array access expressions that use nonnegative integer index values. These variables are called the components of the array. If an array has n components, we say n is the length of the array; the components of the array are referenced using integer indices from 0 to n - 1, inclusive.

Furthermore, the indexing must be by int values, as mentioned in Section 10.4:

Arrays must be indexed by int values;

Therefore, it appears that the limit is indeed 2^31 - 1, as that is the maximum value for a nonnegative int value.

However, there probably are going to be other limitations, such as the maximum allocatable size for an array.

Global Variable in app.js accessible in routes?

To declare a global variable you need do use global object. Like global.yourVariableName. But it is not a true way. To share variables between modules try to use injection style like

someModule.js:

module.exports = function(injectedVariable) {
    return {
        somePublicMethod: function() {
        },
        anotherPublicMethod: function() {
        },
    };
};

app.js

var someModule = require('./someModule')(someSharedVariable);

Or you may use surrogate object to do that. Like hub.

someModule.js:

var hub = require('hub');

module.somePublicMethod = function() {
    // We can use hub.db here
};

module.anotherPublicMethod = function() {
};

app.js

var hub = require('hub');
hub.db = dbConnection;
var someModule = require('./someModule');

How do you access the matched groups in a JavaScript regular expression?

As @cms said in ECMAScript (ECMA-262) you can use matchAll. It return an iterator and by putting it in [... ] (spread operator) it converts to an array.(this regex extract urls of file names)

_x000D_
_x000D_
let text = `<a href="http://myhost.com/myfile_01.mp4">File1</a> <a href="http://myhost.com/myfile_02.mp4">File2</a>`;

let fileUrls = [...text.matchAll(/href="(http\:\/\/[^"]+\.\w{3})\"/g)].map(r => r[1]);

console.log(fileUrls);
_x000D_
_x000D_
_x000D_

What is the reason for java.lang.IllegalArgumentException: No enum const class even though iterating through values() works just fine?

Instead of defining: COLUMN_HEADINGS("columnHeadings")

Try defining it as: COLUMNHEADINGS("columnHeadings")

Then when you call getByName(String name) method, call it with the upper-cased String like this: getByName(myStringVariable.toUpperCase())

I had the same problem as you, and this worked for me.

How to check if array is empty or does not exist?

You want to do the check for undefined first. If you do it the other way round, it will generate an error if the array is undefined.

if (array === undefined || array.length == 0) {
    // array empty or does not exist
}

Update

This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null values, other types of objects with a length property, etc. It is also not very idiomatic JavaScript.

The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length property.

if (!Array.isArray(array) || !array.length) {
  // array does not exist, is not an array, or is empty
  // ? do not attempt to process array
}

To break it down:

  1. Array.isArray(), unsurprisingly, checks whether its argument is an array. This weeds out values like null, undefined and anything else that is not an array.
    Note that this will also eliminate array-like objects, such as the arguments object and DOM NodeList objects. Depending on your situation, this might not be the behavior you're after.

  2. The array.length condition checks whether the variable's length property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0 or array.length !== 0 are not required here.

The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.

In those cases, I tend to go for the following, more idiomatic JavaScript:

if (!array || !array.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or, more frequently, its inverse:

if (array && array.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:

if (!array?.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or the opposite:

if (array?.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?

Easiest way to use this function is to start by 'Recording a Macro'. Once you start recording, save the file to the location you want, with the name you want, and then of course set the file type, most likely 'Excel Macro Enabled Workbook' ~ 'XLSM'

Stop recording and you can start inspecting your code.

I wrote the code below which allows you to save a workbook using the path where the file was originally located, naming it as "Event [date in cell "A1"]"

Option Explicit

Sub SaveFile()

Dim fdate As Date
Dim fname As String
Dim path As String

fdate = Range("A1").Value
path = Application.ActiveWorkbook.path

If fdate > 0 Then
    fname = "Event " & fdate
    Application.ActiveWorkbook.SaveAs Filename:=path & "\" & fname, _
        FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Else
    MsgBox "Chose a date for the event", vbOKOnly
End If

End Sub

Copy the code into a new module and then write a date in cell "A1" e.g. 01-01-2016 -> assign the sub to a button and run. [Note] you need to make a save file before this script will work, because a new workbook is saved to the default autosave location!

how to check if a file is a directory or regular file in python?

os.path.isfile("bob.txt") # Does bob.txt exist?  Is it a file, or a directory?
os.path.isdir("bob")

How to change border color of textarea on :focus

Try out this probably it will work

input{
outline-color: #fff //your color
outline-style: none // it depend on you 
}

Image is not showing in browser?

You put inside img tag physical path you your image. Instead of that you should put virtual path (according to root of web application) to your image. This value depends on location of your image and your html page.

for example if you have:

/yourDir
-page.html
-66.jpg

in your page.html it should be something like that:

<img  src="66.jpg" width="400" height="400" ></img>

second scenario:

/images
-66.jpg
/html
page.html

So your img should look like:

<img  src="../images/66.jpg" width="400" height="400" ></img>

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

Base table or view not found: 1146 Table Laravel 5

I faced this problem too in laravel 5.2 and if declaring the table name doesn't work,it is probably because you have some wrong declaration or mistake in validation code in Request (If you are using one)

What to do about Eclipse's "No repository found containing: ..." error messages?

I had the same problem on windows 10. My eclipse version was installed from an exe, downloaded from eclipse site.

What solved for me was to use the zip version instead: http://www.eclipse.org/downloads/eclipse-packages/

How to replace a string in an existing file in Perl?

Anything wrong with a one-liner?

$ perl -pi.bak -e 's/blue/red/g' *_classification.dat

Explanation

  • -p processes, then prints <> line by line
  • -i activates in-place editing. Files are backed up using the .bak extension
  • The regex substitution acts on the implicit variable, which are the contents of the file, line-by-line

Dynamically add script tag with src that may include document.write

Well, there are multiple ways you can include dynamic javascript, I use this one for many of the projects.

var script = document.createElement("script")
script.type = "text/javascript";
//Chrome,Firefox, Opera, Safari 3+
script.onload = function(){
console.log("Script is loaded");
};
script.src = "file1.js";
document.getElementsByTagName("head")[0].appendChild(script);

You can call create a universal function which can help you to load as many javascript files as needed. There is a full tutorial about this here.

Inserting Dynamic Javascript the right way

Tab separated values in awk

Should this not work?

echo "LOAD_SETTLED    LOAD_INIT       2011-01-13 03:50:01" | awk '{print $1}'

Do HttpClient and HttpClientHandler have to be disposed between requests?

I think one should use singleton pattern to avoid having to create instances of the HttpClient and closing it all the time. If you are using .Net 4.0 you could use a sample code as below. for more information on singleton pattern check here.

class HttpClientSingletonWrapper : HttpClient
{
    private static readonly Lazy<HttpClientSingletonWrapper> Lazy= new Lazy<HttpClientSingletonWrapper>(()=>new HttpClientSingletonWrapper()); 

    public static HttpClientSingletonWrapper Instance {get { return Lazy.Value; }}

    private HttpClientSingletonWrapper()
    {
    }
}

Use the code as below.

var client = HttpClientSingletonWrapper.Instance;

Getting MAC Address

I dont know of a unified way, but heres something that you might find useful:

http://www.codeguru.com/Cpp/I-N/network/networkinformation/article.php/c5451

What I would do in this case would be to wrap these up into a function, and based on the OS it would run the proper command, parse as required and return only the MAC address formatted as you want. Its ofcourse all the same, except that you only have to do it once, and it looks cleaner from the main code.

JQuery Validate Dropdown list

    <div id="msg"></div>
<!-- put above tag on body to see selected value or error -->
<script>
    $(function(){
        $("#HoursEntry").change(function(){
            var HoursEntry = $("#HoursEntry option:selected").val();
            console.log(HoursEntry);
            if(HoursEntry == "")
            {
                $("#msg").html("Please select at least One option");
                return false;
            }
            else
            {
                $("#msg").html("selected val is  "+HoursEntry);
            }
        });
    });
</script>

How can I see the specific value of the sql_mode?

You can also try this to determine the current global sql_mode value:

SELECT @@GLOBAL.sql_mode;

or session sql_mode value:

SELECT @@SESSION.sql_mode;

I also had the feeling that the SQL mode was indeed empty.

C# Create New T()

Another way is to use reflection:

protected T GetObject<T>(Type[] signature, object[] args)
{
    return (T)typeof(T).GetConstructor(signature).Invoke(args);
}

Concat scripts in order with Gulp

With gulp-useref you can concatenate every script declared in your index file, in the order in which you declare it.

https://www.npmjs.com/package/gulp-useref

var $ = require('gulp-load-plugins')();
gulp.task('jsbuild', function () {
  var assets = $.useref.assets({searchPath: '{.tmp,app}'});
  return gulp.src('app/**/*.html')
    .pipe(assets)
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

And in the HTML you have to declare the name of the build file you want to generate, like this:

<!-- build:js js/main.min.js -->
    <script src="js/vendor/vendor.js"></script>
    <script src="js/modules/test.js"></script>
    <script src="js/main.js"></script>

In your build directory you will have the reference to main.min.js which will contain vendor.js, test.js, and main.js

How to configure nginx to enable kinda 'file browser' mode?

Just add this section to server, just before the location / {

location /your/folder/to/browse/ {
        autoindex on;
}

SQL Server 2008 Insert with WHILE LOOP

First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.

But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.

For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used

CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN 
    INSERT hospitals ([Hospital ID], Email, Description) 
    VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid))); 
    SET @hid = @hid + 1;
END

And result would be

ID   Hospital ID Email            Description          
---- ----------- ---------------- ---------------------
1    16          [email protected]  Sample Description16 
2    17          [email protected]  Sample Description17 
...                                                    
84   99          [email protected]  Sample Description99 

How can I convert JSON to CSV?

You can use this code to convert a json file to csv file After reading the file, I am converting the object to pandas dataframe and then saving this to a CSV file

import os
import pandas as pd
import json
import numpy as np

data = []
os.chdir('D:\\Your_directory\\folder')
with open('file_name.json', encoding="utf8") as data_file:    
     for line in data_file:
        data.append(json.loads(line))

dataframe = pd.DataFrame(data)        
## Saving the dataframe to a csv file
dataframe.to_csv("filename.csv", encoding='utf-8',index= False)

How to check if a process is in hang state (Linux)

you could check the files

/proc/[pid]/task/[thread ids]/status

How to print VARCHAR(MAX) using Print Statement?

There is great function called PrintMax written by Bennett Dill.

Here is slightly modified version that uses temp stored procedure to avoid "schema polution"(idea from https://github.com/Toolien/sp_GenMerge/blob/master/sp_GenMerge.sql)

EXEC (N'IF EXISTS (SELECT * FROM tempdb.sys.objects 
                   WHERE object_id = OBJECT_ID(N''tempdb..#PrintMax'') 
                   AND type in (N''P'', N''PC''))
    DROP PROCEDURE #PrintMax;');
EXEC (N'CREATE PROCEDURE #PrintMax(@iInput NVARCHAR(MAX))
AS
BEGIN
    IF @iInput IS NULL
    RETURN;

    DECLARE @ReversedData NVARCHAR(MAX)
          , @LineBreakIndex INT
          , @SearchLength INT;

    SET @SearchLength = 4000;

    WHILE LEN(@iInput) > @SearchLength
    BEGIN
    SET @ReversedData = LEFT(@iInput COLLATE DATABASE_DEFAULT, @SearchLength);
    SET @ReversedData = REVERSE(@ReversedData COLLATE DATABASE_DEFAULT);
    SET @LineBreakIndex = CHARINDEX(CHAR(10) + CHAR(13),
                          @ReversedData COLLATE DATABASE_DEFAULT);
    PRINT LEFT(@iInput, @SearchLength - @LineBreakIndex + 1);
    SET @iInput = RIGHT(@iInput, LEN(@iInput) - @SearchLength 
                        + @LineBreakIndex - 1);
    END;

    IF LEN(@iInput) > 0
    PRINT @iInput;
END;');

DBFiddle Demo

EDIT:

Using CREATE OR ALTER we could avoid two EXEC calls:

EXEC (N'CREATE OR ALTER PROCEDURE #PrintMax(@iInput NVARCHAR(MAX))
AS
BEGIN
    IF @iInput IS NULL
    RETURN;

    DECLARE @ReversedData NVARCHAR(MAX)
          , @LineBreakIndex INT
          , @SearchLength INT;

    SET @SearchLength = 4000;

    WHILE LEN(@iInput) > @SearchLength
    BEGIN
    SET @ReversedData = LEFT(@iInput COLLATE DATABASE_DEFAULT, @SearchLength);
    SET @ReversedData = REVERSE(@ReversedData COLLATE DATABASE_DEFAULT);
    SET @LineBreakIndex = CHARINDEX(CHAR(10) + CHAR(13), @ReversedData COLLATE DATABASE_DEFAULT);
    PRINT LEFT(@iInput, @SearchLength - @LineBreakIndex + 1);
    SET @iInput = RIGHT(@iInput, LEN(@iInput) - @SearchLength + @LineBreakIndex - 1);
    END;

    IF LEN(@iInput) > 0
    PRINT @iInput;
END;');

db<>fiddle Demo

Short circuit Array.forEach like calling break

If you want to keep your forEach syntax, this is a way to keep it efficient (although not as good as a regular for loop). Check immediately for a variable that knows if you want to break out of the loop.

This example uses a anonymous function for creating a function scope around the forEach which you need to store the done information.

_x000D_
_x000D_
(function(){_x000D_
    var element = document.getElementById('printed-result');_x000D_
    var done = false;_x000D_
    [1,2,3,4].forEach(function(item){_x000D_
        if(done){ return; }_x000D_
        var text = document.createTextNode(item);_x000D_
        element.appendChild(text);_x000D_
        if (item === 2){_x000D_
          done = true;_x000D_
          return;_x000D_
        }_x000D_
    });_x000D_
})();
_x000D_
<div id="printed-result"></div>
_x000D_
_x000D_
_x000D_

My two cents.

Best way to check if a drop down list contains a value?

Sometimes the value needs to be trimmed of whitespace or it won't be matched, in such case this additional step can be used (source):

if(((DropDownList) myControl1).Items.Cast<ListItem>().Select(i => i.Value.Trim() == ctrl.value.Trim()).FirstOrDefault() != null){}

Is there an onSelect event or equivalent for HTML <select>?

A long while ago now but in reply to the original question, would this help ? Just put onClick into the SELECT line. Then put what you want each OPTION to do in the OPTION lines. ie:

<SELECT name="your name" onClick>
<option value ="Kilometres" onClick="YourFunction()">Kilometres
-------
-------
</SELECT>

Most pythonic way to delete a file which may not exist

A more pythonic way would be:

try:
    os.remove(filename)
except OSError:
    pass

Although this takes even more lines and looks very ugly, it avoids the unnecessary call to os.path.exists() and follows the python convention of overusing exceptions.

It may be worthwhile to write a function to do this for you:

import os, errno

def silentremove(filename):
    try:
        os.remove(filename)
    except OSError as e: # this would be "except OSError, e:" before Python 2.6
        if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory
            raise # re-raise exception if a different error occurred

How to compare two object variables in EL expression language?

Not sure if I get you right, but the simplest way would be something like:

<c:if test="${languageBean.locale == 'en'">
  <f:selectItems value="#{customerBean.selectableCommands_limited_en}" />
</c:if>

Just a quick copy and paste from an app of mine...

HTH

Get login username in java

inspired by @newacct's answer, a code that can be compiled in any platform:

String osName = System.getProperty( "os.name" ).toLowerCase();
String className = null;
String methodName = "getUsername";

if( osName.contains( "windows" ) ){
    className = "com.sun.security.auth.module.NTSystem";
    methodName = "getName";
}
else if( osName.contains( "linux" ) ){
    className = "com.sun.security.auth.module.UnixSystem";
}
else if( osName.contains( "solaris" ) || osName.contains( "sunos" ) ){
    className = "com.sun.security.auth.module.SolarisSystem";
}

if( className != null ){
    Class<?> c = Class.forName( className );
    Method method = c.getDeclaredMethod( methodName );
    Object o = c.newInstance();
    System.out.println( method.invoke( o ) );
}

List of IP addresses/hostnames from local network in Python

One of the answers in this question might help you. There seems to be a platform agnostic version for python, but I haven't tried it yet.

How to pass a file path which is in assets folder to File(String path)?

AFAIK, you can't create a File from an assets file because these are stored in the apk, that means there is no path to an assets folder.

But, you can try to create that File using a buffer and the AssetManager (it provides access to an application's raw asset files).

Try to do something like:

AssetManager am = getAssets();
InputStream inputStream = am.open("myfoldername/myfilename");
File file = createFileFromInputStream(inputStream);

private File createFileFromInputStream(InputStream inputStream) {

   try{
      File f = new File(my_file_name);
      OutputStream outputStream = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      int length = 0;

      while((length=inputStream.read(buffer)) > 0) {
        outputStream.write(buffer,0,length);
      }

      outputStream.close();
      inputStream.close();

      return f;
   }catch (IOException e) {
         //Logging exception
   }

   return null;
}

Let me know about your progress.

assign multiple variables to the same value in Javascript

Nothing stops you from doing

moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;

Check this example

_x000D_
_x000D_
var a, b, c;_x000D_
a = b = c = 10;_x000D_
console.log(a + b + c)
_x000D_
_x000D_
_x000D_

Twitter Bootstrap vs jQuery UI?

You can use both with relatively few issues. Twitter Bootstrap uses jQuery 1.7.1 (as of this writing), and I can't think of any reasons why you cannot integrate additional Jquery UI components into your HTML templates.

I've been using a combination of HTML5 Boilerplate & Twitter Bootstrap built at Initializr.com. This combines two awesome starter templates into one great starter project. Check out the details at http://html5boilerplate.com/ and http://www.initializr.com/ Or to get started right away, go to http://www.initializr.com/, click the "Bootstrap 2" button, and click "Download It". This will give you all the js and css you need to get started.

And don't be scared off by HTML5 and CSS3. Initializr and HTML5 Boilerplate include polyfills and IE specific code that will allow all features to work in IE 6, 7 8, and 9.

The use of LESS in Twitter Bootstrap is also optional. They use LESS to compile all the CSS that is used by Bootstrap, but if you just want to override or add your own styles, they provide an empty css file for that purpose.

There is also a blank js file (script.js) for you to add custom code. This is where you would add your handlers or selectors for additional jQueryUI components.

SQL ORDER BY date problem

Unsure what dbms you're using however I'd do it this way in Microsoft SQL:

select      [date]
from        tbemp 
order by    cast([date] as datetime) asc

Changing Placeholder Text Color with Swift

Swift 4 :

txtControl.attributedPlaceholder = NSAttributedString(string: "Placeholder String...",attributes: [NSAttributedStringKey.foregroundColor: UIColor.gray])

Objective-C :

UIColor *color = [UIColor grayColor];
txtControl.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Placeholder String..." attributes:@{NSForegroundColorAttributeName: color}];

How to save CSS changes of Styles panel of Chrome Developer Tools?

New versions of Chrome have a feature called workspaces which addresses this issue. You can define which paths on your webserver correspond to which paths on your system, then edit and save with just ctrl-s.

See: http://www.html5rocks.com/en/tutorials/developertools/revolutions2013/

client denied by server configuration

In my case, I modified directory tag.

From

<Directory "D:/Devel/matysart/matysart_dev1">
  Allow from all
  Order Deny,Allow
</Directory>

To

<Directory "D:/Devel/matysart/matysart_dev1">
  Require local
</Directory>

And it seriously worked. It's seems changed with Apache 2.4.2.

Remove HTML tags from string including &nbsp in C#

Sanitizing an Html document involves a lot of tricky things. This package maybe of help: https://github.com/mganss/HtmlSanitizer

How do I pass command line arguments to a Node.js program?

Several great answers here, but it all seems very complex. This is very similar to how bash scripts access argument values and it's already provided standard with node.js as MooGoo pointed out. (Just to make it understandable to somebody that's new to node.js)

Example:

$ node yourscript.js banana monkey

var program_name = process.argv[0]; //value will be "node"
var script_path = process.argv[1]; //value will be "yourscript.js"
var first_value = process.argv[2]; //value will be "banana"
var second_value = process.argv[3]; //value will be "monkey"

How to count lines of Java code using IntelliJ IDEA?

Although it is not an IntelliJ option, you could use a simple Bash command (if your operating system is Linux/Unix). Go to your source directory and type:

find . -type f -name '*.java' | xargs cat | wc -l

‘ant’ is not recognized as an internal or external command

Please follow these steps

  1. In User Variables

    Set VARIABLE NAME=ANT_HOME VARIABLE PATH =C:\Program Files\apache-ant-1.9.7

2.Edit User Variable PATH = %ANT_HOME%\bin

  1. Go to System Variables

    • Set Path =%ANT_HOME%\bin

How to take the nth digit of a number in python

Ok, first of all, use the str() function in python to turn 'number' into a string

number = 9876543210 #declaring and assigning
number = str(number) #converting

Then get the index, 0 = 1, 4 = 3 in index notation, use int() to turn it back into a number

print(int(number[3])) #printing the int format of the string "number"'s index of 3 or '6'

if you like it in the short form

print(int(str(9876543210)[3])) #condensed code lol, also no more variable 'number'

Recover from git reset --hard?

If you use something like IntelliJ:

On the context menu, choose Local History, and click Show History on the submenu:

The local history view for a project or folder shows you everything that you have done during the last few days. In the Action column of the lower part of the dialog box, select the action you want to roll back. [...] So doing, the upper part of the dialog box shows the tree view of changed files. If you want to restore the deleted file only, regardless of the other changes that have been done since then, you can select the file Lost.txt in the tree view and click the Revert button.

http://blog.jetbrains.com/idea/2008/01/using-local-history-to-restore-deleted-files/

This just got my arse out the fire!

ReactJS and images in public folder

1- It's good if you use webpack for configurations but you can simply use image path and react will find out that that it's in public directory.

<img src="/image.jpg">

2- If you want to use webpack which is a standard practice in React. You can use these rules in your webpack.config.dev.js file.

module: {
  rules: [
    {
      test: /\.(jpe?g|gif|png|svg)$/i,
      use: [
        {
          loader: 'url-loader',
          options: {
            limit: 10000
          }
        }
      ]
    }
  ],
},

then you can import image file in react components and use it.

import image from '../../public/images/logofooter.png'

<img src={image}/>

Convert normal date to unix timestamp

parseInt((new Date('2012.08.10').getTime() / 1000).toFixed(0))

It's important to add the toFixed(0) to remove any decimals when dividing by 1000 to convert from milliseconds to seconds.

The .getTime() function returns the timestamp in milliseconds, but true unix timestamps are always in seconds.

How to remove the border highlight on an input text element

This is a common concern.

The default outline that browsers render is ugly.

See this for example:

_x000D_
_x000D_
form,_x000D_
label {_x000D_
  margin: 1em auto;_x000D_
}_x000D_
_x000D_
label {_x000D_
  display: block;_x000D_
}
_x000D_
<form>_x000D_
  <label>Click to see the input below to see the outline</label>_x000D_
  <input type="text" placeholder="placeholder text" />_x000D_
</form>
_x000D_
_x000D_
_x000D_


The most common "fix" that most recommend is outline:none - which if used incorrectly - is disaster for accessibility.


So...of what use is the outline anyway?

There's a very dry-cut website I found which explains everything well.

It provides visual feedback for links that have "focus" when navigating a web document using the TAB key (or equivalent). This is especially useful for folks who can't use a mouse or have a visual impairment. If you remove the outline you are making your site inaccessible for these people.

Ok, let's try it out same example as above, now use the TAB key to navigate.

_x000D_
_x000D_
form,_x000D_
label {_x000D_
  margin: 1em auto;_x000D_
}_x000D_
_x000D_
label {_x000D_
  display: block;_x000D_
}
_x000D_
<form>_x000D_
  <label>Click on this text and then use the TAB key to naviagte inside the snippet.</label>_x000D_
  <input type="text" placeholder="placeholder text" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Notice how you can tell where the focus is even without clicking the input?

Now, let's try outline:none on our trusty <input>

So, once again, use the TAB key to navigate after clicking the text and see what happens.

_x000D_
_x000D_
form,_x000D_
label {_x000D_
  margin: 1em auto;_x000D_
}_x000D_
_x000D_
label {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input {_x000D_
  outline: none;_x000D_
}
_x000D_
<form>_x000D_
  <label>Click on this text and then use the TAB key to naviagte inside the snippet.</label>_x000D_
  <input type="text" placeholder="placeholder text" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

See how it's more difficult to figure out where the focus is? The only telling sign is the cursor blinking. My example above is overly simplistic. In real-world situations, you wouldn't have only one element on the page. Something more along the lines of this.

_x000D_
_x000D_
.wrapper {_x000D_
  width: 500px;_x000D_
  max-width: 100%;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
_x000D_
form,_x000D_
label {_x000D_
  margin: 1em auto;_x000D_
}_x000D_
_x000D_
label {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input {_x000D_
  outline: none;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
_x000D_
  <form>_x000D_
    <label>Click on this text and then use the TAB key to naviagte inside the snippet.</label>_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
  </form>_x000D_
_x000D_
  <form>_x000D_
    First name:<br>_x000D_
    <input type="text" name="firstname"><br> Last name:<br>_x000D_
    <input type="text" name="lastname">_x000D_
  </form>_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <input type="radio" name="gender" value="male" checked> Male<br>_x000D_
    <input type="radio" name="gender" value="female"> Female<br>_x000D_
    <input type="radio" name="gender" value="other"> Other_x000D_
  </form>_x000D_
_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <label for="GET-name">Name:</label>_x000D_
    <input id="GET-name" type="text" name="name">_x000D_
  </form>_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <label for="POST-name">Name:</label>_x000D_
    <input id="POST-name" type="text" name="name">_x000D_
  </form>_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <fieldset>_x000D_
      <legend>Title</legend>_x000D_
      <input type="radio" name="radio" id="radio">_x000D_
      <label for="radio">Click me</label>_x000D_
    </fieldset>_x000D_
  </form>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Now compare that to the same template if we keep the outline:

_x000D_
_x000D_
.wrapper {_x000D_
  width: 500px;_x000D_
  max-width: 100%;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
_x000D_
form,_x000D_
label {_x000D_
  margin: 1em auto;_x000D_
}_x000D_
_x000D_
label {_x000D_
  display: block;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
_x000D_
  <form>_x000D_
    <label>Click on this text and then use the TAB key to naviagte inside the snippet.</label>_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
  </form>_x000D_
_x000D_
  <form>_x000D_
    First name:<br>_x000D_
    <input type="text" name="firstname"><br> Last name:<br>_x000D_
    <input type="text" name="lastname">_x000D_
  </form>_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <input type="radio" name="gender" value="male" checked> Male<br>_x000D_
    <input type="radio" name="gender" value="female"> Female<br>_x000D_
    <input type="radio" name="gender" value="other"> Other_x000D_
  </form>_x000D_
_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <label for="GET-name">Name:</label>_x000D_
    <input id="GET-name" type="text" name="name">_x000D_
  </form>_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <label for="POST-name">Name:</label>_x000D_
    <input id="POST-name" type="text" name="name">_x000D_
  </form>_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <fieldset>_x000D_
      <legend>Title</legend>_x000D_
      <input type="radio" name="radio" id="radio">_x000D_
      <label for="radio">Click me</label>_x000D_
    </fieldset>_x000D_
  </form>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

So we have established the following

  1. Outlines are ugly
  2. Removing them makes life more difficult.

So what's the answer?

Remove the ugly outline and add your own visual cues to indicate focus.

Here's a very simple example of what I mean.

I remove the outline and add a bottom border on :focus and :active. I also remove the default borders on the top, left and right sides by setting them to transparent on :focus and :active (personal preference)

_x000D_
_x000D_
form,_x000D_
label {_x000D_
  margin: 1em auto;_x000D_
}_x000D_
_x000D_
label {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input {_x000D_
  outline: none_x000D_
}_x000D_
_x000D_
input:focus,_x000D_
input:active {_x000D_
  border-color: transparent;_x000D_
  border-bottom: 2px solid red_x000D_
}
_x000D_
<form>_x000D_
  <label>Click to see the input below to see the outline</label>_x000D_
  <input type="text" placeholder="placeholder text" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

So, we try the approach above with our "real-world" example from earlier:

_x000D_
_x000D_
.wrapper {_x000D_
  width: 500px;_x000D_
  max-width: 100%;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
_x000D_
form,_x000D_
label {_x000D_
  margin: 1em auto;_x000D_
}_x000D_
_x000D_
label {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input {_x000D_
  outline: none_x000D_
}_x000D_
_x000D_
input:focus,_x000D_
input:active {_x000D_
  border-color: transparent;_x000D_
  border-bottom: 2px solid red_x000D_
}
_x000D_
<div class="wrapper">_x000D_
_x000D_
  <form>_x000D_
    <label>Click on this text and then use the TAB key to naviagte inside the snippet.</label>_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
  </form>_x000D_
_x000D_
  <form>_x000D_
    First name:<br>_x000D_
    <input type="text" name="firstname"><br> Last name:<br>_x000D_
    <input type="text" name="lastname">_x000D_
  </form>_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <input type="radio" name="gender" value="male" checked> Male<br>_x000D_
    <input type="radio" name="gender" value="female"> Female<br>_x000D_
    <input type="radio" name="gender" value="other"> Other_x000D_
  </form>_x000D_
_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <label for="GET-name">Name:</label>_x000D_
    <input id="GET-name" type="text" name="name">_x000D_
  </form>_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <label for="POST-name">Name:</label>_x000D_
    <input id="POST-name" type="text" name="name">_x000D_
  </form>_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <fieldset>_x000D_
      <legend>Title</legend>_x000D_
      <input type="radio" name="radio" id="radio">_x000D_
      <label for="radio">Click me</label>_x000D_
    </fieldset>_x000D_
  </form>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

This can be extended further by using external libraries that build on the idea of modifying the "outline" as opposed to removing it entirely like Materialize

You can end up with something that is not ugly and works with very little effort

_x000D_
_x000D_
body {_x000D_
  background: #444_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
  padding: 2em;_x000D_
  width: 400px;_x000D_
  max-width: 100%;_x000D_
  text-align: center;_x000D_
  margin: 2em auto;_x000D_
  border: 1px solid #555_x000D_
}_x000D_
_x000D_
button,_x000D_
.wrapper {_x000D_
  border-radius: 3px;_x000D_
}_x000D_
_x000D_
button {_x000D_
  padding: .25em 1em;_x000D_
}_x000D_
_x000D_
input,_x000D_
label {_x000D_
  color: white !important;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.1/css/materialize.min.css" />_x000D_
_x000D_
<div class="wrapper">_x000D_
  <form>_x000D_
    <input type="text" placeholder="Enter Username" name="uname" required>_x000D_
    <input type="password" placeholder="Enter Password" name="psw" required>_x000D_
    <button type="submit">Login</button>_x000D_
  </form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Maven error :Perhaps you are running on a JRE rather than a JDK?

In Installed JREs path see if there is an entry pointing to your JDK path or not. If not, click on Edit button and put the path you configured your JAVA_HOME environment:

Eclipse Path: Window ? Preferences ? Java ? Installed JREs

org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

In our case it was an empty AndroidManifest.xml.

While upgrading Eclispe we ran into the usual trouble, and AndroidManifest.xml must have been checked into SVN by the build script after being clobbered.

Found it by compiling from inside Eclipse, instead of from the command line.

Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized?

The solution I followed is summarized in the below steps:

  1. From Build menu, select Edit Libraries and Dependancies

enter image description here

  1. Make sure you add the latest AppCompat package if not added

enter image description here

enter image description here

  1. After adding it, clean your project and rebuild it.

enter image description here

How do I open a Visual Studio project in design view?

You can double click directly on the .cs file representing your form in the Solution Explorer :

Solution explorer with Design View circled

This will open Form1.cs [Design], which contains the drag&drop controls.

If you are directly in the code behind (The file named Form1.cs, without "[Design]"), you can press Shift + F7 (or only F7 depending on the project type) instead to open it.

From the design view, you can switch back to the Code Behind by pressing F7.

ValueError: not enough values to unpack (expected 11, got 1)

Looks like something is wrong with your data, it isn't in the format you are expecting. It could be a new line character or a blank space in the data that is tinkering with your code.

Image resolution for new iPhone 6 and 6+, @3x support added?

I have tested by making a sample project and all simulators seem to use @3x images , this is confusing.

Create different versions of an image in your asset catalog such that the image itself tells you what version it is:

enter image description here

Now run the app on each simulator in turn. You will see that the 3x image is used only on the iPhone 6 Plus.

The same thing is true if the images are drawn from the app bundle using their names (e.g. one.png, [email protected], and [email protected]) by calling imageNamed: and assigning into an image view.

(However, there's a difference if you assign the image to an image view in Interface Builder - the 2x version is ignored on double-resolution devices. This is presumably a bug, apparently a bug in pathForResource:ofType:.)