Programs & Examples On #Nsdatecomponents

NSDateComponents is a class in Apple's Cocoa and CocoaTouch frameworks which represents either a date or a period of time as composed of several elements -- days, hours, and months, for example.

NSDate get year/month/day

Try this . . .

Code snippet:

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

It gives current year, month, date

Change Orientation of Bluestack : portrait/landscape mode

Try This...

Go to your notification area in the taskbar.

Right click on Bluestacks Agent>Rotate Portrait Apps>Enabled.

There are several options available..

a. Automatic - Selected By Default - It will rotate the app player in portrait mode for portrait apps.

b. Disabled - It will force the portrait apps to work in landscape mode.

c. Enabled - It will force the portrait apps to work in portrait mode only.

This May help you..

Putting an if-elif-else statement on one line?

People have already mentioned ternary expressions. Sometimes with a simple conditional assignment as your example, it is possible to use a mathematical expression to perform the conditional assignment. This may not make your code very readable, but it does get it on one fairly short line. Your example could be written like this:

x = 2*(i>100) | 1*(i<100)

The comparisons would be True or False, and when multiplying with numbers would then be either 1 or 0. One could use a + instead of an | in the middle.

The following classes could not be instantiated: - android.support.v7.widget.Toolbar

Find styles.xml in app/res/values folder.

Parent attribute of the style could be missing "Base". It should start as

<style name="AppTheme" parent="Base.Theme.AppCompat...

CSS way to horizontally align table

Try this:

<table width="200" style="margin-left:auto;margin-right:auto">

Change IPython/Jupyter notebook working directory

Locate your ipython binary. If you have used anaconda to install ipython-notebook on a mac, chances are it will be in the /Users/[name]/anaconda/bin/ directory

in that directory, instead of launching your notebook as

./ipython notebook

add a --notebook-dir=<unicode> option.

./ipython notebook --notebook-dir=u'../rel/path/to/your/python-notebooks'

I use a bashscript in my ipython bin directory to launch my notebooks:

DIR=$(dirname $0)
$DIR/ipython notebook --notebook-dir=u'../rel/path/to/your/python-notebooks'

Note - the path to the notebook dir is relative to the ipython bin directory.

Static class initializer in PHP

Note - the RFC proposing this is still in the draft state.


class Singleton
{
    private static function __static()
    {
        //...
    }
    //...
}

proposed for PHP 7.x (see https://wiki.php.net/rfc/static_class_constructor )

How do I extract the contents of an rpm?

Did you try the rpm2cpio commmand? See the example below:

$ rpm2cpio php-5.1.4-1.esp1.x86_64.rpm | cpio -idmv

/etc/httpd/conf.d/php.conf  
./etc/php.d  
./etc/php.ini  
./usr/bin/php  
./usr/bin/php-cgi  
etc 

How do I list all the files in a directory and subdirectories in reverse chronological order?

ls -lR is to display all files, directories and sub directories of the current directory ls -lR | more is used to show all the files in a flow.

SFTP file transfer using Java JSch

The most trivial way to upload a file over SFTP with JSch is:

JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();

ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();

sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");

Similarly for a download:

sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");

You may need to deal with UnknownHostKey exception.

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

jQuery DataTables Getting selected row values

var table = $('#myTableId').DataTable();
var a= [];
$.each(table.rows('.myClassName').data(), function() {
a.push(this["productId"]);
});

console.log(a[0]);

Select value if condition in SQL Server

Try Case

SELECT   stock.name,
      CASE 
         WHEN stock.quantity <20 THEN 'Buy urgent'
         ELSE 'There is enough'
      END
FROM stock

SHA1 vs md5 vs SHA256: which to use for a PHP login?

What people seem to be missing is that if the hacker has access to the database he probably also has access to the php file that hashes the password and can likely just modify that to send him all the successful user name password combos. If he doesn't have access to the web directory he could always just pick a password hash it, and write that into the database. In other words the hash algorithm doesn't really matter as much as system security, and limiting login attempts also if you don't use SSL then the attacker can just listen in on the connection to get the information. Unless you need the algorithm to take a long time to compute (for your own purposes) then SHA-256 or SHA-512 with a user specific salt should be enough.

As an added security measure set up a script (bash, batch, python, etc) or program and give it an obscure name and have it check and see if login.php has changed (check date/time stamp) and send you an email if it has. Also should probably log all attempts at login with admin rights and log all failed attempts to log into the database and have the logs emailed to you.

How can I convert String to Int?

Convert.ToInt32( TextBoxD1.Text );

Use this if you feel confident that the contents of the text box is a valid int. A safer option is

int val = 0;
Int32.TryParse( TextBoxD1.Text, out val );

This will provide you with some default value you can use. Int32.TryParse also returns a Boolean value indicating whether it was able to parse or not, so you can even use it as the condition of an if statement.

if( Int32.TryParse( TextBoxD1.Text, out val ){
  DoSomething(..);
} else {
  HandleBadInput(..);
}

How to add element to C++ array?

You don't have to use vectors. If you want to stick with plain arrays, you can do something like this:

int arr[] = new int[15];
unsigned int arr_length = 0;

Now, if you want to add an element to the end of the array, you can do this:

if (arr_length < 15) {
  arr[arr_length++] = <number>;
} else {
  // Handle a full array.
}

It's not as short and graceful as the PHP equivalent, but it accomplishes what you were attempting to do. To allow you to easily change the size of the array in the future, you can use a #define.

#define ARRAY_MAX 15

int arr[] = new int[ARRAY_MAX];
unsigned int arr_length = 0;

if (arr_length < ARRAY_MAX) {
  arr[arr_length++] = <number>;
} else {
  // Handle a full array.
}

This makes it much easier to manage the array in the future. By changing 15 to 100, the array size will be changed properly in the whole program. Note that you will have to set the array to the maximum expected size, as you can't change it once the program is compiled. For example, if you have an array of size 100, you could never insert 101 elements.

If you will be using elements off the end of the array, you can do this:

if (arr_length > 0) {
  int value = arr[arr_length--];
} else {
  // Handle empty array.
}

If you want to be able to delete elements off the beginning, (ie a FIFO), the solution becomes more complicated. You need a beginning and end index as well.

#define ARRAY_MAX 15

int arr[] = new int[ARRAY_MAX];
unsigned int arr_length = 0;
unsigned int arr_start = 0;
unsigned int arr_end = 0;

// Insert number at end.
if (arr_length < ARRAY_MAX) {
  arr[arr_end] = <number>;
  arr_end = (arr_end + 1) % ARRAY_MAX;
  arr_length ++;
} else {
  // Handle a full array.
}

// Read number from beginning.
if (arr_length > 0) {
  int value = arr[arr_start];
  arr_start = (arr_start + 1) % ARRAY_MAX;
  arr_length --;
} else {
  // Handle an empty array.
}

// Read number from end.
if (arr_length > 0) {
  int value = arr[arr_end];
  arr_end = (arr_end + ARRAY_MAX - 1) % ARRAY_MAX;
  arr_length --;
} else {
  // Handle an empty array.
}

Here, we are using the modulus operator (%) to cause the indexes to wrap. For example, (99 + 1) % 100 is 0 (a wrapping increment). And (99 + 99) % 100 is 98 (a wrapping decrement). This allows you to avoid if statements and make the code more efficient.

You can also quickly see how helpful the #define is as your code becomes more complex. Unfortunately, even with this solution, you could never insert over 100 items (or whatever maximum you set) in the array. You are also using 100 bytes of memory even if only 1 item is stored in the array.

This is the primary reason why others have recommended vectors. A vector is managed behind the scenes and new memory is allocated as the structure expands. It is still not as efficient as an array in situations where the data size is already known, but for most purposes the performance differences will not be important. There are trade-offs to each approach and it's best to know both.

C# if/then directives for debug vs release

I got to thinking about a better way. It dawned on me that #if blocks are effectively comments in other configurations (assuming DEBUG or RELEASE; but true with any symbol)

public class Mytest
    {
        public DateTime DateAndTimeOfTransaction;
    }

    public void ProcessCommand(Mytest Command)
        {
            CheckMyCommandPreconditions(Command);
            // do more stuff with Command...
        }

        [Conditional("DEBUG")]
        private static void CheckMyCommandPreconditions(Mytest Command)
        {
            if (Command.DateAndTimeOfTransaction > DateTime.Now)
                throw new InvalidOperationException("DateTime expected to be in the past");
        }

Programmatically navigate using react router V4

If you are targeting browser environments, you need to use react-router-dom package, instead of react-router. They are following the same approach as React did, in order to separate the core, (react) and the platform specific code, (react-dom, react-native ) with the subtle difference that you don't need to install two separate packages, so the environment packages contain everything you need. You can add it to your project as:

yarn add react-router-dom

or

npm i react-router-dom

The first thing you need to do is to provide a <BrowserRouter> as the top most parent component in your application. <BrowserRouter> uses the HTML5 history API and manages it for you, so you don't have to worry about instantiating it yourself and passing it down to the <BrowserRouter> component as a prop (as you needed to do in previous versions).

In V4, for navigating programatically you need to access the history object, which is available through React context, as long as you have a <BrowserRouter> provider component as the top most parent in your application. The library exposes through context the router object, that itself contains history as a property. The history interface offers several navigation methods, such as push, replace and goBack, among others. You can check the whole list of properties and methods here.

Important Note to Redux/Mobx users

If you are using redux or mobx as your state management library in your application, you may have come across issues with components that should be location-aware but are not re-rendered after triggering an URL update

That's happening because react-router passes location to components using the context model.

Both connect and observer create components whose shouldComponentUpdate methods do a shallow comparison of their current props and their next props. Those components will only re-render when at least one prop has changed. This means that in order to ensure they update when the location changes, they will need to be given a prop that changes when the location changes.

The 2 approaches for solving this are:

  • Wrap your connected component in a pathless <Route />. The current location object is one of the props that a <Route> passes to the component it renders
  • Wrap your connected component with the withRouter higher-order component, that in fact has the same effect and injects location as a prop

Setting that aside, there are four ways to navigate programatically, ordered by recommendation:

1.- Using a <Route> Component

It promotes a declarative style. Prior to v4, <Route /> components were placed at the top of your component hierarchy, having to think of your routes structure beforehand. However, now you can have <Route> components anywhere in your tree, allowing you to have a finer control for conditionally rendering depending on the URL. Route injects match, location and history as props into your component. The navigation methods (such as push, replace, goBack...) are available as properties of the history object.

There are 3 ways to render something with a Route, by using either component, render or children props, but don't use more than one in the same Route. The choice depends on the use case, but basically the first two options will only render your component if the path matches the url location, whereas with children the component will be rendered whether the path matches the location or not (useful for adjusting the UI based on URL matching).

If you want to customise your component rendering output, you need to wrap your component in a function and use the render option, in order to pass to your component any other props you desire, apart from match, location and history. An example to illustrate:

import { BrowserRouter as Router } from 'react-router-dom'

const ButtonToNavigate = ({ title, history }) => (
  <button
    type="button"
    onClick={() => history.push('/my-new-location')}
  >
    {title}
  </button>
);

const SomeComponent = () => (
  <Route path="/" render={(props) => <ButtonToNavigate {...props} title="Navigate elsewhere" />} />
)    

const App = () => (
  <Router>
    <SomeComponent /> // Notice how in v4 we can have any other component interleaved
    <AnotherComponent />
  </Router>
);

2.- Using withRouter HoC

This higher order component will inject the same props as Route. However, it carries along the limitation that you can have only 1 HoC per file.

import { withRouter } from 'react-router-dom'

const ButtonToNavigate = ({ history }) => (
  <button
    type="button"
    onClick={() => history.push('/my-new-location')}
  >
    Navigate
  </button>
);


ButtonToNavigate.propTypes = {
  history: React.PropTypes.shape({
    push: React.PropTypes.func.isRequired,
  }),
};

export default withRouter(ButtonToNavigate);

3.- Using a Redirect component

Rendering a <Redirect> will navigate to a new location. But keep in mind that, by default, the current location is replaced by the new one, like server-side redirects (HTTP 3xx). The new location is provided by to prop, that can be a string (URL to redirect to) or a location object. If you want to push a new entry onto the history instead, pass a push prop as well and set it to true

<Redirect to="/your-new-location" push />

4.- Accessing router manually through context

A bit discouraged because context is still an experimental API and it is likely to break/change in future releases of React

const ButtonToNavigate = (props, context) => (
  <button
    type="button"
    onClick={() => context.router.history.push('/my-new-location')}
  >
    Navigate to a new location
  </button>
);

ButtonToNavigate.contextTypes = {
  router: React.PropTypes.shape({
    history: React.PropTypes.object.isRequired,
  }),
};

Needless to say there are also other Router components that are meant to be for non browser ecosystems, such as <NativeRouter> that replicates a navigation stack in memory and targets React Native platform, available through react-router-native package.

For any further reference, don't hesitate to take a look at the official docs. There is also a video made by one of the co-authors of the library that provides a pretty cool introduction to react-router v4, highlighting some of the major changes.

Matrix Multiplication in pure Python?

If you really don't want to use numpy you can do something like this:

def matmult(a,b):
    zip_b = zip(*b)
    # uncomment next line if python 3 : 
    # zip_b = list(zip_b)
    return [[sum(ele_a*ele_b for ele_a, ele_b in zip(row_a, col_b)) 
             for col_b in zip_b] for row_a in a]

x = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
y = [[1,2],[1,2],[3,4]]

import numpy as np # I want to check my solution with numpy

mx = np.matrix(x)
my = np.matrix(y)       

Result:

>>> matmult(x,y)
[[12, 18], [27, 42], [42, 66], [57, 90]]
>>> mx * my
matrix([[12, 18],
        [27, 42],
        [42, 66],
        [57, 90]])

List of strings to one string

I would go with option A:

String.Join(String.Empty, los.ToArray());

My reasoning is because the Join method was written for that purpose. In fact if you look at Reflector, you'll see that unsafe code was used to really optimize it. The other two also WORK, but I think the Join function was written for this purpose, and I would guess, the most efficient. I could be wrong though...

As per @Nuri YILMAZ without .ToArray(), but this is .NET 4+:

String.Join(String.Empty, los);

Want to download a Git repository, what do I need (windows machine)?

To change working directory in GitMSYS's Git Bash you can just use cd

cd /path/do/directory

Note that:

  • Directory separators use the forward-slash (/) instead of backslash.
  • Drives are specified with a lower case letter and no colon, e.g. "C:\stuff" should be represented with "/c/stuff".
  • Spaces can be escaped with a backslash (\)
  • Command line completion is your friend. Press TAB at anytime to expand stuff, including Git options, branches, tags, and directories.

Also, you can right click in Windows Explorer on a directory and "Git Bash here".

When to use RabbitMQ over Kafka?

Use RabbitMQ when:

  • You don’t have to handle with Bigdata and you prefer a convenient in-built UI for monitoring
  • No need of automatically replicable queues
  • No multi subscribers for the messages- Since unlike Kafka which is a log, RabbitMQ is a queue and messages are removed once consumed and acknowledgment arrived
  • If you have the requirements to use Wildcards and regex for messages
  • If defining message priority is important

In Short: RabbitMQ is good for simple use cases, with low traffic of data, with the benefit of priority queue and flexible routing options. For massive data and high throughput use Kafka.

Show an image preview before upload

Without FileReader, we can use URL.createObjectURL method to get the DOMString that represents the object ( our image file ).

Don't forget to validate image extension.

<input type="file" id="files" multiple />
<div class="image-preview"></div>
let file_input = document.querySelector('#files');
let image_preview = document.querySelector('.image-preview');

const handle_file_preview = (e) => {
  let files = e.target.files;
  let length = files.length;

  for(let i = 0; i < length; i++) {
      let image = document.createElement('img');
      // use the DOMstring for source
      image.src = window.URL.createObjectURL(files[i]);
      image_preview.appendChild(image);
  }
}

file_input.addEventListener('change', handle_file_preview);

Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied

I have had the same problem with anaconda on windows. It seems that there is an issu with mcAfee antivirus. If you deactivate it while running the updates or the installs, it allows you to properly run the installation.

How do DATETIME values work in SQLite?

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:

TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS"). REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar. INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC. Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.

Having said that, I would use INTEGER and store seconds since Unix epoch (1970-01-01 00:00:00 UTC).

javascript filter array multiple conditions

Using Array.Filter() with Arrow Functions we can achieve this using

users = users.filter(x => x.name == 'Mark' && x.address == 'England');

Here is the complete snippet

_x000D_
_x000D_
// initializing list of users_x000D_
var users = [{_x000D_
    name: 'John',_x000D_
    email: '[email protected]',_x000D_
    age: 25,_x000D_
    address: 'USA'_x000D_
  },_x000D_
  {_x000D_
    name: 'Tom',_x000D_
    email: '[email protected]',_x000D_
    age: 35,_x000D_
    address: 'England'_x000D_
  },_x000D_
  {_x000D_
    name: 'Mark',_x000D_
    email: '[email protected]',_x000D_
    age: 28,_x000D_
    address: 'England'_x000D_
  }_x000D_
];_x000D_
_x000D_
//filtering the users array and saving _x000D_
//result back in users variable_x000D_
users = users.filter(x => x.name == 'Mark' && x.address == 'England');_x000D_
_x000D_
_x000D_
//logging out the result in console_x000D_
console.log(users);
_x000D_
_x000D_
_x000D_

How to reload/refresh jQuery dataTable?

i would recommend using the following code.

table.ajax.reload(null, false); 

The reason for this, user paging will not be reset on reload.
Example:

<button id='refresh'> Refresh </button>

<script>
    $(document).ready(function() {

        table = $("#my-datatable").DataTable();
        $("#refresh").on("click", function () { 
         table.ajax.reload(null, false); 
        });

   });
</script>

detail about this can be found at Here

Why does git revert complain about a missing -m option?

Say the other guy created bar on top of foo, but you created baz in the meantime and then merged, giving a history of

$ git lola
*   2582152 (HEAD, master) Merge branch 'otherguy'
|\  
| * c7256de (otherguy) bar
* | b7e7176 baz
|/  
* 9968f79 foo

Note: git lola is a non-standard but useful alias.

No dice with git revert:

$ git revert HEAD
fatal: Commit 2582152... is a merge but no -m option was given.

Charles Bailey gave an excellent answer as usual. Using git revert as in

$ git revert --no-edit -m 1 HEAD
[master e900aad] Revert "Merge branch 'otherguy'"
 0 files changed, 0 insertions(+), 0 deletions(-)
 delete mode 100644 bar

effectively deletes bar and produces a history of

$ git lola
* e900aad (HEAD, master) Revert "Merge branch 'otherguy'"
*   2582152 Merge branch 'otherguy'
|\  
| * c7256de (otherguy) bar
* | b7e7176 baz
|/  
* 9968f79 foo

But I suspect you want to throw away the merge commit:

$ git reset --hard HEAD^
HEAD is now at b7e7176 baz

$ git lola
* b7e7176 (HEAD, master) baz
| * c7256de (otherguy) bar
|/  
* 9968f79 foo

As documented in the git rev-parse manual

<rev>^, e.g. HEAD^, v1.5.1^0
A suffix ^ to a revision parameter means the first parent of that commit object. ^<n> means the n-th parent (i.e. <rev>^ is equivalent to <rev>^1). As a special rule, <rev>^0 means the commit itself and is used when <rev> is the object name of a tag object that refers to a commit object.

so before invoking git reset, HEAD^ (or HEAD^1) was b7e7176 and HEAD^2 was c7256de, i.e., respectively the first and second parents of the merge commit.

Be careful with git reset --hard because it can destroy work.

Close Window from ViewModel

You can create new Event handler in the ViewModel like this.

public event EventHandler RequestClose;

    protected void OnRequestClose()
    {
        if (RequestClose != null)
            RequestClose(this, EventArgs.Empty);
    }

Then Define RelayCommand for ExitCommand.

private RelayCommand _CloseCommand;
    public ICommand CloseCommand
    {
        get
        {
            if(this._CloseCommand==null)
                this._CloseCommand=new RelayCommand(CloseClick);
            return this._CloseCommand;
        }
    }

    private void CloseClick(object obj)
    {
        OnRequestClose();
    }

Then In XAML file set

<Button Command="{Binding CloseCommand}" />

Set the DataContext in the xaml.cs File and Subscribe to the event we created.

public partial class MainWindow : Window
{
    private ViewModel mainViewModel = null;
    public MainWindow()
    {
        InitializeComponent();
        mainViewModel = new ViewModel();
        this.DataContext = mainViewModel;
        mainViewModel.RequestClose += delegate(object sender, EventArgs args) { this.Close(); };
    }
}

How to overlay density plots in R?

I took the above lattice example and made a nifty function. There is probably a better way to do this with reshape via melt/cast. (Comment or edit if you see an improvement.)

multi.density.plot=function(data,main=paste(names(data),collapse = ' vs '),...){
  ##combines multiple density plots together when given a list
  df=data.frame();
  for(n in names(data)){
    idf=data.frame(x=data[[n]],label=rep(n,length(data[[n]])))
    df=rbind(df,idf)
  }
  densityplot(~x,data=df,groups = label,plot.points = F, ref = T, auto.key = list(space = "right"),main=main,...)
}

Example usage:

multi.density.plot(list(BN1=bn1$V1,BN2=bn2$V1),main='BN1 vs BN2')

multi.density.plot(list(BN1=bn1$V1,BN2=bn2$V1))

git rebase merge conflict

Rebasing can be a real headache. You have to resolve the merge conflicts and continue rebasing. For example you can use the merge tool (which differs depending on your settings)

git mergetool

Then add your changes and go on

git rebase --continue

Good luck

Updating the list view when the adapter data changes

I found a solution that is more efficient than currently accepted answer, because current answer forces all list elements to be refreshed. My solution will refresh only one element (that was touched) by calling adapters getView and recycling current view which adds even more efficiency.

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      // Edit object data that is represented in Viewat at list's "position"
      view = mAdapter.getView(position, view, parent);
    }
});

How to list files in a directory in a C program?

One tiny addition to JB Jansen's answer - in the main readdir() loop I'd add this:

  if (dir->d_type == DT_REG)
  {
     printf("%s\n", dir->d_name);
  }

Just checking if it's really file, not (sym)link, directory, or whatever.

NOTE: more about struct dirent in libc documentation.

Cast Int to enum in Java

In Kotlin:

enum class Status(val id: Int) {
    NEW(0), VISIT(1), IN_WORK(2), FINISHED(3), CANCELLED(4), DUMMY(5);

    companion object {
        private val statuses = Status.values().associateBy(Status::id)

        fun getStatus(id: Int): Status? = statuses[id]
    }
}

Usage:

val status = Status.getStatus(1)!!

Joining three tables using MySQL

Just adding a point to previous answers that in MySQL we can either use

table_factor syntax 

OR

joined_table syntax

mysql documentation

Table_factor example

SELECT prd.name, b.name 
FROM products prd, buyers b

Joined Table example

SELECT prd.name, b.name 
FROM products prd
 left join buyers b on b.bid = prd.bid;

FYI: Please ignore the fact the the left join on the joined table example doesnot make much sense (in reality we would use some sort of join table to link buyer to the product table instead of saving buyerID in product table).

Can a html button perform a POST request?

You can do that with a little help of JS. In the example below, a POST request is being submitted on a button click using the fetch method:

_x000D_
_x000D_
const button = document.getElementById('post-btn');_x000D_
_x000D_
button.addEventListener('click', async _ => {_x000D_
  try {     _x000D_
    const response = await fetch('yourUrl', {_x000D_
      method: 'post',_x000D_
      body: {_x000D_
        // Your body_x000D_
      }_x000D_
    });_x000D_
    console.log('Completed!', response);_x000D_
  } catch(err) {_x000D_
    console.error(`Error: ${err}`);_x000D_
  }_x000D_
});
_x000D_
<button id="post-btn">I'm a button</button>
_x000D_
_x000D_
_x000D_

'App not Installed' Error on Android

Sometimes it is because you have no enough space on your phone. If so, try to clean up your memory to create space for new installations.

How to get random value out of an array?

One line: $ran[rand(0, count($ran) - 1)]

Calling a function on bootstrap modal open

will not work.. use $(window) instead

For Showing

$(window).on('shown.bs.modal', function() { 
    $('#code').modal('show');
    alert('shown');
});

For Hiding

$(window).on('hidden.bs.modal', function() { 
    $('#code').modal('hide');
    alert('hidden');
});

How to set a cron job to run at a exact time?

My use case is that I'm on a metered account. Data transfer is limited on weekdays, Mon - Fri, from 6am - 6pm. I am using bandwidth limiting, but somehow, data still slips through, about 1GB per day!

I strongly suspected it's sickrage or sickbeard, doing a high amount of searches. My download machine is called "download." The following was my solution, using the above,for starting, and stopping the download VM, using KVM:

# Stop download Mon-Fri, 6am
0 6 * * 1,2,3,4,5 root          virsh shutdown download
# Start download Mon-Fri, 6pm
0 18 * * 1,2,3,4,5 root         virsh start download

I think this is correct, and hope it helps someone else too.

Add column to SQL Server

Adding a column using SSMS or ALTER TABLE .. ADD will not drop any existing data.

How to remove element from an array in JavaScript?

You can also do this with reduce:

let arr = [1, 2, 3]

arr.reduce((xs, x, index) => {
        if (index == 0) {
            return xs
        } else {
            return xs.concat(x)
        }
    }, Array())

// Or if you like a oneliner
arr.reduce((xs, x, index) => index == 0 ? xs : xs.concat(x), Array())

Finding modified date of a file/folder

PowerShell code to find all document library files modified from last 2 days.

$web = Get-SPWeb -Identity http://siteName:9090/ 
        $list = $web.GetList("http://siteName:9090/Style Library/")
        $folderquery =  New-Object Microsoft.SharePoint.SPQuery  
        $foldercamlQuery =  
        '<Where>   <Eq> 
                <FieldRef Name="ContentType" />  <Value Type="text">Folder</Value> 
            </Eq> </Where>' 
        $folderquery.Query = $foldercamlQuery 
        $folders = $list.GetItems($folderquery) 
        foreach($folderItem in $folders) 
        { 
            $folder = $folderItem.Folder
            if($folder.ItemCount -gt 0){ 
            Write-Host " find Item count " $folder.ItemCount
                $oldest = $null
                $files = $folder.Files

                $date = (Get-Date).AddDays(-2).ToString(“MM/dd/yyyy”)
                foreach ($file in $files){ 
                    if($file.Item["Modified"]-Ge $date)
                    {
                        Write-Host "Last 2 days modified folder name:"   $folder   " File Name: "  $file.Item["Name"]   " Date of midified: "  $file.Item["Modified"] 
                    } 
                } 
            } 
            else
             { 
                Write-Warning "$folder['Name'] is empty" 
            } 
        }

How to make the overflow CSS property work with hidden as value

I did not get it. I had a similar problem but in my nav bar.

What I was doing is I kept my navBar code in this way: nav>div.navlinks>ul>li*3>a

In order to put hover effects on a I positioned a to relative and designed a::before and a::after then i put a gray background on before and after elements and kept hover effects in such way that as one hovers on <a> they will pop from outside a to fill <a>.

The problem is that the overflow hidden is not working on <a>.

What i discovered is if i removed <li> and simply put <a> without <ul> and <li> then it worked.

What may be the problem?

How to create empty constructor for data class in Kotlin Android

If you give a default value to each primary constructor parameter:

data class Item(var id: String = "",
            var title: String = "",
            var condition: String = "",
            var price: String = "",
            var categoryId: String = "",
            var make: String = "",
            var model: String = "",
            var year: String = "",
            var bodyStyle: String = "",
            var detail: String = "",
            var latitude: Double = 0.0,
            var longitude: Double = 0.0,
            var listImages: List<String> = emptyList(),
            var idSeller: String = "")

and from the class where the instances you can call it without arguments or with the arguments that you have that moment

var newItem = Item()

var newItem2 = Item(title = "exampleTitle",
            condition = "exampleCondition",
            price = "examplePrice",
            categoryId = "exampleCategoryId")

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

Spring MVC: How to return image in @ResponseBody?

This is how I do it with Spring Boot and Guava:

@RequestMapping(value = "/getimage", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public void getImage( HttpServletResponse response ) throws IOException
{
    ByteStreams.copy( getClass().getResourceAsStream( "/preview-image.jpg" ), response.getOutputStream() );
}

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

I was hitting this error in one Spring Boot app, but not in another. Finally, I found the Spring Boot version in the one not working was 2.0.0.RELEASE and the one that was working was 2.0.1.RELEASE. That led to a difference in the MySQL Connector -- 5.1.45 vs. 5.1.46. I updated the Spring Boot version for the app that was throwing this error at startup and now it works.

Delete multiple objects in django

You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model

Post.objects.all().delete()

and to delete any Post with a future publication date

Post.objects.filter(pub_date__gt=datetime.now()).delete()

You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.

EDIT:

Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForms and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.

Create hyperlink to another sheet

In my implementation, the cell I was referencing could have been several options. I used the following format where 'ws' is the current worksheet being edited

For each ws in Activeworkbook.Worksheets
    For i…
       For j...
...
ws.Cells(i, j).Value = "=HYPERLINK(""#'" & SHEET-REF-VAR & "'!" & CELL-REF-VAR & """,""" & SHEET-REF-VAR & """)"

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

I solved this simply:

<div ng-repeat="Object in List | filter: (FilterObj.FilterProperty1 ? {'ObjectProperty1': FilterObj.FilterProperty1} : '') | filter:(FilterObj.FilterProperty2 ? {'ObjectProperty2': FilterObj.FilterProperty2} : '')">

How can I change the color of AlertDialog title and the color of the line under it

This will set the color for the title, icon, and divider. Bound to change with any new Android version.

public static void colorAlertDialogTitle(AlertDialog dialog, int color) {
    int dividerId = dialog.getContext().getResources().getIdentifier("android:id/titleDivider", null, null);
    if (dividerId != 0) {
        View divider = dialog.findViewById(dividerId);
        divider.setBackgroundColor(color);
    }

    int textViewId = dialog.getContext().getResources().getIdentifier("android:id/alertTitle", null, null);
    if (textViewId != 0) {
        TextView tv = (TextView) dialog.findViewById(textViewId);
        tv.setTextColor(color);
    }

    int iconId = dialog.getContext().getResources().getIdentifier("android:id/icon", null, null);
    if (iconId != 0) {
        ImageView icon = (ImageView) dialog.findViewById(iconId);
        icon.setColorFilter(color);
    }
}

Remember to call dialog.show() before calling this method.

Automating the InvokeRequired code pattern

Create a ThreadSafeInvoke.snippet file, and then you can just select the update statements, right click and select 'Surround With...' or Ctrl-K+S:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>ThreadsafeInvoke</Title>
    <Shortcut></Shortcut>
    <Description>Wraps code in an anonymous method passed to Invoke for Thread safety.</Description>
    <SnippetTypes>
      <SnippetType>SurroundsWith</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Code Language="CSharp">
      <![CDATA[
      Invoke( (MethodInvoker) delegate
      {
          $selected$
      });      
      ]]>
    </Code>
  </Snippet>
</CodeSnippet>

How to make php display \t \n as tab and new line instead of characters

Put it in double quotes:

echo "\t";

Single quotes do not expand escaped characters.

Use the documentation when in doubt.

How can I make my string property nullable?

string type is a reference type, therefore it is nullable by default. You can only use Nullable<T> with value types.

public struct Nullable<T> where T : struct

Which means that whatever type is replaced for the generic parameter, it must be a value type.

How can I tell AngularJS to "refresh"

Why $apply should be called?

TL;DR: $apply should be called whenever you want to apply changes made outside of Angular world.


Just to update @Dustin's answer, here is an explanation of what $apply exactly does and why it works.

$apply() is used to execute an expression in AngularJS from outside of the AngularJS framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the AngularJS framework we need to perform proper scope life cycle of exception handling, executing watches.

Angular allows any value to be used as a binding target. Then at the end of any JavaScript code turn, it checks to see if the value has changed. That step that checks to see if any binding values have changed actually has a method, $scope.$digest()1. We almost never call it directly, as we use $scope.$apply() instead (which will call $scope.$digest).

Angular only monitors variables used in expressions and anything inside of a $watch living inside the scope. So if you are changing the model outside of the Angular context, you will need to call $scope.$apply() for those changes to be propagated, otherwise Angular will not know that they have been changed thus the binding will not be updated2.

Grant all on a specific schema in the db to a group role in PostgreSQL

My answer is similar to this one on ServerFault.com.

To Be Conservative

If you want to be more conservative than granting "all privileges", you might want to try something more like these.

GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO some_user_;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO some_user_;

The use of public there refers to the name of the default schema created for every new database/catalog. Replace with your own name if you created a schema.

Access to the Schema

To access a schema at all, for any action, the user must be granted "usage" rights. Before a user can select, insert, update, or delete, a user must first be granted "usage" to a schema.

You will not notice this requirement when first using Postgres. By default every database has a first schema named public. And every user by default has been automatically been granted "usage" rights to that particular schema. When adding additional schema, then you must explicitly grant usage rights.

GRANT USAGE ON SCHEMA some_schema_ TO some_user_ ;

Excerpt from the Postgres doc:

For schemas, allows access to objects contained in the specified schema (assuming that the objects' own privilege requirements are also met). Essentially this allows the grantee to "look up" objects within the schema. Without this permission, it is still possible to see the object names, e.g. by querying the system tables. Also, after revoking this permission, existing backends might have statements that have previously performed this lookup, so this is not a completely secure way to prevent object access.

For more discussion see the Question, What GRANT USAGE ON SCHEMA exactly do?. Pay special attention to the Answer by Postgres expert Craig Ringer.

Existing Objects Versus Future

These commands only affect existing objects. Tables and such you create in the future get default privileges until you re-execute those lines above. See the other answer by Erwin Brandstetter to change the defaults thereby affecting future objects.

How to set minDate to current date in jQuery UI Datepicker?

You can use the minDate property, like this:

$("input.DateFrom").datepicker({
    changeMonth: true, 
    changeYear: true, 
    dateFormat: 'yy-mm-dd',
    minDate: 0, // 0 days offset = today
    maxDate: 'today',
    onSelect: function(dateText) {
        $sD = new Date(dateText);
        $("input#DateTo").datepicker('option', 'minDate', min);
    }
});

You can also specify a date, like this:

minDate: new Date(), // = today

How to update Android Studio automatically?

For this task, I recommend using Android Studio IDE and choose the automatic installation program, and not the compressed file.

  1. On the top menu, select Help -> Check for Update...
  2. Upon the updates dialog below, select Updates link to configure your IDE settings.

Platform and Plugin Updates

  1. For checking updates, my suggestion is to select the Dev channel. I

don't recommend Beta or Canary

channel which is the unstable version and they are not automatic installation, instead a zip file is provided in that case.

Updates dialog

  1. When finished with the configuration, select Update and Restart for downloading the installation EXE.
  2. Run the installation.

Warning: Among different version of Android Studio, the steps may be different. But hopefully you get the idea, as I try to be clear on my intentions.

Extra info: If you want, check for Android Studio updates @ Android Tools Project Site - Recent Builds. This web page seems to be more accurate than other Android pages about tool updates.

How to find out which package version is loaded in R?

To check the version of R execute : R --version

Or after you are in the R shell print the contents of version$version.string

EDIT

To check the version of installed packages do the following.

After loading the library, you can execute sessionInfo ()

But to know the list of all installed packages:

packinfo <- installed.packages(fields = c("Package", "Version"))
packinfo[,c("Package", "Version")]

OR to extract a specific library version, once you have extracted the information using the installed.package function as above just use the name of the package in the first dimension of the matrix.

packinfo["RANN",c("Package", "Version")]
packinfo["graphics",c("Package", "Version")]

The above will print the versions of the RANN library and the graphics library.

Cannot read property length of undefined

The id of the input seems is not WallSearch. Maybe you're confusing that name and id. They are two different properties. name is used to define the name by which the value is posted, while id is the unique identification of the element inside the DOM.

Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value property.

For loop for HTMLCollection elements

You want to change it to

var list= document.getElementsByClassName("events");
console.log(list[0].id); //first console output
for (key in list){
    console.log(list[key].id); //second console output
}

Retrieving subfolders names in S3 bucket from boto3

Short answer:

  • Use Delimiter='/'. This avoids doing a recursive listing of your bucket. Some answers here wrongly suggest doing a full listing and using some string manipulation to retrieve the directory names. This could be horribly inefficient. Remember that S3 has virtually no limit on the number of objects a bucket can contain. So, imagine that, between bar/ and foo/, you have a trillion objects: you would wait a very long time to get ['bar/', 'foo/'].

  • Use Paginators. For the same reason (S3 is an engineer's approximation of infinity), you must list through pages and avoid storing all the listing in memory. Instead, consider your "lister" as an iterator, and handle the stream it produces.

  • Use boto3.client, not boto3.resource. The resource version doesn't seem to handle well the Delimiter option. If you have a resource, say a bucket = boto3.resource('s3').Bucket(name), you can get the corresponding client with: bucket.meta.client.

Long answer:

The following is an iterator that I use for simple buckets (no version handling).

import boto3
from collections import namedtuple
from operator import attrgetter


S3Obj = namedtuple('S3Obj', ['key', 'mtime', 'size', 'ETag'])


def s3list(bucket, path, start=None, end=None, recursive=True, list_dirs=True,
           list_objs=True, limit=None):
    """
    Iterator that lists a bucket's objects under path, (optionally) starting with
    start and ending before end.

    If recursive is False, then list only the "depth=0" items (dirs and objects).

    If recursive is True, then list recursively all objects (no dirs).

    Args:
        bucket:
            a boto3.resource('s3').Bucket().
        path:
            a directory in the bucket.
        start:
            optional: start key, inclusive (may be a relative path under path, or
            absolute in the bucket)
        end:
            optional: stop key, exclusive (may be a relative path under path, or
            absolute in the bucket)
        recursive:
            optional, default True. If True, lists only objects. If False, lists
            only depth 0 "directories" and objects.
        list_dirs:
            optional, default True. Has no effect in recursive listing. On
            non-recursive listing, if False, then directories are omitted.
        list_objs:
            optional, default True. If False, then directories are omitted.
        limit:
            optional. If specified, then lists at most this many items.

    Returns:
        an iterator of S3Obj.

    Examples:
        # set up
        >>> s3 = boto3.resource('s3')
        ... bucket = s3.Bucket(name)

        # iterate through all S3 objects under some dir
        >>> for p in s3ls(bucket, 'some/dir'):
        ...     print(p)

        # iterate through up to 20 S3 objects under some dir, starting with foo_0010
        >>> for p in s3ls(bucket, 'some/dir', limit=20, start='foo_0010'):
        ...     print(p)

        # non-recursive listing under some dir:
        >>> for p in s3ls(bucket, 'some/dir', recursive=False):
        ...     print(p)

        # non-recursive listing under some dir, listing only dirs:
        >>> for p in s3ls(bucket, 'some/dir', recursive=False, list_objs=False):
        ...     print(p)
"""
    kwargs = dict()
    if start is not None:
        if not start.startswith(path):
            start = os.path.join(path, start)
        # note: need to use a string just smaller than start, because
        # the list_object API specifies that start is excluded (the first
        # result is *after* start).
        kwargs.update(Marker=__prev_str(start))
    if end is not None:
        if not end.startswith(path):
            end = os.path.join(path, end)
    if not recursive:
        kwargs.update(Delimiter='/')
        if not path.endswith('/'):
            path += '/'
    kwargs.update(Prefix=path)
    if limit is not None:
        kwargs.update(PaginationConfig={'MaxItems': limit})

    paginator = bucket.meta.client.get_paginator('list_objects')
    for resp in paginator.paginate(Bucket=bucket.name, **kwargs):
        q = []
        if 'CommonPrefixes' in resp and list_dirs:
            q = [S3Obj(f['Prefix'], None, None, None) for f in resp['CommonPrefixes']]
        if 'Contents' in resp and list_objs:
            q += [S3Obj(f['Key'], f['LastModified'], f['Size'], f['ETag']) for f in resp['Contents']]
        # note: even with sorted lists, it is faster to sort(a+b)
        # than heapq.merge(a, b) at least up to 10K elements in each list
        q = sorted(q, key=attrgetter('key'))
        if limit is not None:
            q = q[:limit]
            limit -= len(q)
        for p in q:
            if end is not None and p.key >= end:
                return
            yield p


def __prev_str(s):
    if len(s) == 0:
        return s
    s, c = s[:-1], ord(s[-1])
    if c > 0:
        s += chr(c - 1)
    s += ''.join(['\u7FFF' for _ in range(10)])
    return s

Test:

The following is helpful to test the behavior of the paginator and list_objects. It creates a number of dirs and files. Since the pages are up to 1000 entries, we use a multiple of that for dirs and files. dirs contains only directories (each having one object). mixed contains a mix of dirs and objects, with a ratio of 2 objects for each dir (plus one object under dir, of course; S3 stores only objects).

import concurrent
def genkeys(top='tmp/test', n=2000):
    for k in range(n):
        if k % 100 == 0:
            print(k)
        for name in [
            os.path.join(top, 'dirs', f'{k:04d}_dir', 'foo'),
            os.path.join(top, 'mixed', f'{k:04d}_dir', 'foo'),
            os.path.join(top, 'mixed', f'{k:04d}_foo_a'),
            os.path.join(top, 'mixed', f'{k:04d}_foo_b'),
        ]:
            yield name


with concurrent.futures.ThreadPoolExecutor(max_workers=32) as executor:
    executor.map(lambda name: bucket.put_object(Key=name, Body='hi\n'.encode()), genkeys())

The resulting structure is:

./dirs/0000_dir/foo
./dirs/0001_dir/foo
./dirs/0002_dir/foo
...
./dirs/1999_dir/foo
./mixed/0000_dir/foo
./mixed/0000_foo_a
./mixed/0000_foo_b
./mixed/0001_dir/foo
./mixed/0001_foo_a
./mixed/0001_foo_b
./mixed/0002_dir/foo
./mixed/0002_foo_a
./mixed/0002_foo_b
...
./mixed/1999_dir/foo
./mixed/1999_foo_a
./mixed/1999_foo_b

With a little bit of doctoring of the code given above for s3list to inspect the responses from the paginator, you can observe some fun facts:

  • The Marker is really exclusive. Given Marker=topdir + 'mixed/0500_foo_a' will make the listing start after that key (as per the AmazonS3 API), i.e., with .../mixed/0500_foo_b. That's the reason for __prev_str().

  • Using Delimiter, when listing mixed/, each response from the paginator contains 666 keys and 334 common prefixes. It's pretty good at not building enormous responses.

  • By contrast, when listing dirs/, each response from the paginator contains 1000 common prefixes (and no keys).

  • Passing a limit in the form of PaginationConfig={'MaxItems': limit} limits only the number of keys, not the common prefixes. We deal with that by further truncating the stream of our iterator.

Fixing npm path in Windows 8 and 10

Try this one dude if you're using windows:

1.) Search environment variables at your start menu's search box.
2.) Click it then go to Environment Variables...
3.) Click PATH, click Edit
4.) Click New and try to copy and paste this: C:\Program Files\nodejs\node_modules\npm\bin

If you got an error. Do the number 4.) Click New, then browse the bin folder

  • You may also Visit this link for more info.

How to convert string to integer in UNIX

Use this:

#include <stdlib.h>
#include <string.h>

int main()
{
    const char *d1 = "11";
    int d1int = atoi(d1);
    printf("d1 = %d\n", d1);
    return 0;
}

etc.

Process all arguments except the first one (in a bash script)

If you want a solution that also works in /bin/sh try

first_arg="$1"
shift
echo First argument: "$first_arg"
echo Remaining arguments: "$@"

shift [n] shifts the positional parameters n times. A shift sets the value of $1 to the value of $2, the value of $2 to the value of $3, and so on, decreasing the value of $# by one.

How to limit text width

Try this:

<style> 
p
{
    width:100px; 
    word-wrap:break-word;
}
</style>

<p>Loremipsumdolorsitamet,consecteturadipiscingelit.Fusce non nisl
non ante malesuada mollis quis ut ipsum. Cum sociis natoque penatibus et magnis dis 
parturient montes, nascetur ridiculus mus. Cras ut adipiscing dolor. Nunc congue, 
tellus vehicula mattis porttitor, justo nisi sollicitudin nulla, a rhoncus lectus lacus 
id turpis. Vivamus diam lacus, egestas nec bibendum eu, mattis eget risus</p>

assign headers based on existing row in dataframe in R

The cleanest way is use a function of janitor package that is built for exactly this purpose.

janitor::row_to_names(DF,1)

If you want to use any other row than the first one, pass it in the second parameter.

MySQL Select last 7 days

The WHERE clause is misplaced, it has to follow the table references and JOIN operations.

Something like this:

 FROM tartikel p1 
 JOIN tartikelpict p2 
   ON p1.kArtikel = p2.kArtikel 
  AND p2.nNr = 1
WHERE p1.dErstellt >= DATE(NOW()) - INTERVAL 7 DAY
ORDER BY p1.kArtikel DESC

EDIT (three plus years later)

The above essentially answers the question "I tried to add a WHERE clause to my query and now the query is returning an error, how do I fix it?"

As to a question about writing a condition that checks a date range of "last 7 days"...

That really depends on interpreting the specification, what the datatype of the column in the table is (DATE or DATETIME) and what data is available... what should be returned.

To summarize: the general approach is to identify a "start" for the date/datetime range, and "end" of that range, and reference those in a query. Let's consider something easier... all rows for "yesterday".

If our column is DATE type. Before we incorporate an expression into a query, we can test it in a simple SELECT

 SELECT DATE(NOW()) + INTERVAL -1 DAY 

and verify the result returned is what we expect. Then we can use that same expression in a WHERE clause, comparing it to a DATE column like this:

 WHERE datecol = DATE(NOW()) + INTERVAL -1 DAY

For a DATETIME or TIMESTAMP column, we can use >= and < inequality comparisons to specify a range

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -1 DAY
   AND datetimecol <  DATE(NOW()) + INTERVAL  0 DAY

For "last 7 days" we need to know if that mean from this point right now, back 7 days ... e.g. the last 7*24 hours , including the time component in the comparison, ...

 WHERE datetimecol >= NOW() + INTERVAL -7 DAY
   AND datetimecol <  NOW() + INTERVAL  0 DAY

the last seven complete days, not including today

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -7 DAY
   AND datetimecol <  DATE(NOW()) + INTERVAL  0 DAY

or past six complete days plus so far today ...

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -6 DAY
   AND datetimecol <  NOW()       + INTERVAL  0 DAY

I recommend testing the expressions on the right side in a SELECT statement, we can use a user-defined variable in place of NOW() for testing, not being tied to what NOW() returns so we can test borders, across week/month/year boundaries, and so on.

SET @clock = '2017-11-17 11:47:47' ;

SELECT DATE(@clock)
     , DATE(@clock) + INTERVAL -7 DAY 
     , @clock + INTERVAL -6 DAY 

Once we have expressions that return values that work for "start" and "end" for our particular use case, what we mean by "last 7 days", we can use those expressions in range comparisons in the WHERE clause.

(Some developers prefer to use the DATE_ADD and DATE_SUB functions in place of the + INTERVAL val DAY/HOUR/MINUTE/MONTH/YEAR syntax.

And MySQL provides some convenient functions for working with DATE, DATETIME and TIMESTAMP datatypes... DATE, LAST_DAY,

Some developers prefer to calculate the start and end in other code, and supply string literals in the SQL query, such that the query submitted to the database is

  WHERE datetimecol >= '2017-11-10 00:00'
    AND datetimecol <  '2017-11-17 00:00'

And that approach works too. (My preference would be to explicitly cast those string literals into DATETIME, either with CAST, CONVERT or just the + INTERVAL trick...

  WHERE datetimecol >= '2017-11-10 00:00' + INTERVAL 0 SECOND
    AND datetimecol <  '2017-11-17 00:00' + INTERVAL 0 SECOND

The above all assumes we are storing "dates" in appropriate DATE, DATETIME and/or TIMESTAMP datatypes, and not storing them as strings in variety of formats e.g. 'dd/mm/yyyy', m/d/yyyy, julian dates, or in sporadically non-canonical formats, or as a number of seconds since the beginning of the epoch, this answer would need to be much longer.

Get a particular cell value from HTML table using JavaScript

function Vcount() {
var modify = document.getElementById("C_name1").value;
var oTable = document.getElementById('dataTable');
var i;
var rowLength = oTable.rows.length;
for (i = 1; i < rowLength; i++) {
    var oCells = oTable.rows.item(i).cells;
    if (modify == oCells[0].firstChild.data) {
        document.getElementById("Error").innerHTML = "  * duplicate value";
        return false;
        break;
    }

}

Return string without trailing slash

This snippet is more accurate:

str.replace(/^(.+?)\/*?$/, "$1");
  1. It not strips / strings, as it's a valid url.
  2. It strips strings with multiple trailing slashes.

How do I output lists as a table in Jupyter notebook?

tabletext fit this well

import tabletext

data = [[1,2,30],
        [4,23125,6],
        [7,8,999],
        ]

print tabletext.to_text(data)

result:

+-----------------+
¦ 1 ¦     2 ¦  30 ¦
+---+-------+-----¦
¦ 4 ¦ 23125 ¦   6 ¦
+---+-------+-----¦
¦ 7 ¦     8 ¦ 999 ¦
+-----------------+

How to get the changes on a branch in Git

This is similar to the answer I posted on: Preview a Git push

Drop these functions into your Bash profile:

  • gbout - git branch outgoing
  • gbin - git branch incoming

You can use this like:

  • If on master: gbin branch1 <-- this will show you what's in branch1 and not in master
  • If on master: gbout branch1 <-- this will show you what's in master that's not in branch 1

This will work with any branch.

function parse_git_branch {
  git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'
}

function gbin {
    echo branch \($1\) has these commits and \($(parse_git_branch)\) does not
    git log ..$1 --no-merges --format='%h | Author:%an | Date:%ad | %s' --date=local
}

function gbout {
    echo branch \($(parse_git_branch)\) has these commits and \($1\) does not
    git log $1.. --no-merges --format='%h | Author:%an | Date:%ad | %s' --date=local
}

Finding Android SDK on Mac and adding to PATH

If you don't want to open Android Studio just to modify your path...

They live here with a default installation:

${HOME}/Library/Android/sdk/tools
${HOME}/Library/Android/sdk/platform-tools

Here's what you want to add to your .bashwhatever

export PATH="${HOME}/Library/Android/sdk/tools:${HOME}/Library/Android/sdk/platform-tools:${PATH}"

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

Easiest ways to get file name:

val fileName = File(uri.path).name
// or
val fileName = uri.pathSegments.last()

If they don't give you the right name you should use:

fun Uri.getName(context: Context): String {
    val returnCursor = context.contentResolver.query(this, null, null, null, null)
    val nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
    returnCursor.moveToFirst()
    val fileName = returnCursor.getString(nameIndex)
    returnCursor.close()
    return fileName
}

Unexpected character encountered while parsing value

I have also encountered this error for a Web API (.Net Core 3.0) action that was binding to a string instead to an object or a JObject. The JSON was correct, but the binder tried to get a string from the JSON structure and failed.

So, instead of:

[HttpPost("[action]")]
public object Search([FromBody] string data)

I had to use the more specific:

[HttpPost("[action]")]
public object Search([FromBody] JObject data)

xls to csv converter

Quoting an answer from Scott Ming, which works with workbook containing multiple sheets:

Here is a python script getsheets.py (mirror), you should install pandas and xlrd before you use it.

Run this:

pip3 install pandas xlrd  # or `pip install pandas xlrd`

How does it works?

$ python3 getsheets.py -h
Usage: getsheets.py [OPTIONS] INPUTFILE

Convert a Excel file with multiple sheets to several file with one sheet.

Examples:

    getsheets filename

    getsheets filename -f csv

Options:
-f, --format [xlsx|csv]  Default xlsx.
-h, --help               Show this message and exit.

Convert to several xlsx:

$ python3 getsheets.py goods_temp.xlsx
Sheet.xlsx Done!
Sheet1.xlsx Done!

All Done!

Convert to several csv:

$ python3 getsheets.py goods_temp.xlsx -f csv
Sheet.csv Done!
Sheet1.csv Done!

All Done!

getsheets.py:

# -*- coding: utf-8 -*-

import click
import os
import pandas as pd


def file_split(file):
    s = file.split('.')
    name = '.'.join(s[:-1])  # get directory name
    return name


def getsheets(inputfile, fileformat):
    name = file_split(inputfile)
    try:
        os.makedirs(name)
    except:
        pass

    df1 = pd.ExcelFile(inputfile)
    for x in df1.sheet_names:
        print(x + '.' + fileformat, 'Done!')
        df2 = pd.read_excel(inputfile, sheetname=x)
        filename = os.path.join(name, x + '.' + fileformat)
        if fileformat == 'csv':
            df2.to_csv(filename, index=False)
        else:
            df2.to_excel(filename, index=False)
    print('\nAll Done!')


CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])


@click.command(context_settings=CONTEXT_SETTINGS)
@click.argument('inputfile')
@click.option('-f', '--format', type=click.Choice([
    'xlsx', 'csv']), default='xlsx', help='Default xlsx.')
def cli(inputfile, format):
    '''Convert a Excel file with multiple sheets to several file with one sheet.

    Examples:

    \b
        getsheets filename

    \b
        getsheets filename -f csv
    '''
    if format == 'csv':
        getsheets(inputfile, 'csv')
    else:
        getsheets(inputfile, 'xlsx')


cli()

Check if EditText is empty.

You can use setOnFocusChangeListener , it will check when focus change

        txt_membername.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View arg0, boolean arg1) {
            if (arg1) {
                //do something
            } else {
                if (txt_membername.getText().toString().length() == 0) {
                    txt_membername
                            .setError("Member name is not empty, Plz!");
                }
            }
        }
    });

Why does Vim save files with a ~ extension?

The *.ext~ file is a backup file, containing the file as it was before you edited it.

The *.ext.swp file is the swap file, which serves as a lock file and contains the undo/redo history as well as any other internal info Vim needs. In case of a crash you can re-open your file and Vim will restore its previous state from the swap file (which I find helpful, so I don't switch it off).

To switch off automatic creation of backup files, use (in your vimrc):

set nobackup
set nowritebackup

Where nowritebackup changes the default "save" behavior of Vim, which is:

  1. write buffer to new file
  2. delete the original file
  3. rename the new file

and makes Vim write the buffer to the original file (resulting in the risk of destroying it in case of an I/O error). But you prevent "jumping files" on the Windows desktop with it, which is the primary reason for me to have nowritebackup in place.

Is it possible to "decompile" a Windows .exe? Or at least view the Assembly?

With a debugger you can step through the program assembly interactively.
With a disassembler, you can view the program assembly in more detail.
With a decompiler, you can turn a program back into partial source code, assuming you know what it was written in (which you can find out with free tools such as PEiD - if the program is packed, you'll have to unpack it first OR Detect-it-Easy if you can't find PEiD anywhere. DIE has a strong developer community on github currently).

Debuggers:

  • OllyDbg, free, a fine 32-bit debugger, for which you can find numerous user-made plugins and scripts to make it all the more useful.
  • WinDbg, free, a quite capable debugger by Microsoft. WinDbg is especially useful for looking at the Windows internals, since it knows more about the data structures than other debuggers.
  • SoftICE, SICE to friends. Commercial and development stopped in 2006. SoftICE is kind of a hardcore tool that runs beneath the operating system (and halts the whole system when invoked). SoftICE is still used by many professionals, although might be hard to obtain and might not work on some hardware (or software - namely, it will not work on Vista or NVIDIA gfx cards).

Disassemblers:

  • IDA Pro(commercial) - top of the line disassembler/debugger. Used by most professionals, like malware analysts etc. Costs quite a few bucks though (there exists free version, but it is quite quite limited)
  • W32Dasm(free) - a bit dated but gets the job done. I believe W32Dasm is abandonware these days, and there are numerous user-created hacks to add some very useful functionality. You'll have to look around to find the best version.

Decompilers:

  • Visual Basic: VB Decompiler, commercial, produces somewhat identifiable bytecode.
  • Delphi: DeDe, free, produces good quality source code.
  • C: HexRays, commercial, a plugin for IDA Pro by the same company. Produces great results but costs a big buck, and won't be sold to just anyone (or so I hear).
  • .NET(C#): dotPeek, free, decompiles .NET 1.0-4.5 assemblies to C#. Support for .dll, .exe, .zip, .vsix, .nupkg, and .winmd files.

Some related tools that might come handy in whatever it is you're doing are resource editors such as ResourceHacker (free) and a good hex editor such as Hex Workshop (commercial).

Additionally, if you are doing malware analysis (or use SICE), I wholeheartedly suggest running everything inside a virtual machine, namely VMware Workstation. In the case of SICE, it will protect your actual system from BSODs, and in the case of malware, it will protect your actual system from the target program. You can read about malware analysis with VMware here.

Personally, I roll with Olly, WinDbg & W32Dasm, and some smaller utility tools.

Also, remember that disassembling or even debugging other people's software is usually against the EULA in the very least :)

Regex to replace everything except numbers and a decimal point

Try this:

document.getElementById(target).value = newVal.replace(/^\d+(\.\d{0,2})?$/, "");

Does HTML5 <video> playback support the .avi format?

The current HTML5 draft specification does not specify which video formats browsers should support in the video tag. User agents are free to support any video formats they feel are appropriate.

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

Check if page gets reloaded or refreshed in JavaScript

Store a cookie the first time someone visits the page. On refresh check if your cookie exists and if it does, alert.

function checkFirstVisit() {
  if(document.cookie.indexOf('mycookie')==-1) {
    // cookie doesn't exist, create it now
    document.cookie = 'mycookie=1';
  }
  else {
    // not first visit, so alert
    alert('You refreshed!');
  }
}

and in your body tag:

<body onload="checkFirstVisit()">

From ND to 1D arrays

Use np.ravel (for a 1D view) or np.ndarray.flatten (for a 1D copy) or np.ndarray.flat (for an 1D iterator):

In [12]: a = np.array([[1,2,3], [4,5,6]])

In [13]: b = a.ravel()

In [14]: b
Out[14]: array([1, 2, 3, 4, 5, 6])

Note that ravel() returns a view of a when possible. So modifying b also modifies a. ravel() returns a view when the 1D elements are contiguous in memory, but would return a copy if, for example, a were made from slicing another array using a non-unit step size (e.g. a = x[::2]).

If you want a copy rather than a view, use

In [15]: c = a.flatten()

If you just want an iterator, use np.ndarray.flat:

In [20]: d = a.flat

In [21]: d
Out[21]: <numpy.flatiter object at 0x8ec2068>

In [22]: list(d)
Out[22]: [1, 2, 3, 4, 5, 6]

How to make function decorators and chain them together?

It looks like the other people have already told you how to solve the problem. I hope this will help you understand what decorators are.

Decorators are just syntactical sugar.

This

@decorator
def func():
    ...

expands to

def func():
    ...
func = decorator(func)

How to create a directory using Ansible

You need to use file module for this case. Below playbook you can use for your reference.

    ---
     - hosts: <Your target host group>
       name: play1
       tasks: 
        - name: Create Directory
          files:
           path=/srv/www/
           owner=<Intended User>
           mode=<Intended permission, e.g.: 0750>
           state=directory 

How to have a transparent ImageButton: Android

Use this:

<ImageButton
 android:id="@+id/back"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:background="@null"
 android:padding="10dp"
 android:src="@drawable/backbtn" />

Remove all the children DOM elements in div

node.innerHTML = "";

Non-standard, but fast and well supported.

Using a batch to copy from network drive to C: or D: drive

Just do the following change

echo off
cls

echo Would you like to do a backup?

pause

copy "\\My_Servers_IP\Shared Drive\FolderName\*" C:\TEST_BACKUP_FOLDER

pause

Get the system date and split day, month and year

Without opening an IDE to check my brain works properly for syntax at this time of day...

If you simply want the date in a particular format you can use DateTime's .ToString(string format). There are a number of examples of standard and custom formatting strings if you follow that link.

So

DateTime _date = DateTime.Now;
var _dateString = _date.ToString("dd/MM/yyyy");

would give you the date as a string in the format you request.

Recursive query in SQL Server

Something like this (not tested)

with match_groups as (

  select product_id, 
         matching_product_id,
         product_id as group_id
  from matches
  where product_id not in (select matching_product_id from matches)

  union all

  select m.product_id, m.matching_product_id, p.group_id
  from matches m
    join match_groups p on m.product_id = p.matching_product_id
)
select group_id, product_id
from match_groups
order by group_id;

How can I iterate over the elements in Hashmap?

Need Key & Value in Iteration

Use entrySet() to iterate through Map and need to access value and key:

Map<String, Person> hm = new HashMap<String, Person>();

hm.put("A", new Person("p1"));
hm.put("B", new Person("p2"));
hm.put("C", new Person("p3"));
hm.put("D", new Person("p4"));
hm.put("E", new Person("p5"));

Set<Map.Entry<String, Person>> set = hm.entrySet();

for (Map.Entry<String, Person> me : set) {
  System.out.println("Key :"+me.getKey() +" Name : "+ me.getValue().getName()+"Age :"+me.getValue().getAge());

}

Need Key in Iteration

If you want just to iterate over keys of map you can use keySet()

for(String key: map.keySet()) {
     Person value = map.get(key); 
}

Need Value in Iteration

If you just want to iterate over values of map you can use values()

for(Person person: map.values()) {

}

What is the meaning of the CascadeType.ALL for a @ManyToOne JPA association

You shouldn't use CascadeType.ALL on @ManyToOne since entity state transitions should propagate from parent entities to child ones, not the other way around.

The @ManyToOne side is always the Child association since it maps the underlying Foreign Key column.

Therefore, you should move the CascadeType.ALL from the @ManyToOne association to the @OneToMany side, which should also use the mappedBy attribute since it's the most efficient one-to-many table relationship mapping.

PHP-FPM doesn't write to error log

In my case php-fpm outputs 500 error without any logging because of missing php-mysql module. I moved joomla installation to another server and forgot about it. So apt-get install php-mysql and service restart solved it.

I started with trying to fix broken logging without success. Finally with strace i found fail message after db-related system calls. Though my case is not directly related to op's question, I hope it could be useful.

What are the complexity guarantees of the standard containers?

I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).

Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.

Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.

assignment operator overloading in c++

There are no problems with the second version of the assignment operator. In fact, that is the standard way for an assignment operator.

Edit: Note that I am referring to the return type of the assignment operator, not to the implementation itself. As has been pointed out in comments, the implementation itself is another issue. See here.

Where to put default parameter value in C++?

One more point I haven't found anyone mentioned:

If you have virtual method, each declaration can have its own default value!

It depends on the interface you are calling which value will be used.

Example on ideone

struct iface
{
    virtual void test(int a = 0) { std::cout << a; }
};

struct impl : public iface
{
    virtual void test(int a = 5) override { std::cout << a; }
};

int main()
{
    impl d;
    d.test();
    iface* a = &d;
    a->test();
}

It prints 50

I strongly discourage you to use it like this

ng-if check if array is empty

In my experience, doing this on the HTML template proved difficult so I decided to use an event to call a function on TS and then check the condition. If true make condition equals to true and then use that variable on the ngIf on HTML

    emptyClause(array:any) {


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

            this.emptyMessage=false;

    }else{

            this.emptyMessage=true;
        }
}

HTML

        <div class="row">

        <form>
            <div class="col-md-1 col-sm-1 col-xs-1"></div>
            <div class="col-md-10 col-sm-10 col-xs-10">
        <div [hidden]="emptyMessage" class="alert alert-danger">

            No Clauses Have Been Identified For the Search Criteria

        </div>
            </div>
            <div class="col-md-1 col-sm-1 col-xs-1"></div>
        </form>

UL list style not applying

I had this problem and it turned out I didn't have any padding on the ul, which was stopping the discs from being visible.

Margin messes with this too

Trigger 404 in Spring-MVC controller?

If your controller method is for something like file handling then ResponseEntity is very handy:

@Controller
public class SomeController {
    @RequestMapping.....
    public ResponseEntity handleCall() {
        if (isFound()) {
            return new ResponseEntity(...);
        }
        else {
            return new ResponseEntity(404);
        }
    }
}

Using android.support.v7.widget.CardView in my project (Eclipse)

I have done following and it resolve an issue with recyclerview same you may use for other widget as well if it's not working in eclipse project.

• Go to sdk\extras\android\m2repository\com\android\support\recyclerview-v7\21.0.0-rc1 directory

• Copy recyclerview-v7-21.0.0-rc1.aar file and rename it as .zip

• Unzip the file, you will get classes.jar (rename the jar file more meaningful name)

• Use the following jar in your project build path or lib directory.

and it resolve your error.

happy coding :)

Alternative to header("Content-type: text/xml");

No. You can't send headers after they were sent. Try to use hooks in wordpress

Gradle sync failed: failed to find Build Tools revision 24.0.0 rc1

1) You need to change to version that is available on you studio enter image description here

2) Here is how you find out version that is available for your studio

Go to File -> Project structure. enter image description here

source is from @Siddarth Kanted Thanks to Siddarth Kanted.

3) And when you want to install more versions of build tool you can learn it from @Fangming user from this post.

easy working solution.

The response content cannot be parsed because the Internet Explorer engine is not available, or

Yet another method to solve: updating registry. In my case I could not alter GPO, and -UseBasicParsing breaks parts of the access to the website. Also I had a service user without log in permissions, so I could not log in as the user and run the GUI.
To fix,

  1. log in as a normal user, run IE setup.
  2. Then export this registry key: HKEY_USERS\S-1-5-21-....\SOFTWARE\Microsoft\Internet Explorer
  3. In the .reg file that is saved, replace the user sid with the service account sid
  4. Import the .reg file

In the file

Change One Cell's Data in mysql

UPDATE only changes the values you specify:

UPDATE table SET cell='new_value' WHERE whatever='somevalue'

LogCat message: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included

As for me I've solved this problem by next way - as developer.android.com says, after adding google-play-services_lib you should add <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> in your manifest, but on the new SDK you'll always get an error:

Error: No resource found that matches the given name (at 'value' with value '@integer/ google_play_services_version').

To solve that error many people advise to use a raw value, 4030500, instead of @integer/google_play_services_version, but it is correct ONLY for Google services revision 13.

If you use any older version or version for Froyo (like me) you should put another value in it. To know what value you should put just open a Google Play services manifest and copy-paste a version_code value. For Froyo services, it is 3265130. After adding this I've stopped getting this error, and I've began to receive coordinates in my application at last.

Getting only response header from HTTP POST using curl

The other answers require the response body to be downloaded. But there's a way to make a POST request that will only fetch the header:

curl -s -I -X POST http://www.google.com

An -I by itself performs a HEAD request which can be overridden by -X POST to perform a POST (or any other) request and still only get the header data.

Oracle query to identify columns having special characters

I figured out the answer to above problem. Below query will return rows which have even a signle occurrence of characters besides alphabets, numbers, square brackets, curly brackets,s pace and dot. Please note that position of closing bracket ']' in matching pattern is important.

Right ']' has the special meaning of ending a character set definition. It wouldn't make any sense to end the set before you specified any members, so the way to indicate a literal right ']' inside square brackets is to put it immediately after the left '[' that starts the set definition

SELECT * FROM test WHERE REGEXP_LIKE(sampletext,  '[^]^A-Z^a-z^0-9^[^.^{^}^ ]' );

Accessing the web page's HTTP Headers in JavaScript

Unfortunately, there isn't an API to give you the HTTP response headers for your initial page request. That was the original question posted here. It has been repeatedly asked, too, because some people would like to get the actual response headers of the original page request without issuing another one.


For AJAX Requests:

If an HTTP request is made over AJAX, it is possible to get the response headers with the getAllResponseHeaders() method. It's part of the XMLHttpRequest API. To see how this can be applied, check out the fetchSimilarHeaders() function below. Note that this is a work-around to the problem that won't be reliable for some applications.

myXMLHttpRequest.getAllResponseHeaders();

This will not give you information about the original page request's HTTP response headers, but it could be used to make educated guesses about what those headers were. More on that is described next.


Getting header values from the Initial Page Request:

This question was first asked several years ago, asking specifically about how to get at the original HTTP response headers for the current page (i.e. the same page inside of which the javascript was running). This is quite a different question than simply getting the response headers for any HTTP request. For the initial page request, the headers aren't readily available to javascript. Whether the header values you need will be reliably and sufficiently consistent if you request the same page again via AJAX will depend on your particular application.

The following are a few suggestions for getting around that problem.


1. Requests on Resources which are largely static

If the response is largely static and the headers are not expected to change much between requests, you could make an AJAX request for the same page you're currently on and assume that they're they are the same values which were part of the page's HTTP response. This could allow you to access the headers you need using the nice XMLHttpRequest API described above.

function fetchSimilarHeaders (callback) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (request.readyState === XMLHttpRequest.DONE) {
            //
            // The following headers may often be similar
            // to those of the original page request...
            //
            if (callback && typeof callback === 'function') {
                callback(request.getAllResponseHeaders());
            }
        }
    };

    //
    // Re-request the same page (document.location)
    // We hope to get the same or similar response headers to those which 
    // came with the current page, but we have no guarantee.
    // Since we are only after the headers, a HEAD request may be sufficient.
    //
    request.open('HEAD', document.location, true);
    request.send(null);
}

This approach will be problematic if you truly have to rely on the values being consistent between requests, since you can't fully guarantee that they are the same. It's going to depend on your specific application and whether you know that the value you need is something that won't be changing from one request to the next.


2. Make Inferences

There are some BOM properties (Browser Object Model) which the browser determines by looking at the headers. Some of these properties reflect HTTP headers directly (e.g. navigator.userAgent is set to the value of the HTTP User-Agent header field). By sniffing around the available properties you might be able to find what you need, or some clues to indicate what the HTTP response contained.


3. Stash them

If you control the server side, you can access any header you like as you construct the full response. Values could be passed to the client with the page, stashed in some markup or perhaps in an inlined JSON structure. If you wanted to have every HTTP request header available to your javascript, you could iterate through them on the server and send them back as hidden values in the markup. It's probably not ideal to send header values this way, but you could certainly do it for the specific value you need. This solution is arguably inefficient, too, but it would do the job if you needed it.

How to format numbers?

This will get you your comma seperated values as well as add the fixed notation to the end.

    nStr="1000";
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    commaSeperated = x1 + x2 + ".00";
    alert(commaSeperated);

Source

Redirect from an HTML page

JavaScript

<script type="text/javascript">
    window.location.href = "http://example.com";
</script>

Meta tag

<meta http-equiv="refresh" content="0;url=http://example.com">

Remove android default action bar

I've noticed that if you set the theme in the AndroidManifest, it seems to get rid of that short time where you can see the action bar. So, try adding this to your manifest:

<android:theme="@android:style/Theme.NoTitleBar">

Just add it to your application tag to apply it app-wide.

offsetting an html anchor to adjust for fixed header

The above methods don't work very well if your anchor is a table element or within a table (row or cell).

I had to use javascript and bind to the window hashchange event to work around this (demo):

function moveUnderNav() {
    var $el, h = window.location.hash;
    if (h) {
        $el = $(h);
        if ($el.length && $el.closest('table').length) {
            $('body').scrollTop( $el.closest('table, tr').position().top - 26 );
        }
    }
}

$(window)
    .load(function () {
        moveUnderNav();
    })
    .on('hashchange', function () {
        moveUnderNav();
    });

* Note: The hashchange event is not available in all browsers.

Java - Writing strings to a CSV file

    String filepath="/tmp/employee.csv";
    FileWriter sw = new FileWriter(new File(filepath));
    CSVWriter writer = new CSVWriter(sw);
    writer.writeAll(allRows);

    String[] header= new String[]{"ErrorMessage"};
    writer.writeNext(header);

    List<String[]> errorData = new ArrayList<String[]>();
    for(int i=0;i<1;i++){
        String[] data = new String[]{"ErrorMessage"+i};
        errorData.add(data);
    }
    writer.writeAll(errorData);

    writer.close();

CSS Vertical align does not work with float

Edited:

The vertical-align CSS property specifies the vertical alignment of an inline, inline-block or table-cell element.

Read this article for Understanding vertical-align

How to download a file from a website in C#

You may need to know the status during the file download or use credentials before making the request.

Here is an example that covers these options:

Uri ur = new Uri("http://remotehost.do/images/img.jpg");

using (WebClient client = new WebClient()) {
    //client.Credentials = new NetworkCredential("username", "password");
    String credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("Username" + ":" + "MyNewPassword"));
    client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";

    client.DownloadProgressChanged += WebClientDownloadProgressChanged;
    client.DownloadDataCompleted += WebClientDownloadCompleted;
    client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");
}

And the callback's functions implemented as follows:

void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
}

void WebClientDownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
{
    Console.WriteLine("Download finished!");
}

(Ver 2) - Lambda notation: other possible option for handling the events

client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(delegate(object sender, DownloadProgressChangedEventArgs e) {
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
});

client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(delegate(object sender, DownloadDataCompletedEventArgs e){
    Console.WriteLine("Download finished!");
});

(Ver 3) - We can do better

client.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) =>
{
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
};

client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) => 
{
    Console.WriteLine("Download finished!");
};

(Ver 4) - Or

client.DownloadProgressChanged += (o, e) =>
{
    Console.WriteLine($"Download status: {e.ProgressPercentage}%.");

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
};

client.DownloadDataCompleted += (o, e) => 
{
    Console.WriteLine("Download finished!");
};

Delay/Wait in a test case of Xcode UI testing

In my case sleep created side effect so I used wait

let _ = XCTWaiter.wait(for: [XCTestExpectation(description: "Hello World!")], timeout: 2.0)

Constants in Objective-C

You should create a header file like

// Constants.h
FOUNDATION_EXPORT NSString *const MyFirstConstant;
FOUNDATION_EXPORT NSString *const MySecondConstant;
//etc.

(you can use extern instead of FOUNDATION_EXPORT if your code will not be used in mixed C/C++ environments or on other platforms)

You can include this file in each file that uses the constants or in the pre-compiled header for the project.

You define these constants in a .m file like

// Constants.m
NSString *const MyFirstConstant = @"FirstConstant";
NSString *const MySecondConstant = @"SecondConstant";

Constants.m should be added to your application/framework's target so that it is linked in to the final product.

The advantage of using string constants instead of #define'd constants is that you can test for equality using pointer comparison (stringInstance == MyFirstConstant) which is much faster than string comparison ([stringInstance isEqualToString:MyFirstConstant]) (and easier to read, IMO).

Cut Java String at a number of character

String strOut = str.substring(0, 8) + "...";

How to turn NaN from parseInt into 0 for an empty string?

var value = isNaN(parseInt(tbb)) ? 0 : parseInt(tbb);

CSS: 100% font size - 100% of what?

As you showed convincingly, the font-size: 100%; will not render the same in all browsers. However, you will set your font face in your CSS file, so this will be the same (or a fallback) in all browsers.

I believe font-size: 100%; can be very useful when combining it with em-based design. As this article shows, this will create a very flexible website.

When is this useful? When your site needs to adapt to the visitors' wishes. Take for example an elderly man that puts his default font-size at 24 px. Or someone with a small screen with a large resolution that increases his default font-size because he otherwise has to squint. Most sites would break, but em-based sites are able to cope with these situations.

On Selenium WebDriver how to get Text from Span Tag

I agree css is better. If you did want to do it via Xpath you could try:

    String kk = wd.findElement(By.xpath(.//*div[@id='customSelect_3']/div/span[@class='selectLabel clear'].getText()))

Maven is not working in Java 8 when Javadoc tags are incomplete

Since it depends on the version of your JRE which is used to run the maven command you propably dont want to disable DocLint per default in your pom.xml

Hence, from command line you can use the switch -Dadditionalparam=-Xdoclint:none.

Example: mvn clean install -Dadditionalparam=-Xdoclint:none

How to get the difference between two dictionaries in Python?

Try the following snippet, using a dictionary comprehension:

value = { k : second_dict[k] for k in set(second_dict) - set(first_dict) }

In the above code we find the difference of the keys and then rebuild a dict taking the corresponding values.

Accessing variables from other functions without using global variables

What you're looking for is technically known as currying.

function getMyCallback(randomValue)
{
    return function(otherParam)
    {
        return randomValue * otherParam //or whatever it is you are doing.
    }

}

var myCallback = getMyCallBack(getRand())

alert(myCallBack(1));
alert(myCallBack(2));

The above isn't exactly a curried function but it achieves the result of maintaining an existing value without adding variables to the global namespace or requiring some other object repository for it.

How to view kafka message

Old version includes kafka-simple-consumer-shell.sh (https://kafka.apache.org/downloads#1.1.1) which is convenient since we do not need cltr+c to exit.

For example

kafka-simple-consumer-shell.sh --broker-list $BROKERIP:$BROKERPORT --topic $TOPIC1 --property print.key=true --property key.separator=":"  --no-wait-at-logend

Appending a list or series to a pandas DataFrame as a row?

Could you do something like this?

>>> import pandas as pd
>>> df = pd.DataFrame(columns=['col1', 'col2'])
>>> df = df.append(pd.Series(['a', 'b'], index=['col1','col2']), ignore_index=True)
>>> df = df.append(pd.Series(['d', 'e'], index=['col1','col2']), ignore_index=True) 
>>> df
  col1 col2
0    a    b
1    d    e

Does anyone have a more elegant solution?

Difference between signed / unsigned char

Representation is the same, the meaning is different. e.g, 0xFF, it both represented as "FF". When it is treated as "char", it is negative number -1; but it is 255 as unsigned. When it comes to bit shifting, it is a big difference since the sign bit is not shifted. e.g, if you shift 255 right 1 bit, it will get 127; shifting "-1" right will be no effect.

Count if two criteria match - EXCEL formula

Add the sheet name infront of the cell, e.g.:

=COUNTIFS(stock!A:A,"M",stock!C:C,"Yes")

Assumes the sheet name is "stock"

Finding all possible combinations of numbers to reach a given sum

Here is a better version with better output formatting and C++ 11 features:

void subset_sum_rec(std::vector<int> & nums, const int & target, std::vector<int> & partialNums) 
{
    int currentSum = std::accumulate(partialNums.begin(), partialNums.end(), 0);
    if (currentSum > target)
        return;
    if (currentSum == target) 
    {
        std::cout << "sum([";
        for (auto it = partialNums.begin(); it != std::prev(partialNums.end()); ++it)
            cout << *it << ",";
        cout << *std::prev(partialNums.end());
        std::cout << "])=" << target << std::endl;
    }
    for (auto it = nums.begin(); it != nums.end(); ++it) 
    {
        std::vector<int> remaining;
        for (auto it2 = std::next(it); it2 != nums.end(); ++it2)
            remaining.push_back(*it2);

        std::vector<int> partial = partialNums;
        partial.push_back(*it);
        subset_sum_rec(remaining, target, partial);
    }
}

Error: expected type-specifier before 'ClassName'

For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).

This can be caused in many ways:

  • You forgot to #include the header that defines it.
  • Your inclusion guards (#ifndef BLAH_H) are defective (your #ifndef BLAH_H doesn't match your #define BALH_H due to a typo or copy+paste mistake).
  • Your inclusion guards are accidentally used twice (two separate files both using #define MYHEADER_H, even if they are in separate directories)
  • You forgot that you are using a template (eg. new Vector() should be new Vector<int>())
  • The compiler is thinking you meant one scope when really you meant another (For example, if you have NamespaceA::NamespaceB, AND a <global scope>::NamespaceB, if you are already within NamespaceA, it'll look in NamespaceA::NamespaceB and not bother checking <global scope>::NamespaceB) unless you explicitly access it.
  • You have a name clash (two entities with the same name, such as a class and an enum member).

To explicitly access something in the global namespace, prefix it with ::, as if the global namespace is a namespace with no name (e.g. ::MyType or ::MyNamespace::MyType).

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

If JDK installed but still not working.

In Eclipse follow below steps:- Window --> Preference --> Installed JREs -->Change path of JRE to JDK(add).

The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied)"}

What Worked for me was:

Open localhost/reports
Go to properties tab (SSRS 2008)
Security->New Role Assignment
Add DOMAIN/USERNAME or DOMAIN/USERGROUP
Check Report builder

How to vertically center a <span> inside a div?

At your parent DIV add

display:table;

and at your child element add

 display:table-cell;
 vertical-align:middle;

How can I create an object and add attributes to it?

Try the code below:

$ python
>>> class Container(object):
...     pass 
...
>>> x = Container()
>>> x.a = 10
>>> x.b = 20
>>> x.banana = 100
>>> x.a, x.b, x.banana
(10, 20, 100)
>>> dir(x)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', 
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__',     '__sizeof__', 
'__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'banana']

Select all child elements recursively in CSS

Use a white space to match all descendants of an element:

div.dropdown * {
    color: red;
}

x y matches every element y that is inside x, however deeply nested it may be - children, grandchildren and so on.

The asterisk * matches any element.

Official Specification: CSS 2.1: Chapter 5.5: Descendant Selectors

Datatable to html Table

Since I didn't see this in any of the other answers, and since it's more efficient (in lines of code and in speed), here's a solution in VB.NET using a stringbuilder and lambda functions with String.Join instead of For loops for the columns.

Dim sb As New StringBuilder
sb.Append("<table>")
sb.Append("<tr>" & String.Join("", dt.Columns.OfType(Of DataColumn)().Select(Function(x) "<th>" & x.ColumnName & "</th>").ToArray()) & "</tr>")
For Each row As DataRow In dt.Rows
    sb.Append("<tr>" & String.Join("", row.ItemArray.Select(Function(f) "<td>" & f.ToString() & "</td>")) & "</tr>")
Next
sb.Append("</table>")

You can add your own styles to this pretty easily.

Generate an HTML Response in a Java Servlet

Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:

public void doGet(HttpServletRequest request,
       HttpServletResponse response)
       throws IOException, ServletException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   out.println("HTML from an external file:");     
   request.getRequestDispatcher("/pathToFile/fragment.html")
          .include(request, response); 
   out.close();
}

JQuery: if div is visible

You can use .is(':visible')

Selects all elements that are visible.

For example:

if($('#selectDiv').is(':visible')){

Also, you can get the div which is visible by:

$('div:visible').callYourFunction();

Live example:

_x000D_
_x000D_
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
  display: none;  _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
_x000D_
_x000D_

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve?

Add following at the bottom of your Info.plist

<key>ITSAppUsesNonExemptEncryption</key>
<false/>

request exceeds the configured maxQueryStringLength when using [Authorize]

When an unauthorized request comes in, the entire request is URL encoded, and added as a query string to the request to the authorization form, so I can see where this may result in a problem given your situation.

According to MSDN, the correct element to modify to reset maxQueryStringLength in web.config is the <httpRuntime> element inside the <system.web> element, see httpRuntime Element (ASP.NET Settings Schema). Try modifying that element.

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

Background info:

My IDE

Android Studio 3.1.3
Build #AI-173.4819257, built on June 4, 2018
JRE: 1.8.0_152-release-1024-b02 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 7 6.1

First solution: Import the project again and don't agree to upgrade the android gradle plug-in.

Second solution: Your files should contain these fragments.

build.gradle:

buildscript {
  repositories {
    jcenter()
    google()//this is important for gradle 4.1 and above
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:3.1.3' //this android plugin for gradle requires gradle version 4.4 and above
  }
}
allprojects {
  //...
  repositories {
    jcenter()
    google()//This was not added by update IDE-wizard-button.
    //I need this when using the latest com.android.support:appcompat-v7:25.4.0 in app/build.gradle
  }
}

Either follow the recommendation of your IDE to upgrade your gradle version to 4.4 or consider to have this in gradle/wrapper/gradle-wrapper.properties

distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

Optional change buildToolsVersion in app/build.gradle:

android {
compileSdkVersion 25
buildToolsVersion '27.0.3'

app/build.gradle: comment out the dependencies and let the build fail (automatically or trigger it)

dependencies {
//compile fileTree(dir: 'libs', include: ['*.jar'])
//compile 'com.android.support:appcompat-v7:25.1.0'
}

app/build.gradle: comment in the dependencies again. It's been advised to change them from compile to implementation, but for now it's just a warning issue.

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.1.0'
}

After project rebuilding, the import statement shouldn't be greyed-out anymore; try to invoke Ctrl+h on the class. But for some reason, the error markers on those class-referencing-statements are still present. To get rid of them, we need to hide and restore the project tree view or alternatively close and reopen the project.

Finally that's it.

Further Readings:

Update Gradle

Use the new dependency configurations

If you prefer a picture trail for my solution, you can visit my blog

C - determine if a number is prime

Using Sieve of Eratosthenes, computation is quite faster compare to "known-wide" prime numbers algorithm.

By using pseudocode from it's wiki (https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes), I be able to have the solution on C#.

public bool IsPrimeNumber(int val) {
    // Using Sieve of Eratosthenes.
    if (val < 2)
    {
        return false;
    }

    // Reserve place for val + 1 and set with true.
    var mark = new bool[val + 1];
    for(var i = 2; i <= val; i++)
    {
        mark[i] = true;
    }

    // Iterate from 2 ... sqrt(val).
    for (var i = 2; i <= Math.Sqrt(val); i++)
    {
        if (mark[i])
        {
            // Cross out every i-th number in the places after i (all the multiples of i).
            for (var j = (i * i); j <= val; j += i)
            {
                mark[j] = false;
            }
        }
    }

    return mark[val];
}

IsPrimeNumber(1000000000) takes 21s 758ms.

NOTE: Value might vary depend on hardware specifications.

Get Substring - everything before certain char

Things have moved on a bit since this thread started.

Now, you could use

string.Concat(s.TakeWhile((c) => c != '-'));

Check which element has been clicked with jQuery

So you are doing this a bit backwards. Typically you'd do something like this:

?<div class='article'>
  Article 1
</div>
<div class='article'>
  Article 2
</div>
<div class='article'>
  Article 3
</div>?

And then in your jQuery:

$('.article').click(function(){
    article = $(this).text(); //$(this) is what you clicked!
    });?

When I see things like #search-item .search-article, #search-item .search-article, and #search-item .search-article I sense you are overspecifying your CSS which makes writing concise jQuery very difficult. This should be avoided if at all possible.

Finding whether a point lies inside a rectangle or not

I realise this is an old thread, but for anyone who's interested in looking at this from a purely mathematical perspective, there's an excellent thread on the maths stack exchange, here:

https://math.stackexchange.com/questions/190111/how-to-check-if-a-point-is-inside-a-rectangle

Edit: Inspired by this thread, I've put together a simple vector method for quickly determining where your point lies.

Suppose you have a rectangle with points at p1 = (x1, y1), p2 = (x2, y2), p3 = (x3, y3) and p4 = (x4, y4), going clockwise. If a point p = (x, y) lies inside the rectangle, then the dot product (p - p1).(p2 - p1) will lie between 0 and |p2 - p1|^2, and (p - p1).(p4 - p1) will lie between 0 and |p4 - p1|^2. This is equivalent to taking the projection of the vector p - p1 along the length and width of the rectangle, with p1 as the origin.

This may make more sense if I show an equivalent code:

p21 = (x2 - x1, y2 - y1)
p41 = (x4 - x1, y4 - y1)

p21magnitude_squared = p21[0]^2 + p21[1]^2
p41magnitude_squared = p41[0]^2 + p41[1]^2

for x, y in list_of_points_to_test:

    p = (x - x1, y - y1)

    if 0 <= p[0] * p21[0] + p[1] * p21[1] <= p21magnitude_squared:
        if 0 <= p[0] * p41[0] + p[1] * p41[1]) <= p41magnitude_squared:
            return "Inside"
        else:
            return "Outside"
    else:
        return "Outside"

And that's it. It will also work for parallelograms.

How to quietly remove a directory with content in PowerShell

This worked for me:

Remove-Item $folderPath -Force  -Recurse -ErrorAction SilentlyContinue

Thus the folder is removed with all files in there and it is not producing error if folder path doesn't exists.

Connect multiple devices to one device via Bluetooth

This is the class where the connection is established and messages are recieved. Make sure to pair the devices before you run the application. If you want to have a slave/master connection, where each slave can only send messages to the master , and the master can broadcast messages to all slaves. You should only pair the master with each slave , but you shouldn't pair the slaves together.

    package com.example.gaby.coordinatorv1;
    import java.io.DataInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Set;
    import java.util.UUID;
    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import android.bluetooth.BluetoothServerSocket;
    import android.bluetooth.BluetoothSocket;
    import android.content.Context;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.util.Log;
    import android.widget.Toast;

    public class Piconet {


        private final static String TAG = Piconet.class.getSimpleName();

        // Name for the SDP record when creating server socket
        private static final String PICONET = "ANDROID_PICONET_BLUETOOTH";

        private final BluetoothAdapter mBluetoothAdapter;

        // String: device address
        // BluetoothSocket: socket that represent a bluetooth connection
        private HashMap<String, BluetoothSocket> mBtSockets;

        // String: device address
        // Thread: thread for connection
        private HashMap<String, Thread> mBtConnectionThreads;

        private ArrayList<UUID> mUuidList;

        private ArrayList<String> mBtDeviceAddresses;

        private Context context;


        private Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        Toast.makeText(context, msg.getData().getString("msg"), Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
            };
        };

        public Piconet(Context context) {
            this.context = context;

            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

            mBtSockets = new HashMap<String, BluetoothSocket>();
            mBtConnectionThreads = new HashMap<String, Thread>();
            mUuidList = new ArrayList<UUID>();
            mBtDeviceAddresses = new ArrayList<String>();

            // Allow up to 7 devices to connect to the server
            mUuidList.add(UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666"));
            mUuidList.add(UUID.fromString("54d1cc90-1169-11e2-892e-0800200c9a66"));
            mUuidList.add(UUID.fromString("6acffcb0-1169-11e2-892e-0800200c9a66"));
            mUuidList.add(UUID.fromString("7b977d20-1169-11e2-892e-0800200c9a66"));
            mUuidList.add(UUID.fromString("815473d0-1169-11e2-892e-0800200c9a66"));
            mUuidList.add(UUID.fromString("503c7434-bc23-11de-8a39-0800200c9a66"));
            mUuidList.add(UUID.fromString("503c7435-bc23-11de-8a39-0800200c9a66"));

            Thread connectionProvider = new Thread(new ConnectionProvider());
            connectionProvider.start();

        }



        public void startPiconet() {
            Log.d(TAG, " -- Looking devices -- ");
            // The devices must be already paired
            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
                    .getBondedDevices();
            if (pairedDevices.size() > 0) {
                for (BluetoothDevice device : pairedDevices) {
                    // X , Y and Z are the Bluetooth name (ID) for each device you want to connect to
                    if (device != null && (device.getName().equalsIgnoreCase("X") || device.getName().equalsIgnoreCase("Y")
                            || device.getName().equalsIgnoreCase("Z") || device.getName().equalsIgnoreCase("M"))) {
                        Log.d(TAG, " -- Device " + device.getName() + " found --");
                        BluetoothDevice remoteDevice = mBluetoothAdapter
                                .getRemoteDevice(device.getAddress());
                        connect(remoteDevice);
                    }
                }
            } else {
                Toast.makeText(context, "No paired devices", Toast.LENGTH_SHORT).show();
            }
        }

        private class ConnectionProvider implements Runnable {
            @Override
            public void run() {
                try {
                    for (int i=0; i<mUuidList.size(); i++) {
                        BluetoothServerSocket myServerSocket = mBluetoothAdapter
                                .listenUsingRfcommWithServiceRecord(PICONET, mUuidList.get(i));
                        Log.d(TAG, " ** Opened connection for uuid " + i + " ** ");

                        // This is a blocking call and will only return on a
                        // successful connection or an exception
                        Log.d(TAG, " ** Waiting connection for socket " + i + " ** ");
                        BluetoothSocket myBTsocket = myServerSocket.accept();
                        Log.d(TAG, " ** Socket accept for uuid " + i + " ** ");
                        try {
                            // Close the socket now that the
                            // connection has been made.
                            myServerSocket.close();
                        } catch (IOException e) {
                            Log.e(TAG, " ** IOException when trying to close serverSocket ** ");
                        }

                        if (myBTsocket != null) {
                            String address = myBTsocket.getRemoteDevice().getAddress();

                            mBtSockets.put(address, myBTsocket);
                            mBtDeviceAddresses.add(address);

                            Thread mBtConnectionThread = new Thread(new BluetoohConnection(myBTsocket));
                            mBtConnectionThread.start();

                            Log.i(TAG," ** Adding " + address + " in mBtDeviceAddresses ** ");
                            mBtConnectionThreads.put(address, mBtConnectionThread);
                        } else {
                            Log.e(TAG, " ** Can't establish connection ** ");
                        }
                    }
                } catch (IOException e) {
                    Log.e(TAG, " ** IOException in ConnectionService:ConnectionProvider ** ", e);
                }
            }
        }

        private class BluetoohConnection implements Runnable {
            private String address;

            private final InputStream mmInStream;

            public BluetoohConnection(BluetoothSocket btSocket) {

                InputStream tmpIn = null;

                try {
                    tmpIn = new DataInputStream(btSocket.getInputStream());
                } catch (IOException e) {
                    Log.e(TAG, " ** IOException on create InputStream object ** ", e);
                }
                mmInStream = tmpIn;
            }
            @Override
            public void run() {
                byte[] buffer = new byte[1];
                String message = "";
                while (true) {

                    try {
                        int readByte = mmInStream.read();
                        if (readByte == -1) {
                            Log.e(TAG, "Discarting message: " + message);
                            message = "";
                            continue;
                        }
                        buffer[0] = (byte) readByte;

                        if (readByte == 0) { // see terminateFlag on write method
                            onReceive(message);
                            message = "";
                        } else { // a message has been recieved
                            message += new String(buffer, 0, 1);
                        }
                    } catch (IOException e) {
                        Log.e(TAG, " ** disconnected ** ", e);
                    }

                    mBtDeviceAddresses.remove(address);
                    mBtSockets.remove(address);
                    mBtConnectionThreads.remove(address);
                }
            }
        }

        /**
         * @param receiveMessage
         */
        private void onReceive(String receiveMessage) {
            if (receiveMessage != null && receiveMessage.length() > 0) {
                Log.i(TAG, " $$$$ " + receiveMessage + " $$$$ ");
                Bundle bundle = new Bundle();
                bundle.putString("msg", receiveMessage);
                Message message = new Message();
                message.what = 1;
                message.setData(bundle);
                handler.sendMessage(message);
            }
        }

        /**
         * @param device
         * @param uuidToTry
         * @return
         */
        private BluetoothSocket getConnectedSocket(BluetoothDevice device, UUID uuidToTry) {
            BluetoothSocket myBtSocket;
            try {
                myBtSocket = device.createRfcommSocketToServiceRecord(uuidToTry);
                myBtSocket.connect();
                return myBtSocket;
            } catch (IOException e) {
                Log.e(TAG, "IOException in getConnectedSocket", e);
            }
            return null;
        }

        private void connect(BluetoothDevice device) {
            BluetoothSocket myBtSocket = null;
            String address = device.getAddress();
            BluetoothDevice remoteDevice = mBluetoothAdapter.getRemoteDevice(address);
            // Try to get connection through all uuids available
            for (int i = 0; i < mUuidList.size() && myBtSocket == null; i++) {
                // Try to get the socket 2 times for each uuid of the list
                for (int j = 0; j < 2 && myBtSocket == null; j++) {
                    Log.d(TAG, " ** Trying connection..." + j + " with " + device.getName() + ", uuid " + i + "...** ");
                    myBtSocket = getConnectedSocket(remoteDevice, mUuidList.get(i));
                    if (myBtSocket == null) {
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            Log.e(TAG, "InterruptedException in connect", e);
                        }
                    }
                }
            }
            if (myBtSocket == null) {
                Log.e(TAG, " ** Could not connect ** ");
                return;
            }
            Log.d(TAG, " ** Connection established with " + device.getName() +"! ** ");
            mBtSockets.put(address, myBtSocket);
            mBtDeviceAddresses.add(address);
            Thread mBluetoohConnectionThread = new Thread(new BluetoohConnection(myBtSocket));
            mBluetoohConnectionThread.start();
            mBtConnectionThreads.put(address, mBluetoohConnectionThread);

        }

        public void bluetoothBroadcastMessage(String message) {
            //send message to all except Id
            for (int i = 0; i < mBtDeviceAddresses.size(); i++) {
                sendMessage(mBtDeviceAddresses.get(i), message);
            }
        }

        private void sendMessage(String destination, String message) {
            BluetoothSocket myBsock = mBtSockets.get(destination);
            if (myBsock != null) {
                try {
                    OutputStream outStream = myBsock.getOutputStream();
                    final int pieceSize = 16;
                    for (int i = 0; i < message.length(); i += pieceSize) {
                        byte[] send = message.substring(i,
                                Math.min(message.length(), i + pieceSize)).getBytes();
                        outStream.write(send);
                    }
                    // we put at the end of message a character to sinalize that message
                    // was finished
                    byte[] terminateFlag = new byte[1];
                    terminateFlag[0] = 0; // ascii table value NULL (code 0)
                    outStream.write(new byte[1]);
                } catch (IOException e) {
                    Log.d(TAG, "line 278", e);
                }
            }
        }

    }

Your main activity should be as follow :

package com.example.gaby.coordinatorv1;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

    private Button discoveryButton;
    private Button messageButton;

    private Piconet piconet;

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

        piconet = new Piconet(getApplicationContext());

        messageButton = (Button) findViewById(R.id.messageButton);
        messageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                piconet.bluetoothBroadcastMessage("Hello World---*Gaby Bou Tayeh*");
            }
        });

        discoveryButton = (Button) findViewById(R.id.discoveryButton);
        discoveryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                piconet.startPiconet();
            }
        });

    }

}

And here's the XML Layout :

<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="match_parent"
tools:context=".MainActivity" >

<Button
    android:id="@+id/discoveryButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Discover"
    />

<Button
    android:id="@+id/messageButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Send message"
    />

Do not forget to add the following permissions to your Manifest File :

    <uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

How to merge specific files from Git branches

The simplest solution is:

git checkout the name of the source branch and the paths to the specific files that we want to add to our current branch

git checkout sourceBranchName pathToFile

Regular expression include and exclude special characters

For the allowed characters you can use

^[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$

to validate a complete string that should consist of only allowed characters. Note that - is at the end (because otherwise it'd be a range) and a few characters are escaped.

For the invalid characters you can use

[<>'"/;`%]

to check for them.

To combine both into a single regex you can use

^(?=[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$)(?!.*[<>'"/;`%])

but you'd need a regex engine that allows lookahead.

creating an array of structs in c++

It works perfectly. I have gcc compiler C++11 ready. Try this and you'll see:

#include <iostream>

using namespace std;

int main()
{
    int pause;

    struct Customer
    {
           int uid;
           string name;
    };

    Customer customerRecords[2];
    customerRecords[0] = {25, "Bob Jones"};
    customerRecords[1] = {26, "Jim Smith"};
    cout << customerRecords[0].uid << " " << customerRecords[0].name << endl;
    cout << customerRecords[1].uid << " " << customerRecords[1].name << endl;
    cin >> pause;
return 0;
}

Maven Error: Could not find or load main class

For me the problem was nothing to do with Maven but to do with how I was running the .jar. I wrote some code and packaged it as a .jar with Maven. I ran it with

java target/gs-maven-0.1.0.jar

and got the error in the OP. Actually you need the -jar option:

java -jar target/gs-maven-0.1.0.jar

How to copy to clipboard in Vim?

for OSX, like the 10342 answers above made clear, you need to make sure that vim supports the clipboard feature, said the the one that comes pre-shipped with OSX does NOT support clipboard, and that if you run brew install vim it would work.

Except that running vi will still make you run the preshipped OSX version, not the one you installed from brew.

to get over this, I simply aliased my vim command to the brew version, not the OSX default one:

alias vim="/usr/local/Cellar/vim/8.0.1100_1/bin/vim"

and now i'm golden

Calling jQuery method from onClick attribute in HTML

I don't think there's any reason to add this function to JQuery's namespace. Why not just define the method by itself:

function showMessage(msg) {
   alert(msg);
};

<input type="button" value="ahaha" onclick="showMessage('msg');" />

UPDATE: With a small change to how your method is defined I can get it to work:

<html>
<head>
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
 <script language="javascript">
    // define the function within the global scope
    $.fn.MessageBox = function(msg) {
        alert(msg);
    };

    // or, if you want to encapsulate variables within the plugin
    (function($) {
        $.fn.MessageBoxScoped = function(msg) {
            alert(msg);
        };
    })(jQuery); //<-- make sure you pass jQuery into the $ parameter
 </script>
</head>
<body>
 <div class="Title">Welcome!</div>
 <input type="button" value="ahaha" id="test" onClick="$(this).MessageBox('msg');" />
</body>
</html>

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

just to add another example of what a lambda can do without using map:

a = 10
b = 2

var mixed = (a,b) => a * b; 
// OR
var mixed = (a,b) => { (any logic); return a * b };

console.log(mixed(a,b)) 
// 20

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

Add space between two particular <td>s

The simplest way:

td:nth-child(2) {
    padding-right: 20px;
}?

But that won't work if you need to work with background color or images in your table. In that case, here is a slightly more advanced solution (CSS3):

td:nth-child(2) {
    border-right: 10px solid transparent;
    -webkit-background-clip: padding;
    -moz-background-clip: padding;
    background-clip: padding-box;
}

It places a transparent border to the right of the cell and pulls the background color/image away from the border, creating the illusion of spacing between the cells.

Note: For this to work, the parent table must have border-collapse: separate. If you have to work with border-collapse: collapse then you have to apply the same border style to the next table cell, but on the left side, to accomplish the same results.

How to use PHP to connect to sql server

enable mssql in php.ini

;extension=php_mssql.dll

to

extension=php_mssql.dll

implement time delay in c

Although many implementations have the time function return the current time in seconds, there is no guarantee that every implementation will do so (e.g. some may return milliseconds rather than seconds). As such, a more portable solution is to use the difftime function.

difftime is guaranteed by the C standard to return the difference in time in seconds between two time_t values. As such we can write a portable time delay function which will run on all compliant implementations of the C standard.

#include <time.h>

void delay(double dly){
    /* save start time */
    const time_t start = time(NULL);

    time_t current;
    do{
        /* get current time */
        time(&current);

        /* break loop when the requested number of seconds have elapsed */
    }while(difftime(current, start) < dly);
}

One caveat with the time and difftime functions is that the C standard never specifies a granularity. Most implementations have a granularity of one second. While this is all right for delays lasting several seconds, our delay function may wait too long for delays lasting under one second.

There is a portable standard C alternative: the clock function.

The clock function returns the implementation’s best approximation to the processor time used by the program since the beginning of an implementation-defined era related only to the program invocation. To determine the time in seconds, the value returned by the clock function should be divided by the value of the macro CLOCKS_PER_SEC.

The clock function solution is quite similar to our time function solution:

#include <time.h>

void delay(double dly){
    /* save start clock tick */
    const clock_t start = clock();

    clock_t current;
    do{
        /* get current clock tick */
        current = clock();

        /* break loop when the requested number of seconds have elapsed */
    }while((double)(current-start)/CLOCKS_PER_SEC < dly);
}

There is a caveat in this case similar to that of time and difftime: the granularity of the clock function is left to the implementation. For example, machines with 32-bit values for clock_t with a resolution in microseconds may end up wrapping the value returned by clock after 2147 seconds (about 36 minutes).

As such, consider using the time and difftime implementation of the delay function for delays lasting at least one second, and the clock implementation for delays lasting under one second.

A final word of caution: clock returns processor time rather than calendar time; clock may not correspond with the actual elapsed time (e.g. if the process sleeps).

JAX-WS - Adding SOAP Headers

Also, if you're using Maven to build your project, you'll need to add the following dependency:

    <dependency>
        <groupId>com.sun.xml.ws</groupId>
        <artifactId>jaxws-rt</artifactId>
        <version>{currentversion}/version>
    </dependency>

This provides you with the class com.sun.xml.ws.developer.WSBindingProvider.

Link: https://mvnrepository.com/artifact/com.sun.xml.ws/jaxws-rt

How to set URL query params in Vue with Vue-Router

For adding multiple query params, this is what worked for me (from here https://forum.vuejs.org/t/vue-router-programmatically-append-to-querystring/3655/5).

an answer above was close … though with Object.assign it will mutate this.$route.query which is not what you want to do … make sure the first argument is {} when doing Object.assign

this.$router.push({ query: Object.assign({}, this.$route.query, { newKey: 'newValue' }) });

Maven build debug in Eclipse

The Run/Debug configuration you're using is meant to let you run Maven on your workspace as if from the command line without leaving Eclipse.

Assuming your tests are JUnit based you should be able to debug them by choosing a source folder containing tests with the right button and choose Debug as... -> JUnit tests.

Using command line arguments in VBscript

Set args = Wscript.Arguments

For Each arg In args
  Wscript.Echo arg
Next

From a command prompt, run the script like this:

CSCRIPT MyScript.vbs 1 2 A B "Arg with spaces"

Will give results like this:

1
2
A
B
Arg with spaces

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

iPhone SDK:How do you play video inside a view? Rather than fullscreen

NSString * pathv = [[NSBundle mainBundle] pathForResource:@"vfile" ofType:@"mov"];
playerv = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:pathv]];

[self presentMoviePlayerViewControllerAnimated:playerv];

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

In Ubuntu

Step 1:

sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf

Step 2: Go to last line and add the following

sql_mode = ""

Step 3: Save

Step 4: Restart mysql server.

Decode UTF-8 with Javascript

Perhaps using the textDecoder will be sufficient.

Not supported in IE though.

var decoder = new TextDecoder('utf-8'),
    decodedMessage;

decodedMessage = decoder.decode(message.data);

Handling non-UTF8 text

In this example, we decode the Russian text "??????, ???!", which means "Hello, world." In our TextDecoder() constructor, we specify the Windows-1251 character encoding, which is appropriate for Cyrillic script.

_x000D_
_x000D_
    let win1251decoder = new TextDecoder('windows-1251');
    let bytes = new Uint8Array([207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33]);
    console.log(win1251decoder.decode(bytes)); // ??????, ???!
_x000D_
_x000D_
_x000D_

The interface for the TextDecoder is described here.

Retrieving a byte array from a string is equally simpel:

_x000D_
_x000D_
const decoder = new TextDecoder();
const encoder = new TextEncoder();

const byteArray = encoder.encode('Größe');
// converted it to a byte array

// now we can decode it back to a string if desired
console.log(decoder.decode(byteArray));
_x000D_
_x000D_
_x000D_

If you have it in a different encoding then you must compensate for that upon encoding. The parameter in the constructor for the TextEncoder is any one of the valid encodings listed here.

Can't connect to local MySQL server through socket homebrew

Since I spent quite some time trying to solve this and always came back to this page when looking for this error, I'll leave my solution here hoping that somebody saves the time I've lost. Although in my case I am using mariadb rather than MySql, you might still be able to adapt this solution to your needs.

My problem

is the same, but my setup is a bit different (mariadb instead of mysql):

Installed mariadb with homebrew

$ brew install mariadb

Started the daemon

$ brew services start mariadb

Tried to connect and got the above mentioned error

$ mysql -uroot
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

My solution

find out which my.cnf files are used by mysql (as suggested in this comment):

$ mysql --verbose --help | grep my.cnf
/usr/local/etc/my.cnf ~/.my.cnf
                        order of preference, my.cnf, $MYSQL_TCP_PORT,

check where the Unix socket file is running (almost as described here):

$ netstat -ln | grep mariadb
.... /usr/local/mariadb/data/mariadb.sock

(you might want to grep mysql instead of mariadb)

Add the socket file you found to ~/.my.cnf (create the file if necessary)(assuming ~/.my.cnf was listed when running the mysql --verbose ...-command from above):

[client]
socket = /usr/local/mariadb/data/mariadb.sock

Restart your mariadb:

$ brew services restart mariadb

After this I could run mysql and got:

$ mysql -uroot
ERROR 1698 (28000): Access denied for user 'root'@'localhost'

So I run the command with superuser privileges instead and after entering my password I got:

$ sudo mysql -uroot
MariaDB [(none)]>

Notes:

  1. I'm not quite sure about the groups where you have to add the socket, first I had it [client-server] but then I figured [client] should be enough. So I changed it and it still works.

  2. When running mariadb_config | grep socket I get: --socket [/tmp/mysql.sock] which is a bit confusing since it seems that /usr/local/mariadb/data/mariadb.sock is the actual place (at least on my machine)

  3. I wonder where I can configure the /usr/local/mariadb/data/mariadb.sock to actually be /tmp/mysql.sockso I can use the default settings instead of having to edit my .my.cnf (but I'm too tired now to figure that out...)

  4. At some point I also did things mentioned in other answers before coming up with this.

Sum values in foreach loop php

Use +=

$val = 0;

foreach($arr as $var) {
   $val += $var; 
}

echo $val;

How to set custom location for local installation of npm package?

If you want this in config, you can set npm config like so:

npm config set prefix "$(pwd)/vendor/node_modules"

or

npm config set prefix "$HOME/vendor/node_modules"

Check your config with

npm config ls -l

Or as @pje says and use the --prefix flag

Assign format of DateTime with data annotations?

That works for me

[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]

Why is the minidlna database not being refreshed?

Resolved with crontab root

10 * * * * /usr/bin/minidlnad -r

https with WCF error: "Could not find base address that matches scheme https"

Look at your base address and your endpoint address (can't see it in your sample code). most likely you missed a column or some other typo e.g. https// instead of https://

How do you auto format code in Visual Studio?

I have a Mac and I clicked Code > Preferences > Settings > Workspace > Formatting and then selected Format On Save.

Now every time I hit cmd + s it auto formats the file.

enter image description here

JQuery - Call the jquery button click event based on name property

You can use normal CSS selectors to select an element by name using jquery. Like this:

Button Code
<button type="button" name="mybutton">Click Me!</button>

Selector & Event Bind Code
$("button[name='mybutton']").click(function() {});

Fastest way to check if a file exist using standard C++/C++11/C?

It depends on where the files reside. For instance, if they are all supposed to be in the same directory, you can read all the directory entries into a hash table and then check all the names against the hash table. This might be faster on some systems than checking each file individually. The fastest way to check each file individually depends on your system ... if you're writing ANSI C, the fastest way is fopen because it's the only way (a file might exist but not be openable, but you probably really want openable if you need to "do something on it"). C++, POSIX, Windows all offer additional options.

While I'm at it, let me point out some problems with your question. You say that you want the fastest way, and that you have thousands of files, but then you ask for the code for a function to test a single file (and that function is only valid in C++, not C). This contradicts your requirements by making an assumption about the solution ... a case of the XY problem. You also say "in standard c++11(or)c++(or)c" ... which are all different, and this also is inconsistent with your requirement for speed ... the fastest solution would involve tailoring the code to the target system. The inconsistency in the question is highlighted by the fact that you accepted an answer that gives solutions that are system-dependent and are not standard C or C++.

Reverting single file in SVN to a particular revision

The best way is to:

svn merge -c -RevisionToUndo ^/trunk

This will undo all files of the revision than simply revert those file you don't like to undo. Don't forget the dash (-) as prefix for the revision.

svn revert File1 File2

Now commit the changes back.

Qt jpg image display

Using QPainter and QImage to paint on a window-widget (QMainWindow) (just another method)

class MainWindow : public QMainWindow
{    
    public:
        MainWindow();
    protected:
        void paintEvent(QPaintEvent* event) override;

    protected:
        QImage image = QImage("/path/to/image.jpg");
};

// for convenience resize window to image size
MainWindow::MainWindow()
{
    setMinimumSize(image.size());
}

void MainWindow::paintEvent(QPaintEvent* event)
{
    QPainter painter(this);
    QRect rect = event->rect();
    painter.drawImage(rect, image, rect);
}


int main(int argc, char** argv)
{
    QApplication a(argc, argv);

    MainWindow mainWindow;
    mainWindow.show();
    return a.exec();
}

Difference between uint32 and uint32_t

uint32_t is defined in the standard, in

18.4.1 Header <cstdint> synopsis [cstdint.syn]

namespace std {
//...
typedef unsigned integer type uint32_t; // optional
//...
}

uint32 is not, it's a shortcut provided by some compilers (probably as typedef uint32_t uint32) for ease of use.

Http Basic Authentication in Java using HttpClient?

HttpBasicAuth works for me with smaller changes

  1. I use maven dependency

    <dependency>
        <groupId>net.iharder</groupId>
        <artifactId>base64</artifactId>
        <version>2.3.8</version>
    </dependency>
    
  2. Smaller change

    String encoding = Base64.encodeBytes ((user + ":" + passwd).getBytes());
    

Dynamic type languages versus static type languages

Perhaps the single biggest "benefit" of dynamic typing is the shallower learning curve. There is no type system to learn and no non-trivial syntax for corner cases such as type constraints. That makes dynamic typing accessible to a lot more people and feasible for many people for whom sophisticated static type systems are out of reach. Consequently, dynamic typing has caught on in the contexts of education (e.g. Scheme/Python at MIT) and domain-specific languages for non-programmers (e.g. Mathematica). Dynamic languages have also caught on in niches where they have little or no competition (e.g. Javascript).

The most concise dynamically-typed languages (e.g. Perl, APL, J, K, Mathematica) are domain specific and can be significantly more concise than the most concise general-purpose statically-typed languages (e.g. OCaml) in the niches they were designed for.

The main disadvantages of dynamic typing are:

  • Run-time type errors.

  • Can be very difficult or even practically impossible to achieve the same level of correctness and requires vastly more testing.

  • No compiler-verified documentation.

  • Poor performance (usually at run-time but sometimes at compile time instead, e.g. Stalin Scheme) and unpredictable performance due to dependence upon sophisticated optimizations.

Personally, I grew up on dynamic languages but wouldn't touch them with a 40' pole as a professional unless there were no other viable options.

Count words in a string method?

lambda, in which splitting and storing of the counted words is dispensed with
and only counting is done

String text = "counting w/o apostrophe's problems or consecutive   spaces";

int count = text.codePoints().boxed().collect(
    Collector.of(
        () -> new int[] {0, 0},
        (a, c) -> {
          if( ".,; \t".indexOf( c ) >= 0 )
            a[1] = 0;
          else if( a[1]++ == 0 ) a[0]++;
        }, (a, b) -> {a[0] += b[0]; return( a );},
        a -> a[0] ) );

gets: 7
works as a status machine that counts the transitions from spacing characters .,; \t to words

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

The practical way is setting font-family to a value that is the specific name of the semibold version, such as

font-family: "Myriad pro Semibold"

if that’s the name. (Personally I use my own font listing tool, which runs on Internet Explorer only to see the fonts in my system by names as usable in CSS.)

In this approach, font-weight is not needed (and probably better not set).

Web browsers have been poor at implementing font weights by the book: they largely cannot find the specific weight version, except bold. The workaround is to include the information in the font family name, even though this is not how things are supposed to work.

Testing with Segoe UI, which often exists in different font weight versions on Windows systems, I was able to make Internet Explorer 9 select the proper version when using the logical approach (of using the font family name Segoe UI and different font-weight values), but it failed on Firefox 9 and Chrome 16 (only normal and bold work). On all of these browsers, for example, setting font-family: Segoe UI Light works OK.

Get child node index

ES6:

Array.from(element.parentNode.children).indexOf(element)

Explanation :

  • element.parentNode.children ? Returns the brothers of element, including that element.

  • Array.from ? Casts the constructor of children to an Array object

  • indexOf ? You can apply indexOf because you now have an Array object.

.NET Excel Library that can read/write .xls files

You may consider 3rd party tool that called Excel Jetcell .NET component for read/write excel files:

C# sample

// Create New Excel Workbook
ExcelWorkbook Wbook = new ExcelWorkbook();
ExcelCellCollection Cells = Wbook.Worksheets.Add("Sheet1").Cells;

Cells["A1"].Value = "Excel writer example (C#)";
Cells["A1"].Style.Font.Bold = true;
Cells["B1"].Value = "=550 + 5";

// Write Excel XLS file
Wbook.WriteXLS("excel_net.xls");

VB.NET sample

' Create New Excel Workbook
Dim Wbook As ExcelWorkbook = New ExcelWorkbook()
Dim Cells As ExcelCellCollection = Wbook.Worksheets.Add("Sheet1").Cells

Cells("A1").Value = "Excel writer example (C#)"
Cells("A1").Style.Font.Bold = True
Cells("B1").Value = "=550 + 5"

' Write Excel XLS file
Wbook.WriteXLS("excel_net.xls")

Creating stored procedure with declare and set variables

You should try this syntax - assuming you want to have @OrderID as a parameter for your stored procedure:

CREATE PROCEDURE dbo.YourStoredProcNameHere
   @OrderID INT
AS
BEGIN
 DECLARE @OrderItemID AS INT
 DECLARE @AppointmentID AS INT
 DECLARE @PurchaseOrderID AS INT
 DECLARE @PurchaseOrderItemID AS INT
 DECLARE @SalesOrderID AS INT
 DECLARE @SalesOrderItemID AS INT

 SELECT @OrderItemID = OrderItemID 
 FROM [OrderItem] 
 WHERE OrderID = @OrderID

 SELECT @AppointmentID = AppoinmentID 
 FROM [Appointment] 
 WHERE OrderID = @OrderID

 SELECT @PurchaseOrderID = PurchaseOrderID 
 FROM [PurchaseOrder] 
 WHERE OrderID = @OrderID

END

OF course, that only works if you're returning exactly one value (not multiple values!)

How to get WooCommerce order details

Accessing direct properties and related are explained

// Get an instance of the WC_Order object
            $order = wc_get_order($order_id);
            $order_data = array(
                    'order_id' => $order->get_id(),
                    'order_number' => $order->get_order_number(),
                    'order_date' => date('Y-m-d H:i:s', strtotime(get_post($order->get_id())->post_date)),
                    'status' => $order->get_status(),
                    'shipping_total' => $order->get_total_shipping(),
                    'shipping_tax_total' => wc_format_decimal($order->get_shipping_tax(), 2),
                    'fee_total' => wc_format_decimal($fee_total, 2),
                    'fee_tax_total' => wc_format_decimal($fee_tax_total, 2),
                    'tax_total' => wc_format_decimal($order->get_total_tax(), 2),
                    'cart_discount' => (defined('WC_VERSION') && (WC_VERSION >= 2.3)) ? wc_format_decimal($order->get_total_discount(), 2) : wc_format_decimal($order->get_cart_discount(), 2),
                    'order_discount' => (defined('WC_VERSION') && (WC_VERSION >= 2.3)) ? wc_format_decimal($order->get_total_discount(), 2) : wc_format_decimal($order->get_order_discount(), 2),
                    'discount_total' => wc_format_decimal($order->get_total_discount(), 2),
                    'order_total' => wc_format_decimal($order->get_total(), 2),
                    'order_currency' => $order->get_currency(),
                    'payment_method' => $order->get_payment_method(),
                    'shipping_method' => $order->get_shipping_method(),
                    'customer_id' => $order->get_user_id(),
                    'customer_user' => $order->get_user_id(),
                    'customer_email' => ($a = get_userdata($order->get_user_id() )) ? $a->user_email : '',
                    'billing_first_name' => $order->get_billing_first_name(),
                    'billing_last_name' => $order->get_billing_last_name(),
                    'billing_company' => $order->get_billing_company(),
                    'billing_email' => $order->get_billing_email(),
                    'billing_phone' => $order->get_billing_phone(),
                    'billing_address_1' => $order->get_billing_address_1(),
                    'billing_address_2' => $order->get_billing_address_2(),
                    'billing_postcode' => $order->get_billing_postcode(),
                    'billing_city' => $order->get_billing_city(),
                    'billing_state' => $order->get_billing_state(),
                    'billing_country' => $order->get_billing_country(),
                    'shipping_first_name' => $order->get_shipping_first_name(),
                    'shipping_last_name' => $order->get_shipping_last_name(),
                    'shipping_company' => $order->get_shipping_company(),
                    'shipping_address_1' => $order->get_shipping_address_1(),
                    'shipping_address_2' => $order->get_shipping_address_2(),
                    'shipping_postcode' => $order->get_shipping_postcode(),
                    'shipping_city' => $order->get_shipping_city(),
                    'shipping_state' => $order->get_shipping_state(),
                    'shipping_country' => $order->get_shipping_country(),
                    'customer_note' => $order->get_customer_note(),
                    'download_permissions' => $order->is_download_permitted() ? $order->is_download_permitted() : 0,
            );

Additional details

  $line_items_shipping = $order->get_items('shipping');
            foreach ($line_items_shipping as $item_id => $item) {
                if (is_object($item)) {
                    if ($meta_data = $item->get_formatted_meta_data('')) :
                        foreach ($meta_data as $meta_id => $meta) :
                            if (in_array($meta->key, $line_items_shipping)) {
                                continue;
                            }
                            // html entity decode is not working preoperly
                            $shipping_items[] = implode('|', array('item:' . wp_kses_post($meta->display_key), 'value:' . str_replace('&times;', 'X', strip_tags($meta->display_value))));
                        endforeach;
                    endif;
                }
            }

            //get fee and total
            $fee_total = 0;
            $fee_tax_total = 0;

            foreach ($order->get_fees() as $fee_id => $fee) {

                $fee_items[] = implode('|', array(
                        'name:' .  html_entity_decode($fee['name'], ENT_NOQUOTES, 'UTF-8'),
                        'total:' . wc_format_decimal($fee['line_total'], 2),
                        'tax:' . wc_format_decimal($fee['line_tax'], 2),
                ));

                $fee_total += $fee['line_total'];
                $fee_tax_total += $fee['line_tax'];
            }

            // get tax items
            foreach ($order->get_tax_totals() as $tax_code => $tax) {            
                $tax_items[] = implode('|', array(
                    'rate_id:'.$tax->id,
                    'code:' . $tax_code,
                    'total:' . wc_format_decimal($tax->amount, 2),
                    'label:'.$tax->label,                
                    'tax_rate_compound:'.$tax->is_compound,
                ));
            }

            // add coupons
            foreach ($order->get_items('coupon') as $_ => $coupon_item) {

                $coupon = new WC_Coupon($coupon_item['name']);

                $coupon_post = get_post((WC()->version < '2.7.0') ? $coupon->id : $coupon->get_id());
                $discount_amount = !empty($coupon_item['discount_amount']) ? $coupon_item['discount_amount'] : 0;
                $coupon_items[] = implode('|', array(
                        'code:' . $coupon_item['name'],
                        'description:' . ( is_object($coupon_post) ? $coupon_post->post_excerpt : '' ),
                        'amount:' . wc_format_decimal($discount_amount, 2),
                ));
            }

            foreach ($order->get_refunds() as $refunded_items){
                $refund_items[] = implode('|', array(
                    'amount:' . $refunded_items->get_amount(),
            'reason:' . $refunded_items->get_reason(),
                    'date:'. date('Y-m-d H-i-s',strtotime((WC()->version < '2.7.0') ? $refunded_items->date_created : $refunded_items->get_date_created())),
                ));
            }

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

I experienced a similar error reply while using the openssl command line interface, while having the correct binary key (-K). The option "-nopad" resolved the issue:

Example generating the error:

echo -ne "\x32\xc8\xde\x5c\x68\x19\x7e\x53\xa5\x75\xe1\x76\x1d\x20\x16\xb2\x72\xd8\x40\x87\x25\xb3\x71\x21\x89\xf6\xca\x46\x9f\xd0\x0d\x08\x65\x49\x23\x30\x1f\xe0\x38\x48\x70\xdb\x3b\xa8\x56\xb5\x4a\xc6\x09\x9e\x6c\x31\xce\x60\xee\xa2\x58\x72\xf6\xb5\x74\xa8\x9d\x0c" | openssl aes-128-cbc -d -K 31323334353637383930313233343536 -iv 79169625096006022424242424242424 | od -t x1

Result:

bad decrypt
140181876450560:error:06065064:digital envelope 
routines:EVP_DecryptFinal_ex:bad decrypt:../crypto/evp/evp_enc.c:535:
0000000 2f 2f 07 02 54 0b 00 00 00 00 00 00 04 29 00 00
0000020 00 00 04 a9 ff 01 00 00 00 00 04 a9 ff 02 00 00
0000040 00 00 04 a9 ff 03 00 00 00 00 0d 79 0a 30 36 38

Example with correct result:

echo -ne "\x32\xc8\xde\x5c\x68\x19\x7e\x53\xa5\x75\xe1\x76\x1d\x20\x16\xb2\x72\xd8\x40\x87\x25\xb3\x71\x21\x89\xf6\xca\x46\x9f\xd0\x0d\x08\x65\x49\x23\x30\x1f\xe0\x38\x48\x70\xdb\x3b\xa8\x56\xb5\x4a\xc6\x09\x9e\x6c\x31\xce\x60\xee\xa2\x58\x72\xf6\xb5\x74\xa8\x9d\x0c" | openssl aes-128-cbc -d -K 31323334353637383930313233343536 -iv 79169625096006022424242424242424 -nopad | od -t x1

Result:

0000000 2f 2f 07 02 54 0b 00 00 00 00 00 00 04 29 00 00
0000020 00 00 04 a9 ff 01 00 00 00 00 04 a9 ff 02 00 00
0000040 00 00 04 a9 ff 03 00 00 00 00 0d 79 0a 30 36 38
0000060 30 30 30 34 31 33 31 2f 2f 2f 2f 2f 2f 2f 2f 2f
0000100

casting int to char using C++ style casting

You can implicitly convert between numerical types, even when that loses precision:

char c = i;

However, you might like to enable compiler warnings to avoid potentially lossy conversions like this. If you do, then use static_cast for the conversion.

Of the other casts:

  • dynamic_cast only works for pointers or references to polymorphic class types;
  • const_cast can't change types, only const or volatile qualifiers;
  • reinterpret_cast is for special circumstances, converting between pointers or references and completely unrelated types. Specifically, it won't do numeric conversions.
  • C-style and function-style casts do whatever combination of static_cast, const_cast and reinterpret_cast is needed to get the job done.

No Exception while type casting with a null in java

You can cast null to any reference type without getting any exception.

The println method does not throw null pointer because it first checks whether the object is null or not. If null then it simply prints the string "null". Otherwise it will call the toString method of that object.

Adding more details: Internally print methods call String.valueOf(object) method on the input object. And in valueOf method, this check helps to avoid null pointer exception:

return (obj == null) ? "null" : obj.toString();

For rest of your confusion, calling any method on a null object should throw a null pointer exception, if not a special case.

Variable name as a string in Javascript

This works for basic expressions

const nameof = exp => exp.toString().match(/[.](\w+)/)[1];

Example

nameof(() => options.displaySize);

Snippet:

_x000D_
_x000D_
var nameof = function (exp) { return exp.toString().match(/[.](\w+)/)[1]; };_x000D_
var myFirstName = 'Chuck';_x000D_
var varname = nameof(function () { return window.myFirstName; });_x000D_
console.log(varname);
_x000D_
_x000D_
_x000D_

Regex to match any character including new lines

Yeap, you just need to make . match newline :

$string =~ /(START)(.+?)(END)/s;

How can I delay a method call for 1 second?

NOTE: this will pause your whole thread, not just the one method.
Make a call to sleep/wait/halt for 1000 ms just before calling your method?

Sleep(1000); // does nothing the next 1000 mSek

Methodcall(params); // now do the real thing

Edit: The above answer applies to the general question "How can I delay a method call for 1 second?", which was the question asked at the time of the answer (infact the answer was given within 7 minutes of the original question :-)). No Info was given about the language at that time, so kindly stop bitching about the proper way of using sleep i XCode og the lack of classes...

Turn Pandas Multi-Index into column

This doesn't really apply to your case but could be helpful for others (like myself 5 minutes ago) to know. If one's multindex have the same name like this:

                         value
Trial        Trial
    1              0        13
                   1         3
                   2         4
    2              0       NaN
                   1        12
    3              0        34 

df.reset_index(inplace=True) will fail, cause the columns that are created cannot have the same names.

So then you need to rename the multindex with df.index = df.index.set_names(['Trial', 'measurement']) to get:

                           value
Trial    measurement       

    1              0        13
    1              1         3
    1              2         4
    2              0       NaN
    2              1        12
    3              0        34 

And then df.reset_index(inplace=True) will work like a charm.

I encountered this problem after grouping by year and month on a datetime-column(not index) called live_date, which meant that both year and month were named live_date.

How do I remove the "extended attributes" on a file in Mac OS X?

Use the xattr command. You can inspect the extended attributes:

$ xattr s.7z
com.apple.metadata:kMDItemWhereFroms
com.apple.quarantine

and use the -d option to delete one extended attribute:

$ xattr -d com.apple.quarantine s.7z
$ xattr s.7z
com.apple.metadata:kMDItemWhereFroms

you can also use the -c option to remove all extended attributes:

$ xattr -c s.7z
$ xattr s.7z

xattr -h will show you the command line options, and xattr has a man page.

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

CSS How to set div height 100% minus nPx

You can do something like height: calc(100% - nPx); for example height: calc(100% - 70px);

Generate random numbers uniformly over an entire range

If you want numbers to be uniformly distributed over the range, you should break your range up into a number of equal sections that represent the number of points you need. Then get a random number with a min/max for each section.

As another note, you should probably not use rand() as it's not very good at actually generating random numbers. I don't know what platform you're running on, but there is probably a better function you can call like random().