Programs & Examples On #Sdl.net

SDL.NET is a set of object-oriented CLS-compliant .NET bindings for the SDL gaming library.

How do I merge a specific commit from one branch into another in Git?

If BranchA has not been pushed to a remote then you can reorder the commits using rebase and then simply merge. It's preferable to use merge over rebase when possible because it doesn't create duplicate commits.

git checkout BranchA
git rebase -i HEAD~113
... reorder the commits so the 10 you want are first ...
git checkout BranchB
git merge [the 10th commit]

SQL: Select columns with NULL values only

Try this -

DECLARE @table VARCHAR(100) = 'dbo.table'

DECLARE @sql NVARCHAR(MAX) = ''

SELECT @sql = @sql + 'IF NOT EXISTS(SELECT 1 FROM ' + @table + ' WHERE ' + c.name + ' IS NOT NULL) PRINT ''' + c.name + ''''
FROM sys.objects o
JOIN sys.columns c ON o.[object_id] = c.[object_id]
WHERE o.[type] = 'U'
    AND o.[object_id] = OBJECT_ID(@table)
    AND c.is_nullable = 1

EXEC(@sql)

Remap values in pandas column with a dict

Or do apply:

df['col1'].apply(lambda x: {1: "A", 2: "B"}.get(x,x))

Demo:

>>> df['col1']=df['col1'].apply(lambda x: {1: "A", 2: "B"}.get(x,x))
>>> df
  col1 col2
0    w    a
1    1    2
2    2  NaN
>>> 

Test if registry value exists

I took the Methodology from Carbon above, and streamlined the code into a smaller function, this works very well for me.

    Function Test-RegistryValue($key,$name)
    {
         if(Get-Member -InputObject (Get-ItemProperty -Path $key) -Name $name) 
         {
              return $true
         }
         return $false
    }

Missing Authentication Token while accessing API Gateway?

If you are using an API with endpoint of type PRIVATE, be sure of:

  1. You are invoking the API from within your AWS account (example: from an EC2 instance created in your account)

  2. Put necessary credential (access and secret keys) in the EC2 instance in route ~/.aws/credentials (this route is for linux instances) If IAM user use MFA aws_session_token value will be required too.

  3. Use vpce (vpc endpoint) based URL. Example: curl https://vpce-0c0471b7test-jkznizi5.execute-api.us-east-1.vpce.amazonaws.com/dev/api/v1/status

  4. Your EC2 instance have a security group than allow outbound traffic to another security group owned by the vpce like: EC2 instance sg

  5. Your vpce security group allow inbound traffic from another security group (previous sg from ec2 instance) owned by the EC2 instance like: vpce sg

See: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-apis.html

Repository Pattern Step by Step Explanation

As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.

Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.

With the repository pattern, you would only need to change one object and one repository. The impact is very small.

Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:

  • You have a single place to make changes to your data access

  • You have a single place responsible for a set of tables (usually)

  • It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests

There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!

Jquery select change not firing

$(document).on('change','#multiid',function(){
  // you desired code 
});

reference on

jQuery access input hidden value

To get value, use:

$.each($('input'),function(i,val){
    if($(this).attr("type")=="hidden"){
        var valueOfHidFiled=$(this).val();
        alert(valueOfHidFiled);
    }
});

or:

var valueOfHidFiled=$('input[type=hidden]').val();
alert(valueOfHidFiled);

To set value, use:

$('input[type=hidden]').attr('value',newValue);

Global variables in R

What about .GlobalEnv$a <- "new" ? I saw this explicit way of creating a variable in a certain environment here: http://adv-r.had.co.nz/Environments.html. It seems shorter than using the assign() function.

What's the difference between ASCII and Unicode?

ASCII has 128 code positions, allocated to graphic characters and control characters (control codes).

Unicode has 1,114,112 code positions. About 100,000 of them have currently been allocated to characters, and many code points have been made permanently noncharacters (i.e. not used to encode any character ever), and most code points are not yet assigned.

The only things that ASCII and Unicode have in common are: 1) They are character codes. 2) The 128 first code positions of Unicode have been defined to have the same meanings as in ASCII, except that the code positions of ASCII control characters are just defined as denoting control characters, with names corresponding to their ASCII names, but their meanings are not defined in Unicode.

Sometimes, however, Unicode is characterized (even in the Unicode standard!) as “wide ASCII”. This is a slogan that mainly tries to convey the idea that Unicode is meant to be a universal character code the same way as ASCII once was (though the character repertoire of ASCII was hopelessly insufficient for universal use), as opposite to using different codes in different systems and applications and for different languages.

Unicode as such defines only the “logical size” of characters: Each character has a code number in a specific range. These code numbers can be presented using different transfer encodings, and internally, in memory, Unicode characters are usually represented using one or two 16-bit quantities per character, depending on character range, sometimes using one 32-bit quantity per character.

What is path of JDK on Mac ?

/System/Library/Frameworks/JavaVM.framework/

Also see Java 7 path on mountain lion

SQL Server 2008 Insert with WHILE LOOP

Assuming that ID is an identity column:

INSERT INTO TheTable(HospitalID, Email, Description)
SELECT 32, Email, Description FROM TheTable
WHERE HospitalID <> 32

Try to avoid loops with SQL. Try to think in terms of sets instead.

How do I correctly setup and teardown for my pytest class with tests?

Your code should work just as you expect it to if you add @classmethod decorators.

@classmethod 
def setup_class(cls):
    "Runs once per class"

@classmethod 
def teardown_class(cls):
    "Runs at end of class"

See http://pythontesting.net/framework/pytest/pytest-xunit-style-fixtures/

How do you add an SDK to Android Studio?

You have to put your SDK's in a given directory or .app directory. You have to do it in finder while you are out of the application i'm assuming, but personally I'd use terminal in Mac instead of doing it in the App itself or finder. According to Google:

On Windows and Mac, the individual tools and other SDK packages are saved within the Android Studio application directory. To access the tools directly, use a terminal to navigate into the application and locate the sdk/ directory. For example:

 Windows: \Users\<user>\AppData\Local\Android\android-studio\sdk\
 Mac: /Applications/Android\ Studio.app/sdk/

TypeError: $.browser is undefined

i did solved it using jQuery migrate link specified below:

<script src="http://code.jquery.com/jquery-migrate-1.0.0.js"></script>

Check if a value is within a range of numbers

You must want to determine the lower and upper bound before writing the condition

function between(value,first,last) {

 let lower = Math.min(first,last) , upper = Math.max(first,last);
 return value >= lower &&  value <= upper ;

}

Attaching a Sass/SCSS to HTML docs

You can not "attach" a SASS/SCSS file to an HTML document.

SASS/SCSS is a CSS preprocessor that runs on the server and compiles to CSS code that your browser understands.

There are client-side alternatives to SASS that can be compiled in the browser using javascript such as LESS CSS, though I advise you compile to CSS for production use.

It's as simple as adding 2 lines of code to your HTML file.

<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>

Detect changed input text box

I think you can use keydown too:

$('#fieldID').on('keydown', function (e) {
  //console.log(e.which);
  if (e.which === 8) {
    //do something when pressing delete
    return true;
  } else {
    //do something else
    return false;
  }
});

Convert spark DataFrame column to python list

If you get the error below :

AttributeError: 'list' object has no attribute 'collect'

This code will solve your issues :

mvv_list = mvv_count_df.select('mvv').collect()

mvv_array = [int(i.mvv) for i in mvv_list]

Find all controls in WPF Window by type

For some reason, none of the answers posted here helped me to get all controls of given type contained in a given control in my MainWindow. I needed to find all menu items in one menu to iterate them. They were not all direct descendants of the menu, so i managed to collect only the first lilne of them using any of the code above. This extension method is my solution for the problem for anyone who will continue to read all the way down here.

public static void FindVisualChildren<T>(this ICollection<T> children, DependencyObject depObj) where T : DependencyObject
    {
        if (depObj != null)
        {
            var brethren = LogicalTreeHelper.GetChildren(depObj);
            var brethrenOfType = LogicalTreeHelper.GetChildren(depObj).OfType<T>();
            foreach (var childOfType in brethrenOfType)
            {
                children.Add(childOfType);
            }

            foreach (var rawChild in brethren)
            {
                if (rawChild is DependencyObject)
                {
                    var child = rawChild as DependencyObject;
                    FindVisualChildren<T>(children, child);
                }
            }
        }
    }

Hope it helps.

Random String Generator Returning Same String

Just for people stopping by and what to have a random string in just one single line of code

int yourRandomStringLength = 12; //maximum: 32
Guid.NewGuid().ToString("N").Substring(0, yourRandomStringLength);

PS: Please keep in mind that yourRandomStringLength cannot exceed 32 as Guid has max length of 32.

Received fatal alert: handshake_failure through SSLHandshakeException

In my case I had one issue with the version 1.1. I was reproducing the issue easily with curl. The server didn't support lower versions than TLS1.2.

This received handshake issue:

curl --insecure --tlsv1.1 -i https://youhost --noproxy "*"

With version 1.2 it was working fine:

curl --insecure --tlsv1.2 -i https://youhost --noproxy "*"

The server was running a Weblogic, and adding this argument in setEnvDomain.sh made it to work with TLSv1.1:

-Dweblogic.security.SSL.minimumProtocolVersion=TLSv1.1

'cout' was not declared in this scope

Put the following code before int main():

using namespace std;

And you will be able to use cout.

For example:

#include<iostream>
using namespace std;
int main(){
    char t = 'f';
    char *t1;
    char **t2;
    cout<<t;        
    return 0;
}

Now take a moment and read up on what cout is and what is going on here: http://www.cplusplus.com/reference/iostream/cout/


Further, while its quick to do and it works, this is not exactly a good advice to simply add using namespace std; at the top of your code. For detailed correct approach, please read the answers to this related SO question.

How do I add a placeholder on a CharField in Django?

You can use this code to add placeholder attr for every TextInput field in you form. Text for placeholders will be taken from model field labels.

class PlaceholderDemoForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(PlaceholderDemoForm, self).__init__(*args, **kwargs)
        for field_name in self.fields:
            field = self.fields.get(field_name)  
            if field:
                if type(field.widget) in (forms.TextInput, forms.DateInput):
                    field.widget = forms.TextInput(attrs={'placeholder': field.label})

    class Meta:
        model = DemoModel

List files with certain extensions with ls and grep

ls -R | findstr ".mp3"

ls -R => lists subdirectories recursively

postgresql duplicate key violates unique constraint

Intro

I also encountered this problem and the solution proposed by @adamo was basically the right solution. However, I had to invest a lot of time in the details, which is why I am now writing a new answer in order to save this time for others.

Case

My case was as follows: There was a table that was filled with data using an app. Now a new entry had to be inserted manually via SQL. After that the sequence was out of sync and no more records could be inserted via the app.

Solution

As mentioned in the answer from @adamo, the sequence must be synchronized manually. For this purpose the name of the sequence is needed. For Postgres, the name of the sequence can be determined with the command PG_GET_SERIAL_SEQUENCE. Most examples use lower case table names. In my case the tables were created by an ORM middleware (like Hibernate or Entity Framework Core etc.) and their names all started with a capital letter.

In an e-mail from 2004 (link) I got the right hint.

(Let's assume for all examples, that Foo is the table's name and Foo_id the related column.)

Command to get the sequence name:

SELECT PG_GET_SERIAL_SEQUENCE('"Foo"', 'Foo_id');

So, the table name must be in double quotes, surrounded by single quotes.

1. Validate, that the sequence is out-of-sync

SELECT CURRVAL(PG_GET_SERIAL_SEQUENCE('"Foo"', 'Foo_id')) AS "Current Value", MAX("Foo_id") AS "Max Value" FROM "Foo";

When the Current Value is less than Max Value, your sequence is out-of-sync.

2. Correction

SELECT SETVAL((SELECT PG_GET_SERIAL_SEQUENCE('"Foo"', 'Foo_id')), (SELECT (MAX("Foo_id") + 1) FROM "Foo"), FALSE);

Reading a cell value in Excel vba and write in another Cell

surely you can do this with worksheet formulas, avoiding VBA entirely:

so for this value in say, column AV S:1 P:0 K:1 Q:1

you put this formula in column BC:

=MID(AV:AV,FIND("S",AV:AV)+2,1)

then these formulas in columns BD, BE...

=MID(AV:AV,FIND("P",AV:AV)+2,1)
=MID(AV:AV,FIND("K",AV:AV)+2,1)
=MID(AV:AV,FIND("Q",AV:AV)+2,1)

so these formulas look for the values S:1, P:1 etc in column AV. If the FIND function returns an error, then 0 is returned by the formula, else 1 (like an IF, THEN, ELSE

Then you would just copy down the formulas for all the rows in column AV.

HTH Philip

Get MIME type from filename extension

Just to make Shimmy's answer more clear:

var mimeType = MimeMapping.GetMimeMapping(fileName);

System.Web.dll v4.5

// Summary:
//     Returns the MIME mapping for the specified file name.
//
// Parameters:
//   fileName:
//     The file name that is used to determine the MIME type.
public static string GetMimeMapping(string fileName);

Selecting fields from JSON output

Assuming you are dealing with a JSON-string in the input, you can parse it using the json package, see the documentation.

In the specific example you posted you would need

x = json.loads("""{
 "accountWide": true,
 "criteria": [
     {
         "description": "some description",
         "id": 7553,
         "max": 1,
         "orderIndex": 0
     }
  ]
 }""")
description = x['criteria'][0]['description']
id = x['criteria'][0]['id']
max = x['criteria'][0]['max']

Can't compare naive and aware datetime.now() <= challenge.datetime_end

It is working form me. Here I am geeting the table created datetime and adding 10 minutes on the datetime. later depending on the current time, Expiry Operations are done.

from datetime import datetime, time, timedelta
import pytz

Added 10 minutes on database datetime

table_datetime = '2019-06-13 07:49:02.832969' (example)

# Added 10 minutes on database datetime
# table_datetime = '2019-06-13 07:49:02.832969' (example)

table_expire_datetime = table_datetime + timedelta(minutes=10 )

# Current datetime
current_datetime = datetime.now()


# replace the timezone in both time
expired_on = table_expire_datetime.replace(tzinfo=utc)
checked_on = current_datetime.replace(tzinfo=utc)


if expired_on < checked_on:
    print("Time Crossed)
else:
    print("Time not crossed ")

It worked for me.

I need to convert an int variable to double

Either use casting as others have already said, or multiply one of the int variables by 1.0:

double firstSolution = ((1.0* b1 * a22 - b2 * a12) / (a11 * a22 - a12 * a21));

setting JAVA_HOME & CLASSPATH in CentOS 6

I had to change /etc/profile.d/java_env.sh to point to the new path and then logout/login.

Page scroll when soft keyboard popped up

Ok, I have searched several hours now to find the problem, and I found it.

None of the changes like fillViewport="true" or android:windowSoftInputMode="adjustResize" helped me.

I use Android 4.4 and this is the big mistake:

android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"

Somehow, the Fullscreen themes prevent the ScrollViews from scrolling when the SoftKeyboard is visible.

At the moment, I ended up using this instead:

android:theme="@android:style/Theme.Black.NoTitleBar

I don't know how to get rid of the top system bar with time and battery display, but at least I got the problem.

Hope this helps others who have the same problem.

EDIT: I got a little workaround for my case, so I posted it here:

I am not sure if this will work for you, but it will definitely help you in understanding, and clear some things up.

EDIT2: Here is another good topic that will help you to go in the right direction or even solve your problem.

Proper way to rename solution (and directories) in Visual Studio

The Rename operations in Visual Studio only change the filename, i.e. *.prj for a project, and *.sln for a solution. You will need to rename folders separately using the filesystem, and you will need to remove and re-add the projects since they will have new folder names. However, note that the solution and project files are respectively text and xml files. You could write your own program that parses them and renames both the folder names, filenames, and fixes the project/solution files internally.

Android view pager with page indicator

you have to do following:

1-Download the full project from here https://github.com/JakeWharton/ViewPagerIndicator ViewPager Indicator 2- Import into the Eclipse.

After importing if you want to make following type of screen then follow below steps -

Screen Shot

change in

Sample circles Default

  package com.viewpagerindicator.sample;
  import android.os.Bundle;  
  import android.support.v4.view.ViewPager;
  import com.viewpagerindicator.CirclePageIndicator;

  public class SampleCirclesDefault extends BaseSampleActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_circles);

    mAdapter = new TestFragmentAdapter(getSupportFragmentManager());

    mPager = (ViewPager)findViewById(R.id.pager);
  //  mPager.setAdapter(mAdapter);

    ImageAdapter adapter = new ImageAdapter(SampleCirclesDefault.this);
    mPager.setAdapter(adapter);


    mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);
    mIndicator.setViewPager(mPager);
  }
}

ImageAdapter

 package com.viewpagerindicator.sample;

 import android.content.Context;
 import android.support.v4.view.PagerAdapter;
 import android.support.v4.view.ViewPager;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ImageView;
 import android.widget.TextView;

 public class ImageAdapter extends PagerAdapter {
 private Context mContext;

 private Integer[] mImageIds = { R.drawable.about1, R.drawable.about2,
        R.drawable.about3, R.drawable.about4, R.drawable.about5,
        R.drawable.about6, R.drawable.about7

 };

 public ImageAdapter(Context context) {
    mContext = context;
 }

 public int getCount() {
    return mImageIds.length;
 }

 public Object getItem(int position) {
    return position;
 }

 public long getItemId(int position) {
    return position;
 }

 @Override
 public Object instantiateItem(ViewGroup container, final int position) {

    LayoutInflater inflater = (LayoutInflater) container.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View convertView = inflater.inflate(R.layout.gallery_view, null);

    ImageView view_image = (ImageView) convertView
            .findViewById(R.id.view_image);
    TextView description = (TextView) convertView
            .findViewById(R.id.description);

    view_image.setImageResource(mImageIds[position]);
    view_image.setScaleType(ImageView.ScaleType.FIT_XY);

    description.setText("The natural habitat of the Niligiri tahr,Rajamala          Rajamala is 2695 Mts above sea level"
        + "The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level"
                    + "The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level");

    ((ViewPager) container).addView(convertView, 0);

    return convertView;
 }

 @Override
 public boolean isViewFromObject(View view, Object object) {
    return view == ((View) object);
 }

 @Override
 public void destroyItem(ViewGroup container, int position, Object object) {
    ((ViewPager) container).removeView((ViewGroup) object);
 }
}

gallery_view.xml

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

<LinearLayout
    android:id="@+id/about_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1" >

    <LinearLayout
        android:id="@+id/about_layout1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".4"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/view_image"
            android:layout_width="match_parent"
            android:layout_height="match_parent" 
            android:background="@drawable/about1">
     </ImageView>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/about_layout2"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight=".6"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SIGNATURE LANDMARK OF MALAYSIA-SINGAPORE CAUSEWAY"
            android:textColor="#000000"
            android:gravity="center"
            android:padding="18dp"
            android:textStyle="bold"
            android:textAppearance="?android:attr/textAppearance" />


        <ScrollView
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:fillViewport="false"
            android:orientation="vertical"
            android:scrollbars="none"
            android:layout_marginBottom="10dp"
            android:padding="10dp" >

            <TextView
                android:id="@+id/description"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textColor="#000000"
                android:text="TextView" />

            </ScrollView>
    </LinearLayout>
 </LinearLayout>

Kotlin: How to get and set a text to TextView in Android using Kotlin?

to set text in kotlin

textview.text = "write here"

Can you use CSS to mirror/flip text?

That works fine with font icons like 's7 stroke icons' and 'font-awesome':

.mirror {
  display: inline-block;
  transform: scaleX(-1);
}

And then on target element:

<button>
  <span class="s7-back mirror"></span>
  <span>Next</span>
</button>

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

If you have a JPA dependency in your pom.xml then just remove it. This solution worked for me.

How does @synchronized lock/unlock in Objective-C?

The Objective-C language level synchronization uses the mutex, just like NSLock does. Semantically there are some small technical differences, but it is basically correct to think of them as two separate interfaces implemented on top of a common (more primitive) entity.

In particular with a NSLock you have an explicit lock whereas with @synchronized you have an implicit lock associated with the object you are using to synchronize. The benefit of the language level locking is the compiler understands it so it can deal with scoping issues, but mechanically they behave basically the same.

You can think of @synchronized as a compiler rewrite:

- (NSString *)myString {
  @synchronized(self) {
    return [[myString retain] autorelease];
  }
}

is transformed into:

- (NSString *)myString {
  NSString *retval = nil;
  pthread_mutex_t *self_mutex = LOOK_UP_MUTEX(self);
  pthread_mutex_lock(self_mutex);
  retval = [[myString retain] autorelease];
  pthread_mutex_unlock(self_mutex);
  return retval;
}

That is not exactly correct because the actual transform is more complex and uses recursive locks, but it should get the point across.

How do I find out my python path using python?

sys.path might include items that aren't specifically in your PYTHONPATH environment variable. To query the variable directly, use:

import os
try:
    user_paths = os.environ['PYTHONPATH'].split(os.pathsep)
except KeyError:
    user_paths = []

Counting null and non-null values in a single query

As i understood your query, You just run this script and get Total Null,Total NotNull rows,

select count(*) - count(a) as 'Null', count(a) as 'Not Null' from us;

How do I get a reference to the app delegate in Swift?

Swift 4.2

In Swift, easy to access in your VC's

extension UIViewController {
    var appDelegate: AppDelegate {
    return UIApplication.shared.delegate as! AppDelegate
   }
}

How to make EditText not editable through XML in Android?

disable from XML (one line):

 android:focusable="false"

re-enable from Java, if need be (also one line):

editText.setFocusableInTouchMode(true);

Android - running a method periodically using postDelayed() call

Perhaps involve the activity's life-cycle methods to achieve this:

Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      handler.post(sendData);
}

@Override
protected void onDestroy() {
      super.onDestroy();
      handler.removeCallbacks(sendData);
}


private final Runnable sendData = new Runnable(){
    public void run(){
        try {
            //prepare and send the data here..


            handler.postDelayed(this, 1000);    
        }
        catch (Exception e) {
            e.printStackTrace();
        }   
    }
};

In this approach, if you press back-key on your activity or call finish();, it will also stop the postDelayed callings.

How to convert strings into integers in Python?

Yet another functional solution for Python 2:

from functools import partial

map(partial(map, int), T1)

Python 3 will be a little bit messy though:

list(map(list, map(partial(map, int), T1)))

we can fix this with a wrapper

def oldmap(f, iterable):
    return list(map(f, iterable))

oldmap(partial(oldmap, int), T1)

How can I protect my .NET assemblies from decompilation?

Host your service in any cloud service provider.

apt-get for Cygwin?

You can do this using Cygwin’s setup.exe from Windows command line. Example:

cd C:\cygwin64
setup-x86_64 -q -P wget,tar,gawk,bzip2,subversion,vim

For a more convenient installer, you may want to use the apt-cyg package manager. Its syntax is similar to apt-get, which is a plus. For this, follow the above steps and then use Cygwin Bash for the following steps:

wget rawgit.com/transcode-open/apt-cyg/master/apt-cyg
install apt-cyg /bin

Now that apt-cyg is installed. Here are a few examples of installing some packages:

apt-cyg install nano
apt-cyg install git
apt-cyg install ca-certificates

Android : Fill Spinner From Java Code Programmatically

// you need to have a list of data that you want the spinner to display
List<String> spinnerArray =  new ArrayList<String>();
spinnerArray.add("item1");
spinnerArray.add("item2");

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
    this, android.R.layout.simple_spinner_item, spinnerArray);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner sItems = (Spinner) findViewById(R.id.spinner1);
sItems.setAdapter(adapter);

also to find out what is selected you could do something like this

String selected = sItems.getSelectedItem().toString();
if (selected.equals("what ever the option was")) {
}

Passing on command line arguments to runnable JAR

Why not ?

Just modify your Main-Class to receive arguments and act upon the argument.

public class wiki2txt {

    public static void main(String[] args) {

          String fileName = args[0];

          // Use FileInputStream, BufferedReader etc here.

    }
}

Specify the full path in the commandline.

java -jar wiki2txt /home/bla/enwiki-....xml

Disabling vertical scrolling in UIScrollView

Try setting the contentSize's height to the scrollView's height. Then the vertical scroll should be disabled because there would be nothing to scroll vertically.

scrollView.contentSize = CGSizeMake(scrollView.contentSize.width,scrollView.frame.size.height);

How to update values using pymongo?

You can use the $set syntax if you want to set the value of a document to an arbitrary value. This will either update the value if the attribute already exists on the document or create it if it doesn't. If you need to set a single value in a dictionary like you describe, you can use the dot notation to access child values.

If p is the object retrieved:

existing = p['d']['a']

For pymongo versions < 3.0

db.ProductData.update({
  '_id': p['_id']
},{
  '$set': {
    'd.a': existing + 1
  }
}, upsert=False, multi=False)

For pymongo versions >= 3.0

db.ProductData.update_one({
  '_id': p['_id']
},{
  '$set': {
    'd.a': existing + 1
  }
}, upsert=False)

However if you just need to increment the value, this approach could introduce issues when multiple requests could be running concurrently. Instead you should use the $inc syntax:

For pymongo versions < 3.0:

db.ProductData.update({
  '_id': p['_id']
},{
  '$inc': {
    'd.a': 1
  }
}, upsert=False, multi=False)

For pymongo versions >= 3.0:

db.ProductData.update_one({
  '_id': p['_id']
},{
  '$inc': {
    'd.a': 1
  }
}, upsert=False)

This ensures your increments will always happen.

CMD command to check connected USB devices

You could use wmic command:

wmic logicaldisk where drivetype=2 get <DeviceID, VolumeName, Description, ...>

Drivetype 2 indicates that its a removable disk.

How to send emails from my Android application?

Use .setType("message/rfc822") or the chooser will show you all of the (many) applications that support the send intent.

Escaping quotes and double quotes

In Powershell 5 escaping double quotes can be done by backtick (`). But sometimes you need to provide your double quotes escaped which can be done by backslash + backtick (\`). Eg in this curl call:

C:\Windows\System32\curl.exe -s -k -H "Content-Type: application/json" -XPOST localhost:9200/index_name/inded_type -d"{\`"velocity\`":3.14}"

JPA - Persisting a One to Many relationship

One way to do that is to set the cascade option on you "One" side of relationship:

class Employee {
   // 

   @OneToMany(cascade = {CascadeType.PERSIST})
   private Set<Vehicles> vehicles = new HashSet<Vehicles>();

   //
}

by this, when you call

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

it will save the vehicles too.

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

To point your apex/root/naked domain at a Heroku-hosted application, you'll need to use a DNS provider who supports CNAME-like records (often referred to as ALIAS or ANAME records). Currently Heroku recommends:

Whichever of those you choose, your record will look like the following:

Record: ALIAS or ANAME

Name: empty or @

Target: example.com.herokudns.com.

That's all you need.


However, it's not good for SEO to have both the www version and non-www version resolve. One should point to the other as the canonical URL. How you decide to do that depends on if you're using HTTPS or not. And if you're not, you probably should be as Heroku now handles SSL certificates for you automatically and for free for all applications running on paid dynos.

If you're not using HTTPS, you can just set up a 301 Redirect record with most DNS providers pointing name www to http://example.com.

If you are using HTTPS, you'll most likely need to handle the redirection at the application level. If you want to know why, check out these short and long explanations but basically since your DNS provider or other URL forwarding service doesn't have, and shouldn't have, your SSL certificate and private key, they can't respond to HTTPS requests for your domain.

To handle the redirects at the application level, you'll need to:

  • Add both your apex and www host names to the Heroku application (heroku domains:add example.com and heroku domains:add www.example.com)
  • Set up your SSL certificates
  • Point your apex domain record at Heroku using an ALIAS or ANAME record as described above
  • Add a CNAME record with name www pointing to www.example.com.herokudns.com.
  • And then in your application, 301 redirect any www requests to the non-www URL (here's an example of how to do it in Django)
  • Also in your application, you should probably redirect any HTTP requests to HTTPS (for example, in Django set SECURE_SSL_REDIRECT to True)

Check out this post from DNSimple for more.

Changing the sign of a number in PHP?

A trivial

$num = $num <= 0 ? $num : -$num ;

or, the better solution, IMHO:

$num = -1 * abs($num)

As @VegardLarsen has posted,

the explicit multiplication can be avoided for shortness but I prefer readability over shortness

I suggest to avoid if/else (or equivalent ternary operator) especially if you have to manipulate a number of items (in a loop or using a lambda function), as it will affect performance.

"If the float is a negative, make it a positive."

In order to change the sign of a number you can simply do:

$num = 0 - $num;

or, multiply it by -1, of course :)

How can I tell if a Java integer is null?

I don't think you can use "exists" on an integer in Perl, only on collections. Can you give an example of what you mean in Perl which matches your example in Java.

Given an expression that specifies a hash element or array element, returns true if the specified element in the hash or array has ever been initialized, even if the corresponding value is undefined.

This indicates it only applies to hash or array elements!

bootstrap responsive table content wrapping

The UberNeo response is Ok and i like it because you do not have to modify anything else except the TD. The only point is that you also have to add "white-space:normal" to the style in order to maintain the responsive characteristics of the table, if not, at certain resolutions the wrap is not made and the scroll of the table does not appear.

style="word-wrap: break-word;min-width: 160px;max-width: 160px;white-space:normal;"

How to Specify "Vary: Accept-Encoding" header in .htaccess

if anyone needs this for NGINX configuration file here is the snippet:

location ~* \.(js|css|xml|gz)$ {
    add_header Vary "Accept-Encoding";
    (... other headers or rules ...)
}

How to get a resource id with a known resource name?

Kotlin Version via Extension Function

To find a resource id by its name In Kotlin, add below snippet in a kotlin file:

ExtensionFunctions.kt

import android.content.Context
import android.content.res.Resources

fun Context.resIdByName(resIdName: String?, resType: String): Int {
    resIdName?.let {
        return resources.getIdentifier(it, resType, packageName)
    }
    throw Resources.NotFoundException()
}


Usage

Now all resource ids are accessible wherever you have a context reference using resIdByName method:

val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
val stringResId = context.resIdByName("title_home", "string")
.
.
.    

Defined Edges With CSS3 Filter Blur

Insert the image inside a with position: relative; and overflow: hidden;

HTML

<div><img src="#"></div>

CSS

div {
    position: relative;
    overflow: hidden;
}
img {
    filter: blur(5px);
        -webkit-filter: blur(5px);
        -moz-filter: blur(5px);
        -o-filter: blur(5px);
        -ms-filter: blur(5px);
}

This also works on variable sizes elements, like dynamic div's.

how to get current location in google map android

All solution mentioned above using that code which are deprecated now!Here is the new solution

  1. Add implementation 'com.google.android.gms:play-services-places:15.0.1' dependency in your gradle file

  2. Add network permission in your manifest file:

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

  1. Now use this code to get current location

      FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    
      mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {
                        // GPS location can be null if GPS is switched off
                            currentLat = location.getLatitude();
                            currentLong = location.getLongitude();
                            Toast.makeText(HomeNavigationBarActivtiy.this, "lat " + location.getLatitude() + "\nlong " + location.getLongitude(), Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        e.printStackTrace();
                    }
                });
    

Understanding slice notation

I don't think that the Python tutorial diagram (cited in various other answers) is good as this suggestion works for positive stride, but does not for a negative stride.

This is the diagram:

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

From the diagram, I expect a[-4,-6,-1] to be yP but it is ty.

>>> a = "Python"
>>> a[2:4:1] # as expected
'th'
>>> a[-4:-6:-1] # off by 1
'ty'

What always work is to think in characters or slots and use indexing as a half-open interval -- right-open if positive stride, left-open if negative stride.

This way, I can think of a[-4:-6:-1] as a(-6,-4] in interval terminology.

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
   0   1   2   3   4   5  
  -6  -5  -4  -3  -2  -1

 +---+---+---+---+---+---+---+---+---+---+---+---+
 | P | y | t | h | o | n | P | y | t | h | o | n |
 +---+---+---+---+---+---+---+---+---+---+---+---+
  -6  -5  -4  -3  -2  -1   0   1   2   3   4   5  

Dilemma: when to use Fragments vs Activities:

Since Jetpack, Single-Activity app is the preferred architecture. Usefull especially with the Navigation Architecture Component.

source

python catch exception and continue try block

You could iterate through your methods...

for m in [do_smth1, do_smth2]:
    try:
        m()
    except:
        pass

How to set timeout in Retrofit library?

public class ApiClient {
    private static Retrofit retrofit = null;
    private static final Object LOCK = new Object();

    public static void clear() {
        synchronized (LOCK) {
            retrofit = null;
        }
    }

    public static Retrofit getClient() {
        synchronized (LOCK) {
            if (retrofit == null) {

                Gson gson = new GsonBuilder()
                        .setLenient()
                        .create();

                OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                        .connectTimeout(40, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .writeTimeout(60, TimeUnit.SECONDS)
                        .build();

                // Log.e("jjj", "=" + (MySharedPreference.getmInstance().isEnglish() ? Constant.WEB_SERVICE : Constant.WEB_SERVICE_ARABIC));
                retrofit = new Retrofit.Builder()
                        .client(okHttpClient)
                        .baseUrl(Constants.WEB_SERVICE)
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        .build();
            }
            return retrofit;
        }`enter code here`

    }

    public static RequestBody plain(String content) {
        return getRequestBody("text/plain", content);
    }

    public static RequestBody getRequestBody(String type, String content) {
        return RequestBody.create(MediaType.parse(type), content);
    }
}


-------------------------------------------------------------------------


    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)

Try this:

(function ( $ ) { 

    // put all that "wl_alert" code here   

}( jQuery ));

So, the $ variable is apparently corrupted, but the jQuery variable should still refer to the jQuery object. (In normal circumstances, both the $ and jQuery variables refer to the (same) jQuery object.)

Instead of having to replace the $ name with the jQuery name in your entire code, you can simply use an IIFE to alias the name manually. So, the outside-variable jQuery is aliased with the $ variable inside the function.

Here's a simple example to help you understand this concept:

var foo = 'Peter';

(function ( bar ) {

    bar // evaluates to 'Peter'

}( foo ));

Spring mvc @PathVariable

suppose you want to write a url to fetch some order, you can say

www.mydomain.com/order/123

where 123 is orderId.

So now the url you will use in spring mvc controller would look like

/order/{orderId}

Now order id can be declared a path variable

@RequestMapping(value = " /order/{orderId}", method=RequestMethod.GET)
public String getOrder(@PathVariable String orderId){
//fetch order
}

if you use url www.mydomain.com/order/123, then orderId variable will be populated by value 123 by spring

Also note that PathVariable differs from requestParam as pathVariable is part of URL. The same url using request param would look like www.mydomain.com/order?orderId=123

API DOC
Spring Official Reference

How can I monitor the thread count of a process on linux?

try

ps huH p <PID_OF_U_PROCESS> | wc -l

or htop

SameSite warning Chrome 77

If you are testing on localhost and you have no control of the response headers, you can disable it with a chrome flag.

Visit the url and disable it: chrome://flags/#same-site-by-default-cookies SameSite by default cookies screenshot

I need to disable it because Chrome Canary just started enforcing this rule as of approximately V 82.0.4078.2 and now it's not setting these cookies.

Note: I only turn this flag on in Chrome Canary that I use for development. It's best not to turn the flag on for everyday Chrome browsing for the same reasons that google is introducing it.

Start/Stop and Restart Jenkins service on Windows

So by default you can open CMD and write

java -jar jenkins.war

But if your port 8080 is already is in use,so you have to change the Jenkins port number, so for that open Jenkins folder in Program File and open Jenkins.XML file and change the port number such as 8088

Now Open CMD and write

java -jar jenkins.war --httpPort=8088

Error inflating class android.support.design.widget.NavigationView

None of the above fixes worked for me.

What worked for me was changing

<item name="android:textColorSecondary">#FFFFFF</item>

to

<item name="android:textColorSecondary">@color/colorWhite</item>

You obviously need to add colorWhite to your colors.xml

AttributeError: 'DataFrame' object has no attribute

value_counts work only for series. It won't work for entire DataFrame. Try selecting only one column and using this attribute. For example:

df['accepted'].value_counts()

It also won't work if you have duplicate columns. This is because when you select a particular column, it will also represent the duplicate column and will return dataframe instead of series. At that time remove duplicate column by using

df = df.loc[:,~df.columns.duplicated()]
df['accepted'].value_counts()

invalid use of incomplete type

Not exactly what you were asking, but you can make action a template member function:

template<typename Subclass>
class A {
    public:
        //Why doesn't it like this?
        template<class V> void action(V var) {
                (static_cast<Subclass*>(this))->do_action();
        }
};

class B : public A<B> {
    public:
        typedef int mytype;

        B() {}

        void do_action(mytype var) {
                // Do stuff
        }
};

int main(int argc, char** argv) {
    B myInstance;
    return 0;
}

Constants in Objective-C

If you want to call something like this NSString.newLine; from objective c, and you want it to be static constant, you can create something like this in swift:

public extension NSString {
    @objc public static let newLine = "\n"
}

And you have nice readable constant definition, and available from within a type of your choice while stile bounded to context of type.

Function to convert column number to letter?

I'm surprised nobody suggested: **<code></code> <code>Columns(</code>***<code>Column Index</code>***<code>).Address</code> <code></code>**

  • For example: MsgBox Columns( 9347 ).Address returns **<code>$MUM:$MUM</code>**.

To return ONLY the column letter(s): Split((Columns(Column Index).Address(,0)),":")(0)

  • For example: MsgBox Split((Columns( 2734 ).Address(,0)),":")(0) returns **<code>DAD</code>**.

More Examples


Uploading Laravel Project onto Web Server

No, but you have a couple of options:

The easiest is to upload all the files you have into that directory you're in (i.e. the cPanel user home directory), and put the contents of public into public_html. That way your directory structure will be something like this (slightly messy but it works):

/
    .composer/
    .cpanel/
    ...
    app/                 <- your laravel app directory
    etc/
    bootstrap/           <- your laravel bootstrap directory
    mail/
    public_html/         <- your laravel public directory
    vendor/
    artisan              <- your project's root files

You may also need to edit bootstrap/paths.php to point at the correct public directory.

The other solution, if you don't like having all these files in that 'root' directory would be to put them in their own directory (maybe 'laravel') that's still in the root directory and then edit the paths to work correctly. You'll still need to put the contents of public in public_html, though, and this time edit your public_html/index.php to correctly bootstrap the application. Your folder structure will be a lot tidier this way (though there could be some headaches with paths due to messing with the framework's designed structure more):

/
    .composer/
    .cpanel/
    ...
    etc/
    laravel/      <- a directory containing all your project files except public
        app/
        bootstrap/
        vendor/
        artisan
    mail/
    public_html/  <- your laravel public directory

Python 2.7.10 error "from urllib.request import urlopen" no module named request

from urllib.request import urlopen, Request

Should solve everything

creating a random number using MYSQL

This is correct formula to find integers from i to j where i <= R <= j

FLOOR(min+RAND()*(max-min))

Use own username/password with git and bitbucket

I figured I should share my solution, since I wasn't able to find it anywhere, and only figured it out through trial and error.

I indeed was able to transfer ownership of the repository to a team on BitBucket.

Don't add the remote URL that BitBuckets suggests:

git remote add origin https://[email protected]/teamName/repo.git

Instead, add the remote URL without your username:

git remote add origin https://bitbucket.org/teamName/repo.git

This way, when you go to pull from or push to a repo, it prompts you for your username, then for your password: everyone on the team has access to it under their own credentials. This approach only works with teams on BitBucket, even though you can manage user permissions on single-owner repos.

Questions every good Database/SQL developer should be able to answer

What is the difference between a clustered index and a nonclustered index?

Another question I would ask that is not for a specific server would be:

What is a deadlock?

INSERT INTO TABLE from comma separated varchar-list

Something like this should work:

INSERT INTO #IMEIS (imei) VALUES ('val1'), ('val2'), ...

UPDATE:

Apparently this syntax is only available starting on SQL Server 2008.

Convert Java Object to JsonNode in Jackson

As of Jackson 1.6, you can use:

JsonNode node = mapper.valueToTree(map);

or

JsonNode node = mapper.convertValue(object, JsonNode.class);

Source: is there a way to serialize pojo's directly to treemodel?

Java, How to add library files in netbeans?

How to import a commons-library into netbeans.

  1. Evaluate the error message in NetBeans:

    java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    
  2. NoClassDeffFoundError means somewhere under the hood in the code you used, a method called another method which invoked a class that cannot be found. So what that means is your code did this: MyFoobarClass foobar = new MyFoobarClass() and the compiler is confused because nowhere is defined this MyFoobarClass. This is why you get an error.

  3. To know what to do next, you have to look at the error message closely. The words 'org/apache/commons' lets you know that this is the codebase that provides the tools you need. You have a choice, either you can import EVERYTHING in apache commons, or you could import JUST the LogFactory class, or you could do something in between. Like for example just get the logging bit of apache commons.

  4. You'll want to go the middle of the road and get commons-logging. Excellent choice, fire up the google and search for apache commons-logging. The first link takes you to http://commons.apache.org/proper/commons-logging/. Go to downloads. There you will find the most up-to-date ones. If your project was compiled under ancient versions of commons-logging, then use those same ancient ones because if you use the newer ones, the code may fail because the newer versions are different.

  5. You're going to want to download the commons-logging-1.1.3-bin.zip or something to that effect. Read what the name is saying. The .zip means it's a compressed file. commons-logging means that this one should contain the LogFactory class you desire. the middle 1.1.3 means that is the version. if you are compiling for an old version, you'll need to match these up, or else you risk the code not compiling right due to changes due to upgrading.

  6. Download that zip. Unzip it. Search around for things that end in .jar. In netbeans right click your project, click properties, click libraries, click "add jar/folder" and import those jars. Save the project, and re-run, and the errors should be gone.

The binaries don't include the source code, so you won't be able to drill down and see what is happening when you debug. As programmers you should be downloading "the source" of apache commons and compiling from source, generating the jars yourself and importing those for experience. You should be smart enough to understand and correct the source code you are importing. These ancient versions of apache commons might have been compiled under an older version of Java, so if you go too far back, they may not even compile unless you compile them under an ancient version of java.

JavaScript object: access variable property by name as string

ThiefMaster's answer is 100% correct, although I came across a similar problem where I needed to fetch a property from a nested object (object within an object), so as an alternative to his answer, you can create a recursive solution that will allow you to define a nomenclature to grab any property, regardless of depth:

function fetchFromObject(obj, prop) {

    if(typeof obj === 'undefined') {
        return false;
    }

    var _index = prop.indexOf('.')
    if(_index > -1) {
        return fetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index + 1));
    }

    return obj[prop];
}

Where your string reference to a given property ressembles property1.property2

Code and comments in JsFiddle.

How to implement authenticated routes in React Router 4?

I know it's been a while but I've been working on an npm package for private and public routes.

Here's how to make a private route:

<PrivateRoute exact path="/private" authed={true} redirectTo="/login" component={Title} text="This is a private route"/>

And you can also make Public routes that only unauthed user can access

<PublicRoute exact path="/public" authed={false} redirectTo="/admin" component={Title} text="This route is for unauthed users"/>

I hope it helps!

Finding multiple occurrences of a string within a string in Python

Brand new to programming in general and working through an online tutorial. I was asked to do this as well, but only using the methods I had learned so far (basically strings and loops). Not sure if this adds any value here, and I know this isn't how you would do it, but I got it to work with this:

needle = input()
haystack = input()
counter = 0
n=-1
for i in range (n+1,len(haystack)+1):
   for j in range(n+1,len(haystack)+1):
      n=-1
      if needle != haystack[i:j]:
         n = n+1
         continue
      if needle == haystack[i:j]:
         counter = counter + 1
print (counter)

How do I alter the position of a column in a PostgreSQL database table?

One, albeit a clumsy option to rearrange the columns when the column order must absolutely be changed, and foreign keys are in use, is to first dump the entire database with data, then dump just the schema (pg_dump -s databasename > databasename_schema.sql). Next edit the schema file to rearrange the columns as you would like, then recreate the database from the schema, and finally restore the data into the newly created database.

round a single column in pandas

If you are doing machine learning and use tensorflow, many float are of 'float32', not 'float64', and none of the methods mentioned in this thread likely to work. You will have to first convert to float64 first.

x.astype('float')

before round(...).

Read large files in Java

You can use java.nio which is faster than classical Input/Output stream:

http://java.sun.com/javase/6/docs/technotes/guides/io/index.html

How do I use 'git reset --hard HEAD' to revert to a previous commit?

WARNING: git clean -f will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.


Try this and see git clean -f.

git reset --hard will not remove untracked files, where as git-clean will remove any files from the tracked root directory that are not under Git tracking.

Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)

  • git clean -df
  • git clean -xdf CAUTION! This will also delete ignored files

com.android.build.transform.api.TransformException

I solved this issue by change to use latest buildToolsVersion

android {
    //...
    buildToolsVersion '26.0.2' // change from '23.0.2'
    //...
}

What are the differences between char literals '\n' and '\r' in Java?

On the command line, \r will move the cursor back to the beginning of the current line. To see the difference you must run your code from a command prompt. Eclipse's console show similar output for both the expression. For complete list of escape sequences, click here https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.6

Vertical and horizontal align (middle and center) with CSS

There are many methods :

  1. Center horizontal and vertical align of an element with fixed measure

CSS

 <div style="width:200px;height:100px;position:absolute;left:50%;top:50%;
margin-left:-100px;margin-top:-50px;">
<!–content–>
</div> 

2 . Center horizontally and vertically a single line of text

CSS

<div style="width:400px;height:200px;text-align:center;line-height:200px;">
<!–content–>
</div>  

3 . Center horizontal and vertical align of an element with no specific measure

CSS

<div style="display:table;height:300px;text-align:center;">
<div style="display:table-cell;vertical-align:middle;">
<!–content–>
</div>
</div>  

how to get session id of socket.io client in Client

On Server side

io.on('connection', socket => {
    console.log(socket.id)
})

On Client side

import io from 'socket.io-client';

socket = io.connect('http://localhost:5000');
socket.on('connect', () => {
    console.log(socket.id, socket.io.engine.id, socket.json.id)
})

If socket.id, doesn't work, make sure you call it in on('connect') or after the connection.

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

x = ["0", "1", "2"] 
y = int(x[0]) #accessing the zeroth element

If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)

If your list elements are not strings, you'll have to convert them to strings before using str.join:

x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

Also, as stated above, make sure that you're not returning a nested list.

What is the difference between GitHub and gist?

You can access Gist by visiting the following url gist.github.com. Alternatively you can access it from within your Github account (after logging in) as shown in the picture below:

how to access gist from within the github console

 

Github: A hosting service that houses a web-based git repository. It includes all the fucntionality of git with additional features added in.

 

Gist: Is an additional feature added to github to allow the sharing of code snippets, notes, to do lists and more. You can save your Gists as secret or public. Secret Gists are hidden from search engines but visible to anyone you share the url with.

For example. If you wanted to write a private to-do list. You could write one using Github Markdown as follows:

how to write a private to do list

NB: It is important to preserve the whitespace as shown above between the dash and brackets. It is also important that you save the file with the extension .md because we want the markdown to format properly. Remember to save this Gist as secret if you do not want others to see it.

 

The end result looks like the image below. The checkboxes are clickable because we saved this Gist with the extension .md

What the to do list looks like if you have formatted it properly

Get a substring of a char*

Assuming you know the position and the length of the substring:

char *buff = "this is a test string";
printf("%.*s", 4, buff + 10);

You could achieve the same thing by copying the substring to another memory destination, but it's not reasonable since you already have it in memory.

This is a good example of avoiding unnecessary copying by using pointers.

Reading serial data in realtime in Python

From the manual:

Possible values for the parameter timeout: … x set timeout to x seconds

and

readlines(sizehint=None, eol='\n') Read a list of lines, until timeout. sizehint is ignored and only present for API compatibility with built-in File objects.

Note that this function only returns on a timeout.

So your readlines will return at most every 2 seconds. Use read() as Tim suggested.

ldap query for group members

The query should be:

(&(objectCategory=user)(memberOf=CN=Distribution Groups,OU=Mybusiness,DC=mydomain.local,DC=com))

You missed & and ()

Show and hide divs at a specific time interval using jQuery

Try this

      $('document').ready(function(){
         window.setTimeout('test()',time in milliseconds);
      });

      function test(){

      $('#divid').hide();

      } 

case-insensitive matching in xpath?

You mentioned that PHP solutions were acceptable, and PHP does offer a way to accomplish this even though it only supports XPath v1.0. You can extend the XPath support to allow PHP function calls.

$xpathObj = new DOMXPath($docObj);
$xpathObj->registerNamespace('php','http://php.net/xpath'); // (required)
$xpathObj->registerPhpFunctions("strtolower"); // (leave empty to allow *any* PHP function)
$xpathObj->query('//CD[php:functionString("strtolower",@title) = "empire burlesque"]');

See the PHP registerPhpFunctions documentation for more examples. It basically demonstrates that "php:function" is for boolean evaluation and "php:functionString" is for string evaluation.

What is the difference between <p> and <div>?

The previous code was

<p class='item'><span class='name'>*Scrambled eggs on crusty Italian ciabatta and bruschetta tomato</span><span class='price'>$12.50</span></p>

So I have to changed it to

<div class='item'><span class='name'>*Scrambled eggs on crusty Italian ciabatta and bruschetta tomato</span><span class='price'>$12.50</span></div>

It was the easy fix. And the CSS for the above code is

.item {
    position: relative;
    border: 1px solid green;
    height: 30px;
}

.item .name {
    position: absolute;
    top: 0px;
    left: 0px;
}

.item .price {
    position: absolute;
    right: 0px;
    bottom: 0px;
}

So div tag can contain other elements. P should not be forced to do that.

Centering FontAwesome icons vertically and horizontally

If you are using twitter Bootstrap add the class text-center to your code.

<div class='login-icon'><i class="icon-lock text-center"></i></div>

TypeError: 'bool' object is not callable

You do cls.isFilled = True. That overwrites the method called isFilled and replaces it with the value True. That method is now gone and you can't call it anymore. So when you try to call it again you get an error, since it's not there anymore.

The solution is use a different name for the variable than you do for the method.

Java: Enum parameter in method

You could also reuse SwingConstants.{LEFT,RIGHT}. They are not enums, but they do already exist and are used in many places.

What is http multipart request?

I have found an excellent and relatively short explanation here.

A multipart request is a REST request containing several packed REST requests inside its entity.

Conditionally hide CommandField or ButtonField in Gridview

First, convert your ButtonField or CommandField to a TemplateField, then bind the Visible property of the button to a method that implements the business logic:

<asp:GridView runat="server" ID="GV1" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Age" HeaderText="Age" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button runat="server" Text="Reject" 
                Visible='<%# IsOverAgeLimit((Decimal)Eval("Age")) %>' 
                CommandName="Select"/>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Then, in the code behind, add in the method:

protected Boolean IsOverAgeLimit(Decimal Age) {
    return Age > 35M;
}

The advantage here is you can test the IsOverAgeLimit method fairly easily.

Show whitespace characters in Visual Studio Code

I'd like to offer this suggestion as a side note.
If you're looking to fix all the 'trailing whitespaces' warnings your linter throws at you.
You can have VSCode automatically trim whitespaces from an entire file using the keyboard chord.
CTRL+K / X (by default)

I was looking into showing whitespaces because my linter kept bugging me with whitespace warnings. So that's why I'm here.

Android. WebView and loadData

 String strWebData="html...." //**Your html string**

 WebView webDetail=(WebView) findViewById(R.id.webView1);

 WebSettings websetting = webDetail.getSettings();

 websetting.setDefaultTextEncodingName("utf-8");

 webDetail.loadData(strWebData, "text/html; charset=utf-8", null);

Adding ID's to google map markers

Why not use an cache that stores each marker object and references an ID?

var markerCache= {};
var idGen= 0;

function codeAddress(addr, contentStr){
    // create marker
    // store
    markerCache[idGen++]= marker;
}

Edit: of course this relies on a numeric index system that doesn't offer a length property like an array. You could of course prototype the Object object and create a length, etc for just such a thing. OTOH, generating a unique ID value (MD5, etc) of each address might be the way to go.

How can I send an inner <div> to the bottom of its parent <div>?

Make the outer div position="relative" and the inner div position="absolute" and set it's bottom="0".

Share cookie between subdomain and domain

Please everyone note that you can set a cookie from a subdomain on a domain.

(sent in the response for requesting subdomain.mydomain.com)

Set-Cookie: name=value; Domain=mydomain.com // GOOD

But you CAN'T set a cookie from a domain on a subdomain.

(sent in the response for requesting mydomain.com)

Set-Cookie: name=value; Domain=subdomain.mydomain.com // Browser rejects cookie

WHY ?

According to the specifications RFC 6265 section 5.3.6 Storage Model

If the canonicalized request-host does not domain-match the domain-attribute: Ignore the cookie entirely and abort these steps.

and RFC 6265 section 5.1.3 Domain Matching

Domain Matching

A string domain-matches a given domain string if at least one of the following conditions hold:

  1. The domain string and the string are identical. (Note that both the domain string and the string will have been canonicalized to lower case at this point.)

  2. All of the following conditions hold:

    • The domain string is a suffix of the string.

    • The last character of the string that is not included in the domain string is a %x2E (".") character.

    • The string is a host name (i.e., not an IP address).

So "subdomain.mydomain.com" domain-matches "mydomain.com", but "mydomain.com" does NOT domain-match "subdomain.mydomain.com"

Check this answer also.

What uses are there for "placement new"?

I've used it for storing objects with memory mapped files.
The specific example was an image database which processed vey large numbers of large images (more than could fit in memory).

How to make UIButton's text alignment center? Using IB

This will make exactly what you were expecting:

Objective-C:

 [myButton.titleLabel setTextAlignment:UITextAlignmentCenter];

For iOS 6 or higher it's

 [myButton.titleLabel setTextAlignment: NSTextAlignmentCenter];

as explained in tyler53's answer

Swift:

myButton.titleLabel?.textAlignment = NSTextAlignment.Center

Swift 4.x and above

myButton.titleLabel?.textAlignment = .center

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

I have just found this site – http://unused-css.com/

Looks good but I would need to thoroughly check its outputted 'clean' css before uploading it to any of my sites.

Also as with all these tools I would need to check it didn't strip id's and classes with no style but are used as JavaScript selectors.

The below content is taken from http://unused-css.com/ so credit to them for recommending other solutions:

Latish Sehgal has written a windows application to find and remove unused CSS classes. I haven't tested it but from the description, you have to provide the path of your html files and one CSS file. The program will then list the unused CSS selectors. From the screenshot, it looks like there is no way to export this list or download a new clean CSS file. It also looks like the service is limited to one CSS file. If you have multiple files you want to clean, you have to clean them one by one.

Dust-Me Selectors is a Firefox extension (for v1.5 or later) that finds unused CSS selectors. It extracts all the selectors from all the stylesheets on the page you're viewing, then analyzes that page to see which of those selectors are not used. The data is then stored so that when testing subsequent pages, selectors can be crossed off the list as they're encountered. This tool is supposed to be able to spider a whole website but I unfortunately could make it work. Also, I don't believe you can configure and download the CSS file with the styles removed.

Topstyle is a windows application including a bunch of tools to edit CSS. I haven't tested it much but it looks like it has the ability to removed unused CSS selectors. This software costs 80 USD.

Liquidcity CSS cleaner is a php script that uses regular expressions to check the styles of one page. It will tell you the classes that aren't available in the HTML code. I haven't tested this solution.

Deadweight is a CSS coverage tool. Given a set of stylesheets and a set of URLs, it determines which selectors are actually used and lists which can be "safely" deleted. This tool is a ruby module and will only work with rails website. The unused selectors have to be manually removed from the CSS file.

Helium CSS is a javascript tool for discovering unused CSS across many pages on a web site. You first have to install the javascript file to the page you want to test. Then, you have to call a helium function to start the cleaning.

UnusedCSS.com is web application with an easy to use interface. Type the url of a site and you will get a list of CSS selectors. For each selector, a number indicates how many times a selector is used. This service has a few limitations. The @import statement is not supported. You can't configure and download the new clean CSS file.

CSSESS is a bookmarklet that helps you find unused CSS selectors on any site. This tool is pretty easy to use but it won't let you configure and download clean CSS files. It will only list unused CSS files.

Select the top N values by group

dplyr does the trick

mtcars %>% 
arrange(desc(mpg)) %>% 
group_by(cyl) %>% slice(1:2)


 mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1  33.9     4  71.1    65  4.22 1.835 19.90     1     1     4     1
2  32.4     4  78.7    66  4.08 2.200 19.47     1     1     4     1
3  21.4     6 258.0   110  3.08 3.215 19.44     1     0     3     1
4  21.0     6 160.0   110  3.90 2.620 16.46     0     1     4     4
5  19.2     8 400.0   175  3.08 3.845 17.05     0     0     3     2
6  18.7     8 360.0   175  3.15 3.440 17.02     0     0     3     2

Explain ggplot2 warning: "Removed k rows containing missing values"

The behavior you're seeing is due to how ggplot2 deals with data that are outside the axis ranges of the plot. You can change this behavior depending on whether you use scale_y_continuous (or, equivalently, ylim) or coord_cartesian to set axis ranges, as explained below.

library(ggplot2)

# All points are visible in the plot
ggplot(mtcars, aes(mpg, hp)) + 
  geom_point()

In the code below, one point with hp = 335 is outside the y-range of the plot. Also, because we used scale_y_continuous to set the y-axis range, this point is not included in any other statistics or summary measures calculated by ggplot, such as the linear regression line.

ggplot(mtcars, aes(mpg, hp)) + 
  geom_point() +
  scale_y_continuous(limits=c(0,300)) +  # Change this to limits=c(0,335) and the warning disappars
  geom_smooth(method="lm")

Warning messages:
1: Removed 1 rows containing missing values (stat_smooth). 
2: Removed 1 rows containing missing values (geom_point).

In the code below, the point with hp = 335 is still outside the y-range of the plot, but this point is nevertheless included in any statistics or summary measures that ggplot calculates, such as the linear regression line. This is because we used coord_cartesian to set the y-axis range, and this function does not exclude points that are outside the plot ranges when it does other calculations on the data.

If you compare this and the previous plot, you can see that the linear regression line in the second plot has a slightly steeper slope, because the point with hp=335 is included when calculating the regression line, even though it's not visible in the plot.

ggplot(mtcars, aes(mpg, hp)) + 
  geom_point() +
  coord_cartesian(ylim=c(0,300)) +
  geom_smooth(method="lm")

How do I set hostname in docker-compose?

Based on docker documentation: https://docs.docker.com/compose/compose-file/#/command

I simply put hostname: <string> in my docker-compose file.

E.g.:

[...]

lb01:
  hostname: at-lb01
  image: at-client-base:v1

[...]

and container lb01 picks up at-lb01 as hostname.

Show loading image while $.ajax is performed

I think this might be better if you have tons of $.ajax calls

$(document).ajaxSend(function(){
    $(AnyElementYouWantToShowOnAjaxSend).fadeIn(250);
});
$(document).ajaxComplete(function(){
    $(AnyElementYouWantToShowOnAjaxSend).fadeOut(250);
});

NOTE:

If you use CSS. The element you want to shown while ajax is fetching data from your back-end code must be like this.

AnyElementYouWantToShowOnAjaxSend {
    position: fixed;
    top: 0;
    left: 0;
    height: 100vh; /* to make it responsive */
    width: 100vw; /* to make it responsive */
    overflow: hidden; /*to remove scrollbars */
    z-index: 99999; /*to make it appear on topmost part of the page */
    display: none; /*to make it visible only on fadeIn() function */
}

How to increase time in web.config for executing sql query

You should add the httpRuntime block and deal with executionTimeout (in seconds).

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
...
 <system.web>
   <httpRuntime executionTimeout="90" maxRequestLength="4096"
    useFullyQualifiedRedirectUrl="false"
    minFreeThreads="8"
    minLocalRequestFreeThreads="4"
    appRequestQueueLimit="100" />
 </system.web>
... 
</configuration>

For more information, please, see msdn page.

What is the difference between a .cpp file and a .h file?

A header (.h, .hpp, ...) file contains

  • Class definitions ( class X { ... }; )
  • Inline function definitions ( inline int get_cpus() { ... } )
  • Function declarations ( void help(); )
  • Object declarations ( extern int debug_enabled; )

A source file (.c, .cpp, .cxx) contains

  • Function definitions ( void help() { ... } or void X::f() { ... } )
  • Object definitions ( int debug_enabled = 1; )

However, the convention that headers are named with a .h suffix and source files are named with a .cpp suffix is not really required. One can always tell a good compiler how to treat some file, irrespective of its file-name suffix ( -x <file-type> for gcc. Like -x c++ ).

Source files will contain definitions that must be present only once in the whole program. So if you include a source file somewhere and then link the result of compilation of that file and then the one of the source file itself together, then of course you will get linker errors, because you have those definitions now appear twice: Once in the included source file, and then in the file that included it. That's why you had problems with including the .cpp file.

How to get my project path?

var requiredPath = Path.GetDirectoryName(Path.GetDirectoryName(
System.IO.Path.GetDirectoryName( 
      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase )));

Two versions of python on linux. how to make 2.7 the default

Add /usr/local/bin to your PATH environment variable, earlier in the list than /usr/bin.

Generally this is done in your shell's rc file, e.g. for bash, you'd put this in .bashrc:

export PATH="/usr/local/bin:$PATH"

This will cause your shell to look first for a python in /usr/local/bin, before it goes with the one in /usr/bin.

(Of course, this means you also need to have /usr/local/bin/python point to python2.7 - if it doesn't already, you'll need to symlink it.)

Do fragments really need an empty constructor?

Here is my simple solution:

1 - Define your fragment

public class MyFragment extends Fragment {

    private String parameter;

    public MyFragment() {
    }

    public void setParameter(String parameter) {
        this.parameter = parameter;
    } 
}

2 - Create your new fragment and populate the parameter

    myfragment = new MyFragment();
    myfragment.setParameter("here the value of my parameter");

3 - Enjoy it!

Obviously you can change the type and the number of parameters. Quick and easy.

What is the proper way to re-attach detached objects in Hibernate?

So it seems that there is no way to reattach a stale detached entity in JPA.

merge() will push the stale state to the DB, and overwrite any intervening updates.

refresh() cannot be called on a detached entity.

lock() cannot be called on a detached entity, and even if it could, and it did reattach the entity, calling 'lock' with argument 'LockMode.NONE' implying that you are locking, but not locking, is the most counterintuitive piece of API design I've ever seen.

So you are stuck. There's an detach() method, but no attach() or reattach(). An obvious step in the object lifecycle is not available to you.

Judging by the number of similar questions about JPA, it seems that even if JPA does claim to have a coherent model, it most certainly does not match the mental model of most programmers, who have been cursed to waste many hours trying understand how to get JPA to do the simplest things, and end up with cache management code all over their applications.

It seems the only way to do it is discard your stale detached entity and do a find query with the same id, that will hit the L2 or the DB.

Mik

Reading Excel files from C#

Just did a quick demo project that required managing some excel files. The .NET component from GemBox software was adequate for my needs. It has a free version with a few limitations.

http://www.gemboxsoftware.com/GBSpreadsheet.htm

Force an Android activity to always use landscape mode

Arslan, why do you want to force orientation pro grammatically, though there's already a way in manifest <activity android:name=".youractivityName" android:screenOrientation="portrait" />

How can I get useful error messages in PHP?

Turning on error reporting is the correct solution, however it does not seem to take effect in the program that turns it on, but only in subsequently included programs.

Thus, I always create a file/program (which I usually call "genwrap.php") which has essentially the same code as the popular solution here (ie. turn on error reporting) and it also then includes the page I actually want to call.

There are 2 steps to implement this debugging;

One - create genwrap.php and put this code in it:

<?php
error_reporting(-1);
ini_set('display_errors', 'On');

include($_REQUEST['page']);
?>

Two - change the link to the program/page you want to debug to go via genwrap.php,

Eg: change:

$.ajax('dir/pgm.php?param=val').done(function(data) { /* ... */

to

$.ajax('dir/genwrap.php?page=pgm.php&param=val').done(function(data) { /* ... */

PowerShell script to return members of multiple security groups

This is cleaner and will put in a csv.

Import-Module ActiveDirectory

$Groups = (Get-AdGroup -filter * | Where {$_.name -like "**"} | select name -expandproperty name)


$Table = @()

$Record = [ordered]@{
"Group Name" = ""
"Name" = ""
"Username" = ""
}



Foreach ($Group in $Groups)
{

$Arrayofmembers = Get-ADGroupMember -identity $Group | select name,samaccountname

foreach ($Member in $Arrayofmembers)
{
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord

}

}

$Table | export-csv "C:\temp\SecurityGroups.csv" -NoTypeInformation

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

As everyone has mentioned http.server module is equivalent to python -m SimpleHTTPServer.
But as a warning from https://docs.python.org/3/library/http.server.html#module-http.server

Warning: http.server is not recommended for production. It only implements basic security checks.

Usage

http.server can also be invoked directly using the -m switch of the interpreter.

python -m http.server

The above command will run a server by default on port number 8000. You can also give the port number explicitly while running the server

python -m http.server 9000

The above command will run an HTTP server on port 9000 instead of 8000.

By default, server binds itself to all interfaces. The option -b/--bind specifies a specific address to which it should bind. Both IPv4 and IPv6 addresses are supported. For example, the following command causes the server to bind to localhost only:

python -m http.server 8000 --bind 127.0.0.1

or

python -m http.server 8000 -b 127.0.0.1

Python 3.8 version also supports IPv6 in the bind argument.

Directory Binding

By default, server uses the current directory. The option -d/--directory specifies a directory to which it should serve the files. For example, the following command uses a specific directory:

python -m http.server --directory /tmp/

Directory binding is introduced in python 3.7

How to get substring from string in c#?

string newString = str.Substring(0,10)

will give you the first 10 characters (from position 0 to position 9).

See here.

How to Truncate a string in PHP to the word closest to a certain number of characters?

// a looonnng string ...
$str = "Le Lorem Ipsum est simplement du 
faux texte employé dans la composition et 
la mise en page avant impression. 
Le Lorem Ipsum est le faux texte standard de 
l'imprimerie depuis les années 1500, quand un 
imprimeur anonyme assembla ensemble des morceaux 
de texte pour réaliser un livre spécimen de polices
de texte. Il n'a pas fait que survivre cinq siècles,
mais s'est aussi adapté à la bureautique informatique,
sans que son contenu n'en soit modifié. Il a été 
popularisé dans les années 1960 grâce à la vente 
de feuilles Letraset contenant des passages du
Lorem Ipsum, et, plus récemment, par son inclusion 
dans des applications de mise en page de texte, 
comme Aldus PageMaker";
// number chars to cut
$number_to_cut = 300;
// string truncated in one line !
$truncated_string = 
substr($str, 0, strrpos(substr($str, 0, $number_to_cut), ' '));
// test return
echo $truncated_string;

// variation (add ellipsis) : echo $truncated_string.' ...';

// output :
/* Le Lorem Ipsum est simplement du 
faux texte employé dans la composition et 
la mise en page avant impression. 
Le Lorem Ipsum est le faux texte standard de 
l'imprimerie depuis les années 1500, quand un 
imprimeur anonyme assembla ensemble des morceaux 
de texte pour réaliser un livre
*/

Error Code: 1406. Data too long for column - MySQL

Besides the answer given above, I just want to add that this error can also occur while importing data with incorrect lines terminated character.

For example I save the dump file in csv format in windows. then while importing

LOAD DATA INFILE '/path_to_csv_folder/db.csv' INTO TABLE table1
 FIELDS TERMINATED BY ',' 
 ENCLOSED BY '"'
 ESCAPED BY '"'
 LINES TERMINATED BY '\n'
IGNORE 1 LINES;

Windows saved end of line as \r\n (i.e. CF LF) where as I was using \n. I was getting crazy why phpMyAdmin was able to import the file while I couldn't. Only when I open the file in notepadd++ and saw the end of file then I realized that mysql was unable to find any lines terminated symbol (and I guess it consider all the lines as input to the field; making it complain.)

Anyway after making from \n to \r\n; it work like a charm.

LOAD DATA INFILE '/path_to_csv_folder/db.csv' INTO TABLE table1
 FIELDS TERMINATED BY ',' 
 ENCLOSED BY '"'
 ESCAPED BY '"'
 LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;

Drawing an SVG file on a HTML5 canvas

Mozilla has a simple way for drawing SVG on canvas called "Drawing DOM objects into a canvas"

What is difference between @RequestBody and @RequestParam?

@RequestParam annotation tells Spring that it should map a request parameter from the GET/POST request to your method argument. For example:

request:

GET: http://someserver.org/path?name=John&surname=Smith

endpoint code:

public User getUser(@RequestParam(value = "name") String name, 
                    @RequestParam(value = "surname") String surname){ 
    ...  
    }

So basically, while @RequestBody maps entire user request (even for POST) to a String variable, @RequestParam does so with one (or more - but it is more complicated) request param to your method argument.

Stop executing further code in Java

Just do:

public void onClick() {
    if(condition == true) {
        return;
    }
    string.setText("This string should not change if condition = true");
}

It's redundant to write if(condition == true), just write if(condition) (This way, for example, you'll not write = by mistake).

Using CSS how to change only the 2nd column of a table

To change only the second column of a table use the following:

General Case:

table td + td{  /* this will go to the 2nd column of a table directly */

background:red

}

Your case:

.countTable table table td + td{ 

background: red

}

Note: this works for all browsers (Modern and old ones) that's why I added my answer to an old question

Change default timeout for mocha

Just adding to the correct answer you can set the timeout with the arrow function like this:

it('Some test', () => {

}).timeout(5000)

Access files stored on Amazon S3 through web browser

I had the same problem and I fixed it by using the

  1. new context menu "Make Public".
  2. Go to https://console.aws.amazon.com/s3/home,
  3. select the bucket and then for each Folder or File (or multiple selects) right click and
  4. "make public"

Load view from an external xib file in storyboard

My full example is here, but I will provide a summary below.

Layout

Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).

Make the swift file the xib file's owner.

enter image description here Code

Add the following code to the .swift file and hook up the outlets and actions from the .xib file.

import UIKit
class ResuableCustomView: UIView {

    let nibName = "ReusableCustomView"
    var contentView: UIView?

    @IBOutlet weak var label: UILabel!
    @IBAction func buttonTap(_ sender: UIButton) {
        label.text = "Hi"
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        guard let view = loadViewFromNib() else { return }
        view.frame = self.bounds
        self.addSubview(view)
        contentView = view
    }

    func loadViewFromNib() -> UIView? {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName, bundle: bundle)
        return nib.instantiate(withOwner: self, options: nil).first as? UIView
    }
}

Use it

Use your custom view anywhere in your storyboard. Just add a UIView and set the class name to your custom class name.

enter image description here


For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.

  1. Create a custom UIView class in a .swift file to control your xib. i.e. MyCustomClass.swift
  2. Create a .xib file and style it as you want. i.e. MyCustomClass.xib
  3. Set the File's Owner of the .xib file to be your custom class (MyCustomClass)
  4. GOTCHA: leave the class value (under the identity Inspector) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.
  5. Hook up your outlets as you normally would using the Assistant Editor.
    • NOTE: If you look at the Connections Inspector you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass), but rather reference File's Owner. Since File's Owner is specified to be your custom class, the outlets will hook up and work propery.
  6. Make sure your custom class has @IBDesignable before the class statement.
  7. Make your custom class conform to the NibLoadable protocol referenced below.
    • NOTE: If your custom class .swift file name is different from your .xib file name, then set the nibName property to be the name of your .xib file.
  8. Implement required init?(coder aDecoder: NSCoder) and override init(frame: CGRect) to call setupFromNib() like the example below.
  9. Add a UIView to your desired storyboard and set the class to be your custom class name (i.e. MyCustomClass).
  10. Watch IBDesignable in action as it draws your .xib in the storyboard with all of it's awe and wonder.

Here is the protocol you will want to reference:

public protocol NibLoadable {
    static var nibName: String { get }
}

public extension NibLoadable where Self: UIView {

    public static var nibName: String {
        return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
    }

    public static var nib: UINib {
        let bundle = Bundle(for: Self.self)
        return UINib(nibName: Self.nibName, bundle: bundle)
    }

    func setupFromNib() {
        guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
        addSubview(view)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
        view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
        view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
    }
}

And here is an example of MyCustomClass that implements the protocol (with the .xib file being named MyCustomClass.xib):

@IBDesignable
class MyCustomClass: UIView, NibLoadable {

    @IBOutlet weak var myLabel: UILabel!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupFromNib()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupFromNib()
    }

}

NOTE: If you miss the Gotcha and set the class value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder) method which then calls Self.nib.instantiate and calls the init again.

No increment operator (++) in Ruby?

I don't think that notation is available because—unlike say PHP or C—everything in Ruby is an object.

Sure you could use $var=0; $var++ in PHP, but that's because it's a variable and not an object. Therefore, $var = new stdClass(); $var++ would probably throw an error.

I'm not a Ruby or RoR programmer, so I'm sure someone can verify the above or rectify it if it's inaccurate.

NSDate get year/month/day

Try this . . .

Code snippet:

 NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
 int year = [components year];
 int month = [components month];
 int day = [components day];

It gives current year, month, date

How to write a JSON file in C#?

var responseData = //Fetch Data
string jsonData = JsonConvert.SerializeObject(responseData, Formatting.None);
System.IO.File.WriteAllText(Server.MapPath("~/JsonData/jsondata.txt"), jsonData);

Multipart File Upload Using Spring Rest Template + Spring Web MVC

The Multipart File Upload worked after following code modification to Upload using RestTemplate

LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new ClassPathResource(file));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);

HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new    HttpEntity<LinkedMultiValueMap<String, Object>>(
                    map, headers);
ResponseEntity<String> result = template.get().exchange(
                    contextPath.get() + path, HttpMethod.POST, requestEntity,
                    String.class);

And adding MultipartFilter to web.xml

    <filter>
        <filter-name>multipartFilter</filter-name>
        <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>multipartFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

How do I check if the user is pressing a key?

In java you don't check if a key is pressed, instead you listen to KeyEvents. The right way to achieve your goal is to register a KeyEventDispatcher, and implement it to maintain the state of the desired key:

import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;

public class IsKeyPressed {
    private static volatile boolean wPressed = false;
    public static boolean isWPressed() {
        synchronized (IsKeyPressed.class) {
            return wPressed;
        }
    }

    public static void main(String[] args) {
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {

            @Override
            public boolean dispatchKeyEvent(KeyEvent ke) {
                synchronized (IsKeyPressed.class) {
                    switch (ke.getID()) {
                    case KeyEvent.KEY_PRESSED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = true;
                        }
                        break;

                    case KeyEvent.KEY_RELEASED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = false;
                        }
                        break;
                    }
                    return false;
                }
            }
        });
    }
}

Then you can always use:

if (IsKeyPressed.isWPressed()) {
    // do your thing.
}

You can, of course, use same method to implement isPressing("<some key>") with a map of keys and their state wrapped inside IsKeyPressed.

List(of String) or Array or ArrayList

Sometimes I don't want to add items to a list when I instantiate it.

Instantiate a blank list

Dim blankList As List(Of String) = New List(Of String)

Add to the list

blankList.Add("Dis be part of me list") 'blankList is no longer blank, but you get the drift

Loop through the list

For Each item in blankList
  ' write code here, for example:
  Console.WriteLine(item)
Next

PHP find difference between two datetimes

Here is my full post with topic: PHP find difference between two datetimes

USAGE EXAMPLE


    echo timeDifference('2016-05-27 02:00:00', 'Y-m-d H:i:s', '2017-08-30 00:01:59', 'Y-m-d H:i:s', false, '%a days %h hours');
    #459 days 22 hours (string)

    echo timeDifference('2016-05-27 02:00:00', 'Y-m-d H:i:s', '2016-05-27 07:00:00', 'Y-m-d H:i:s', true, 'hours',true);
    #-5 (int)

Is iterating ConcurrentHashMap values thread safe?

What does it mean?

It means that you should not try to use the same iterator in two threads. If you have two threads that need to iterate over the keys, values or entries, then they each should create and use their own iterators.

What happens if I try to iterate the map with two threads at the same time?

It is not entirely clear what would happen if you broke this rule. You could just get confusing behavior, in the same way that you do if (for example) two threads try to read from standard input without synchronizing. You could also get non-thread-safe behavior.

But if the two threads used different iterators, you should be fine.

What happens if I put or remove a value from the map while iterating it?

That's a separate issue, but the javadoc section that you quoted adequately answers it. Basically, the iterators are thread-safe, but it is not defined whether you will see the effects of any concurrent insertions, updates or deletions reflected in the sequence of objects returned by the iterator. In practice, it probably depends on where in the map the updates occur.

How to get setuptools and easy_install?

For linux versions(ubuntu/linux mint), you can always type this in the command prompt:

sudo apt-get install python-setuptools

this will automatically install eas-_install

Split by comma and strip whitespace in Python

import re
mylist = [x for x in re.compile('\s*[,|\s+]\s*').split(string)]

Simply, comma or at least one white spaces with/without preceding/succeeding white spaces.

Please try!

Open File Dialog, One Filter for Multiple Excel Extensions?

If you want to merge the filters (eg. CSV and Excel files), use this formula:

OpenFileDialog of = new OpenFileDialog();
of.Filter = "CSV files (*.csv)|*.csv|Excel Files|*.xls;*.xlsx";

Or if you want to see XML or PDF files in one time use this:

of.Filter = @" XML or PDF |*.xml;*.pdf";

How to parse a date?

You cannot expect to parse a date with a SimpleDateFormat that is set up with a different format.

To parse your "Thu Jun 18 20:56:02 EDT 2009" date string you need a SimpleDateFormat like this (roughly):

SimpleDateFormat parser=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");

Use this to parse the string into a Date, and then your other SimpleDateFormat to turn that Date into the format you want.

        String input = "Thu Jun 18 20:56:02 EDT 2009";
        SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
        Date date = parser.parse(input);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = formatter.format(date);

        ...

JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

JavaScript - Replace all commas in a string

The third parameter of String.prototype.replace() function was never defined as a standard, so most browsers simply do not implement it.

The best way is to use regular expression with g (global) flag.

_x000D_
_x000D_
var myStr = 'this,is,a,test';_x000D_
var newStr = myStr.replace(/,/g, '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

Still have issues?

It is important to note, that regular expressions use special characters that need to be escaped. As an example, if you need to escape a dot (.) character, you should use /\./ literal, as in the regex syntax a dot matches any single character (except line terminators).

_x000D_
_x000D_
var myStr = 'this.is.a.test';_x000D_
var newStr = myStr.replace(/\./g, '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

If you need to pass a variable as a replacement string, instead of using regex literal you may create RegExp object and pass a string as the first argument of the constructor. The normal string escape rules (preceding special characters with \ when included in a string) will be necessary.

_x000D_
_x000D_
var myStr = 'this.is.a.test';_x000D_
var reStr = '\\.';_x000D_
var newStr = myStr.replace(new RegExp(reStr, 'g'), '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

Find text string using jQuery?

This will select just the leaf elements that contain "I am a simple string".

$('*:contains("I am a simple string")').each(function(){
     if($(this).children().length < 1) 
          $(this).css("border","solid 2px red") });

Paste the following into the address bar to test it.

javascript: $('*:contains("I am a simple string")').each(function(){ if($(this).children().length < 1) $(this).css("border","solid 2px red") }); return false;

If you want to grab just "I am a simple string". First wrap the text in an element like so.

$('*:contains("I am a simple string")').each(function(){
     if($(this).children().length < 1) 
          $(this).html( 
               $(this).text().replace(
                    /"I am a simple string"/
                    ,'<span containsStringImLookingFor="true">"I am a simple string"</span>' 
               )  
           ) 
});

and then do this.

$('*[containsStringImLookingFor]').css("border","solid 2px red");

How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project

You'll need AJAX if you want to update a part of your page without reloading the entire page.

main cshtml view

<div id="refTable">
     <!-- partial view content will be inserted here -->
</div>

@Html.TextBox("yearSelect3", Convert.ToDateTime(tempItem3.Holiday_date).Year.ToString());
<button id="pY">PrevY</button>

<script>
    $(document).ready(function() {
        $("#pY").on("click", function() {
            var val = $('#yearSelect3').val();
            $.ajax({
                url: "/Holiday/Calendar",
                type: "GET",
                data: { year: ((val * 1) + 1) }
            })
            .done(function(partialViewResult) {
                $("#refTable").html(partialViewResult);
            });
        });
    });
</script>

You'll need to add the fields I have omitted. I've used a <button> instead of submit buttons because you don't have a form (I don't see one in your markup) and you just need them to trigger javascript on the client side.

The HolidayPartialView gets rendered into html and the jquery done callback inserts that html fragment into the refTable div.

HolidayController Update action

[HttpGet]
public ActionResult Calendar(int year)
{
    var dates = new List<DateTime>() { /* values based on year */ };
    HolidayViewModel model = new HolidayViewModel {
        Dates = dates
    };
    return PartialView("HolidayPartialView", model);
}

This controller action takes the year parameter and returns a list of dates using a strongly-typed view model instead of the ViewBag.

view model

public class HolidayViewModel
{
    IEnumerable<DateTime> Dates { get; set; }
}

HolidayPartialView.csthml

@model Your.Namespace.HolidayViewModel;

<table class="tblHoliday">
    @foreach(var date in Model.Dates)
    {
        <tr><td>@date.ToString("MM/dd/yyyy")</td></tr>
    }
</table>

This is the stuff that gets inserted into your div.

Check if decimal value is null

Assuming you are reading from a data row, what you want is:

if ( !rdrSelect.IsNull(23) ) 
{ 
   //handle parsing
}

Python: Converting string into decimal number

use the built in float() function in a list comprehension.

A2 = [float(v.replace('"','').strip()) for v in A1]

What is the difference between concurrency and parallelism?

Say you have a program that has two threads. The program can run in two ways:

Concurrency                 Concurrency + parallelism
(Single-Core CPU)           (Multi-Core CPU)
 ___                         ___ ___
|th1|                       |th1|th2|
|   |                       |   |___|
|___|___                    |   |___
    |th2|                   |___|th2|
 ___|___|                    ___|___|
|th1|                       |th1|
|___|___                    |   |___
    |th2|                   |   |th2|

In both cases we have concurrency from the mere fact that we have more than one thread running.

If we ran this program on a computer with a single CPU core, the OS would be switching between the two threads, allowing one thread to run at a time.

If we ran this program on a computer with a multi-core CPU then we would be able to run the two threads in parallel - side by side at the exact same time.

Python name 'os' is not defined

The problem is that you forgot to import os. Add this line of code:

import os

And everything should be fine. Hope this helps!

Set Google Chrome as the debugging browser in Visual Studio

If you don't see the "Browse With..." option stop debugging first. =)

Flask Download a File

You need to make sure that the value you pass to the directory argument is an absolute path, corrected for the current location of your application.

The best way to do this is to configure UPLOAD_FOLDER as a relative path (no leading slash), then make it absolute by prepending current_app.root_path:

@app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def download(filename):
    uploads = os.path.join(current_app.root_path, app.config['UPLOAD_FOLDER'])
    return send_from_directory(directory=uploads, filename=filename)

It is important to reiterate that UPLOAD_FOLDER must be relative for this to work, e.g. not start with a /.

A relative path could work but relies too much on the current working directory being set to the place where your Flask code lives. This may not always be the case.

How to redirect user's browser URL to a different page in Nodejs?

In Express you can use

res.redirect('http://example.com');

to redirect user from server.

To include a status code 301 or 302 it can be used

res.redirect(301, 'http://example.com');

How to print a query string with parameter values when using Hibernate

I like this for log4j:

log4j.logger.org.hibernate.SQL=trace
log4j.logger.org.hibernate.engine.query=trace
log4j.logger.org.hibernate.type=trace
log4j.logger.org.hibernate.jdbc=trace
log4j.logger.org.hibernate.type.descriptor.sql.BasicExtractor=error 
log4j.logger.org.hibernate.type.CollectionType=error 

Error parsing XHTML: The content of elements must consist of well-formed character data or markup

Sometimes you will need this :

 /*<![CDATA[*/
 /*]]>*/

and not only this :

 <![CDATA[
 ]]>

Detecting a long press with Android

setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {

                int action = MotionEventCompat.getActionMasked(event);


                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        longClick = false;
                        x1 = event.getX();
                        break;

                    case MotionEvent.ACTION_MOVE:
                        if (event.getEventTime() - event.getDownTime() > 500 && Math.abs(event.getX() - x1) < MIN_DISTANCE) {
                            longClick = true;
                        }
                        break;

                    case MotionEvent.ACTION_UP:
                                if (longClick) {
                                    Toast.makeText(activity, "Long preess", Toast.LENGTH_SHORT).show();
                                } 
                }
                return true;
            }
        });

100% width table overflowing div container

From a purely "make it fit in the div" perspective, add the following to your table class (jsfiddle):

table-layout: fixed;
width: 100%;

Set your column widths as desired; otherwise, the fixed layout algorithm will distribute the table width evenly across your columns.

For quick reference, here are the table layout algorithms, emphasis mine:

  • Fixed (source)
    With this (fast) algorithm, the horizontal layout of the table does not depend on the contents of the cells; it only depends on the table's width, the width of the columns, and borders or cell spacing.
  • Automatic (source)
    In this algorithm (which generally requires no more than two passes), the table's width is given by the width of its columns [, as determined by content] (and intervening borders).

    [...] This algorithm may be inefficient since it requires the user agent to have access to all the content in the table before determining the final layout and may demand more than one pass.

Click through to the source documentation to see the specifics for each algorithm.

Importing class/java files in Eclipse

You can import a bunch of .java files to your existing project without creating a new project. Here are the steps:

  1. Right-click on the Default Package in the Project Manager pane underneath your project and choose Import
  2. An Import Wizard window will display. Choose File system and select the Next button
  3. You are now prompted to choose a file
  4. Simply browse your folder with .java files in it
  5. Select desired .java files
  6. Click on Finish to finish the import wizard

Check the following webpage for more information: http://people.cs.uchicago.edu/~kaharris/10200/tutorials/eclipse/Step_04.html

What are the differences between ArrayList and Vector?

ArrayList is newer and 20-30% faster.

If you don't need something explitly apparent in Vector, use ArrayList

Angular 2: 404 error occur when I refresh through the browser

In fact, it's normal that you have a 404 error when refreshing your application since the actual address within the browser is updating (and without # / hashbang approach). By default, HTML5 history is used for reusing in Angular2.

To fix the 404 error, you need to update your server to serve the index.html file for each route path you defined.

If you want to switch to the HashBang approach, you need to use this configuration:

import {bootstrap} from 'angular2/platform/browser';
import {provide} from 'angular2/core';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {LocationStrategy, HashLocationStrategy} from '@angular/common';

import {MyApp} from './myapp';

bootstrap(MyApp, [
  ROUTER_PROVIDERS,
  {provide: LocationStrategy, useClass: HashLocationStrategy}
]);

In this case, when you refresh the page, it will be displayed again (but you will have a # in your address).

This link could help you as well: When I refresh my website I get a 404. This is with Angular2 and firebase.

Hope it helps you, Thierry

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

Your vm does not find the class org/apache/juli/logging/LogFactory check if this class is present in the tomcat-juli.jar that you use (unzip it and search the file), if it's not present download the library from apache web site else if it's present put the tomcat-juli.jar in a path (the lib directory) that Tomcat use to load classes. If your Tomcat does not find it you can copy the jar in the lib directory of the JRE that you are using.

Python Requests package: Handling xml response

requests does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.

Python comes with built-in XML parsers. I recommend you use the ElementTree API:

import requests
from xml.etree import ElementTree

response = requests.get(url)

tree = ElementTree.fromstring(response.content)

or, if the response is particularly large, use an incremental approach:

    response = requests.get(url, stream=True)
    # if the server sent a Gzip or Deflate compressed response, decompress
    # as we read the raw stream:
    response.raw.decode_content = True

    events = ElementTree.iterparse(response.raw)
    for event, elem in events:
        # do something with `elem`

The external lxml project builds on the same API to give you more features and power still.

Replace all whitespace with a line break/paragraph mark to make a word list

You can also do it with xargs:

cat old | xargs -n1 > new

or

xargs -n1 < old > new

Removing body margin in CSS

I would say that using:

* {
  margin: 0;
  padding: 0;
}

is a bad way of solving this.

The reason for the h1 margin popping out of the parent is that the parent does not have a padding.

If you add a padding to the parent element of the h1, the margin will be inside the parent.

Resetting all paddings and margins to 0 can cause a lot of side effects. Then it's better to remove margin-top for this specific headline.

How to order results with findBy() in Doctrine

The second parameter of findBy is for ORDER.

$ens = $em->getRepository('AcmeBinBundle:Marks')
          ->findBy(
             array('type'=> 'C12'), 
             array('id' => 'ASC')
           );

How do I disable a Button in Flutter?

The simple answer is onPressed : null gives a disabled button.

How do you Programmatically Download a Webpage in Java

Jetty has an HTTP client which can be use to download a web page.

package com.zetcode;

import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;

public class ReadWebPageEx5 {

    public static void main(String[] args) throws Exception {

        HttpClient client = null;

        try {

            client = new HttpClient();
            client.start();

            String url = "http://www.something.com";

            ContentResponse res = client.GET(url);

            System.out.println(res.getContentAsString());

        } finally {

            if (client != null) {

                client.stop();
            }
        }
    }
}

The example prints the contents of a simple web page.

In a Reading a web page in Java tutorial I have written six examples of dowloading a web page programmaticaly in Java using URL, JSoup, HtmlCleaner, Apache HttpClient, Jetty HttpClient, and HtmlUnit.

How to add manifest permission to an application?

When using eclipse, Follow these steps

1) Double click on the manifest to show it on the editor
2) Click on the permissions tab below the manifest editor
3) Click on Add button
4) on the dialog that appears Click uses permission. (Ussually the last item on the list)
5) Notice the view that appears on the rigth side Select "android.permission.INTERNET"
6) Then a series of Ok and finally save.

Hope this helps

Process with an ID #### is not running in visual studio professional 2013 update 3

It looks like there are many solutions that work and some that don't...

My issue kept surfacing after a few test iterations. Yes restarting the PC and/or VS would resolve the issue...but temporarily.

My solution was to undo a security change I had enabled a couple days earlier to Controlled folder access under Ransomware protection.

I undid this change by:
(right click Start) Setting->Update & Security->Windows Security->Virus & threat protection-> Virus & threat protection settings->Manage settings

Under Controlled folder access Click->Manage Controlled folder access (this is also the Ransomware protection screen)

Turn Controlled folder access off.

This was 100% the issue for me as I was able to run my test without restarting VS.

adb shell su works but adb root does not

In some developer-friendly ROMs you could just enable Root Access in Settings > Developer option > Root access. After that adb root becomes available. Unfortunately it does not work for most stock ROMs on the market.

Return file in ASP.Net Core Web API

You can return FileResult with this methods:

1: Return FileStreamResult

    [HttpGet("get-file-stream/{id}"]
    public async Task<FileStreamResult> DownloadAsync(string id)
    {
        var fileName="myfileName.txt";
        var mimeType="application/...."; 
        var stream = await GetFileStreamById(id);

        return new FileStreamResult(stream, mimeType)
        {
            FileDownloadName = fileName
        };
    }

2: Return FileContentResult

    [HttpGet("get-file-content/{id}"]
    public async Task<FileContentResult> DownloadAsync(string id)
    {
        var fileName="myfileName.txt";
        var mimeType="application/...."; 
        var fileBytes = await GetFileBytesById(id);

        return new FileContentResult(fileBytes, mimeType)
        {
            FileDownloadName = fileName
        };
    }

How to change the default collation of a table?

To change the default character set and collation of a table including those of existing columns (note the convert to clause):

alter table <some_table> convert to character set utf8mb4 collate utf8mb4_unicode_ci;

Edited the answer, thanks to the prompting of some comments:

Should avoid recommending utf8. It's almost never what you want, and often leads to unexpected messes. The utf8 character set is not fully compatible with UTF-8. The utf8mb4 character set is what you want if you want UTF-8. – Rich Remer Mar 28 '18 at 23:41

and

That seems quite important, glad I read the comments and thanks @RichRemer . Nikki , I think you should edit that in your answer considering how many views this gets. See here https://dev.mysql.com/doc/refman/8.0/en/charset-unicode-utf8.html and here What is the difference between utf8mb4 and utf8 charsets in MySQL? – Paulpro Mar 12 at 17:46

How would you make a comma-separated string from a list of strings?

Don't you just want:

",".join(l)

Obviously it gets more complicated if you need to quote/escape commas etc in the values. In that case I would suggest looking at the csv module in the standard library:

https://docs.python.org/library/csv.html

customize Android Facebook Login button

In order to have completely custom facebook login button without using com.facebook.widget.LoginButton.

According to facebook sdk 4.x,

There new concept of login as from facebook

LoginManager and AccessToken - These new classes perform Facebook Login

So, Now you can access Facebook authentication without Facebook login button as

layout.xml

    <Button
            android:id="@+id/btn_fb_login"
            .../>

MainActivity.java

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

        FacebookSdk.sdkInitialize(this.getApplicationContext());

        callbackManager = CallbackManager.Factory.create();

        LoginManager.getInstance().registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        Log.d("Success", "Login");

                    }

                    @Override
                    public void onCancel() {
                        Toast.makeText(MainActivity.this, "Login Cancel", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onError(FacebookException exception) {
                        Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });

        setContentView(R.layout.activity_main);

        Button btn_fb_login = (Button)findViewById(R.id.btn_fb_login);

        btn_fb_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                  LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile", "user_friends"));
            }
        });

    }

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    callbackManager.onActivityResult(requestCode, resultCode, data); 
}

How to make a list of n numbers in Python and randomly select any number?

You can try this code

import random
N = 5
count_list = range(1,N+1)
random.shuffle(count_list)

while count_list:
    value = count_list.pop()
    # do whatever you want with 'value'

Error in Process.Start() -- The system cannot find the file specified

You can use the folowing to get the full path to your program like this:

Environment.CurrentDirectory

Understanding the Rails Authenticity Token

The authenticity token is designed so that you know your form is being submitted from your website. It is generated from the machine on which it runs with a unique identifier that only your machine can know, thus helping prevent cross-site request forgery attacks.

If you are simply having difficulty with rails denying your AJAX script access, you can use

<%= form_authenticity_token %>

to generate the correct token when you are creating your form.

You can read more about it in the documentation.

JavaScript naming conventions

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

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

How can I convince IE to simply display application/json rather than offer to download it?

I found the answer.

You can configure IE8 to display application/json in the browser window by updating the registry. There's no need for an external tool. I haven't tested this broadly, but it works with IE8 on Vista.

To use this, remember, all the usual caveats about updating the registry apply. Stop IE. Then, cut and paste the following into a file, by the name of json-ie.reg.

Windows Registry Editor Version 5.00
;
; Tell IE to open JSON documents in the browser.  
; 25336920-03F9-11cf-8FD0-00AA00686F13 is the CLSID for the "Browse in place" .
;  

[HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00

[HKEY_CLASSES_ROOT\MIME\Database\Content Type\text/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00

Then double-click the .reg file. Restart IE. The new behavior you get when tickling a URL that returns a doc with Content-Type: application/json or Content-Type: text/json is like this:

alt text

What it does, why it works:

The 25336920-03F9-11cf-8FD0-00AA00686F13 is the CLSID for the "Browse in place" action. Basically this registry entry is telling IE that for docs that have a mime type of application/json, just view it in place. This won't affect any application/json documents downloaded via <script> tags, or via XHR, and so on.

The CLSID and Encoding keys get the same values used for image/gif, image/jpeg, and text/html.

This hint came from this site, and from Microsoft's article Handling MIME Types in Internet Explorer .


In FF, you don't need an external add-on either. You can just use the view-source: pseudo-protocol. Enter a URL like this into the address bar:

view-source:http://myserver/MyUrl/That/emits/Application/json

This pseudo-protocol used to be supported in IE, also, until WinXP-sp2, when Microsoft disabled it for security reasons.

g++ ld: symbol(s) not found for architecture x86_64

finally solved my problem.

I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.

Using HTML5/JavaScript to generate and save a file

Saving large files

Long data URIs can give performance problems in browsers. Another option to save client-side generated files, is to put their contents in a Blob (or File) object and create a download link using URL.createObjectURL(blob). This returns an URL that can be used to retrieve the contents of the blob. The blob is stored inside the browser until either URL.revokeObjectURL() is called on the URL or the document that created it is closed. Most web browsers have support for object URLs, Opera Mini is the only one that does not support them.

Forcing a download

If the data is text or an image, the browser can open the file, instead of saving it to disk. To cause the file to be downloaded upon clicking the link, you can use the the download attribute. However, not all web browsers have support for the download attribute. Another option is to use application/octet-stream as the file's mime-type, but this causes the file to be presented as a binary blob which is especially user-unfriendly if you don't or can't specify a filename. See also 'Force to open "Save As..." popup open at text link click for pdf in HTML'.

Specifying a filename

If the blob is created with the File constructor, you can also set a filename, but only a few web browsers (including Chrome & Firefox) have support for the File constructor. The filename can also be specified as the argument to the download attribute, but this is subject to a ton of security considerations. Internet Explorer 10 and 11 provides its own method, msSaveBlob, to specify a filename.

Example code

_x000D_
_x000D_
var file;_x000D_
var data = [];_x000D_
data.push("This is a test\n");_x000D_
data.push("Of creating a file\n");_x000D_
data.push("In a browser\n");_x000D_
var properties = {type: 'text/plain'}; // Specify the file's mime-type._x000D_
try {_x000D_
  // Specify the filename using the File constructor, but ..._x000D_
  file = new File(data, "file.txt", properties);_x000D_
} catch (e) {_x000D_
  // ... fall back to the Blob constructor if that isn't supported._x000D_
  file = new Blob(data, properties);_x000D_
}_x000D_
var url = URL.createObjectURL(file);_x000D_
document.getElementById('link').href = url;
_x000D_
<a id="link" target="_blank" download="file.txt">Download</a>
_x000D_
_x000D_
_x000D_

Display string as html in asp.net mvc view

you can use @Html.Raw(str)

See MSDN for more

Returns markup that is not HTML encoded.

This method wraps HTML markup using the IHtmlString class, which renders unencoded HTML.

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

You mention the certificate is self-signed (by you)? Then you have two choices:

  • add the certificate to your trust store (fetching cacert.pem from cURL website won't do anything, since it's self-signed)
  • don't bother verifying the certificate: you trust yourself, don't you?

Here's a list of SSL context options in PHP: https://secure.php.net/manual/en/context.ssl.php

Set allow_self_signed if you import your certificate into your trust store, or set verify_peer to false to skip verification.

The reason why we trust a specific certificate is because we trust its issuer. Since your certificate is self-signed, no client will trust the certificate as the signer (you) is not trusted. If you created your own CA when signing the certificate, you can add the CA to your trust store. If your certificate doesn't contain any CA, then you can't expect anyone to connect to your server.

JSON.parse unexpected character error

Not true for the OP, but this error can be caused by using single quotation marks (') instead of double (") for strings.

The JSON spec requires double quotation marks for strings.

E.g:

JSON.parse(`{"myparam": 'myString'}`)

gives the error, whereas

JSON.parse(`{"myparam": "myString"}`)

does not. Note the quotation marks around myString.

Related: https://stackoverflow.com/a/14355724/1461850

Why is the Java main method static?

I think the keyword 'static' makes the main method a class method, and class methods have only one copy of it and can be shared by all, and also, it does not require an object for reference. So when the driver class is compiled the main method can be invoked. (I'm just in alphabet level of java, sorry if I'm wrong)

What is the difference between SQL and MySQL?

SQL is the actual language that as defined by the ISO and ANSI. Here is a link to the Wikipedia article. MySQL is a specific implementation of this standard. I believe Oracle bought the company that originally developed MySQL. Other companies also have their own implementations of the SQL standard.

Angular2 @Input to a property with get/set

@Paul Cavacas, I had the same issue and I solved by setting the Input() decorator above the getter.

  @Input('allowDays')
  get in(): any {
    return this._allowDays;
  }

  //@Input('allowDays')
  // not working
  set in(val) {
    console.log('allowDays = '+val);
    this._allowDays = val;
  }

See this plunker: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview