Programs & Examples On #Registerclass

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

Solution for me is: I clean both the solution and the project. And just rebuild the project. This error happens because I tried to delete the main file (only keep library files) in the previous build so at the current build the old stuff is still kept in the built directory. That's why unresolved things happened. "unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ) "

How to detect tableView cell touched or clicked in swift

In Swift 3.0

You can find the event for the touch/click of the cell of tableview through it delegate method. As well, can find the section and row value of the cell like this.

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       print("section: \(indexPath.section)")
       print("row: \(indexPath.row)")
}

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

let layout = myCollectionView.collectionViewLayout as? UICollectionViewFlowLayout
layout?.minimumLineSpacing = 8

self.tableView.reloadData() not working in Swift

You'll need to reload the table on the UI thread via:

//swift 2.3
dispatch_async(dispatch_get_main_queue(), { () -> Void in
    self.tableView.reloadData()
})

//swift 5
DispatchQueue.main.async{
    self.tableView.reloadData()
}

Follow up: An easier alternative to the connection.start() approach is to instead use NSURLConnection.sendAsynchronousRequest(...)

//NSOperationQueue.mainQueue() is the main thread
NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: url), queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
    //check error
    var jsonError: NSError?
    let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &jsonError)
    //check jsonError
    self.collectionView?.reloadData()
}

This doesn't allow you the flexibility of tracking the bytes though, for example you might want to calculate the progress of the download via bytesDownloaded/bytesNeeded

Add swipe to delete UITableViewCell

Xcode asks for UIContextualAction, here what worked for me for the updated version:

For Trailing Swipe Actions:->

 func delete(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
        let company = companies[indexPath.row]
        let action = UIContextualAction(style: .destructive, title: "Delete") { (action, view, _) in
           // Perform Delete Action
        }
        return action
    }
    
    func edit(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
        let action  = UIContextualAction(style: .normal, title: "Edit") { (action, view, escaping) in
            // Perform Edit Action
        }
        return action
    }
    
    override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let delete = self.delete(forRowAtIndexPath: indexPath)
        let edit = self.edit(forRowAtIndexPath: indexPath)
        let swipe = UISwipeActionsConfiguration(actions: [delete, edit])
        return swipe
    }

For Leading Swipe Actions:->

 func delete(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
        let company = companies[indexPath.row]
        let action = UIContextualAction(style: .destructive, title: "Delete") { (action, view, _) in
           // Perform Delete Action
        }
        return action
    }
    
    func edit(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
        let action  = UIContextualAction(style: .normal, title: "Edit") { (action, view, escaping) in
            // Perform Edit Action
        }
        return action
    }
    
    override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let delete = self.delete(forRowAtIndexPath: indexPath)
        let edit = self.edit(forRowAtIndexPath: indexPath)
        let swipe = UISwipeActionsConfiguration(actions: [delete, edit])
        return swipe
    }

Return true for canEditRowAt for tableView Delegate:->

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

UICollectionView current visible cell index

Also check this snippet

let isCellVisible = collectionView.visibleCells.map { collectionView.indexPath(for: $0) }.contains(inspectingIndexPath)

Creating a UITableView Programmatically

When you register a class, and use dequeueReusableCellWithIdentifier:forIndexPath:, the dequeue method is guaranteed to return a cell, so your if (cell == nil) clause is never entered. So, just do it the old way, don't register the class, and use dequeueReusableCellWithIdentifier:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"newFriendCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
//etc.
return cell;
}

As for the segue, it can't be called because you can't make a segue to a table that you've created in code, not in IB. Again, go back to the old way and use tableView:didSelectRowAtIndexPath: which will be called when you select a cell. Instantiate your detail controller there and do the trasition in code.

After edit:

I didn't see your added code there. You've implemented didDeselectRowAtIndexPath rather than didSelectRowAtIndexPath. If you change that, your segue should work.

adb is not recognized as internal or external command on windows

If you get your adb from Android Studio (which most will nowadays since Android is deprecated on Eclipse), your adb program will most likely be located here:

%USERPROFILE%\AppData\Local\Android\sdk\platform-tools

Where %USERPROFILE% represents something like C:\Users\yourName.

If you go into your computer's environmental variables and add %USERPROFILE%\AppData\Local\Android\sdk\platform-tools to the PATH (just copy-paste that line, even with the % --- it will work fine, at least on Windows, you don't need to hardcode your username) then it should work now. Open a new command prompt and type adb to check.

Where does flask look for image files?

Is the image file ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg in your static directory? If you move it to your static directory and update your HTML as such:

<img src="/static/ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg">

It should work.

Also, it is worth noting, there is a better way to structure this.

File structure:

app.py
static
   |----ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg
templates
   |----index.html

app.py

from flask import Flask, render_template, url_for
app = Flask(__name__)

@app.route('/index', methods=['GET', 'POST'])
def lionel(): 
    return render_template('index.html')

if __name__ == '__main__':
    app.run()

templates/index.html

<html>
  <head>

  </head>
  <body>
    <h1>Hi Lionel Messi</h1>

  <img src="{{url_for('static', filename='ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg')}}" />

  </body>

</html>

Doing it this way ensures that you are not hard-coding a URL path for your static assets.

How can I display a list view in an Android Alert Dialog?

This is how to show custom layout dialog with custom list item, can be customised as per your requirement.

enter image description here

STEP - 1 Create the layout of the DialogBox ie:-

R.layout.assignment_dialog_list_view

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/rectangle_round_corner_assignment_alert"
    android:orientation="vertical">
    <TextView
        android:id="@+id/tv_popup_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:singleLine="true"
        android:paddingStart="4dp"
        android:text="View as:"
        android:textColor="#4f4f4f" />

    <ListView
        android:id="@+id/lv_assignment_users"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>

STEP - 2 Create custom list item layout as per your business logic

R.layout.item_assignment_dialog_list_layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:padding="4dp"
    android:orientation="horizontal">
    <ImageView
        android:id="@+id/iv_user_profile_image"
        android:visibility="visible"
        android:layout_width="42dp"
        android:layout_height="42dp" />
    <TextView
        android:id="@+id/tv_user_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="8dp"
        android:layout_marginStart="8dp"
        android:paddingBottom="8dp"
        android:textColor="#666666"
        android:textSize="18sp"
        tools:text="ABCD XYZ" />
</LinearLayout>

STEP - 3 Create a Data model class of your own choice

public class AssignmentUserModel {

private String userId;
private String userName;
private String userRole;
private Bitmap userProfileBitmap;

public AssignmentUserModel(String userId, String userName, String userRole, Bitmap userProfileBitmap) {
    this.userId = userId;
    this.userName = userName;
    this.userRole = userRole;
    this.userProfileBitmap = userProfileBitmap;
}


public String getUserId() {
    return userId;
}

public void setUserId(String userId) {
    this.userId = userId;
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getUserRole() {
    return userRole;
}

public void setUserRole(String userRole) {
    this.userRole = userRole;
}

public Bitmap getUserProfileBitmap() {
    return userProfileBitmap;
}

public void setUserProfileBitmap(Bitmap userProfileBitmap) {
    this.userProfileBitmap = userProfileBitmap;
}

}

STEP - 4 Create custom adapter

public class UserListAdapter extends ArrayAdapter<AssignmentUserModel> {
private final Context context;
private final List<AssignmentUserModel> userList;
   
public UserListAdapter(@NonNull Context context, int resource, @NonNull List<AssignmentUserModel> objects) {
    super(context, resource, objects);
    userList = objects;
    this.context = context;
 }

@SuppressLint("ViewHolder")
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.item_assignment_dialog_list_layout, parent, false);
    ImageView profilePic = rowView.findViewById(R.id.iv_user_profile_image);
    TextView userName = rowView.findViewById(R.id.tv_user_name);
    AssignmentUserModel user = userList.get(position);

    userName.setText(user.getUserName());

    Bitmap bitmap = user.getUserProfileBitmap();

    profilePic.setImageDrawable(bitmap);

    return rowView;
}

}

STEP - 5 Create this function and provide ArrayList of above data model in this method

// Pass list of your model as arraylist
private void showCustomAlertDialogBoxForUserList(ArrayList<AssignmentUserModel> allUsersList) {
        final Dialog dialog = new Dialog(mActivity);
        dialog.setContentView(R.layout.assignment_dialog_list_view);
        if (dialog.getWindow() != null) {
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); // this is optional
        }
        ListView listView = dialog.findViewById(R.id.lv_assignment_users);
        TextView tv = dialog.findViewById(R.id.tv_popup_title);
        ArrayAdapter arrayAdapter = new UserListAdapter(context, R.layout.item_assignment_dialog_list_layout, allUsersList);
        listView.setAdapter(arrayAdapter);
        listView.setOnItemClickListener((adapterView, view, which, l) -> {
            Log.d(TAG, "showAssignmentsList: " + allUsersList.get(which).getUserId());
           // TODO : Listen to click callbacks at the position
        });
        dialog.show();
    }

Step - 6 Giving round corner background to dialog box

@drawable/rectangle_round_corner_assignment_alert

    <?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#ffffffff" />
    <corners android:radius="16dp" />
    <padding
        android:bottom="16dp"
        android:left="16dp"
        android:right="16dp"
        android:top="16dp" />
</shape>

How can I link a photo in a Facebook album to a URL

You can only do this to you own photos. Due to recent upgrades, Facebook has made this more difficult. To do this, go to the album page where the photo is that you want to link to. You should see thumbnail images of the photos in the album. Hold down the "Control" or "Command" key while clicking the photo that you wish to link to. A new browser tab will open with the picture you clicked. Under the picture there is a URL that you can send to others to share the photo. You might have to have the privacy settings for that album set so that anyone can see the photos in that album. If you don't the person who clicks the link may have to be signed in and also be your "friend."

Here is an example of one of my photos: http://www.facebook.com/photo.php?pid=43764341&l=0d8a526a64&id=25502298 -it's my cat.

Update:

The link below the photo no longer appears. Once you open the photo in a new tab you can right click the photo (Control+click for Mac users) and click "Copy Image URL" or similar and then share this link. Based on my tests the person who clicks the link doesn't need to use Facebook. The photo will load without the Facebook interface. Like this - http://a1.sphotos.ak.fbcdn.net/hphotos-ak-ash4/189088_867367406856_25502298_43764341_1304758_n.jpg

How can I export Excel files using JavaScript?

Similar answer posted here.

Link for working example

var sheet_1_data = [{Col_One:1, Col_Two:11}, {Col_One:2, Col_Two:22}];
var sheet_2_data = [{Col_One:10, Col_Two:110}, {Col_One:20, Col_Two:220}];
var opts = [{sheetid:'Sheet One',header:true},{sheetid:'Sheet Two',header:false}];
var result = alasql('SELECT * INTO XLSX("sample_file.xlsx",?) FROM ?', [opts,[sheet_1_data ,sheet_2_data]]);

Main libraries required -

<script src="http://alasql.org/console/alasql.min.js"></script> 
<script src="http://alasql.org/console/xlsx.core.min.js"></script> 

Operation Not Permitted when on root - El Capitan (rootless disabled)

Nvm. For anyone else having this problem you need to reboot your mac and press ?+R when booting up. Then go into Utilities > Terminal and type the following commands:

csrutil disable
reboot 

This is a result of System Integrity Protection. More info here.

EDIT

If you know what you are doing and are used to running Linux, you should use the above solution as many of the SIP restrictions are a complete pain in the ass.

However, if you are a tinkerer/noob/"poweruser" and don't know what you are doing, this can be very dangerous and you are better off using the answer below.

Source file not compiled Dev C++

I was facing the same issue as described above.

It can be resolved by creating a new project and creating a new file in that project. Save the file and then try to build and run.

Hope that helps. :)

How can I uninstall Ruby on ubuntu?

Run the following command on the terminal:

sudo apt-get autoremove ruby

Unable to negotiate with XX.XXX.XX.XX: no matching host key type found. Their offer: ssh-dss

If you're like me, and would rather not make this security hole system or user-wide, then you can add a config option to any git repos that need this by running this command in those repos. (note only works with git version >= 2.10, released 2016-09-04)

git config core.sshCommand 'ssh -oHostKeyAlgorithms=+ssh-dss'

This only works after the repo is setup however. If you're not comfortable adding a remote manually (and just want to clone) then you can run the clone like this:

GIT_SSH_COMMAND='ssh -oHostKeyAlgorithms=+ssh-dss' git clone ssh://user@host/path-to-repository

then run the first command to make it permanent.

If you don't have the latest, and still would like to keep the hole as local as possible I recommend putting

export GIT_SSH_COMMAND='ssh -oHostKeyAlgorithms=+ssh-dss'

in a file somewhere, say git_ssh_allow_dsa_keys.sh, and sourceing it when needed.

Launch Minecraft from command line - username and password as prefix

Those are all ways to start the standard minecraft launcher with those credentials in the text boxes.

There used to be a way to login to minecraft without the launcher using the command line, but it has since been patched.

If you want to make a custom launcher using the command line then good luck, the only way to login to the minecraft jar(IE: the way the launcher does it) is to send a post request to https://login.minecraft.net/ with the username,password,launcher version, and a RSA key. It then parses the pseudo Json, and uses the session token from that to authenticate the jar from the command line with a load of arguments.

If you are trying to make a minecraft launcher and you have no knowledge of java,http requests or json then you have no chance.

Swift

The Import android.support.v7 cannot be resolved

completing the answer @Jorgesys, in my case it was exactly the same way but the export configuration was missing in the library:

  1. right click on appcompat-v7 project;
  2. properties;
  3. left tab, Java Build Path;
  4. Right tab, Order and export;
  5. Check classes.jar with appcompat-v7;

export lib

How to tell git to use the correct identity (name and email) for a given project?

git config user.email "[email protected]"

Doing that one inside a repo will set the configuration on THAT repo, and not globally.

Seems like that's pretty much what you're after, unless I'm misreading you.

How to get RegistrationID using GCM in android

Use this code to get Registration ID using GCM

String regId = "", msg = "";

public void getRegisterationID() {

    new AsyncTask() {
        @Override
        protected Object doInBackground(Object...params) {

            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(Login.this);
                }
                regId = gcm.register(YOUR_SENDER_ID);
                Log.d("in async task", regId);

                // try
                msg = "Device registered, registration ID=" + regId;

            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
            }
            return msg;
        }
    }.execute(null, null, null);
 }

and don't forget to write permissions in manifest...
I hope it helps!

dyld: Library not loaded: @rpath/libswiftCore.dylib

What worked for me in Xcode 11 was going to General -> Frameworks, Libraries, and Embedded Content and changing the "Embed" option for the framework in question to "Embed & Sign"

Embed and Sign option

Regex AND operator

Example of a Boolean (AND) plus Wildcard search, which I'm using inside a javascript Autocomplete plugin:

String to match: "my word"

String to search: "I'm searching for my funny words inside this text"

You need the following regex: /^(?=.*my)(?=.*word).*$/im

Explaining:

^ assert position at start of a line

?= Positive Lookahead

.* matches any character (except newline)

() Groups

$ assert position at end of a line

i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])

m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

Test the Regex here: https://regex101.com/r/iS5jJ3/1

So, you can create a javascript function that:

  1. Replace regex reserved characters to avoid errors
  2. Split your string at spaces
  3. Encapsulate your words inside regex groups
  4. Create a regex pattern
  5. Execute the regex match

Example:

_x000D_
_x000D_
function fullTextCompare(myWords, toMatch){_x000D_
    //Replace regex reserved characters_x000D_
    myWords=myWords.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');_x000D_
    //Split your string at spaces_x000D_
    arrWords = myWords.split(" ");_x000D_
    //Encapsulate your words inside regex groups_x000D_
    arrWords = arrWords.map(function( n ) {_x000D_
        return ["(?=.*"+n+")"];_x000D_
    });_x000D_
    //Create a regex pattern_x000D_
    sRegex = new RegExp("^"+arrWords.join("")+".*$","im");_x000D_
    //Execute the regex match_x000D_
    return(toMatch.match(sRegex)===null?false:true);_x000D_
}_x000D_
_x000D_
//Using it:_x000D_
console.log(_x000D_
    fullTextCompare("my word","I'm searching for my funny words inside this text")_x000D_
);_x000D_
_x000D_
//Wildcards:_x000D_
console.log(_x000D_
    fullTextCompare("y wo","I'm searching for my funny words inside this text")_x000D_
);
_x000D_
_x000D_
_x000D_

create array from mysql query php

You could also make life easier using a wrapper, e.g. with ADODb:

$myarray=$db->GetCol("SELECT type FROM cars ".
    "WHERE owner=? and selling=0", 
    array($_SESSION['username']));

A good wrapper will do all your escaping for you too, making things easier to read.

How to Automatically Start a Download in PHP?

Send the following headers before outputting the file:

header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($File));
header("Connection: close");

@grom: Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download' :)

How can I make a UITextField move up when the keyboard is present - on starting to edit?

This will work Perfectly.The scroll view atmatically adjust by textfield position.i am sure you will feel good

static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.25;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;
static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 162;
@interface LoginVC ()
{
  CGFloat animatedDistance;
   CGRect viewFrameKey;
}

 //In ViewDidLoad
   viewFrameKey=self.view.frame;



- (void)textFieldDidBeginEditing:(UITextField *)textField
{
CGRect textFieldRect =
[self.view.window convertRect:textField.bounds fromView:textField];
CGRect viewRect =
[self.view.window convertRect:self.view.bounds fromView:self.view];
CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
CGFloat numerator =
midline - viewRect.origin.y
- MINIMUM_SCROLL_FRACTION * viewRect.size.height;
CGFloat denominator =
(MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION)
* viewRect.size.height;
CGFloat heightFraction = numerator / denominator;
if (heightFraction < 0.0)
{
    heightFraction = 0.0;
}
else if (heightFraction > 1.0)
{
    heightFraction = 1.0;
}
UIInterfaceOrientation orientation =
[[UIApplication sharedApplication] statusBarOrientation];
if (orientation == UIInterfaceOrientationPortrait ||
    orientation == UIInterfaceOrientationPortraitUpsideDown)
{
    animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
}
else
{
    animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
}
CGRect viewFrame = self.view.frame;
viewFrame.origin.y -= animatedDistance;

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

[self.view setFrame:viewFrame];

[UIView commitAnimations];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
[self.view setFrame:viewFrameKey];
[UIView commitAnimations];
}

Getting all types in a namespace via reflection

using System.Reflection;
using System.Collections.Generic;
//...

static List<string> GetClasses(string nameSpace)
{
    Assembly asm = Assembly.GetExecutingAssembly();

    List<string> namespacelist = new List<string>();
    List<string> classlist = new List<string>();

    foreach (Type type in asm.GetTypes())
    {
        if (type.Namespace == nameSpace)
            namespacelist.Add(type.Name);
    }

    foreach (string classname in namespacelist)
        classlist.Add(classname);

    return classlist;
}

NB: The above code illustrates what's going on. Were you to implement it, a simplified version can be used:

using System.Linq;
using System.Reflection;
using System.Collections.Generic;
//...

static IEnumerable<string> GetClasses(string nameSpace)
{
    Assembly asm = Assembly.GetExecutingAssembly();
    return asm.GetTypes()
        .Where(type => type.Namespace == nameSpace)
        .Select(type => type.Name);
}

What are all the differences between src and data-src attributes?

The attributes src and data-src have nothing in common, except that they are both allowed by HTML5 CR and they both contain the letters src. Everything else is different.

The src attribute is defined in HTML specs, and it has a functional meaning.

The data-src attribute is just one of the infinite set of data-* attributes, which have no defined meaning but can be used to include invisible data in an element, for use in scripting (or styling).

Writelines writes lines without newline, Just fills the file

This is actually a pretty common problem for newcomers to Python—especially since, across the standard library and popular third-party libraries, some reading functions strip out newlines, but almost no writing functions (except the log-related stuff) add them.

So, there's a lot of Python code out there that does things like:

fw.write('\n'.join(line_list) + '\n')

or

fw.write(line + '\n' for line in line_list)

Either one is correct, and of course you could even write your own writelinesWithNewlines function that wraps it up…

But you should only do this if you can't avoid it.

It's better if you can create/keep the newlines in the first place—as in Greg Hewgill's suggestions:

line_list.append(new_line + "\n")

And it's even better if you can work at a higher level than raw lines of text, e.g., by using the csv module in the standard library, as esuaro suggests.

For example, right after defining fw, you might do this:

cw = csv.writer(fw, delimiter='|')

Then, instead of this:

new_line = d[looking_for]+'|'+'|'.join(columns[1:])
line_list.append(new_line)

You do this:

row_list.append(d[looking_for] + columns[1:])

And at the end, instead of this:

fw.writelines(line_list)

You do this:

cw.writerows(row_list)

Finally, your design is "open a file, then build up a list of lines to add to the file, then write them all at once". If you're going to open the file up top, why not just write the lines one by one? Whether you're using simple writes or a csv.writer, it'll make your life simpler, and your code easier to read. (Sometimes there can be simplicity, efficiency, or correctness reasons to write a file all at once—but once you've moved the open all the way to the opposite end of the program from the write, you've pretty much lost any benefits of all-at-once.)

How to scroll to top of a div using jQuery?

Use the following function

window.scrollTo(xpos, ypos)

Here xpos is Required. The coordinate to scroll to, along the x-axis (horizontal), in pixels

ypos is also Required. The coordinate to scroll to, along the y-axis (vertical), in pixels

What is the difference between <html lang="en"> and <html lang="en-US">?

RFC 3066 gives the details of the allowed values (emphasis and links added):

All 2-letter subtags are interpreted as ISO 3166 alpha-2 country codes from [ISO 3166], or subsequently assigned by the ISO 3166 maintenance agency or governing standardization bodies, denoting the area to which this language variant relates.

I interpret that as meaning any valid (according to ISO 3166) 2-letter code is valid as a subtag. The RFC goes on to state:

Tags with second subtags of 3 to 8 letters may be registered with IANA, according to the rules in chapter 5 of this document.

By the way, that looks like a typo, since chapter 3 seems to relate to the the registration process, not chapter 5.

A quick search for the IANA registry reveals a very long list, of all the available language subtags. Here's one example from the list (which would be used as en-scouse):

Type: variant

Subtag: scouse

Description: Scouse

Added: 2006-09-18

Prefix: en

Comments: English Liverpudlian dialect known as 'Scouse'

There are all sorts of subtags available; a quick scroll has already revealed fr-1694acad (17th century French).


The usefulness of some of these (I would say the vast majority of these) tags, when it comes to documents designed for display in the browser, is limited. The W3C Internationalization specification simply states:

Browsers and other applications can use information about the language of content to deliver to users the most appropriate information, or to present information to users in the most appropriate way. The more content is tagged and tagged correctly, the more useful and pervasive such applications will become.

I'm struggling to find detailed information on how browsers behave when encountering different language tags, but they are most likely going to offer some benefit to those users who use a screen reader, which can use the tag to determine the language/dialect/accent in which to present the content.

C char* to int conversion

atoi can do that for you

Example:

char string[] = "1234";
int sum = atoi( string );
printf("Sum = %d\n", sum ); // Outputs: Sum = 1234

Pandas: rolling mean by time interval

This example seems to call for a weighted mean as suggested in @andyhayden's comment. For example, there are two polls on 10/25 and one each on 10/26 and 10/27. If you just resample and then take the mean, this effectively gives twice as much weighting to the polls on 10/26 and 10/27 compared to the ones on 10/25.

To give equal weight to each poll rather than equal weight to each day, you could do something like the following.

>>> wt = df.resample('D',limit=5).count()

            favorable  unfavorable  other
enddate                                  
2012-10-25          2            2      2
2012-10-26          1            1      1
2012-10-27          1            1      1

>>> df2 = df.resample('D').mean()

            favorable  unfavorable  other
enddate                                  
2012-10-25      0.495        0.485  0.025
2012-10-26      0.560        0.400  0.040
2012-10-27      0.510        0.470  0.020

That gives you the raw ingredients for doing a poll-based mean instead of a day-based mean. As before, the polls are averaged on 10/25, but the weight for 10/25 is also stored and is double the weight on 10/26 or 10/27 to reflect that two polls were taken on 10/25.

>>> df3 = df2 * wt
>>> df3 = df3.rolling(3,min_periods=1).sum()
>>> wt3 = wt.rolling(3,min_periods=1).sum()

>>> df3 = df3 / wt3  

            favorable  unfavorable     other
enddate                                     
2012-10-25   0.495000     0.485000  0.025000
2012-10-26   0.516667     0.456667  0.030000
2012-10-27   0.515000     0.460000  0.027500
2012-10-28   0.496667     0.465000  0.041667
2012-10-29   0.484000     0.478000  0.042000
2012-10-30   0.488000     0.474000  0.042000
2012-10-31   0.530000     0.450000  0.020000
2012-11-01   0.500000     0.465000  0.035000
2012-11-02   0.490000     0.470000  0.040000
2012-11-03   0.490000     0.465000  0.045000
2012-11-04   0.500000     0.448333  0.035000
2012-11-05   0.501429     0.450000  0.032857
2012-11-06   0.503333     0.450000  0.028333
2012-11-07   0.510000     0.435000  0.010000

Note that the rolling mean for 10/27 is now 0.51500 (poll-weighted) rather than 52.1667 (day-weighted).

Also note that there have been changes to the APIs for resample and rolling as of version 0.18.0.

rolling (what's new in pandas 0.18.0)

resample (what's new in pandas 0.18.0)

Renaming Column Names in Pandas Groupby function

For the first question I think answer would be:

<your DataFrame>.rename(columns={'count':'Total_Numbers'})

or

<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']

As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of python datamodel:

Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.dict["x"]

SQL Update to the SUM of its joined values

How about this:

UPDATE p
SET p.extrasPrice = t.sumPrice
FROM BookingPitches AS p
INNER JOIN
    (
        SELECT PitchID, SUM(Price) sumPrice
        FROM BookingPitchExtras
        WHERE [required] = 1
        GROUP BY PitchID 
    ) t
    ON t.PitchID = p.ID
WHERE p.bookingID = 1

Callback functions in Java

If you mean somthing like .NET anonymous delegate, I think Java's anonymous class can be used as well.

public class Main {

    public interface Visitor{
        int doJob(int a, int b);
    }


    public static void main(String[] args) {
        Visitor adder = new Visitor(){
            public int doJob(int a, int b) {
                return a + b;
            }
        };

        Visitor multiplier = new Visitor(){
            public int doJob(int a, int b) {
                return a*b;
            }
        };

        System.out.println(adder.doJob(10, 20));
        System.out.println(multiplier.doJob(10, 20));

    }
}

How to return a result from a VBA function

The below code stores the return value in to the variable retVal and then MsgBox can be used to display the value:

Dim retVal As Integer
retVal = test()
Msgbox retVal

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

Maybe unrelated to the original reason in this question, but for those who would face same with gradle and local module dependency

dependencies {
    checkstyle project(":module")
}

this error could happen, if module doesn't contain group and version, so in the module/build.gradle just need to be specified

plugins {
    id 'java-library'
}

group = "com.example"
version = "master-SNAPSHOT"

Print directly from browser without print popup window

this.print(false);

I tried this in Chrome, Firefox and IE. It works only in Firefox and IE, it uses the default printer (with default print settings) and only works when I render a PDF (I use Foxit Reader with Safe Reading Mode disabled). Chrome shows the print dialog, also the other browsers when I render an HTML page.

How do I make an html link look like a button?

By using border, color and background color properties you can create a button lookalike html link!

_x000D_
_x000D_
a {_x000D_
background-color: white;_x000D_
color: black;_x000D_
padding: 5px;_x000D_
text-decoration: none;_x000D_
border: 1px solid black;_x000D_
}_x000D_
a:hover {_x000D_
background-color: black;_x000D_
color: white;_x000D_
_x000D_
}
_x000D_
<a href="https://stackoverflow.com/_x000D_
_x000D_
">Open StackOverflow</a>
_x000D_
_x000D_
_x000D_

Hope this helps :]

css width: calc(100% -100px); alternative using jquery

Its not that hard to replicate in javascript :-) , though it will only work for width and height the best but you can expand it as per your expectations :-)

function calcShim(element,property,expression){
    var calculated = 0;
    var freed_expression = expression.replace(/ /gi,'').replace("(","").replace(")","");
    // Remove all the ( ) and spaces 
    // Now find the parts 
    var parts = freed_expression.split(/[\*+-\/]/gi);

    var units = {
        'px':function(quantity){
            var part = 0;
            part = parseFloat(quantity,10);
            return part;
        },
        '%':function(quantity){
            var part = 0,
            parentQuantity = parseFloat(element.parent().css(property));
            part = parentQuantity * ((parseFloat(quantity,10))/100);
            return part;
        } // you can always add more units here.
    }

    for( var i = 0; i < parts.length; i++ ){
        for( var unit in units ){
            if( parts[i].indexOf(unit) != -1 ){
               // replace the expression by calculated part.
               expression = expression.replace(parts[i],units[unit](parts[i]));
               break;
            }
        }
    }
    // And now compute it. though eval is evil but in some cases its a good friend.
    // Though i wish there was math. calc
    element.css(property,eval(expression));
}

How do you loop in a Windows batch file?

FOR will give you any information you'll ever need to know about FOR loops, including examples on proper usage.

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

Enable cross-origin requests in ASP.NET Web API click for more info

Enable CORS in the WebService app. First, add the CORS NuGet package. In Visual Studio, from the Tools menu, select NuGet Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:

Install-Package Microsoft.AspNet.WebApi.Cors

This command installs the latest package and updates all dependencies, including the core Web API libraries. Use the -Version flag to target a specific version. The CORS package requires Web API 2.0 or later.

Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method:

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Next, add the [EnableCors] attribute to your controller/ controller methods

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebService.Controllers
{
    [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...
    }
}

Enable Cross-Origin Requests (CORS) in ASP.NET Core

How to break out of while loop in Python?

A couple of changes mean that only an R or r will roll. Any other character will quit

import random

while True:
    print('Your score so far is {}.'.format(myScore))
    print("Would you like to roll or quit?")
    ans = input("Roll...")
    if ans.lower() == 'r':
        R = np.random.randint(1, 8)
        print("You rolled a {}.".format(R))
        myScore = R + myScore
    else:
        print("Now I'll see if I can break your score...")
        break

check if variable is dataframe

Use isinstance, nothing else:

if isinstance(x, pd.DataFrame):
    ... # do something

PEP8 says explicitly that isinstance is the preferred way to check types

No:  type(x) is pd.DataFrame
No:  type(x) == pd.DataFrame
Yes: isinstance(x, pd.DataFrame)

And don't even think about

if obj.__class__.__name__ = 'DataFrame':
    expect_problems_some_day()

isinstance handles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either str or unicode), because they derive from basestring)

if isinstance(obj, basestring):
    i_am_string(obj)

Specifically for pandas DataFrame objects:

import pandas as pd
isinstance(var, pd.DataFrame)

Convert PDF to clean SVG?

I am currently using PDFBox which has good support for graphic output. There is good support for extracting the vector strokes and also for managing fonts. There are some good tools for trying it out (e.g. PDFReader will display as Java Graphics2D). You can intercept the graphics tool with an SVG tool like Batik (I do this and it gives good capture).

There is no simple way to convert all PDF to SVG - it depends on the strategy and tools used to create the PDFs. Some text is converted to vectors and cannot be easily reconstructed - you have to install vector fonts and look them up.

UPDATE: I have now developed this into a package PDF2SVG which does not use Batik any more:

which has been tested on a range of PDFs. It produces SVG output consisting of

  • characters as one <svg:text> per character
  • paths as <svg:path>
  • images as <svg:image>

Later packages will (hopefully) convert the characters to running text and the paths to higher-level graphics objects

UPDATE: We can now re-create running text from the SVG characters. We've also converted diagrams to domain-specific XML (e.g. chemical spectra). See https://bitbucket.org/petermr/svg2xml-dev. It's still in Alpha, but is moving at a useful speed. Anyone can join in!

UPDATE. (@Tim Kelty) We are continuing to work on PDF2SVG and also downstream tools that do (limited) Java OCR and creation of higher-level graphics primitives (arrows, boxes, etc.) See https://bitbucket.org/petermr/imageanalysis https://bitbucket.org/petermr/diagramanalyzer https://bitbucket.org/petermr/norma and https://bitbucket.org/petermr/ami-core . This is a funded project to capture 100 million facts from the scientific literature (contentmine.org) much of which is PDF.

Using a BOOL property

Apple simply recommends declaring an isX getter for stylistic purposes. It doesn't matter whether you customize the getter name or not, as long as you use the dot notation or message notation with the correct name. If you're going to use the dot notation it makes no difference, you still access it by the property name:

@property (nonatomic, assign) BOOL working;

[self setWorking:YES];         // Or self.working = YES;
BOOL working = [self working]; // Or = self.working;

Or

@property (nonatomic, assign, getter=isWorking) BOOL working;

[self setWorking:YES];           // Or self.working = YES;, same as above
BOOL working = [self isWorking]; // Or = self.working;, also same as above

Undo git update-index --assume-unchanged <file>

Nothing here that is not covered. But would like to add my 2 cents. At times, I run a build and it changes lot of files and then I want to work on something, so this command really helps me a lot.

git update-index --assume-unchanged `git status | grep modified | sed 's|modified:||g'| xargs`

Hope someone else find it useful as well.

Fast way of finding lines in one file that are not in another?

You can achieve this by controlling the formatting of the old/new/unchanged lines in GNU diff output:

diff --new-line-format="" --unchanged-line-format=""  file1 file2

The input files should be sorted for this to work. With bash (and zsh) you can sort in-place with process substitution <( ):

diff --new-line-format="" --unchanged-line-format="" <(sort file1) <(sort file2)

In the above new and unchanged lines are suppressed, so only changed (i.e. removed lines in your case) are output. You may also use a few diff options that other solutions don't offer, such as -i to ignore case, or various whitespace options (-E, -b, -v etc) for less strict matching.


Explanation

The options --new-line-format, --old-line-format and --unchanged-line-format let you control the way diff formats the differences, similar to printf format specifiers. These options format new (added), old (removed) and unchanged lines respectively. Setting one to empty "" prevents output of that kind of line.

If you are familiar with unified diff format, you can partly recreate it with:

diff --old-line-format="-%L" --unchanged-line-format=" %L" \
     --new-line-format="+%L" file1 file2

The %L specifier is the line in question, and we prefix each with "+" "-" or " ", like diff -u (note that it only outputs differences, it lacks the --- +++ and @@ lines at the top of each grouped change). You can also use this to do other useful things like number each line with %dn.


The diff method (along with other suggestions comm and join) only produce the expected output with sorted input, though you can use <(sort ...) to sort in place. Here's a simple awk (nawk) script (inspired by the scripts linked-to in Konsolebox's answer) which accepts arbitrarily ordered input files, and outputs the missing lines in the order they occur in file1.

# output lines in file1 that are not in file2
BEGIN { FS="" }                         # preserve whitespace
(NR==FNR) { ll1[FNR]=$0; nl1=FNR; }     # file1, index by lineno
(NR!=FNR) { ss2[$0]++; }                # file2, index by string
END {
    for (ll=1; ll<=nl1; ll++) if (!(ll1[ll] in ss2)) print ll1[ll]
}

This stores the entire contents of file1 line by line in a line-number indexed array ll1[], and the entire contents of file2 line by line in a line-content indexed associative array ss2[]. After both files are read, iterate over ll1 and use the in operator to determine if the line in file1 is present in file2. (This will have have different output to the diff method if there are duplicates.)

In the event that the files are sufficiently large that storing them both causes a memory problem, you can trade CPU for memory by storing only file1 and deleting matches along the way as file2 is read.

BEGIN { FS="" }
(NR==FNR) {  # file1, index by lineno and string
  ll1[FNR]=$0; ss1[$0]=FNR; nl1=FNR;
}
(NR!=FNR) {  # file2
  if ($0 in ss1) { delete ll1[ss1[$0]]; delete ss1[$0]; }
}
END {
  for (ll=1; ll<=nl1; ll++) if (ll in ll1) print ll1[ll]
}

The above stores the entire contents of file1 in two arrays, one indexed by line number ll1[], one indexed by line content ss1[]. Then as file2 is read, each matching line is deleted from ll1[] and ss1[]. At the end the remaining lines from file1 are output, preserving the original order.

In this case, with the problem as stated, you can also divide and conquer using GNU split (filtering is a GNU extension), repeated runs with chunks of file1 and reading file2 completely each time:

split -l 20000 --filter='gawk -f linesnotin.awk - file2' < file1

Note the use and placement of - meaning stdin on the gawk command line. This is provided by split from file1 in chunks of 20000 line per-invocation.

For users on non-GNU systems, there is almost certainly a GNU coreutils package you can obtain, including on OSX as part of the Apple Xcode tools which provides GNU diff, awk, though only a POSIX/BSD split rather than a GNU version.

How to set css style to asp.net button?

I Found the coding...

 input[type="submit"]
    {
     //css coding
    }
 input[type="submit"]:Hover  
    {
     //css coding
    }

This is the solution for my issue..... Thanks everyone for the valuable answers.......

Use Awk to extract substring

You don't need awk for this...

echo aaa0.bbb.ccc | cut -d. -f1
cut -d. -f1 <<< aaa0.bbb.ccc

echo aaa0.bbb.ccc | { IFS=. read a _ ; echo $a ; }
{ IFS=. read a _ ; echo $a ; } <<< aaa0.bbb.ccc 

x=aaa0.bbb.ccc; echo ${x/.*/}

Heavier options:

sed:
echo aaa0.bbb.ccc | sed 's/\..*//'
sed 's/\..*//' <<< aaa0.bbb.ccc 
awk:
echo aaa0.bbb.ccc | awk -F. '{print $1}'
awk -F. '{print $1}' <<< aaa0.bbb.ccc 

How to change color of Toolbar back button in Android?

You don't have to change style for it. After setting up your toolbar as actionbar, You can code like this

android.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
android.getSupportActionBar().setHomeAsUpIndicator(R.drawable.back);
//here back is your drawable image

But You cannot change color of back arrow by this method

Get Line Number of certain phrase in file Python

You can use list comprehension:

content = open("path/to/file.txt").readlines()

lookup = 'the dog barked'

lines = [line_num for line_num, line_content in enumerate(content) if lookup in line_content]

print(lines)

How do I exit a foreach loop in C#?

Just use the statement:

break;

Simple prime number generator in Python

SymPy is a Python library for symbolic mathematics. It provides several functions to generate prime numbers.

isprime(n)              # Test if n is a prime number (True) or not (False).

primerange(a, b)        # Generate a list of all prime numbers in the range [a, b).
randprime(a, b)         # Return a random prime number in the range [a, b).
primepi(n)              # Return the number of prime numbers less than or equal to n.

prime(nth)              # Return the nth prime, with the primes indexed as prime(1) = 2. The nth prime is approximately n*log(n) and can never be larger than 2**n.
prevprime(n, ith=1)     # Return the largest prime smaller than n
nextprime(n)            # Return the ith prime greater than n

sieve.primerange(a, b)  # Generate all prime numbers in the range [a, b), implemented as a dynamically growing sieve of Eratosthenes. 

Here are some examples.

>>> import sympy
>>> 
>>> sympy.isprime(5)
True
>>> list(sympy.primerange(0, 100))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
>>> sympy.randprime(0, 100)
83
>>> sympy.randprime(0, 100)
41
>>> sympy.prime(3)
5
>>> sympy.prevprime(50)
47
>>> sympy.nextprime(50)
53
>>> list(sympy.sieve.primerange(0, 100))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

How do I remove the space between inline/inline-block elements?

I tried out the font-size: 0 solution to a similar problem in React and Sass for a Free Code Camp project I am currently working through.

And it works!

First, the script:

var ActionBox = React.createClass({
    render: function() {
        return(
            <div id="actionBox">
                </div>
        );
    },
});

var ApplicationGrid = React.createClass({
    render: function() {
        var row = [];
        for(var j=0; j<30; j++){
            for(var i=0; i<30; i++){
                row.push(<ActionBox />);
            }
        }
        return(
            <div id="applicationGrid">
                {row}
            </div>
        );
     },
});

var ButtonsAndGrid = React.createClass({
    render: function() {
        return(
            <div>
                <div id="buttonsDiv">
                </div>
                <ApplicationGrid />
            </div>
        );
    },
});

var MyApp = React.createClass({
    render: function() {
        return(
            <div id="mainDiv">
                <h1> Game of Life! </h1>
                <ButtonsAndGrid />
            </div>
        );
    },
});

ReactDOM.render(
    <MyApp />,
    document.getElementById('GoL')
);

Then, the Sass:

html, body
    height: 100%

body
    height: 100%
    margin: 0
    padding: 0

#mainDiv
    width: 80%
    height: 60%
    margin: auto
    padding-top: 5px
    padding-bottom: 5px
    background-color: DeepSkyBlue
    text-align: center
    border: 2px solid #381F0B
    border-radius: 4px
    margin-top: 20px

#buttonsDiv
    width: 80%
    height: 60%
    margin: auto
    margin-bottom: 0px
    padding-top: 5px
    padding-bottom: 0px
    background-color: grey
    text-align: center
    border: 2px solid #381F0B
    border-radius: 4px
    margin-top: 20px

#applicationGrid
    width: 65%
    height: 50%
    padding-top: 0px
    margin: auto
    font-size: 0
    margin-top: 0px
    padding-bottom: 5px
    background-color: white
    text-align: center
    border: 2px solid #381F0B
    border-radius: 4px
    margin-top: 20px

#actionBox
    width: 20px
    height: 20PX
    padding-top: 0px
    display: inline-block
    margin-top: 0px
    padding-bottom: 0px
    background-color: lightgrey
    text-align: center
    border: 2px solid grey
    margin-bottom: 0px

MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Try this (on Windows, i don't know how in others), if you have changed password a now don't work.

1) kill mysql 2) back up /mysql/data folder 3) go to folder /mysql/backup 4) copy files from /mysql/backup/mysql folder to /mysql/data/mysql (rewrite) 5) run mysql

In my XAMPP on Win7 it works.

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

Make sure you run the command

docker build . -t docker-whale 

from the directory that has the dockerfile

How do I sort a list of dictionaries by a value of the dictionary?

Here is the alternative general solution - it sorts elements of a dict by keys and values.

The advantage of it - no need to specify keys, and it would still work if some keys are missing in some of dictionaries.

def sort_key_func(item):
    """ Helper function used to sort list of dicts

    :param item: dict
    :return: sorted list of tuples (k, v)
    """
    pairs = []
    for k, v in item.items():
        pairs.append((k, v))
    return sorted(pairs)
sorted(A, key=sort_key_func)

How do you use youtube-dl to download live streams (that are live)?

I'll be using this Live Event from NASA TV as an example:

https://www.youtube.com/watch?v=21X5lGlDOfg

First, list the formats for the video:

$  ~ youtube-dl --list-formats https://www.youtube.com/watch\?v\=21X5lGlDOfg
[youtube] 21X5lGlDOfg: Downloading webpage
[youtube] 21X5lGlDOfg: Downloading m3u8 information
[youtube] 21X5lGlDOfg: Downloading MPD manifest
[info] Available formats for 21X5lGlDOfg:
format code  extension  resolution note
91           mp4        256x144    HLS  197k , avc1.42c00b, 30.0fps, mp4a.40.5@ 48k
92           mp4        426x240    HLS  338k , avc1.4d4015, 30.0fps, mp4a.40.5@ 48k
93           mp4        640x360    HLS  829k , avc1.4d401e, 30.0fps, mp4a.40.2@128k
94           mp4        854x480    HLS 1380k , avc1.4d401f, 30.0fps, mp4a.40.2@128k
300          mp4        1280x720   3806k , avc1.4d4020, 60.0fps, mp4a.40.2 (best)

Pick the format you wish to download, and fetch the HLS m3u8 URL of the video from the manifest. I'll be using 94 mp4 854x480 HLS 1380k , avc1.4d401f, 30.0fps, mp4a.40.2@128k for this example:

?  ~ youtube-dl -f 94 -g https://www.youtube.com/watch\?v\=21X5lGlDOfg
https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1592099895/ei/1y_lXuLOEsnXyQWYs4GABw/ip/81.190.155.248/id/21X5lGlDOfg.3/itag/94/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/goi/160/sgoap/gir%3Dyes%3Bitag%3D140/sgovp/gir%3Dyes%3Bitag%3D135/hls_chunk_host/r5---sn-h0auphxqp5-f5fs.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/8270/mh/N8/mm/44/mn/sn-h0auphxqp5-f5fs/ms/lva/mv/m/mvi/4/pl/16/dover/11/keepalive/yes/beids/9466586/mt/1592078245/disable_polymer/true/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,goi,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAM2dGSece2shUTgS73Qa3KseLqnf85ca_9u7Laz7IDfSAiEAj8KHw_9xXVS_PV3ODLlwDD-xfN6rSOcLVNBpxKgkRLI%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRQIhAJCO6kSwn7PivqMW7sZaiYFvrultXl6Qmu9wppjCvImzAiA7vkub9JaanJPGjmB4qhLVpHJOb9fZyhMEeh1EUCd-3Q%3D%3D/playlist/index.m3u8

Note that link could be different and it contains expiration timestamp, in this case 1592099895 (about 6 hours).

Now that you have the HLS playlist, you can open this URL in VLC and save it using "Record", or write a small ffmpeg command:

ffmpeg -i \
https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1592099895/ei/1y_lXuLOEsnXyQWYs4GABw/ip/81.190.155.248/id/21X5lGlDOfg.3/itag/94/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/goi/160/sgoap/gir%3Dyes%3Bitag%3D140/sgovp/gir%3Dyes%3Bitag%3D135/hls_chunk_host/r5---sn-h0auphxqp5-f5fs.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/8270/mh/N8/mm/44/mn/sn-h0auphxqp5-f5fs/ms/lva/mv/m/mvi/4/pl/16/dover/11/keepalive/yes/beids/9466586/mt/1592078245/disable_polymer/true/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,goi,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAM2dGSece2shUTgS73Qa3KseLqnf85ca_9u7Laz7IDfSAiEAj8KHw_9xXVS_PV3ODLlwDD-xfN6rSOcLVNBpxKgkRLI%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRQIhAJCO6kSwn7PivqMW7sZaiYFvrultXl6Qmu9wppjCvImzAiA7vkub9JaanJPGjmB4qhLVpHJOb9fZyhMEeh1EUCd-3Q%3D%3D/playlist/index.m3u8 \
-c copy output.ts

Rename all files in directory from $filename_h to $filename_half?

Although the answer set is complete, I need to add another missing one.

for i in *_h.png;
  do name=`echo "$i" | cut -d'_' -f1`
  echo "Executing of name $name" 
  mv "$i" "${name}_half.png"
done

How can I group by date time column without taking time into consideration

Here's an example that I used when I needed to count the number of records for a particular date without the time portion:

select count(convert(CHAR(10), dtcreatedate, 103) ),convert(char(10), dtcreatedate, 103)
FROM dbo.tbltobecounted
GROUP BY CONVERT(CHAR(10),dtcreatedate,103)
ORDER BY CONVERT(CHAR(10),dtcreatedate,103)

No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0

I hit this recently and remember where it comes from. It's a mismatch between the Xamarin.Android.* version and the installed Android SDK version.

The current VS2017 15.5.3 new project defaults for nuGet Xamarin.Android.* are 25.4.0.2 and the default VS install for cross platform development are the following Android SDK packages:

  • Android 7.1 - Nougat
    • Android SDK Platform 25
    • Google APIs Intel x86 Atom System Image

If you upgraded you solution nuGet for Xamarin.Android.* to 26.1.0.1 then you will need to install the follow in the Android SDK:

  • Android 8.0 - Oreo
    • Android SDK Platform 26
    • Google APIs Intel x86 Atom System Image

How to check if click event is already bound - JQuery

JQuery has solution:

$( "#foo" ).one( "click", function() {
  alert( "This will be displayed only once." );
}); 

equivalent:

$( "#foo" ).on( "click", function( event ) {
  alert( "This will be displayed only once." );
  $( this ).off( event );
});

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

user8657661's answer is closest to my needs (of lining things up across several lines). However, I couldn't get the example code to work as provided, but I needed to change it as follows:

<html>
    <head>
        <style>
            .tab9 {position:absolute;left:150px; }
        </style>
    </head>

    <body>
        Dog Food: <span class="tab9"> $30</span><br/>
        Milk of Magnesia:<span class="tab9"> $30</span><br/>
        Pizza Kit:<span class="tab9"> $5</span><br/>
        Mt Dew <span class="tab9"> $1.75</span><br/>
    </body>
</html>

If you need right-aligned numbers you can change left:150px to right:150px, but you'll need to alter the number based on the width of the screen (as written the numbers would be 150 pixels from the right edge of the screen).

Java URLConnection Timeout

Are you on Windows? The underlying socket implementation on Windows seems not to support the SO_TIMEOUT option very well. See also this answer: setSoTimeout on a client socket doesn't affect the socket

How to compare binary files to check if they are the same?

Try diff -s

Short answer: run diff with the -s switch.

Long answer: read on below.


Here's an example. Let's start by creating two files with random binary contents:

$ dd if=/dev/random bs=1k count=1 of=test1.bin
1+0 records in
1+0 records out
1024 bytes (1,0 kB, 1,0 KiB) copied, 0,0100332 s, 102 kB/s

                                                                                  
$ dd if=/dev/random bs=1k count=1 of=test2.bin
1+0 records in
1+0 records out
1024 bytes (1,0 kB, 1,0 KiB) copied, 0,0102889 s, 99,5 kB/s

Now let's make a copy of the first file:

$ cp test1.bin copyoftest1.bin

Now test1.bin and test2.bin should be different:

$ diff test1.bin test2.bin
Binary files test1.bin and test2.bin differ

... and test1.bin and copyoftest1.bin should be identical:

$ diff test1.bin copyoftest1.bin

But wait! Why is there no output?!?

The answer is: this is by design. There is no output on identical files.

But there are different error codes:

$ diff test1.bin test2.bin
Binary files test1.bin and test2.bin differ

$ echo $?
1


$ diff test1.bin copyoftest1.bin

$ echo $?
0

Now fortunately you don't have to check error codes each and every time because you can just use the -s (or --report-identical-files) switch to make diff be more verbose:

$ diff -s test1.bin copyoftest1.bin
Files test1.bin and copyoftest1.bin are identical

Check if two unordered lists are equal

If elements are always nearly sorted as in your example then builtin .sort() (timsort) should be fast:

>>> a = [1,1,2]
>>> b = [1,2,2]
>>> a.sort()
>>> b.sort()
>>> a == b
False

If you don't want to sort inplace you could use sorted().

In practice it might always be faster then collections.Counter() (despite asymptotically O(n) time being better then O(n*log(n)) for .sort()). Measure it; If it is important.

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

Look at the r.status_code attribute:

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

Demo:

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

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

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

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

if r:
    # successful response

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

Getter and Setter of Model object in Angular 4

The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date') declare the date property like so: private _date: string;. Also, make sure you are instantiating the model with the new keyword. Lastly, access the property using regular dot notation.

Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :

let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}

And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview

Pass Javascript variable to PHP via ajax

Since you're not using JSON as the data type no your AJAX call, I would assume that you can't access the value because the PHP you gave will only ever be true or false. isset is a function to check if something exists and has a value, not to get access to the value.

Change your PHP to be:

$uid = (isset($_POST['userID'])) ? $_POST['userID'] : 0;

The above line will check to see if the post variable exists. If it does exist it will set $uid to equal the posted value. If it does not exist then it will set $uid equal to 0.

Later in your code you can check the value of $uid and react accordingly

if($uid==0) {
    echo 'User ID not found';
}

This will make your code more readable and also follow what I consider to be best practices for handling data in PHP.

How to add an element to a list?

I would do this:

data["list"].append({'b':'2'})

so simply you are adding an object to the list that is present in "data"

Hiding button using jQuery

Try this:

$('input[name=Comanda]')
.click(
     function ()
     {
         $(this).hide();
     }
);

For doing everything else you can use something like this one:

$('input[name=Comanda]')
.click(
     function ()
     {
         $(this).hide();

         $(".ClassNameOfShouldBeHiddenElements").hide();
     }
);

For hidding any other elements based on their IDs, use this one:

$('input[name=Comanda]')
.click(
     function ()
     {
         $(this).hide();

         $("#FirstElement").hide();
         $("#SecondElement").hide();
         $("#ThirdElement").hide();
     }
);

Using variables inside strings

Up to C#5 (-VS2013) you have to call a function/method for it. Either a "normal" function such as String.Format or an overload of the + operator.

string str = "Hello " + name; // This calls an overload of operator +.

In C#6 (VS2015) string interpolation has been introduced (as described by other answers).

How can I git stash a specific file?

I usually add to index changes I don't want to stash and then stash with --keep-index option.

git add app/controllers/cart_controller.php
git stash --keep-index
git reset

Last step is optional, but usually you want it. It removes changes from index.


Warning As noted in the comments, this puts everything into the stash, both staged and unstaged. The --keep-index just leaves the index alone after the stash is done. This can cause merge conflicts when you later pop the stash.

Initial size for the ArrayList

Being late to this, but after Java 8, I personally find this following approach with the Stream API more concise and can be an alternative to the accepted answer.

For example,

Arrays.stream(new int[size]).boxed().collect(Collectors.toList())

where size is the desired List size and without the disadvantage mentioned here, all elements in the List are initialized as 0.

(I did a quick search and did not see stream in any answers posted - feel free to let me know if this answer is redundant and I can remove it)

How do you add a Dictionary of items into another Dictionary

A more readable variant using an extension.

extension Dictionary {    
    func merge(dict: Dictionary<Key,Value>) -> Dictionary<Key,Value> {
        var mutableCopy = self        
        for (key, value) in dict {
            // If both dictionaries have a value for same key, the value of the other dictionary is used.           
            mutableCopy[key] = value 
        }        
        return mutableCopy
    }    
}

Python urllib2: Receive JSON response from url

resource_url = 'http://localhost:8080/service/'
response = json.loads(urllib2.urlopen(resource_url).read())

Where to change default pdf page width and font size in jspdf.debug.js?

For anyone trying to this in react. There is a slight difference.

// Document of 8.5 inch width and 11 inch high
new jsPDF('p', 'in', [612, 792]);

or

// Document of 8.5 inch width and 11 inch high
new jsPDF({
        orientation: 'p', 
        unit: 'in', 
        format: [612, 792]
});

When i tried the @Aidiakapi solution the pages were tiny. For a difference size take size in inches * 72 to get the dimensions you need. For example, i wanted 8.5 so 8.5 * 72 = 612. This is for [email protected].

Xcode 10, Command CodeSign failed with a nonzero exit code

What worked for me - found elsewhere - was very simple:

flutter clean

(run it in Terminal from the base dir of the project)

Note that Clean Project in XCode did not make a difference, tried that first.

I can't delete a remote master branch on git

The quickest way is to switch default branch from master to another and you can remove master branch from the web interface.

Java Returning method which returns arraylist?

List<Integer> numbers = new TheClassName().myNumbers();

How to negate the whole regex?

\b(?=\w)(?!(ma|(t){1}))\b(\w*)

this is for the given regex.
the \b is to find word boundary.
the positive look ahead (?=\w) is here to avoid spaces.
the negative look ahead over the original regex is to prevent matches of it.
and finally the (\w*) is to catch all the words that are left.
the group that will hold the words is group 3.
the simple (?!pattern) will not work as any sub-string will match
the simple ^(?!(?:m{2}|t)$).*$ will not work as it's granularity is full lines

Set disable attribute based on a condition for Html.TextBoxFor

I achieved it using some extension methods

private const string endFieldPattern = "^(.*?)>";

    public static MvcHtmlString IsDisabled(this MvcHtmlString htmlString, bool disabled)
    {
        string rawString = htmlString.ToString();
        if (disabled)
        {
            rawString = Regex.Replace(rawString, endFieldPattern, "$1 disabled=\"disabled\">");
        }

        return new MvcHtmlString(rawString);
    }

    public static MvcHtmlString IsReadonly(this MvcHtmlString htmlString, bool @readonly)
    {
        string rawString = htmlString.ToString();
        if (@readonly)
        {
            rawString = Regex.Replace(rawString, endFieldPattern, "$1 readonly=\"readonly\">");
        }

        return new MvcHtmlString(rawString);
    }

and then....

@Html.TextBoxFor(model => model.Name, new { @class= "someclass"}).IsDisabled(Model.ExpireDate == null)

How to get the current working directory using python 3?

It seems that IDLE changes its current working dir to location of the script that is executed, while when running the script using cmd doesn't do that and it leaves CWD as it is.

To change current working dir to the one containing your script you can use:

import os
os.chdir(os.path.dirname(__file__))
print(os.getcwd())

The __file__ variable is available only if you execute script from file, and it contains path to the file. More on it here: Python __file__ attribute absolute or relative?

Retrieving Dictionary Value Best Practices

TryGetValue is slightly faster, because FindEntry will only be called once.

How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.

FYI: It's not actually catching an error.

It's calling:

public bool TryGetValue(TKey key, out TValue value)
{
    int index = this.FindEntry(key);
    if (index >= 0)
    {
        value = this.entries[index].value;
        return true;
    }
    value = default(TValue);
    return false;
}

ContainsKey is this:

public bool ContainsKey(TKey key)
{
    return (this.FindEntry(key) >= 0);
}

Copying files from server to local computer using SSH

It depends on what your local OS is.

If your local OS is Unix-like, then try:

scp username@remoteHost:/remote/dir/file.txt /local/dir/

If your local OS is Windows ,then you should use pscp.exe utility. For example, below command will download file.txt from remote to D: disk of local machine.

pscp.exe username@remoteHost:/remote/dir/file.txt d:\

It seems your Local OS is Unix, so try the former one.


For those who don't know what pscp.exe is and don't know where it is, you can always go to putty official website to download it. And then open a CMD prompt, go to the pscp.exe directory where you put it. Then execute the command as provided above

How to step through Python code to help debug issues?

Starting in Python 3.7, you can use the breakpoint() built-in function to enter the debugger:

foo()
breakpoint()  # drop into the debugger at this point
bar()

By default, breakpoint() will import pdb and call pdb.set_trace(). However, you can control debugging behavior via sys.breakpointhook() and use of the environment variable PYTHONBREAKPOINT.

See PEP 553 for more information.

How can I loop through a List<T> and grab each item?

foreach:

foreach (var money in myMoney) {
    Console.WriteLine("Amount is {0} and type is {1}", money.amount, money.type);
}

MSDN Link

Alternatively, because it is a List<T>.. which implements an indexer method [], you can use a normal for loop as well.. although its less readble (IMO):

for (var i = 0; i < myMoney.Count; i++) {
    Console.WriteLine("Amount is {0} and type is {1}", myMoney[i].amount, myMoney[i].type);
}

How do I make a C++ console program exit?

exit(0); // at the end of main function before closing curly braces

Android AudioRecord example

Here I am posting you the some code example which record good quality of sound using AudioRecord API.

Note: If you use in emulator the sound quality will not much good because we are using sample rate 8k which only supports in emulator. In device use sample rate to 44.1k for better quality.

public class Audio_Record extends Activity {
    private static final int RECORDER_SAMPLERATE = 8000;
    private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
    private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
    private AudioRecord recorder = null;
    private Thread recordingThread = null;
    private boolean isRecording = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        setButtonHandlers();
        enableButtons(false);

        int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,
                RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING); 
    }

    private void setButtonHandlers() {
        ((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
        ((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick);
    }

    private void enableButton(int id, boolean isEnable) {
        ((Button) findViewById(id)).setEnabled(isEnable);
    }

    private void enableButtons(boolean isRecording) {
        enableButton(R.id.btnStart, !isRecording);
        enableButton(R.id.btnStop, isRecording);
    }

    int BufferElements2Rec = 1024; // want to play 2048 (2K) since 2 bytes we use only 1024
    int BytesPerElement = 2; // 2 bytes in 16bit format

    private void startRecording() {

        recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
                RECORDER_SAMPLERATE, RECORDER_CHANNELS,
                RECORDER_AUDIO_ENCODING, BufferElements2Rec * BytesPerElement);

        recorder.startRecording();
        isRecording = true;
        recordingThread = new Thread(new Runnable() {
            public void run() {
                writeAudioDataToFile();
            }
        }, "AudioRecorder Thread");
        recordingThread.start();
    }

        //convert short to byte
    private byte[] short2byte(short[] sData) {
        int shortArrsize = sData.length;
        byte[] bytes = new byte[shortArrsize * 2];
        for (int i = 0; i < shortArrsize; i++) {
            bytes[i * 2] = (byte) (sData[i] & 0x00FF);
            bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
            sData[i] = 0;
        }
        return bytes;

    }

    private void writeAudioDataToFile() {
        // Write the output audio in byte

        String filePath = "/sdcard/voice8K16bitmono.pcm";
        short sData[] = new short[BufferElements2Rec];

        FileOutputStream os = null;
        try {
            os = new FileOutputStream(filePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        while (isRecording) {
            // gets the voice output from microphone to byte format

            recorder.read(sData, 0, BufferElements2Rec);
            System.out.println("Short writing to file" + sData.toString());
            try {
                // // writes the data to file from buffer
                // // stores the voice buffer
                byte bData[] = short2byte(sData);
                os.write(bData, 0, BufferElements2Rec * BytesPerElement);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void stopRecording() {
        // stops the recording activity
        if (null != recorder) {
            isRecording = false;
            recorder.stop();
            recorder.release();
            recorder = null;
            recordingThread = null;
        }
    }

    private View.OnClickListener btnClick = new View.OnClickListener() {
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.btnStart: {
                enableButtons(true);
                startRecording();
                break;
            }
            case R.id.btnStop: {
                enableButtons(false);
                stopRecording();
                break;
            }
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}

For more detail try this AUDIORECORD BLOG.

Happy Coding !!

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

I think this will work even though this was forever ago.

SELECT employee_number, Row_Number()  
   OVER (PARTITION BY course_code ORDER BY course_completion_date DESC ) as rownum
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
   AND rownum = 1

If you want to get the last Id if the date is the same then you can use this assuming your primary key is Id.

SELECT employee_number, Row_Number()  
   OVER (PARTITION BY course_code ORDER BY course_completion_date DESC, Id Desc) as rownum    FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
   AND rownum = 1

How to execute cmd commands via Java

Here is a simpler example that does not require multiple threads:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class SimplePty
{
    public SimplePty(Process process) throws IOException
    {
        while (process.isAlive())
        {
            sync(process.getErrorStream(), System.err);
            sync(process.getInputStream(), System.out);
            sync(System.in, process.getOutputStream());
        }
    }
    
    private void sync(InputStream in, OutputStream out) throws IOException
    {
        while (in.available() > 0)
        {
            out.write(in.read());
            out.flush();
        }
    }
    
    public static void main( String[] args ) throws IOException
    {
        String os = System.getProperty("os.name").toLowerCase();
        String shell = os.contains("win") ? "cmd" : "bash";
        Process process = new ProcessBuilder(shell).start();
        new SimplePty(process);
    }
}

HTTP Error 503, the service is unavailable

In my case the problem was the DefaultAppPool. I changed the "Load User Profile" to false and now it works. However, I don't know if there are side effects to this. enter image description here

Get the index of a certain value in an array in PHP

array_search should work fine, just tested this and it returns the keys as expected:

$list = array('string1', 'string2', 'string3');
echo "Key = ".array_search('string1', $list);
echo " Key = ".array_search('string2', $list);
echo " Key = ".array_search('string3', $list);

Or for the index, you could use

$list = array('string1', 'string2', 'string3');
echo "Index = ".array_search('string1', array_merge($list));
echo " Index = ".array_search('string2', array_merge($list));
echo " Index = ".array_search('string3', array_merge($list));

Trying to get property of non-object in

$sidemenu is not an object, so you can't call methods on it. It is probably not being sent to your view, or $sidemenus is empty.

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

You must set Access-Control-Allow-Credentials: true, if you want to use "cookie" via "Credentials"

app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

Convert to Datetime MM/dd/yyyy HH:mm:ss in Sql Server

use

select convert(varchar(10),GETDATE(), 103) + 
       ' '+
       right(convert(varchar(32),GETDATE(),108),8) AS Date_Time

It will Produce:

Date_Time 30/03/2015 11:51:40

C++ convert from 1 char to string?

All of

std::string s(1, c); std::cout << s << std::endl;

and

std::cout << std::string(1, c) << std::endl;

and

std::string s; s.push_back(c); std::cout << s << std::endl;

worked for me.

How can I get the MAC and the IP address of a connected client in PHP?

Use this class (https://github.com/BlakeGardner/php-mac-address)

This is a PHP class for MAC address manipulation on top of Unix, Linux and Mac OS X operating systems. it was primarily written to help with spoofing for wireless security audits.

background: fixed no repeat not working on mobile

This is what i do and it works everythere :)

.container {
  background: url(${myImage})
  background-attachment: fixed;
  background-size: cover;
 transform: scale(1.1, 1.1);

}

then...

@media only screen and (max-width: 768px){
   background-size: 100% 100vh;
}

pandas: filter rows of DataFrame with operator chaining

I had the same question except that I wanted to combine the criteria into an OR condition. The format given by Wouter Overmeire combines the criteria into an AND condition such that both must be satisfied:

In [96]: df
Out[96]:
   A  B  C  D
a  1  4  9  1
b  4  5  0  2
c  5  5  1  0
d  1  3  9  6

In [99]: df[(df.A == 1) & (df.D == 6)]
Out[99]:
   A  B  C  D
d  1  3  9  6

But I found that, if you wrap each condition in (... == True) and join the criteria with a pipe, the criteria are combined in an OR condition, satisfied whenever either of them is true:

df[((df.A==1) == True) | ((df.D==6) == True)]

How do Python functions handle the types of the parameters that you pass in?

Python is not strongly typed in the sense of static or compile-time type checking.

Most Python code falls under so-called "Duck Typing" -- for example, you look for a method read on an object -- you don't care if the object is a file on disk or a socket, you just want to read N bytes from it.

Any way to write a Windows .bat file to kill processes?

Download PSKill. Write a batch file that calls it for each process you want dead, passing in the name of the process for each.

How to do a less than or equal to filter in Django queryset?

Less than or equal:

User.objects.filter(userprofile__level__lte=0)

Greater than or equal:

User.objects.filter(userprofile__level__gte=0)

Likewise, lt for less than and gt for greater than. You can find them all in the documentation.

Return outside function error in Python

You can only return from inside a function and not from a loop.

It seems like your return should be outside the while loop, and your complete code should be inside a function.

def func():
    N = int(input("enter a positive integer:"))
    counter = 1
    while (N > 0):
        counter = counter * N
        N -= 1
    return counter  # de-indent this 4 spaces to the left.

print func()

And if those codes are not inside a function, then you don't need a return at all. Just print the value of counter outside the while loop.

How to get Url Hash (#) from server side

RFC 2396 section 4.1:

When a URI reference is used to perform a retrieval action on the identified resource, the optional fragment identifier, separated from the URI by a crosshatch ("#") character, consists of additional reference information to be interpreted by the user agent after the retrieval action has been successfully completed. As such, it is not part of a URI, but is often used in conjunction with a URI.

(emphasis added)

Installing a pip package from within a Jupyter Notebook not working

! pip install --user <package>

The ! tells the notebook to execute the cell as a shell command.

How to get current user in asp.net core

It would appear that as of now (April of 2017) that the following works:

public string LoggedInUser => User.Identity.Name;

At least while within a Controller

Running python script inside ipython

In python there is no difference between modules and scripts; You can execute both scripts and modules. The file must be on the pythonpath AFAIK because python must be able to find the file in question. If python is executed from a directory, then the directory is automatically added to the pythonpath.

Refer to What is the best way to call a Python script from another Python script? for more information about modules vs scripts

There is also a builtin function execfile(filename) that will do what you want

Cannot bulk load. Operating system error code 5 (Access is denied.)

  1. Go to start run=>services.msc=>SQL SERVER(MSSQLSERVER) stop the service
  2. Right click on SQL SERVER(MSSQLSERVER)=> properties=>LogOn Tab=>Local System Account=>OK
  3. Restart the SQL server Management Studio.

add new element in laravel collection object

If you want to add item to the beginning of the collection you can use prepend:

$item->prepend($product, 'key');

Angular 2: Get Values of Multiple Checked Checkboxes

Since I spent a long time solving a similar problem, I'm answering to share my experience. My problem was the same, to know, getting many checkboxes value after a specified event has been triggered. I tried a lot of solutions but for me the sexiest is using ViewChildren.

import { ViewChildren, QueryList } from '@angular/core';

/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components: QueryList<any>;

ngAfterViewInit(){
    // print array of CustomComponent objects
    console.log(this.components.toArray());
}

Found here: https://stackoverflow.com/a/40165639/4775727

Potential other solutions for ref, there are a lot of similar topic, none of them purpose this solution...:

How do I export (and then import) a Subversion repository?

The tool to do that would be

svnadmin dump

But for this to work, you need filesystem-access to the repository. And once you have that (and provided the repository is in FSFS format), you can just copy the repository to its new location (if it's in BDB format, dump/load is strongly recommended).

If you do not have filesystem access, you would have to ask your repository provider to provide the dump for you (and make them delete their repository - and hope they comply)

Set default value of javascript object attributes

Object.withDefault = (defaultValue,o={}) => {
  return new Proxy(o, {
    get: (o, k) => (k in o) ? o[k] : defaultValue 
  });
}

o = Object.withDefault(42);
o.x  //=> 42

o.x = 10
o.x  //=> 10
o.xx //=> 42

Save Dataframe to csv directly to s3 Python

This is a more up to date answer:

import s3fs

s3 = s3fs.S3FileSystem(anon=False)

# Use 'w' for py3, 'wb' for py2
with s3.open('<bucket-name>/<filename>.csv','w') as f:
    df.to_csv(f)

The problem with StringIO is that it will eat away at your memory. With this method, you are streaming the file to s3, rather than converting it to string, then writing it into s3. Holding the pandas dataframe and its string copy in memory seems very inefficient.

If you are working in an ec2 instant, you can give it an IAM role to enable writing it to s3, thus you dont need to pass in credentials directly. However, you can also connect to a bucket by passing credentials to the S3FileSystem() function. See documention:https://s3fs.readthedocs.io/en/latest/

What is a web service endpoint?

This is a shorter and hopefully clearer answer... Yes, the endpoint is the URL where your service can be accessed by a client application. The same web service can have multiple endpoints, for example in order to make it available using different protocols.

How do I animate constraint changes?

// Step 1, update your constraint
self.myOutletToConstraint.constant = 50; // New height (for example)

// Step 2, trigger animation
[UIView animateWithDuration:2.0 animations:^{

    // Step 3, call layoutIfNeeded on your animated view's parent
    [self.view layoutIfNeeded];
}];

How do I tell if .NET 3.5 SP1 is installed?

Assuming that the name is everywhere "Microsoft .NET Framework 3.5 SP1", you can use this:

string uninstallKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(uninstallKey))
{
    return rk.GetSubKeyNames().Contains("Microsoft .NET Framework 3.5 SP1");
}

How to get all key in JSON object (javascript)

I use Object.keys which is built into JavaScript Object, it will return an array of keys from given object MDN Reference

var obj = {name: "Jeeva", age: "22", gender: "Male"}
console.log(Object.keys(obj))

How to make div same height as parent (displayed as table-cell)

You have to set the height for the parents (container and child) explicitly, here is another work-around (if you don't want to set that height explicitly):

.child {
  width: 30px;
  background-color: red;
  display: table-cell;
  vertical-align: top;
  position:relative;
}

.content {
  position:absolute;
  top:0;
  bottom:0;
  width:100%;
  background-color: blue;
}

Fiddle

How to convert a string to an integer in JavaScript?

There are two main ways to convert a string to a number in javascript. One way is to parse it and the other way is to change its type to a Number. All of the tricks in the other answers (e.g. unary plus) involve implicitly coercing the type of the string to a number. You can also do the same thing explicitly with the Number function.

Parsing

var parsed = parseInt("97", 10);

parseInt and parseFloat are the two functions used for parsing strings to numbers. Parsing will stop silently if it hits a character it doesn't recognise, which can be useful for parsing strings like "92px", but it's also somewhat dangerous, since it won't give you any kind of error on bad input, instead you'll get back NaN unless the string starts with a number. Whitespace at the beginning of the string is ignored. Here's an example of it doing something different to what you want, and giving no indication that anything went wrong:

var widgetsSold = parseInt("97,800", 10); // widgetsSold is now 97

It's good practice to always specify the radix as the second argument. In older browsers, if the string started with a 0, it would be interpreted as octal if the radix wasn't specified which took a lot of people by surprise. The behaviour for hexadecimal is triggered by having the string start with 0x if no radix is specified, e.g. 0xff. The standard actually changed with ecmascript 5, so modern browsers no longer trigger octal when there's a leading 0 if no radix has been specified. parseInt understands radixes up to base 36, in which case both upper and lower case letters are treated as equivalent.

Changing the Type of a String to a Number

All of the other tricks mentioned above that don't use parseInt, involve implicitly coercing the string into a number. I prefer to do this explicitly,

var cast = Number("97");

This has different behavior to the parse methods (although it still ignores whitespace). It's more strict: if it doesn't understand the whole of the string than it returns NaN, so you can't use it for strings like 97px. Since you want a primitive number rather than a Number wrapper object, make sure you don't put new in front of the Number function.

Obviously, converting to a Number gives you a value that might be a float rather than an integer, so if you want an integer, you need to modify it. There are a few ways of doing this:

var rounded = Math.floor(Number("97.654"));  // other options are Math.ceil, Math.round
var fixed = Number("97.654").toFixed(0); // rounded rather than truncated
var bitwised = Number("97.654")|0;  // do not use for large numbers

Any bitwise operator (here I've done a bitwise or, but you could also do double negation as in an earlier answer or a bitshift) will convert the value to a 32bit integer, and most of them will convert to a signed integer. Note that this will not do want you want for large integers. If the integer cannot be represented in 32bits, it will wrap.

~~"3000000000.654" === -1294967296
// This is the same as
Number("3000000000.654")|0
"3000000000.654" >>> 0 === 3000000000 // unsigned right shift gives you an extra bit
"300000000000.654" >>> 0 === 3647256576 // but still fails with larger numbers

To work correctly with larger numbers, you should use the rounding methods

Math.floor("3000000000.654") === 3000000000
// This is the same as
Math.floor(Number("3000000000.654"))

Bear in mind that coeercion understands exponential notation and Infinity, so 2e2 is 200 rather than NaN, while the parse methods don't.

Custom

It's unlikely that either of these methods do exactly what you want. For example, usually I would want an error thrown if parsing fails, and I don't need support for Infinity, exponentials or leading whitespace. Depending on your usecase, sometimes it makes sense to write a custom conversion function.

Always check that the output of Number or one of the parse methods is the sort of number you expect. You will almost certainly want to use isNaN to make sure the number is not NaN (usually the only way you find out that the parse failed).

Error in strings.xml file in Android

1. for error: unescaped apostrophe in string

what I found is that AAPT2 tool points to wrong row in xml, sometimes. So you should correct whole strings.xml file

In Android Studio, in problem file use :

Edit->find->replace

Then write in first field \' (or \&,>,\<,\")
in second put '(or &,>,<,")
then replace each if needed.(or "reptlace all" in case with ')
Then in first field again put '(or &,>,<,")
and in second write \'
then replace each if needed.(or "replace all" in case with ')

2. for other problematic symbols
I use to comment each next half part +rebuild until i won't find the wrong sign.

E.g. an escaped word "\update" unexpectedly drops such error :)

Print a list of space-separated elements in Python 3

You can apply the list as separate arguments:

print(*L)

and let print() take care of converting each element to a string. You can, as always, control the separator by setting the sep keyword argument:

>>> L = [1, 2, 3, 4, 5]
>>> print(*L)
1 2 3 4 5
>>> print(*L, sep=', ')
1, 2, 3, 4, 5
>>> print(*L, sep=' -> ')
1 -> 2 -> 3 -> 4 -> 5

Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join():

joined_string = ' '.join([str(v) for v in L])
print(joined_string)
# do other things with joined_string

Note that this requires manual conversion to strings for any non-string values in L!

Changing Font Size For UITableView Section Headers

Swift 2:

As OP asked, only adjust the size, not setting it as a system bold font or whatever:

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        if let headerView = view as? UITableViewHeaderFooterView, textLabel = headerView.textLabel {

            let newSize = CGFloat(16)
            let fontName = textLabel.font.fontName
            textLabel.font = UIFont(name: fontName, size: newSize)
        }
    }

Check if a string is a palindrome

Just for fun:

return myString.SequenceEqual(myString.Reverse());

How can I pass a reference to a function, with parameters?

The following is equivalent to your second code block:

var f = function () {
        //Some logic here...
    };

var fr = f;

fr(pars);

If you want to actually pass a reference to a function to some other function, you can do something like this:

function fiz(x, y, z) {
    return x + y + z;
}

// elsewhere...

function foo(fn, p, q, r) {
    return function () {
        return fn(p, q, r);
    }
}

// finally...

f = foo(fiz, 1, 2, 3);
f(); // returns 6

You're almost certainly better off using a framework for this sort of thing, though.

How to check internet access on Android? InetAddress never times out

check this code... it worked for me :)

public static void isNetworkAvailable(final Handler handler, final int timeout) {
    // ask fo message '0' (not connected) or '1' (connected) on 'handler'
    // the answer must be send before before within the 'timeout' (in milliseconds)

    new Thread() {
        private boolean responded = false;   
        @Override
        public void run() { 
            // set 'responded' to TRUE if is able to connect with google mobile (responds fast) 
            new Thread() {      
                @Override
                public void run() {
                    HttpGet requestForTest = new HttpGet("http://m.google.com");
                    try {
                        new DefaultHttpClient().execute(requestForTest); // can last...
                        responded = true;
                    } 
                    catch (Exception e) {
                    }
                } 
            }.start();

            try {
                int waited = 0;
                while(!responded && (waited < timeout)) {
                    sleep(100);
                    if(!responded ) { 
                        waited += 100;
                    }
                }
            } 
            catch(InterruptedException e) {} // do nothing 
            finally { 
                if (!responded) { handler.sendEmptyMessage(0); } 
                else { handler.sendEmptyMessage(1); }
            }
        }
    }.start();
}

Then, I define the handler:

Handler h = new Handler() {
    @Override
    public void handleMessage(Message msg) {

        if (msg.what != 1) { // code if not connected

        } else { // code if connected

        }   
    }
};

...and launch the test:

isNetworkAvailable(h,2000); // get the answser within 2000 ms

Logarithmic returns in pandas dataframe

Single line, and only calculating logs once. First convert to log-space, then take the 1-period diff.

    np.diff(np.log(df.price))

In earlier versions of numpy:

    np.log(df.price)).diff()

Refer to a cell in another worksheet by referencing the current worksheet's name?

Here is how I made monthly page in similar manner as Fernando:

  1. I wrote manually on each page number of the month and named that place as ThisMonth. Note that you can do this only before you make copies of the sheet. After copying Excel doesn't allow you to use same name, but with sheet copy it does it still. This solution works also without naming.
  2. I added number of weeks in the month to location C12. Naming is fine also.
  3. I made five weeks on every page and on fifth week I made function

      =IF(C12=5,DATE(YEAR(B48),MONTH(B48),DAY(B48)+7),"")
    

    that empties fifth week if this month has only four weeks. C12 holds the number of weeks.

  4. ...
  5. I created annual Excel, so I had 12 sheets in it: one for each month. In this example name of the sheet is "Month". Note that this solutions works also with the ODS file standard except you need to change all spaces as "_" characters.
  6. I renamed first "Month" sheet as "Month (1)" so it follows the same naming principle. You could also name it as "Month1" if you wish, but "January" would require a bit more work.
  7. Insert following function on the first day field starting sheet #2:

     =INDIRECT(CONCATENATE("'Month (",ThisMonth-1,")'!B15"))+INDIRECT(CONCATENATE("'Month (",ThisMonth-1,")'!C12"))*7
    

    So in another word, if you fill four or five weeks on the previous sheet, this calculates date correctly and continues from correct date.

Package php5 have no installation candidate (Ubuntu 16.04)

If you just want to install PHP no matter what version it is, try PHP7

sudo apt-get install php7.0 php7.0-mcrypt

Using Java 8 to convert a list of objects into a string obtained from the toString() method

String actual = list.stream().reduce((t, u) -> t + "," + u).get();

How to bind Events on Ajax loaded Content?

if your question is "how to bind events on ajax loaded content" you can do like this :

$("img.lazy").lazyload({
    effect : "fadeIn",
    event: "scrollstop",
    skip_invisible : true
}).removeClass('lazy');

// lazy load to DOMNodeInserted event
$(document).bind('DOMNodeInserted', function(e) {
    $("img.lazy").lazyload({
        effect : "fadeIn",
        event: "scrollstop",
        skip_invisible : true
    }).removeClass('lazy');
});

so you don't need to place your configuration to every you ajax code

Why does the Google Play store say my Android app is incompatible with my own device?

I found an additional way in which this problem occurs:
My LG phone's original OS was Froyo (Android 2.2) and was updated to ICS (Android 4.0.4). But the Google Play Developers' Console shows that it detects my phone as a Froyo device. (Google Play did not allow the app to be downloaded because of the false 'incompatibility', but it somehow still detects the installation.)

The phone's settings, in 'software', shows ICS V4.0.4. It seems that the Google Play server info for the phone is not updated to reflect the ICS update on the device. The app manifest minSDK is set to Honeycomb (3.0), so of course Google Play filters out the app.

Of addition interest:
The app uses In-app Billing V3. The first time through IabHelper allows the app to make purchases through the Google Play service. But after the purchase is made, the purchase is NOT put in the inventory and IabHelper reports no items are owned. Debug messages show a 'purchase failed' result from the purchase even though the Google Play window announces "purchase successful."

How to cancel a pull request on github?

Super EASY way to close a Pull Request - LATEST!

  1. Navigate to the Original Repository where the pull request has been submitted to.
  2. Select the Pull requests tab
  3. Select your pull request that you wish to remove. This will open it up.
  4. Towards the bottom, just enter a valid comment for closure and press Close Pull Request button

enter image description here

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

I know, I am late but here is the correct way of doing it. using base64. This technique will convert the array to string.

import base64
import numpy as np
random_array = np.random.randn(32,32)
string_repr = base64.binascii.b2a_base64(random_array).decode("ascii")
array = np.frombuffer(base64.binascii.a2b_base64(string_repr.encode("ascii"))) 

For array to string

Convert binary data to a line of ASCII characters in base64 coding and decode to ASCII to get string repr.

For string to array

First, encode the string in ASCII format then Convert a block of base64 data back to binary and return the binary data.

Setting the selected attribute on a select list using jQuery

This can be a solution

$(document).on('change', 'select', function () {
            var value = $(this).val();
            $(this).find('option[value="' + value + '"]').attr("selected", "selected");
        })

How to trigger a phone call when clicking a link in a web page on mobile phone

Want to add an answer here for the sake of completeness.

<a href="tel:1234567">Call 123-4567</a>

Works just fine on most devices. However, on desktops this will appear as a link which does nothing when you click on it so you should consider using CSS to make it conditionally visible only on mobile devices.

Also, you should know that Skype (which is fairly popular) uses a different syntax by default (but can be parametered to use tel:).

<a href="callto:1234567">Call 123-4567</a>

However, I think in latest mobile browsers (I know for sure on Android) now the tel syntax should offer a popup of available applications that can be used to complete the calling action.

Uploading Images to Server android

Main activity class to take pick and upload

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
//import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;


public class MainActivity extends Activity {

    Button btpic, btnup;
    private Uri fileUri;
    String picturePath;
    Uri selectedImage;
    Bitmap photo;
    String ba1;
    public static String URL = "Paste your URL here";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btpic = (Button) findViewById(R.id.cpic);
        btpic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickpic();
            }
        });

        btnup = (Button) findViewById(R.id.up);
        btnup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                upload();
            }
        });
    }

    private void upload() {
        // Image location URL
        Log.e("path", "----------------" + picturePath);

        // Image
        Bitmap bm = BitmapFactory.decodeFile(picturePath);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
        byte[] ba = bao.toByteArray();
       //ba1 = Base64.encodeBytes(ba);

        Log.e("base64", "-----" + ba1);

        // Upload image to server
        new uploadToServer().execute();

    }

    private void clickpic() {
        // Check Camera
        if (getApplicationContext().getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            // Open default camera
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

            // start the image capture Intent
            startActivityForResult(intent, 100);

        } else {
            Toast.makeText(getApplication(), "Camera not supported", Toast.LENGTH_LONG).show();
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == RESULT_OK) {

            selectedImage = data.getData();
            photo = (Bitmap) data.getExtras().get("data");

            // Cursor to get image uri to display

            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            cursor.close();

            Bitmap photo = (Bitmap) data.getExtras().get("data");
            ImageView imageView = (ImageView) findViewById(R.id.Imageprev);
            imageView.setImageBitmap(photo);
        }
    }

    public class uploadToServer extends AsyncTask<Void, Void, String> {

        private ProgressDialog pd = new ProgressDialog(MainActivity.this);
        protected void onPreExecute() {
            super.onPreExecute();
            pd.setMessage("Wait image uploading!");
            pd.show();
        }

        @Override
        protected String doInBackground(Void... params) {

            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("base64", ba1));
            nameValuePairs.add(new BasicNameValuePair("ImageName", System.currentTimeMillis() + ".jpg"));
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(URL);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                String st = EntityUtils.toString(response.getEntity());
                Log.v("log_tag", "In the try Loop" + st);

            } catch (Exception e) {
                Log.v("log_tag", "Error in http connection " + e.toString());
            }
            return "Success";

        }

        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            pd.hide();
            pd.dismiss();
        }
    }
}

php code to handle upload image and also create image from base64 encoded data

<?php
error_reporting(E_ALL);
if(isset($_POST['ImageName'])){
$imgname = $_POST['ImageName'];
$imsrc = base64_decode($_POST['base64']);
$fp = fopen($imgname, 'w');
fwrite($fp, $imsrc);
if(fclose($fp)){
 echo "Image uploaded";
}else{
 echo "Error uploading image";
}
}
?>

Redirecting to authentication dialog - "An error occurred. Please try again later"

Another possible mistake, if you directly copied the code from Facebook SDK example then you may get the same error despite of having everything correct. http://developers.facebook.com/docs/reference/php/

This is because in their example they have used backquotes instead of single quotes for the key of the array. The correct code is as follows.

require_once("facebook.php");

$config = array();
$config['appId'] = 'YOUR_APP_ID';
$config['secret'] = 'YOUR_APP_SECRET';
$config['fileUpload'] = false; // optional

$facebook = new Facebook($config);

Android design support library for API 28 (P) not working

Add this:

tools:replace="android:appComponentFactory"
android:appComponentFactory="whateverString"

to your manifest application

<application
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    tools:replace="android:appComponentFactory"
    android:appComponentFactory="whateverString">

hope it helps

Does Visual Studio Code have box select/multi-line edit?

Box Selecting

Windows & Linux: Shift + Alt + 'Mouse Left Button'

macOS: Shift + option + 'Click'

Esc to exit selection.

MacOS: Shift + Alt/Option + Command + 'arrow key'

How to read large text file on windows?

I have been using the BareTail for quite some time for viewing large logs (some GBs) and it is working very well is very fast. There is a free version and a commercial Pro version.

They say that it has

  • Real-time file
  • Optimised real-time viewing engine View files of any size (> 2GB)
  • Scroll to any point in the whole file instantly
  • View files over a network
  • Configurable line wrapping
  • Configurable TAB expansion
  • Configurable font, including spacing and offset to maximise use of screen space

Another alternative is Far Manager. Viewing a several GBs file is no problem (little memory footprint), but attempting to open the text file in the Editing mode might take several GBs of RAM, so be aware of that. I am not aware of the file size limit that can be viewed/edited in Far.

How do you reverse a string in place in JavaScript?

I think String.prototype.reverse is a good way to solve this problem; the code as below;

String.prototype.reverse = function() {
  return this.split('').reverse().join('');
}

var str = 'this is a good example for string reverse';
str.reverse();
-> "esrever gnirts rof elpmaxe doog a si siht";

How to submit http form using C#

I had a similar issue in MVC (which lead me to this problem).

I am receiving a FORM as a string response from a WebClient.UploadValues() request, which I then have to submit - so I can't use a second WebClient or HttpWebRequest. This request returned the string.

using (WebClient client = new WebClient())
  {
    byte[] response = client.UploadValues(urlToCall, "POST", new NameValueCollection()
    {
        { "test", "value123" }
    });

    result = System.Text.Encoding.UTF8.GetString(response);
  }

My solution, which could be used to solve the OP, is to append a Javascript auto submit to the end of the code, and then using @Html.Raw() to render it on a Razor page.

result += "<script>self.document.forms[0].submit()</script>";
someModel.rawHTML = result;
return View(someModel);

Razor Code:

@model SomeModel

@{
    Layout = null;
}

@Html.Raw(@Model.rawHTML)

I hope this can help anyone who finds themselves in the same situation.

Angularjs - simple form submit

I have been doing quite a bit of research and in attempt to resolve a different issue I ended up coming to a good portion of the solution in my other post here:

Angularjs - Form Post Data Not Posted?

The solution does not include uploading images currently but I intend to expand upon and create a clear and well working example. If updating these posts is possible I will keep them up to date all the way until a stable and easy to learn from example is compiled.

How to merge specific files from Git branches

When content is in file.py from branch2 that is no longer applies to branch1, it requires picking some changes and leaving others. For full control do an interactive merge using the --patch switch:

$ git checkout --patch branch2 file.py

The interactive mode section in the man page for git-add(1) explains the keys that are to be used:

y - stage this hunk
n - do not stage this hunk
q - quit; do not stage this hunk nor any of the remaining ones
a - stage this hunk and all later hunks in the file
d - do not stage this hunk nor any of the later hunks in the file
g - select a hunk to go to
/ - search for a hunk matching the given regex
j - leave this hunk undecided, see next undecided hunk
J - leave this hunk undecided, see next hunk
k - leave this hunk undecided, see previous undecided hunk
K - leave this hunk undecided, see previous hunk
s - split the current hunk into smaller hunks
e - manually edit the current hunk
? - print help

The split command is particularly useful.

inline conditionals in angular.js

Angular UI library has built-in directive ui-if for condition in template/Views upto angular ui 1.1.4

Example: Support in Angular UI upto ui 1.1.4

<div ui-if="array.length>0"></div>

ng-if available in all the angular version after 1.1.4

<div ng-if="array.length>0"></div>

if you have any data in array variable then only the div will appear

Android ListView headers

You probably are looking for an ExpandableListView which has headers (groups) to separate items (childs).

Nice tutorial on the subject: here.

getting error while updating Composer

This works for me with php 7.2

sudo apt-get install php7.2-xml

Invalid application of sizeof to incomplete type with a struct

The cause of errors such as "Invalid application of sizeof to incomplete type with a struct ... " is always lack of an include statement. Try to find the right library to include.

How do I restrict an input to only accept numbers?

Using ng-pattern on the text field:

<input type="text"  ng-model="myText" name="inputName" ng-pattern="onlyNumbers">

Then include this on your controller

$scope.onlyNumbers = /^\d+$/;

How to call a function, PostgreSQL

I had this same issue while trying to test a very similar function that uses a SELECT statement to decide if a INSERT or an UPDATE should be done. This function was a re-write of a T-SQL stored procedure.
When I tested the function from the query window I got the error "query has no destination for result data". I finally figured out that because I used a SELECT statement inside the function that I could not test the function from the query window until I assigned the results of the SELECT to a local variable using an INTO statement. This fixed the problem.

If the original function in this thread was changed to the following it would work when called from the query window,

$BODY$
DECLARE
   v_temp integer;
BEGIN
SELECT 1 INTO v_temp
FROM "USERS"
WHERE "userID" = $1;

String to Dictionary in Python

This data is JSON! You can deserialize it using the built-in json module if you're on Python 2.6+, otherwise you can use the excellent third-party simplejson module.

import json    # or `import simplejson as json` if on Python < 2.6

json_string = u'{ "id":"123456789", ... }'
obj = json.loads(json_string)    # obj now contains a dict of the data

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

This is how you get rid of that notice and be able to open those grid cells for edit

1) click "STRUCTURE"

2) go to the field you want to be a primary key (and this usually is the 1st one ) and then click on the "PRIMARY" and "INDEX" fields for that field and accept the PHPMyadmin's pop-up question "OK".

3) pad yourself in the back.

Match all elements having class name starting with a specific string

It's not a direct answer to the question, however I would suggest in most cases to simply set multiple classes to each element:

<div class="myclass one"></div>
<div class="myclass two></div>
<div class="myclass three"></div>

In this way you can set rules for all myclass elements and then more specific rules for one, two and three.

.myclass { color: #f00; }

.two { font-weight: bold; }

etc.

Is div inside list allowed?

If I recall correctly, a div inside a li used to be invalid.

@Flower @Superstringcheese Div should semantically define a section of a document, but it has already practically lost this role. Span should however contain text.

Missing maven .m2 folder

Check the configurations in {M2_HOME}\conf\setting.xml as mentioned in the following link.

http://www.mkyong.com/maven/where-is-maven-local-repository/

Hope this helps.

HTML5 video - show/hide controls programmatically

Here's how to do it:

var myVideo = document.getElementById("my-video")    
myVideo.controls = false;

Working example: https://jsfiddle.net/otnfccgu/2/

See all available properties, methods and events here: https://www.w3schools.com/TAGs/ref_av_dom.asp

Horizontal swipe slider with jQuery and touch devices support?

If I was you, I would implement my own solution based on the event specs. Basically, what swipe is - it's handling of touch down, touch move, touch up events. here is excerpt of my own lib for handling iPhone touch events:

touch_object.prototype.handle_touchstart = function(e){
    if (e.targetTouches.length != 1){
        return false;
    }
    this.obj.style.zIndex = 100;
    e.preventDefault();
    this.startX = e.targetTouches[0].pageX - this.geometry.x;
    this.startY = e.targetTouches[0].pageY - this.geometry.y;
    /* adjust for left /top */
    this.bind_handler('touchmove');
    this.bind_handler('touchend');
}
touch_object.prototype.handle_touchmove = function(e) {
    e.preventDefault();
    if (e.targetTouches.length != 1){
        return false;
    }
    var x=e.targetTouches[0].pageX - this.startX;
    var y=e.targetTouches[0].pageY - this.startY;
    this.move(x,y);

}
touch_object.prototype.handle_touchend = function(e){
    this.obj.style.zIndex = 10;
    this.unbind_handler('touchmove');
    this.unbind_handler('touchend');
}

I used that code to "move things around". But, instead of moving, you can create your own algorithm for e.g. triggering redirect to some other location, or you can use that move to "move/swipe" the element, on which the swipe is on to other location.

so, it really helps to understand basics of how things work and then create more complicated solutions. this might help as well.

I used this, to create my solution:

http://developer.apple.com/library/IOs/#documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html

Doctrine and LIKE query

This is not possible with the magic find methods. Try using the query builder:

$result = $em->getRepository("Orders")->createQueryBuilder('o')
   ->where('o.OrderEmail = :email')
   ->andWhere('o.Product LIKE :product')
   ->setParameter('email', '[email protected]')
   ->setParameter('product', 'My Products%')
   ->getQuery()
   ->getResult();

Understanding REST: Verbs, error codes, and authentication

re 1: This looks fine so far. Remember to return the URI of the newly created user in a "Location:" header as part of the response to POST, along with a "201 Created" status code.

re 2: Activation via GET is a bad idea, and including the verb in the URI is a design smell. You might want to consider returning a form on a GET. In a Web app, this would be an HTML form with a submit button; in the API use case, you might want to return a representation that contains a URI to PUT to to activate the account. Of course you can include this URI in the response on POST to /users, too. Using PUT will ensure your request is idempotent, i.e. it can safely be sent again if the client isn't sure about success. In general, think about what resources you can turn your verbs into (sort of "nounification of verbs"). Ask yourself what method your specific action is most closely aligned with. E.g. change_password -> PUT; deactivate -> probably DELETE; add_credit -> possibly POST or PUT. Point the client to the appropriate URIs by including them in your representations.

re 3. Don't invent new status codes, unless you believe they're so generic they merit being standardized globally. Try hard to use the most appropriate status code available (read about all of them in RFC 2616). Include additional information in the response body. If you really, really are sure you want to invent a new status code, think again; if you still believe so, make sure to at least pick the right category (1xx -> OK, 2xx -> informational, 3xx -> redirection; 4xx-> client error, 5xx -> server error). Did I mention that inventing new status codes is a bad idea?

re 4. If in any way possible, use the authentication framework built into HTTP. Check out the way Google does authentication in GData. In general, don't put API keys in your URIs. Try to avoid sessions to enhance scalability and support caching - if the response to a request differs because of something that has happened before, you've usually tied yourself to a specific server process instance. It's much better to turn session state into either client state (e.g. make it part of subsequent requests) or make it explicit by turning it into (server) resource state, i.e. give it its own URI.

How do I keep CSS floats in one line?

Wrap your floaters in a div with a min-width greater than the combined width+margin of the floaters.

No hacks or HTML tables needed.

sklearn: Found arrays with inconsistent numbers of samples when calling LinearRegression.fit()

To analyze two arrays (array1 and array2) they need to meet the following two requirements:

1) They need to be a numpy.ndarray

Check with

type(array1)
# and
type(array2)

If that is not the case for at least one of them perform

array1 = numpy.ndarray(array1)
# or
array2 = numpy.ndarray(array2)

2) The dimensions need to be as follows:

array1.shape #shall give (N, 1)
array2.shape #shall give (N,)

N is the number of items that are in the array. To provide array1 with the right number of axes perform:

array1 = array1[:, numpy.newaxis]

Regex remove all special characters except numbers?

Use the global flag:

var name = name.replace(/[^a-zA-Z ]/g, "");
                                    ^

If you don't want to remove numbers, add it to the class:

var name = name.replace(/[^a-zA-Z0-9 ]/g, "");

How to create a sleep/delay in nodejs that is Blocking?

Just use child_process.execSync and call the system's sleep function.

//import child_process module
const child_process = require("child_process");
// Sleep for 5 seconds
child_process.execSync("sleep 5");

// Sleep for 250 microseconds
child_process.execSync("usleep 250");

// Sleep for a variable number of microseconds
var numMicroSeconds = 250;
child_process.execFileSync("usleep", [numMicroSeconds]);

I use this in a loop at the top of my main application script to make Node wait until network drives are attached before running the rest of the application.

Are 64 bit programs bigger and faster than 32 bit versions?

Unless you need to access more memory that 32b addressing will allow you, the benefits will be small, if any.

When running on 64b CPU, you get the same memory interface no matter if you are running 32b or 64b code (you are using the same cache and same BUS).

While x64 architecture has a few more registers which allows easier optimizations, this is often counteracted by the fact pointers are now larger and using any structures with pointers results in a higher memory traffic. I would estimate the increase in the overall memory usage for a 64b application compared to a 32b one to be around 15-30 %.

"Unable to locate tools.jar" when running ant

I was also having the same problem So I just removed the JDK path from the end and put it in start even before all System or Windows 32 paths.

Before it was like this:

C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Users\Rajkaran\AppData\Local\Smartbar\Application\;C:\Users\Rajkaran\AppData\Local\Smartbar\Application\;C:\Program Files\doxygen\bin;%JAVA_HOME%\bin;%ANT_HOME%\bin

So I made it like this:

%JAVA_HOME%\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Users\Rajkaran\AppData\Local\Smartbar\Application\;C:\Users\Rajkaran\AppData\Local\Smartbar\Application\;C:\Program Files\doxygen\bin;%ANT_HOME%\bin

moment.js - UTC gives wrong date

Both Date and moment will parse the input string in the local time zone of the browser by default. However Date is sometimes inconsistent with this regard. If the string is specifically YYYY-MM-DD, using hyphens, or if it is YYYY-MM-DD HH:mm:ss, it will interpret it as local time. Unlike Date, moment will always be consistent about how it parses.

The correct way to parse an input moment as UTC in the format you provided would be like this:

moment.utc('07-18-2013', 'MM-DD-YYYY')

Refer to this documentation.

If you want to then format it differently for output, you would do this:

moment.utc('07-18-2013', 'MM-DD-YYYY').format('YYYY-MM-DD')

You do not need to call toString explicitly.

Note that it is very important to provide the input format. Without it, a date like 01-04-2013 might get processed as either Jan 4th or Apr 1st, depending on the culture settings of the browser.

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

Create a button programmatically and set a background image

This is how you can create a beautiful button with a bezel and rounded edges:

loginButton = UIButton(frame: CGRectMake(self.view.bounds.origin.x + (self.view.bounds.width * 0.325), self.view.bounds.origin.y + (self.view.bounds.height * 0.8), self.view.bounds.origin.x + (self.view.bounds.width * 0.35), self.view.bounds.origin.y + (self.view.bounds.height * 0.05)))
loginButton.layer.cornerRadius = 18.0
loginButton.layer.borderWidth = 2.0
loginButton.backgroundColor = UIColor.whiteColor()
loginButton.layer.borderColor = UIColor.whiteColor().CGColor
loginButton.setTitle("Login", forState: UIControlState.Normal)
loginButton.setTitleColor(UIColor(red: 24.0/100, green: 116.0/255, blue: 205.0/205, alpha: 1.0), forState: UIControlState.Normal)

How to declare and display a variable in Oracle

Did you recently switch from MySQL and are now longing for the logical equivalents of its more simple commands in Oracle? Because that is the case for me and I had the very same question. This code will give you a quick and dirty print which I think is what you're looking for:

Variable n number
begin
    :n := 1;
end;
print n

The middle section is a PL/SQL bit that binds the variable. The output from print n is in column form, and will not just give the value of n, I'm afraid. When I ran it in Toad 11 it returned like this

        n
---------
        1

I hope that helps

Invoking a PHP script from a MySQL trigger

Run away from store procedures as much as possible. They are pretty hard to maintain and are VERY OLD STUFF ;)

Using an image caption in Markdown Jekyll

The correct HTML to use for images with captions, is <figure> with <figcaption>.

There's no Markdown equivalent for this, so if you're only adding the occasional caption, I'd encourage you to just add that html into your Markdown document:

Lorem ipsum dolor sit amet, consectetur adipiscing elit...

<figure>
  <img src="{{site.url}}/assets/image.jpg" alt="my alt text"/>
  <figcaption>This is my caption text.</figcaption>
</figure>

Vestibulum eu vulputate magna...

The Markdown spec encourages you to embed HTML in cases like this, so it will display just fine. It's also a lot simpler than messing with plugins.

If you're trying to use other Markdown-y features (like tables, asterisks, etc) to produce captions, then you're just hacking around how Markdown was intended to be used.

Unable to specify the compiler with CMake

Never try to set the compiler in the CMakeLists.txt file.

See the CMake FAQ about how to use a different compiler:

https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler

(Note that you are attempting method #3 and the FAQ says "(avoid)"...)

We recommend avoiding the "in the CMakeLists" technique because there are problems with it when a different compiler was used for a first configure, and then the CMakeLists file changes to try setting a different compiler... And because the intent of a CMakeLists file should be to work with multiple compilers, according to the preference of the developer running CMake.

The best method is to set the environment variables CC and CXX before calling CMake for the very first time in a build tree.

After CMake detects what compilers to use, it saves them in the CMakeCache.txt file so that it can still generate proper build systems even if those variables disappear from the environment...

If you ever need to change compilers, you need to start with a fresh build tree.

How to add smooth scrolling to Bootstrap's scroll spy function

I combined it, and this is the results -

$(document).ready(function() {
     $("#toTop").hide();

            // fade in & out
       $(window).scroll(function () {
                    if ($(this).scrollTop() > 400) {
                        $('#toTop').fadeIn();
                    } else {
                        $('#toTop').fadeOut();
                    }
                });     
  $('a[href*=#]').each(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
    && location.hostname == this.hostname
    && this.hash.replace(/#/,'') ) {
      var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
      var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
       if ($target) {
         var targetOffset = $target.offset().top;
         $(this).click(function() {
           $('html, body').animate({scrollTop: targetOffset}, 400);
           return false;
         });
      }
    }
  });
});

I tested it and it works fine. hope this will help someone :)

Can we locate a user via user's phone number in Android?

Yess, possible with conditions:

If you have your app installed in the user phone and a server app communicating with this app, and there at last one of location service providers activated in the user phone, and some horrible android permissions!

In most of android phones there 3 location providers that can give exact location (GPS_PROVIDER 1m) or estimated (NETWORK_PROVIDER around 2-20m) and PASSIVE_PROVIDER (more in LocationManager official documentation).

1* App sends SMS to user's phone

Yess, can be server app or you create an android app if you want something automated, so you can do it manually by sending SMS from your default SMS app! I use Kannel: Open Source WAP and SMS Gateway and here (lot of APIs to send SMS )

2* App receives SMS at user's phone from the SMS sender

Yess, you can get all received SMS, and you can filter them by sender phone number! and do some actions when your specified sms received, basic tuto here (i do some actions according to the content of my SMS)

3* App gets location coordinates of the user's phone

Yess, you can get actual user coordinates easily if one of location providers is activated, so you can get last known location when the user have activated one of location providers, if those disabled or the phone don't have GPS hardware you can use Open Cell Id api to get the nearest cell coordinates(10m-10Km) or Loc8 api but those not available in all around the world, and some apps use IP location apis to get the country, city and province, here the simplest way to get current user location.

4* App sends location coordinates to the SMS sender via SMS

Yess, you can get sender phone number and send user location, immediately when SMS received or at specified times in the day.

(Those 4 yesses for you :) )

Viber and other apps that access to users locations, identify there users by there phone numbers by obligating them to send SMS to the server app to create an account and activate the free service (Ex:VOIP) , and lunch a service that can:

  • Listen for location changes (GPS, Network or Cell Id)
  • Send user location periodically(Ex: each 2 hours) or when user position changed!
  • Stock user locations in file and create a map based on daily locations
  • Receive SMS and update user location
  • Receive server app commend and update user location
  • Send events when user go inside or outside of a defined circle
  • Listen for what user say and record it or open live voip call :s
  • Maybe anything you think or u want to do :) !

And your application users must accept all of that when installing it, of corse i don't gonna install apps like this because i read permissions before installing :) and permissions maybe something like that:

<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />    
<uses-permission android:name="android.permission.INTERNET" />
<-- and more if you wanna more -->

The final user will accept for something like that (those permissions of an android app u asked about):

This app has access to these permissions:

Your accounts -create accounts and set passwords -find accounts on the device -add or remove accounts -use accounts on the device -read Google service configuration

Your location -approximate location (network-based) -precise location (GPS and network-based)

Your messages -receive text messages (SMS) -send SMS messages -edit your text messages (SMS or MMS) -read your text messages (SMS or MMS)

Network communication -receive data from Internet -full network access -view Wi-Fi connections -view network connections -change network connectivity

Phone calls -read phone status and identity -directly call phone numbers

Storage -modify or delete the contents of your USB storage

Your applications information -retrieve running apps -close other apps -run at startup

Bluetooth -pair with Bluetooth devices -access Bluetooth settings

Camera -take pictures and videos

Other Application UI -draw over other apps

Microphone -record audio

Lock screen -disable your screen lock

Your social information -read your contacts -modify your contacts -read call log -write call log -read your social stream -write to your social stream

Development tools -read sensitive log data

System tools -modify system settings -send sticky broadcast -test access to protected storage

Affects battery -control vibration -prevent device from sleeping

Audio settings -change your audio settings

Sync Settings -read sync settings -toggle sync on and off -read sync statistics

Wallpaper -set wallpaper

Why doesn't height: 100% work to expand divs to the screen height?

You will also need to set 100% height on the html element:

html { height:100%; }

Initializing C# auto-properties

This will be possible in C# 6.0:

public int Y { get; } = 2;

$(window).width() not the same as media query

It may be due to scrollbar, use innerWidth instead of width like

if($(window).innerWidth() <= 751) {
   $("#body-container .main-content").remove()
                                .insertBefore($("#body-container .left-sidebar"));
} else {
   $("#body-container .main-content").remove()
                                .insertAfter($("#body-container .left-sidebar"));
}

Also you can get the viewport like

function viewport() {
    var e = window, a = 'inner';
    if (!('innerWidth' in window )) {
        a = 'client';
        e = document.documentElement || document.body;
    }
    return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}

Above code Source

How to create CSV Excel file C#?

How about using string.Join instead of all the foreach Loops?

How to set the text color of TextView in code?

Use:

TextView tv = new TextView(this);
tv.setTextColor(Color.rgb(285,0,0));

How to convert a time string to seconds?

def time_to_sec(time):
    sep = ','
    rest = time.split(sep, 1)[0]
    splitted = rest.split(":")
    emel = len(splitted) - 1
    i = 0
    summa = 0
    for numb in splitted:
        szor = 60 ** (emel - i)
        i += 1
        summa += int(numb) * szor
    return summa

How to trap the backspace key using jQuery?

Working on the same idea as above , but generalizing a bit . Since the backspace should work fine on the input elements , but should not work if the focus is a paragraph or something , since it is there where the page tends to go back to the previous page in history .

$('html').on('keydown' , function(event) {

        if(! $(event.target).is('input')) {
            console.log(event.which);
           //event.preventDefault();
           if(event.which == 8) {
            //  alert('backspace pressed');
            return false;
         }
        }
});

returning false => both event.preventDefault and event.stopPropagation are in effect .

How to order a data frame by one descending and one ascending column?

The correct way is:

rum[order(rum$T1, rum$T2, decreasing=c(T,F)), ]

CSS checkbox input styling

input[type="checkbox"] {
 /* your style */
}

But this will only work for browsers except IE7 and below, for those you will have to use a class.

How to install latest version of git on CentOS 7.x/6.x

Adding a roundabout answer here. I was struggling to install git on an RHEL 6.0 Amazon instance, and what ended up saving me was ... conda, as in Anaconda Python.

I installed conda on the command line from the archives (code modeled after this):

wget http://repo.continuum.io/miniconda/Miniconda2-4.2.12-Linux-x86_64.sh -O ~/miniconda.sh
bash ~/miniconda.sh -b -p $HOME/miniconda
export PATH="$HOME/miniconda/bin:$PATH"

and then ran

conda install git

and a relatively recent version git was installed. Today is 12/26/2016 and the version is 2.9.3.

Default passwords of Oracle 11g?

Once installed in windows Followed the instructions starting from Run SQL Command Line (command prompt)

then... v. SQL> connect /as sysdba

Connected. [SQL prompt response]

vi. SQL> alter user SYS identified by "newpassword";

User altered. [SQL prompt response]

Thank you. This minimized a headache

Should I call Close() or Dispose() for stream objects?

On many classes which support both Close() and Dispose() methods, the two calls would be equivalent. On some classes, however, it is possible to re-open an object which has been closed. Some such classes may keep some resources alive after a Close, in order to permit reopening; others may not keep any resources alive on Close(), but might set a flag on Dispose() to explicitly forbid re-opening.

The contract for IDisposable.Dispose explicitly requires that calling it on an object which will never be used again will be at worst harmless, so I would recommend calling either IDisposable.Dispose or a method called Dispose() on every IDisposable object, whether or not one also calls Close().

getting the screen density programmatically in android?

I am using following code to access DPI from modules (no need for having access to a context object):

(Resources.getSystem().getDisplayMetrics().xdpi
Resources.getSystem().getDisplayMetrics().ydpi)/2

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

List<Map<String, Object>> List = getJdbcTemplate().queryForList(SELECT_ALL_CONVERSATIONS_SQL_FULL, new Object[] {userId, dateFrom, dateTo});
for (Map<String, Object> rowMap : resultList) {
    DTO dTO = new DTO();
    dTO.setrarchyID((Long) (rowMap.get("ID")));
}

What does API level mean?

This actually sums it up pretty nicely.

API Levels generally mean that as a programmer, you can communicate with the devices' built in functions and functionality. As the API level increases, functionality adds up (although some of it can get deprecated).

Choosing an API level for an application development should take at least two thing into account:

  1. Current distribution - How many devices can actually support my application, if it was developed for API level 9, it cannot run on API level 8 and below, then "only" around 60% of devices can run it (true to the date this post was made).
  2. Choosing a lower API level may support more devices but gain less functionality for your app. you may also work harder to achieve features you could've easily gained if you chose higher API level.

Android API levels can be divided to five main groups (not scientific, but what the heck):

  1. Android 1.5 - 2.3 (Cupcake to Gingerbread) - (API levels 3-10) - Android made specifically for smartphones.
  2. Android 3.0 - 3.2 (Honeycomb) (API levels 11-13) - Android made for tablets.
  3. Android 4.0 - 4.4 (KitKat) - (API levels 14-19) - A big merge with tons of additional functionality, totally revamped Android version, for both phone and tablets.
  4. Android 5.0 - 5.1 (Lollipop) - (API levels 21-22) - Material Design introduced.
  5. Android 6.0 - 6.… (Marshmallow) - (API levels 23-…) - Runtime Permissions,Apache HTTP Client Removed

Why is SQL Server 2008 Management Studio Intellisense not working?

No need to reinstall.

Click on the setup file. Then go to maintenance and click on Repair. This should correct the intellisense problem.

How do I perform HTML decoding/encoding using Python/Django?

Use daniel's solution if the set of encoded characters is relatively restricted. Otherwise, use one of the numerous HTML-parsing libraries.

I like BeautifulSoup because it can handle malformed XML/HTML :

http://www.crummy.com/software/BeautifulSoup/

for your question, there's an example in their documentation

from BeautifulSoup import BeautifulStoneSoup
BeautifulStoneSoup("Sacr&eacute; bl&#101;u!", 
                   convertEntities=BeautifulStoneSoup.HTML_ENTITIES).contents[0]
# u'Sacr\xe9 bleu!'

Allowed memory size of 536870912 bytes exhausted in Laravel

I realize there is an accepted answer, and apparently it was either the size of memory chosen or the infinite loop suggestion that solved the issue for the OP.

For me, I added an array to the config file earlier and made some other changes prior to running artisan and getting the out of memory error and no amount of increasing memory helped. What it turned out to be was a missing comma after the array I added to the config file.

I am adding this answer in hopes that it helps someone else figure out what might be causing out of memory error. I am using laravel 5.4 under MAMP.

Android textview usage as label and value

You should implement a Custom List View, such that you define a Layout once and draw it for every row in the list view.

How can I one hot encode in Python?

Much easier to use Pandas for basic one-hot encoding. If you're looking for more options you can use scikit-learn.

For basic one-hot encoding with Pandas you pass your data frame into the get_dummies function.

For example, if I have a dataframe called imdb_movies:

enter image description here

...and I want to one-hot encode the Rated column, I do this:

pd.get_dummies(imdb_movies.Rated)

enter image description here

This returns a new dataframe with a column for every "level" of rating that exists, along with either a 1 or 0 specifying the presence of that rating for a given observation.

Usually, we want this to be part of the original dataframe. In this case, we attach our new dummy coded frame onto the original frame using "column-binding.

We can column-bind by using Pandas concat function:

rated_dummies = pd.get_dummies(imdb_movies.Rated)
pd.concat([imdb_movies, rated_dummies], axis=1)

enter image description here

We can now run an analysis on our full dataframe.

SIMPLE UTILITY FUNCTION

I would recommend making yourself a utility function to do this quickly:

def encode_and_bind(original_dataframe, feature_to_encode):
    dummies = pd.get_dummies(original_dataframe[[feature_to_encode]])
    res = pd.concat([original_dataframe, dummies], axis=1)
    return(res)

Usage:

encode_and_bind(imdb_movies, 'Rated')

Result:

enter image description here

Also, as per @pmalbu comment, if you would like the function to remove the original feature_to_encode then use this version:

def encode_and_bind(original_dataframe, feature_to_encode):
    dummies = pd.get_dummies(original_dataframe[[feature_to_encode]])
    res = pd.concat([original_dataframe, dummies], axis=1)
    res = res.drop([feature_to_encode], axis=1)
    return(res) 

You can encode multiple features at the same time as follows:

features_to_encode = ['feature_1', 'feature_2', 'feature_3',
                      'feature_4']
for feature in features_to_encode:
    res = encode_and_bind(train_set, feature)

Dialog to pick image from gallery or from camera

I have merged some solutions to make a complete util for picking an image from Gallery or Camera. These are the features of ImagePicker util gist (also in a Github lib):

  • Merged intents for Gallery and Camera resquests.
  • Resize selected big images (e.g.: 2500 x 1600)
  • Rotate image if necesary

Screenshot:

ImagePicker starting intent

Edit: Here is a fragment of code to get a merged Intent for Gallery and Camera apps together. You can see the full code at ImagePicker util gist (also in a Github lib):

public static Intent getPickImageIntent(Context context) {
    Intent chooserIntent = null;

    List<Intent> intentList = new ArrayList<>();

    Intent pickIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    takePhotoIntent.putExtra("return-data", true);
    takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(context)));
    intentList = addIntentsToList(context, intentList, pickIntent);
    intentList = addIntentsToList(context, intentList, takePhotoIntent);

    if (intentList.size() > 0) {
        chooserIntent = Intent.createChooser(intentList.remove(intentList.size() - 1),
                context.getString(R.string.pick_image_intent_text));
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray(new Parcelable[]{}));
    }

    return chooserIntent;
}

private static List<Intent> addIntentsToList(Context context, List<Intent> list, Intent intent) {
    List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(intent, 0);
    for (ResolveInfo resolveInfo : resInfo) {
        String packageName = resolveInfo.activityInfo.packageName;
        Intent targetedIntent = new Intent(intent);
        targetedIntent.setPackage(packageName);
        list.add(targetedIntent);
    }
    return list;
}

Get Row Index on Asp.net Rowcommand event

If you have a built-in command of GridView like insert, update or delete, on row command you can use the following code to get the index:

int index = Convert.ToInt32(e.CommandArgument);

In a custom command, you can set the command argument to yourRow.RowIndex.ToString() and then get it back in the RowCommand event handler. Unless, of course, you need the command argument for another purpose.

C++ array initialization

You can declare the array in C++ in these type of ways. If you know the array size then you should declare the array for: integer: int myArray[array_size]; Double: double myArray[array_size]; Char and string : char myStringArray[array_size]; The difference between char and string is as follows

char myCharArray[6]={'a','b','c','d','e','f'};
char myStringArray[6]="abcdef";

If you don't know the size of array then you should leave the array blank like following.

integer: int myArray[array_size];

Double: double myArray[array_size];

How to generate java classes from WSDL file

jdk 6 comes with wsimport that u can use to create Java-classes from a WSDL. It also creates a Service-class.

http://docs.oracle.com/javase/6/docs/technotes/tools/share/wsimport.html

CryptographicException 'Keyset does not exist', but only through WCF

I was getting the error : CryptographicException 'Keyset does not exist' when i run the MVC application.

Solution was : to give access to the personal certificates to the account that application pool is running under. In my case it was to add IIS_IUSRS and choosing the right location resolved this issue.

RC on the Certificate - > All tasks -> Manage Private Keys -> Add->  
For the From this location : Click on Locations and make sure to select the Server name. 
In the Enter the object names to select : IIS_IUSRS and click ok. 

How to recover Git objects damaged by hard disk failure?

Here are the steps I followed to recover from a corrupt blob object.

1) Identify corrupt blob

git fsck --full
  error: inflate: data stream error (incorrect data check)
  error: sha1 mismatch 241091723c324aed77b2d35f97a05e856b319efd
  error: 241091723c324aed77b2d35f97a05e856b319efd: object corrupt or missing
  ...

Corrupt blob is 241091723c324aed77b2d35f97a05e856b319efd

2) Move corrupt blob to a safe place (just in case)

mv .git/objects/24/1091723c324aed77b2d35f97a05e856b319efd ../24/

3) Get parent of corrupt blob

git fsck --full
  Checking object directories: 100% (256/256), done.
  Checking objects: 100% (70321/70321), done.
  broken link from    tree 0716831e1a6c8d3e6b2b541d21c4748cc0ce7180
              to    blob 241091723c324aed77b2d35f97a05e856b319efd

Parent hash is 0716831e1a6c8d3e6b2b541d21c4748cc0ce7180.

4) Get file name corresponding to corrupt blob

git ls-tree 0716831e1a6c8d3e6b2b541d21c4748cc0ce7180
  ...
  100644 blob 241091723c324aed77b2d35f97a05e856b319efd    dump.tar.gz
  ...

Find this particular file in a backup or in the upstream git repository (in my case it is dump.tar.gz). Then copy it somewhere inside your local repository.

5) Add previously corrupted file in the git object database

git hash-object -w dump.tar.gz

6) Celebrate!

git gc
  Counting objects: 75197, done.
  Compressing objects: 100% (21805/21805), done.
  Writing objects: 100% (75197/75197), done.
  Total 75197 (delta 52999), reused 69857 (delta 49296)

Are the days of passing const std::string & as a parameter over?

The problem is that "const" is a non-granular qualifier. What is usually meant by "const string ref" is "don't modify this string", not "don't modify the reference count". There is simply no way, in C++, to say which members are "const". They either all are, or none of them are.

In order to hack around this language issue, STL could allow "C()" in your example to make a move-semantic copy anyway, and dutifully ignore the "const" with regard to the reference count (mutable). As long as it was well-specified, this would be fine.

Since STL doesn't, I have a version of a string that const_casts<> away the reference counter (no way to retroactively make something mutable in a class hierarchy), and - lo and behold - you can freely pass cmstring's as const references, and make copies of them in deep functions, all day long, with no leaks or issues.

Since C++ offers no "derived class const granularity" here, writing up a good specification and making a shiny new "const movable string" (cmstring) object is the best solution I've seen.

Conversion of Char to Binary in C

unsigned char c;

for( int i = 7; i >= 0; i-- ) {
    printf( "%d", ( c >> i ) & 1 ? 1 : 0 );
}

printf("\n");

Explanation:

With every iteration, the most significant bit is being read from the byte by shifting it and binary comparing with 1.

For example, let's assume that input value is 128, what binary translates to 1000 0000. Shifting it by 7 will give 0000 0001, so it concludes that the most significant bit was 1. 0000 0001 & 1 = 1. That's the first bit to print in the console. Next iterations will result in 0 ... 0.

dlib installation on Windows 10

Install Dlib from .whl

Dlib 19.7.0

pip install https://pypi.python.org/packages/da/06/bd3e241c4eb0a662914b3b4875fc52dd176a9db0d4a2c915ac2ad8800e9e/dlib-19.7.0-cp36-cp36m-win_amd64.whl#md5=b7330a5b2d46420343fbed5df69e6a3f

You can test it, downloading an example from the site, for example SVM_Binary_Classifier.py and running it on your machine.

Note: if this message occurs you have to build dlib from source:

dlib-19.7.0-cp36-cp36m-win_amd64.whl is not a supported wheel on this platform


Install Dlib from source (If the solution above doesn't work)

Windows Dlib > 19.7.0

  1. Download the CMake installer and install it: https://cmake.org/download/
  2. Add CMake executable path to the Enviroment Variables:

    set PATH="%PATH%;C:\Program Files\CMake\bin"

    note: The path of the executable could be different from C:\Program Files\CMake\bin, just set the PATH accordingly.

    note: The path will be set temporarily, to make the change permanent you have to set it in the “Advanced system settings” ? “Environment Variables” tab.

  3. Restart The Cmd or PowerShell window for changes to take effect.

  4. Download the Dlib source(.tar.gz) from the Python Package Index : https://pypi.org/project/dlib/#files extract it and enter into the folder.
  5. Check the Python version: python -V. This is my output: Python 3.7.2 so I'm installing it for Python3.x and not for Python2.x

    note: You can install it for both Python 2 and Python 3, if you have set different variables for different binaries i.e: python2 -V, python3 -V

  6. Run the installation: python setup.py install


Linux Dlib 19.17.0

sudo apt-get install cmake

wget https://files.pythonhosted.org/packages/05/57/e8a8caa3c89a27f80bc78da39c423e2553f482a3705adc619176a3a24b36/dlib-19.17.0.tar.gz

tar -xvzf dlib-19.17.0.tar.gz

cd dlib-19.17.0/

sudo python3 setup.py install

note: To install Dlib for Python 2.x use python instead of python3 you can check your python version via python -V

Android getText from EditText field

Try out this will solve ur problem ....

EditText etxt = (EditText)findviewbyid(R.id.etxt);
String str_value = etxt.getText().toString();