Programs & Examples On #Android vibration

The Android framework includes support for Vibration available on devices, allowing you to control the device's vibrations from your application. Questions regarding practical and advanced use of Vibrations must fall under this tag.

How to make an Android device vibrate? with different frequency?

Try:

import android.os.Vibrator;
...
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
    //deprecated in API 26 
    v.vibrate(500);
}

Note:

Don't forget to include permission in AndroidManifest.xml file:

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

What is the difference between lower bound and tight bound?

The basic difference between

Blockquote

asymptotically upper bound and asymptotically tight Asym.upperbound means a given algorythm that can executes with maximum amount of time depending upon the number of inputs ,for eg in sorting algo if all the array (n)elements are in descending order then for ascending them it will take a running time of O(n) which shows upper bound complexity ,but if they are already sorted then it will take ohm(1).so we generally used "O"notation for upper bound complexity.

Asym. tightbound bound shows the for eg(c1g(n)<=f(n)<=c2g(n)) shows the tight bound limit such that the function have the value in between two bound (upper bound and lower bound),giving the average case.

How to round a number to n decimal places in Java

Real's Java How-to posts this solution, which is also compatible for versions before Java 1.6.

BigDecimal bd = new BigDecimal(Double.toString(d));
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();

UPDATE: BigDecimal.ROUND_HALF_UP is deprecated - Use RoundingMode

BigDecimal bd = new BigDecimal(Double.toString(number));
bd = bd.setScale(decimalPlaces, RoundingMode.HALF_UP);
return bd.doubleValue();

DataGrid get selected rows' column values

If you are using an SQL query to populate your DataGrid you can do this :

Datagrid fill

Private Sub UserControl_Loaded(sender As Object, e As RoutedEventArgs)
        Dim cmd As SqlCommand
        Dim da As SqlDataAdapter
        Dim dt As DataTable

        cmd = New SqlCommand With {
            .CommandText = "SELECT * FROM temp_rech_dossier_route",
            .Connection = connSQLServer
        }
        da = New SqlDataAdapter(cmd)
        dt = New DataTable("RECH")
        da.Fill(dt)
        DataGridRech.ItemsSource = dt.DefaultView
End Sub

Value diplay

    Private Sub DataGridRech_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles DataGridRech.SelectionChanged
        Dim val As DataRowView
        val = CType(DataGridRech.SelectedItem, DataRowView)
        Console.WriteLine(val.Row.Item("num_dos"))
    End Sub

I know it's in VB.Net but it can be translated into C#. I put this solution here, it might be useful for someone.

How to get last month/year in java?

You need to be aware that month is zero based so when you do the getMonth you will need to add 1. In the example below we have to add 1 to Januaray as 1 and not 0

    Calendar c = Calendar.getInstance();
    c.set(2011, 2, 1);
    c.add(Calendar.MONTH, -1);
    int month = c.get(Calendar.MONTH) + 1;
    assertEquals(1, month);

How to use jquery $.post() method to submit form values

You have to select and send the form data as well:

$("#post-btn").click(function(){        
    $.post("process.php", $("#reg-form").serialize(), function(data) {
        alert(data);
    });
});

Take a look at the documentation for the jQuery serialize method, which encodes the data from the form fields into a data-string to be sent to the server.

Custom ImageView with drop shadow

I manage to apply gradient border using this code..

public static Bitmap drawShadow(Bitmap bitmap, int leftRightThk, int bottomThk, int padTop) {
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

    int newW = w - (leftRightThk * 2);
    int newH = h - (bottomThk + padTop);

    Bitmap.Config conf = Bitmap.Config.ARGB_8888;
    Bitmap bmp = Bitmap.createBitmap(w, h, conf);
    Bitmap sbmp = Bitmap.createScaledBitmap(bitmap, newW, newH, false);

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    Canvas c = new Canvas(bmp);

    // Left
    int leftMargin = (leftRightThk + 7)/2;
    Shader lshader = new LinearGradient(0, 0, leftMargin, 0, Color.TRANSPARENT, Color.BLACK, TileMode.CLAMP);
    paint.setShader(lshader);
    c.drawRect(0, padTop, leftMargin, newH, paint); 

    // Right
    Shader rshader = new LinearGradient(w - leftMargin, 0, w, 0, Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
    paint.setShader(rshader);
    c.drawRect(newW, padTop, w, newH, paint);

    // Bottom
    Shader bshader = new LinearGradient(0, newH, 0, bitmap.getHeight(), Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
    paint.setShader(bshader);
    c.drawRect(leftMargin -3, newH, newW + leftMargin + 3, bitmap.getHeight(), paint);
    c.drawBitmap(sbmp, leftRightThk, 0, null);

    return bmp;
}

hope this helps !

SecurityError: The operation is insecure - window.history.pushState()

In my case I was missing 'www.' from the url I was pushing. It must be exact match, if you're working on www.test.com, you must push to www.test.com and not test.com

Converting JSON to XLS/CSV in Java

A JSON document basically consists of lists and dictionaries. There is no obvious way to map such a datastructure on a two-dimensional table.

Can't escape the backslash with regex?

If it's not a literal, you have to use \\\\ so that you get \\ which means an escaped backslash.

That's because there are two representations. In the string representation of your regex, you have "\\\\", Which is what gets sent to the parser. The parser will see \\ which it interprets as a valid escaped-backslash (which matches a single backslash).

Get output parameter value in ADO.NET

Not my code, but a good example i think

source: http://www.eggheadcafe.com/PrintSearchContent.asp?LINKID=624

using System; 
using System.Data; 
using System.Data.SqlClient; 


class OutputParams 
{ 
    [STAThread] 
    static void Main(string[] args) 
    { 

    using( SqlConnection cn = new SqlConnection("server=(local);Database=Northwind;user id=sa;password=;")) 
    { 
        SqlCommand cmd = new SqlCommand("CustOrderOne", cn); 
        cmd.CommandType=CommandType.StoredProcedure ; 

        SqlParameter parm= new SqlParameter("@CustomerID",SqlDbType.NChar) ; 
        parm.Value="ALFKI"; 
        parm.Direction =ParameterDirection.Input ; 
        cmd.Parameters.Add(parm); 

        SqlParameter parm2= new SqlParameter("@ProductName",SqlDbType.VarChar); 
        parm2.Size=50; 
        parm2.Direction=ParameterDirection.Output; 
        cmd.Parameters.Add(parm2); 

        SqlParameter parm3=new SqlParameter("@Quantity",SqlDbType.Int); 
        parm3.Direction=ParameterDirection.Output; 
        cmd.Parameters.Add(parm3);

        cn.Open(); 
        cmd.ExecuteNonQuery(); 
        cn.Close(); 

        Console.WriteLine(cmd.Parameters["@ProductName"].Value); 
        Console.WriteLine(cmd.Parameters["@Quantity"].Value.ToString());
        Console.ReadLine(); 
    } 
} 

Speed up rsync with Simultaneous/Concurrent File Transfers?

Updated answer (Jan 2020)

xargs is now the recommended tool to achieve parallel execution. It's pre-installed almost everywhere. For running multiple rsync tasks the command would be:

ls /srv/mail | xargs -n1 -P4 -I% rsync -Pa % myserver.com:/srv/mail/

This will list all folders in /srv/mail, pipe them to xargs, which will read them one-by-one and and run 4 rsync processes at a time. The % char replaces the input argument for each command call.

Original answer using parallel:

ls /srv/mail | parallel -v -j8 rsync -raz --progress {} myserver.com:/srv/mail/{}

INNER JOIN vs INNER JOIN (SELECT . FROM)

You are correct. You did exactly the right thing, checking the query plan rather than trying to second-guess the optimiser. :-)

How to detect online/offline event cross-browser?

Today there's an open source JavaScript library that does this job: it's called Offline.js.

Automatically display online/offline indication to your users.

https://github.com/HubSpot/offline

Be sure to check the full README. It contains events that you can hook into.

Here's a test page. It's beautiful/has a nice feedback UI by the way! :)

Offline.js Simulate UI is an Offline.js plug-in that allows you to test how your pages respond to different connectivity states without having to use brute-force methods to disable your actual connectivity.

How to detect escape key press with pure JS or jQuery?

Using JavaScript you can do check working jsfiddle

document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 27) {
        alert('Esc key pressed.');
    }
};

Using jQuery you can do check working jsfiddle

jQuery(document).on('keyup',function(evt) {
    if (evt.keyCode == 27) {
       alert('Esc key pressed.');
    }
});

Control the size of points in an R scatterplot?

As rcs stated, cex will do the job in base graphics package. I reckon that you're not willing to do your graph in ggplot2 but if you do, there's a size aesthetic attribute, that you can easily control (ggplot2 has user-friendly function arguments: instead of typing cex (character expansion), in ggplot2 you can type e.g. size = 2 and you'll get 2mm point).

Here's the example:

### base graphics ###
plot(mpg ~ hp, data = mtcars, pch = 16, cex = .9)

### ggplot2 ###
# with qplot()
qplot(mpg, hp, data = mtcars, size = I(2))
# or with ggplot() + geom_point()
ggplot(mtcars, aes(mpg, hp), size = 2) + geom_point()
# or another solution:
ggplot(mtcars, aes(mpg, hp)) + geom_point(size = 2)

How do I load a file from resource folder?

Try Flowing codes on Spring project

ClassPathResource resource = new ClassPathResource("fileName");
InputStream inputStream = resource.getInputStream();

Or on non spring project

 ClassLoader classLoader = getClass().getClassLoader();
 File file = new File(classLoader.getResource("fileName").getFile());
 InputStream inputStream = new FileInputStream(file);

How to do error logging in CodeIgniter (PHP)

Also make sure that you have allowed codeigniter to log the type of messages you want in a config file.

i.e $config['log_threshold'] = [log_level ranges 0-4];

MySQL compare now() (only date, not time) with a datetime field

Use DATE(NOW()) to compare dates

DATE(NOW()) will give you the date part of current date and DATE(duedate) will give you the date part of the due date. then you can easily compare the dates

So you can compare it like

DATE(NOW()) = DATE(duedate)

OR

DATE(duedate) = CURDATE() 

See here

C# ASP.NET Send Email via TLS

On SmtpClient there is an EnableSsl property that you would set.

i.e.

SmtpClient client = new SmtpClient(exchangeServer);
client.EnableSsl = true;
client.Send(msg);

Java: Reading integers from a file into an array

For comparison, here is another way to read the file. It has one advantage that you don't need to know how many integers there are in the file.

File file = new File("Tall.txt");
byte[] bytes = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bytes);
fis.close();
String[] valueStr = new String(bytes).trim().split("\\s+");
int[] tall = new int[valueStr.length];
for (int i = 0; i < valueStr.length; i++) 
    tall[i] = Integer.parseInt(valueStr[i]);
System.out.println(Arrays.asList(tall));

Create normal zip file programmatically

Here's some code I wrote after using the above posts. Thanks for all your help.

This code accepts a list of file paths and creates a zip file out of them.

public class Zip
{
    private string _filePath;
    public string FilePath { get { return _filePath; } }

    /// <summary>
    /// Zips a set of files
    /// </summary>
    /// <param name="filesToZip">A list of filepaths</param>
    /// <param name="sZipFileName">The file name of the new zip (do not include the file extension, nor the full path - just the name)</param>
    /// <param name="deleteExistingZip">Whether you want to delete the existing zip file</param>
    /// <remarks>
    /// Limitation - all files must be in the same location. 
    /// Limitation - must have read/write/edit access to folder where first file is located.
    /// Will throw exception if the zip file already exists and you do not specify deleteExistingZip
    /// </remarks>
    public Zip(List<string> filesToZip, string sZipFileName, bool deleteExistingZip = true)
    {
        if (filesToZip.Count > 0)
        {
            if (File.Exists(filesToZip[0]))
            {

                // Get the first file in the list so we can get the root directory
                string strRootDirectory = Path.GetDirectoryName(filesToZip[0]);

                // Set up a temporary directory to save the files to (that we will eventually zip up)
                DirectoryInfo dirTemp = Directory.CreateDirectory(strRootDirectory + "/" + DateTime.Now.ToString("yyyyMMddhhmmss"));

                // Copy all files to the temporary directory
                foreach (string strFilePath in filesToZip)
                {
                    if (!File.Exists(strFilePath))
                    {
                        throw new Exception(string.Format("File {0} does not exist", strFilePath));
                    }
                    string strDestinationFilePath = Path.Combine(dirTemp.FullName, Path.GetFileName(strFilePath));
                    File.Copy(strFilePath, strDestinationFilePath);
                }

                // Create the zip file using the temporary directory
                if (!sZipFileName.EndsWith(".zip")) { sZipFileName += ".zip"; }
                string strZipPath = Path.Combine(strRootDirectory, sZipFileName);
                if (deleteExistingZip == true && File.Exists(strZipPath)) { File.Delete(strZipPath); }
                ZipFile.CreateFromDirectory(dirTemp.FullName, strZipPath, CompressionLevel.Fastest, false);

                // Delete the temporary directory
                dirTemp.Delete(true);

                _filePath = strZipPath;                    
            }
            else
            {
                throw new Exception(string.Format("File {0} does not exist", filesToZip[0]));
            }
        }
        else
        {
            throw new Exception("You must specify at least one file to zip.");
        }
    }
}

Reload an iframe with jQuery

with jquery you can use this:

$('#iframeid',window.parent.document).attr('src',$('#iframeid',window.parent.document).attr('src'));

Datatable to html Table

I have seen some solutions here worth noting, as Omer Eldan posted. but here follows. ASP C#

using System.Data;
using System.Web.UI.HtmlControls;

public static Table DataTableToHTMLTable(DataTable dt, bool includeHeaders)
{
    Table tbl = new Table();
    TableRow tr = null;
    TableCell cell = null;

    int rows = dt.Rows.Count;
    int cols = dt.Columns.Count;

    if (includeHeaders)
    {
        TableHeaderRow htr = new TableHeaderRow();
        TableHeaderCell hcell = null;
        for (int i = 0; i < cols; i++)
        {
            hcell = new TableHeaderCell();
            hcell.Text = dt.Columns[i].ColumnName.ToString();
            htr.Cells.Add(hcell);
        }
        tbl.Rows.Add(htr);
    }

    for (int j = 0; j < rows; j++)
    {
        tr = new TableRow();
        for (int k = 0; k < cols; k++)
        {
            cell = new TableCell();
            cell.Text = dt.Rows[j][k].ToString();
            tr.Cells.Add(cell);
        }
        tbl.Rows.Add(tr);
    }
    return tbl;
}

why this solution? Because you can easily just add this to a panel ie:

panel.Controls.Add(DataTableToHTMLTable(dtExample,true));

Second question , why do you have one column datatables and not just array's? Are you sure that these DataTables are uniform, because if the data is jagged then it's no use. If You really have to join these DataTables, there is many examples of Linq operations, or just use (beware though of same name columns as this will conflict in both linq operations and this solution if not handled):

public DataTable joinUniformTable(DataTable dt1, DataTable dt2)
{
    int dt2ColsCount = dt2.Columns.Count;
    int dt1lRowsCount = dt1.Rows.Count;

    DataColumn column;
    for (int i = 0; i < dt2ColsCount; i++)
    {
        column = new DataColumn();
        string colName = dt2.Columns[i].ColumnName;
        System.Type colType = dt2.Columns[i].DataType;
        column.ColumnName = colName;
        column.DataType = colType;
        dt1.Columns.Add(column);

        for (int j = 0; j < dt1lRowsCount; j++)
        {
            dt1.Rows[j][colName] = dt2.Rows[j][colName];
        }
    }
    return dt1;
}

and your solution would look something like:

panel.Controls.Add(DataTableToHTMLTable(joinUniformTable(joinUniformTable(LivDT,BathDT),BedDT),true));

interpret the rest, and have fun.

IOS 7 Navigation Bar text and arrow color

Swift / iOS8

let textAttributes = NSMutableDictionary(capacity:1)
textAttributes.setObject(UIColor.whiteColor(), forKey: NSForegroundColorAttributeName)
navigationController?.navigationBar.titleTextAttributes = textAttributes

laravel throwing MethodNotAllowedHttpException

<?php echo Form::open(array('action' => 'MemberController@validateCredentials')); ?>

by default, Form::open() assumes a POST method.

you have GET in your routes. change it to POST in the corresponding route.

or if you want to use the GET method, then add the method param.

e.g.

Form::open(array('url' => 'foo/bar', 'method' => 'get'))

Check if a string is a date value

Use Regular expression to validate it.

isDate('2018-08-01T18:30:00.000Z');

isDate(_date){
        const _regExp  = new RegExp('^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?(Z)?$');
        return _regExp.test(_date);
    }

How to remove blank lines from a Unix file

grep . file

grep looks at your file line-by-line; the dot . matches anything except a newline character. The output from grep is therefore all the lines that consist of something other than a single newline.

What's the difference between @Component, @Repository & @Service annotations in Spring?

all these annotations are type of stereo type type of annotation,the difference between these three annotations are

  • If we add the @Component then it tells the role of class is a component class it means it is a class consisting some logic,but it does not tell whether a class containing a specifically business or persistence or controller logic so we don't use directly this @Component annotation
  • If we add @Service annotation then it tells that a role of class consisting business logic
  • If we add @Repository on top of class then it tells that a class consisting persistence logic
  • Here @Component is a base annotation for @Service,@Repository and @Controller annotations

for example

package com.spring.anno;
@Service
public class TestBean
{
    public void m1()
    {
       //business code
    }
}

package com.spring.anno;
@Repository
public class TestBean
{
    public void update()
    {
       //persistence code
    }
}
  • whenever we adds the @Service or @Repositroy or @Controller annotation by default @Component annotation is going to existence on top of the class

django: TypeError: 'tuple' object is not callable

You're missing comma (,) inbetween:

>>> ((1,2) (2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Put comma:

>>> ((1,2), (2,3))
((1, 2), (2, 3))

Create a temporary table in a SELECT statement without a separate CREATE TABLE

Engine must be before select:

CREATE TEMPORARY TABLE temp1 ENGINE=MEMORY 
as (select * from table1)

How can you profile a Python script?

A new tool to handle profiling in Python is PyVmMonitor: http://www.pyvmmonitor.com/

It has some unique features such as

  • Attach profiler to a running (CPython) program
  • On demand profiling with Yappi integration
  • Profile on a different machine
  • Multiple processes support (multiprocessing, django...)
  • Live sampling/CPU view (with time range selection)
  • Deterministic profiling through cProfile/profile integration
  • Analyze existing PStats results
  • Open DOT files
  • Programatic API access
  • Group samples by method or line
  • PyDev integration
  • PyCharm integration

Note: it's commercial, but free for open source.

Python read in string from file and split it into values

I would do something like:

filename = "mynumbers.txt"
mynumbers = []
with open(filename) as f:
    for line in f:
        mynumbers.append([int(n) for n in line.strip().split(',')])
for pair in mynumbers:
    try:
        x,y = pair[0],pair[1]
        # Do Something with x and y
    except IndexError:
        print "A line in the file doesn't have enough entries."

The with open is recommended in http://docs.python.org/tutorial/inputoutput.html since it makes sure files are closed correctly even if an exception is raised during the processing.

How does cellForRowAtIndexPath work?

Basically it's designing your cell, The cellforrowatindexpath is called for each cell and the cell number is found by indexpath.row and section number by indexpath.section . Here you can use a label, button or textfied image anything that you want which are updated for all rows in the table. Answer for second question In cell for row at index path use an if statement

In Objective C

-(UITableViewCell *)tableView:(UITableView *)tableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

 NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

  if(tableView == firstTableView)
  {
      //code for first table view 
      [cell.contentView addSubview: someView];
  }

  if(tableview == secondTableView)
  {
      //code for secondTableView 
      [cell.contentView addSubview: someView];
  }
  return cell;
}

In Swift 3.0

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{
  let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!

  if(tableView == firstTableView)   {
     //code for first table view 
  }

  if(tableview == secondTableView)      {
     //code for secondTableView 
  }

  return cell
}

How to return a specific status code and no contents from Controller?

this.HttpContext.Response.StatusCode = 418; // I'm a teapot

How to end the request?

Try other solution, just:

return StatusCode(418);


You could use StatusCode(???) to return any HTTP status code.


Also, you can use dedicated results:

Success:

  • return Ok() ? Http status code 200
  • return Created() ? Http status code 201
  • return NoContent(); ? Http status code 204

Client Error:

  • return BadRequest(); ? Http status code 400
  • return Unauthorized(); ? Http status code 401
  • return NotFound(); ? Http status code 404


More details:

How to use matplotlib tight layout with Figure?

Just call fig.tight_layout() as you normally would. (pyplot is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)

There shouldn't be a difference between the QtAgg backend and the default backend (or if there is, it's a bug).

E.g.

import matplotlib.pyplot as plt

#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so 
#--    we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

plt.show()

Before Tight Layout

enter image description here

After Tight Layout

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

fig.tight_layout()

plt.show()

enter image description here

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

python setup.py --help

...to get a list of commands. What you are looking to do is...

python setup.py install

How to check if a scope variable is undefined in AngularJS template?

As @impulsgraw wrote. You need to check for undefined after the pipes:

<div ng-show="foo || undefined">
    Show this if foo is defined!
</div>
<div ng-show="boo || !undefined">
    Show this if boo is undefined!
</div>

https://jsfiddle.net/mjfz2q9h/11/

Creating a constant Dictionary in C#

Just another idea since I am binding to a winforms combobox:

public enum DateRange {
    [Display(Name = "None")]
    None = 0,
    [Display(Name = "Today")]
    Today = 1,
    [Display(Name = "Tomorrow")]
    Tomorrow = 2,
    [Display(Name = "Yesterday")]
    Yesterday = 3,
    [Display(Name = "Last 7 Days")]
    LastSeven = 4,
    [Display(Name = "Custom")]
    Custom = 99
    };

int something = (int)DateRange.None;

To get the int value from the display name from:

public static class EnumHelper<T>
{
    public static T GetValueFromName(string name)
    {
        var type = typeof(T);
        if (!type.IsEnum) throw new InvalidOperationException();

        foreach (var field in type.GetFields())
        {
            var attribute = Attribute.GetCustomAttribute(field,
                typeof(DisplayAttribute)) as DisplayAttribute;
            if (attribute != null)
            {
                if (attribute.Name == name)
                {
                    return (T)field.GetValue(null);
                }
            }
            else
            {
                if (field.Name == name)
                    return (T)field.GetValue(null);
            }
        }

        throw new ArgumentOutOfRangeException("name");
    }
}

usage:

var z = (int)EnumHelper<DateRange>.GetValueFromName("Last 7 Days");

Formula to check if string is empty in Crystal Reports

if {le_gur_bond.gur1}="" or IsNull({le_gur_bond.gur1})   Then
    ""
else 
 "and " + {le_gur_bond.gur2} + " of "+ {le_gur_bond.grr_2_address2}

How to make div background color transparent in CSS

The problem with opacity is that it will also affect the content, when often you do not want this to happen.

If you just want your element to be transparent, it's really as easy as :

background-color: transparent;

But if you want it to be in colors, you can use:

background-color: rgba(255, 0, 0, 0.4);

Or define a background image (1px by 1px) saved with the right alpha.
(To do so, use Gimp, Paint.Net or any other image software that allows you to do that.
Just create a new image, delete the background and put a semi-transparent color in it, then save it in png.)

As said by René, the best thing to do would be to mix both, with the rgba first and the 1px by 1px image as a fallback if the browser doesn't support alpha :

background: url('img/red_transparent_background.png');
background: rgba(255, 0, 0, 0.4);

See also : http://www.w3schools.com/cssref/css_colors_legal.asp.

Demo : My JSFiddle

Reporting Services export to Excel with Multiple Worksheets

As @huttelihut pointed out, this is now possible as of SQL Server 2008 R2 - Read More Here

Prior to 2008 R2 it does't appear possible but MSDN Social has some suggested workarounds.

When is std::weak_ptr useful?

A good example would be a cache.

For recently accessed objects, you want to keep them in memory, so you hold a strong pointer to them. Periodically, you scan the cache and decide which objects have not been accessed recently. You don't need to keep those in memory, so you get rid of the strong pointer.

But what if that object is in use and some other code holds a strong pointer to it? If the cache gets rid of its only pointer to the object, it can never find it again. So the cache keeps a weak pointer to objects that it needs to find if they happen to stay in memory.

This is exactly what a weak pointer does -- it allows you to locate an object if it's still around, but doesn't keep it around if nothing else needs it.

Find the index of a char in string?

Contanis occur if using the method of the present letter, and store the corresponding number using the IndexOf method, see example below.

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim myString As String = "abcdef"
    Dim numberString As String = String.Empty

    If myString.Contains("d") Then
        numberString = myString.IndexOf("d")
    End If
End Sub

Another sample with TextBox

  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim myString As String = "abcdef"
    Dim numberString As String = String.Empty

    If myString.Contains(me.TextBox1.Text) Then
        numberString = myString.IndexOf(Me.TextBox1.Text)
    End If
End Sub

Regards

Typescript empty object for a typed variable

If you declare an empty object literal and then assign values later on, then you can consider those values optional (may or may not be there), so just type them as optional with a question mark:

type User = {
    Username?: string;
    Email?: string;
}

Elevating process privilege programmatically?

This code puts the above all together and restarts the current wpf app with admin privs:

if (IsAdministrator() == false)
{
    // Restart program and run as admin
    var exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
    ProcessStartInfo startInfo = new ProcessStartInfo(exeName);
    startInfo.Verb = "runas";
    System.Diagnostics.Process.Start(startInfo);
    Application.Current.Shutdown();
    return;
}

private static bool IsAdministrator()
{
    WindowsIdentity identity = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(identity);
    return principal.IsInRole(WindowsBuiltInRole.Administrator);
}


// To run as admin, alter exe manifest file after building.
// Or create shortcut with "as admin" checked.
// Or ShellExecute(C# Process.Start) can elevate - use verb "runas".
// Or an elevate vbs script can launch programs as admin.
// (does not work: "runas /user:admin" from cmd-line prompts for admin pass)

Update: The app manifest way is preferred:

Right click project in visual studio, add, new application manifest file, change the file so you have requireAdministrator set as shown in the above.

A problem with the original way: If you put the restart code in app.xaml.cs OnStartup, it still may start the main window briefly even though Shutdown was called. My main window blew up if app.xaml.cs init was not run and in certain race conditions it would do this.

How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line?

Although I've tried all the previous answers, only the following one worked out:

1 - Open Powershell (as Admin)

2 - Run:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

3 - Run:

Install-PackageProvider -Name NuGet

The author is Niels Weistra: Microsoft Forum

How to print a string multiple times?

If you want to print something = '@' 2 times in a line, you can write this:

print(something * 2)

If you want to print 4 lines of something, you can use a for loop:

for i in range(4):
     print(something)

How to get the number of characters in a std::string?

std::string str("a string");
std::cout << str.size() << std::endl;

Can we set a Git default to fetch all tags during a remote pull?

For me the following seemed to work.

git pull --tags

javascript cell number validation

Verify this code : It works on change of phone number field in ms crm 2016 form .

function validatePhoneNumber() {

    var mob = Xrm.Page.getAttribute("gen_phone").getValue();
    var length = mob.length;
    if (length < 10 || length > 10) {
        alert("Please Enter 10 Digit Number:");
        Xrm.Page.getAttribute("gen_phone").setValue(null);
        return true;
    }
    if (mob > 31 && (mob < 48 || mob > 57)) {} else {
        alert("Please Enter 10 Digit Number:");
        Xrm.Page.getAttribute("gen_phone").setValue(null);
        return true;
    }
}

How to enable file sharing for my app?

According to apple doc:

File-Sharing Support
File-sharing support lets apps make user data files available in iTunes 9.1 and later. An app that declares its support for file sharing makes the contents of its /Documents directory available to the user. The user can then move files in and out of this directory as needed from iTunes. This feature does not allow your app to share files with other apps on the same device; that behavior requires the pasteboard or a document interaction controller object.

To enable file sharing for your app, do the following:

  1. Add the UIFileSharingEnabled key to your app’s Info.plist file, and set the value of the key to YES. (The actual key name is "Application supports iTunes file sharing")

  2. Put whatever files you want to share in your app’s Documents directory.

  3. When the device is plugged into the user’s computer, iTunes displays a File Sharing section in the Apps tab of the selected device.

  4. The user can add files to this directory or move files to the desktop.

Apps that support file sharing should be able to recognize when files have been added to the Documents directory and respond appropriately. For example, your app might make the contents of any new files available from its interface. You should never present the user with the list of files in this directory and ask them to decide what to do with those files.

For additional information about the UIFileSharingEnabled key, see Information Property List Key Reference.

How to specify credentials when connecting to boto3 S3?

You can create a session:

import boto3
session = boto3.Session(
    aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY,
    aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY,
)

Then use that session to get an S3 resource:

s3 = session.resource('s3')

Convert php array to Javascript

Keep it simple :

var jsObject = JSON.parse('<?= addslashes(json_encode($phpArray)) ?>');

How to empty the message in a text area with jquery?

$('#message').val('');

Explanation (from @BalusC):
textarea is an input element with a value. You actually want to "empty" the value. So as for every other input element (input, select, textarea) you need to use element.val('');.

Also see docs

What is the use of "object sender" and "EventArgs e" parameters?

Those two parameters (or variants of) are sent, by convention, with all events.

  • sender: The object which has raised the event
  • e an instance of EventArgs including, in many cases, an object which inherits from EventArgs. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.

In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs are Empty as there is no further information about the event.

Looking at the 2 parameters separately, here are some examples where they are useful.

sender

Say you have multiple buttons on a form. These buttons could contain a Tag describing what clicking them should do. You could handle all the Click events with the same handler, and depending on the sender do something different

private void HandleButtonClick(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    if(btn.Tag == "Hello")
      MessageBox.Show("Hello")
    else if(btn.Tag == "Goodbye")
       Application.Exit();
    // etc.
}

Disclaimer : That's a contrived example; don't do that!

e

Some events are cancelable. They send CancelEventArgs instead of EventArgs. This object adds a simple boolean property Cancel on the event args. Code handling this event can cancel the event:

private void HandleCancellableEvent(object sender, CancelEventArgs e)
{
    if(/* some condition*/)
    {
       // Cancel this event
       e.Cancel = true;
    }
}

Making a list of evenly spaced numbers in a certain range in python

f = 0.5
a = 0
b = 9
d = [x * f for x in range(a, b)]

would be a way to do it.

Microsoft Web API: How do you do a Server.MapPath?

The selected answer did not work in my Web API application. I had to use

System.Web.HttpRuntime.AppDomainAppPath

Converting VS2012 Solution to VS2010

Simple solution which worked for me.

  1. Install Vim editor for windows.
  2. Open VS 2012 project solution using Vim editor and modify the version targetting Visual studio solution 10.
  3. Open solution with Visual studio 2010.. and continue with your work ;)

Append an array to another array in JavaScript

If you want to modify the original array instead of returning a new array, use .push()...

array1.push.apply(array1, array2);
array1.push.apply(array1, array3);

I used .apply to push the individual members of arrays 2 and 3 at once.

or...

array1.push.apply(array1, array2.concat(array3));

To deal with large arrays, you can do this in batches.

for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
    array1.push.apply(array1, to_add.slice(n, n+300));
}

If you do this a lot, create a method or function to handle it.

var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);

Object.defineProperty(Array.prototype, "pushArrayMembers", {
    value: function() {
        for (var i = 0; i < arguments.length; i++) {
            var to_add = arguments[i];
            for (var n = 0; n < to_add.length; n+=300) {
                push_apply(this, slice_call(to_add, n, n+300));
            }
        }
    }
});

and use it like this:

array1.pushArrayMembers(array2, array3);

_x000D_
_x000D_
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
    value: function() {_x000D_
        for (var i = 0; i < arguments.length; i++) {_x000D_
            var to_add = arguments[i];_x000D_
            for (var n = 0; n < to_add.length; n+=300) {_x000D_
                push_apply(this, slice_call(to_add, n, n+300));_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
_x000D_
_x000D_

Is there a way to get the source code from an APK file?

apktool is THE way to go. Online apktool service exists as well: http://www.javadecompilers.com/apktool

Some limitations, obviously, exist due to the service ‘online nature’: you may extract and research assets and the manifest file, but it is impossible to recompile the application at the moment.

Still, this is a no-hassle way to 'open' the android application.

How do I resolve a path relative to an ASP.NET MVC 4 application root?

To get the absolute path use this:

String path = HttpContext.Current.Server.MapPath("~/Data/data.html");

EDIT:

To get the Controller's Context remove .Current from the above line. By using HttpContext by itself it's easier to Test because it's based on the Controller's Context therefore more localized.

I realize now that I dislike how Server.MapPath works (internally eventually calls HostingEnvironment.MapPath) So I now recommend to always use HostingEnvironment.MapPath because its static and not dependent on the context unless of course you want that...

How to find length of a string array?

Well, in this case the car variable will be null, so dereferencing it (as you do when you access car.length) will throw a NullPointerException.

In fact, you can't access that variable at all until some value has definitely been assigned to it - otherwise the compiler will complain that "variable car might not have been initialized".

What is it you're trying to do here (it's not clear to me exactly what "solution" you're looking for)?

C++11 reverse range-based for-loop

If not using C++14, then I find below the simplest solution.

#define METHOD(NAME, ...) auto NAME __VA_ARGS__ -> decltype(m_T.r##NAME) { return m_T.r##NAME; }
template<typename T>
struct Reverse
{
  T& m_T;

  METHOD(begin());
  METHOD(end());
  METHOD(begin(), const);
  METHOD(end(), const);
};
#undef METHOD

template<typename T>
Reverse<T> MakeReverse (T& t) { return Reverse<T>{t}; }

Demo.
It doesn't work for the containers/data-types (like array), which doesn't have begin/rbegin, end/rend functions.

Adding Counter in shell script

Try this:

counter=0
while true; do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       break
  elif [[ "$counter" -gt 20 ]]; then
       echo "Counter limit reached, exit script."
       exit 1
  else
       let counter++
       echo "Sleeping for another half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

Explanation

  • break - if files are present, it will break and allow the script to process the files.
  • [[ "$counter" -gt 20 ]] - if the counter variable is greater than 20, the script will exit.
  • let counter++ - increments the counter by 1 at each pass.

Getting an element from a Set

To answer the precise question "Why doesn't Set provide an operation to get an element that equals another element?", the answer would be: because the designers of the collection framework were not very forward looking. They didn't anticipate your very legitimate use case, naively tried to "model the mathematical set abstraction" (from the javadoc) and simply forgot to add the useful get() method.

Now to the implied question "how do you get the element then": I think the best solution is to use a Map<E,E> instead of a Set<E>, to map the elements to themselves. In that way, you can efficiently retrieve an element from the "set", because the get() method of the Map will find the element using an efficient hash table or tree algorithm. If you wanted, you could write your own implementation of Set that offers the additional get() method, encapsulating the Map.

The following answers are in my opinion bad or wrong:

"You don't need to get the element, because you already have an equal object": the assertion is wrong, as you already showed in the question. Two objects that are equal still can have different state that is not relevant to the object equality. The goal is to get access to this state of the element contained in the Set, not the state of the object used as a "query".

"You have no other option but to use the iterator": that is a linear search over a collection which is totally inefficient for large sets (ironically, internally the Set is organized as hash map or tree that could be queried efficiently). Don't do it! I have seen severe performance problems in real-life systems by using that approach. In my opinion what is terrible about the missing get() method is not so much that it is a bit cumbersome to work around it, but that most programmers will use the linear search approach without thinking of the implications.

Counter increment in Bash loop not working

Instead of using a temporary file, you can avoid creating a subshell around the while loop by using process substitution.

while ...
do
   ...
done < <(grep ...)

By the way, you should be able to transform all that grep, grep, awk, awk, awk into a single awk.

Starting with Bash 4.2, there is a lastpipe option that

runs the last command of a pipeline in the current shell context. The lastpipe option has no effect if job control is enabled.

bash -c 'echo foo | while read -r s; do c=3; done; echo "$c"'

bash -c 'shopt -s lastpipe; echo foo | while read -r s; do c=3; done; echo "$c"'
3

Vim multiline editing like in sublimetext?

My solution is to use these 2 mappings:

map <leader>n <Esc><Esc>0qq
map <leader>m q:'<,'>-1normal!@q<CR><Down>

How to use them:

  1. Select your lines. If I want to select the next 12 lines I just press V12j
  2. Press <leader>n
  3. Make your changes to the line
  4. Make sure you're in normal mode and then press <leader>m

To make another edit you don't need to make the selection again. Just press <leader>n, make your edit and press <leader>m to apply.


How this works:

  • <Esc><Esc>0qq Exit the visual selection, go to the beginning of the line and start recording a macro.

  • q Stop recording the macro.

  • :'<,'>-1normal!@q<CR> From the start of the visual selection to the line before the end, play the macro on each line.

  • <Down> Go back down to the last line.


You can also just map the same key but for different modes:

vmap <leader>m <Esc><Esc>0qq
nmap <leader>m q:'<,'>-1normal!@q<CR><Down>

Although this messes up your ability to make another edit. You'll have to re-select your lines.

Typescript: Type 'string | undefined' is not assignable to type 'string'

You can now use the non-null assertion operator that is here exactly for your use case.

It tells TypeScript that even though something looks like it could be null, it can trust you that it's not:

let name1:string = person.name!; 
//                            ^ note the exclamation mark here  

Make elasticsearch only return certain fields?

A REST API GET request could be made with '_source' parameter.

Example Request

http://localhost:9200/opt_pr/_search?q=SYMBOL:ITC AND OPTION_TYPE=CE AND TRADE_DATE=2017-02-10 AND EXPIRY_DATE=2017-02-23&_source=STRIKE_PRICE

Response

{
"took": 59,
"timed_out": false,
"_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
},
"hits": {
    "total": 104,
    "max_score": 7.3908954,
    "hits": [
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLc",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 160
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLh",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 185
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLi",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 190
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLm",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 210
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLp",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 225
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLr",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 235
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLw",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 260
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uL5",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 305
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLd",
            "_score": 7.381078,
            "_source": {
                "STRIKE_PRICE": 165
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLy",
            "_score": 7.381078,
            "_source": {
                "STRIKE_PRICE": 270
            }
        }
    ]
}

}

Convert.ToDateTime: how to set format

You should probably use either DateTime.ParseExact or DateTime.TryParseExact instead. They allow you to specify specific formats. I personally prefer the Try-versions since I think they produce nicer code for the error cases.

Pure Javascript listen to input value change

Default usage

el.addEventListener('input', function () {
    fn();
});

But, if you want to fire event when you change inputs value manualy via JS you should use custom event(any name, like 'myEvent' \ 'ev' etc.) IF you need to listen forms 'change' or 'input' event and you change inputs value via JS - you can name your custom event 'change' \ 'input' and it will work too.

var event = new Event('input');
el.addEventListener('input', function () { 
  fn();
});
form.addEventListener('input', function () { 
  anotherFn();
});


el.value = 'something';
el.dispatchEvent(input);

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

JNZ & CMP Assembly Instructions

JNZ is short for "Jump if not zero (ZF = 0)", and NOT "Jump if the ZF is set".

If it's any easier to remember, consider that JNZ and JNE (jump if not equal) are equivalent. Therefore, when you're doing cmp al, 47 and the content of AL is equal to 47, the ZF is set, ergo the jump (if Not Equal - JNE) should not be taken.

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

Also worth checking is if there are any errors in the return type of your interface methods. I could reproduce this issue by having an unintended return type like Call<Call<ResponseBody>>

Concatenating variables and strings in React

the best way to concat props/variables:

var sample = "test";    
var result = `this is just a ${sample}`;    
//this is just a test

Positive Number to Negative Number in JavaScript?

var x = 100;
var negX = ( -x ); // => -100

Copy data into another table

This is the proper way to do it:

INSERT INTO destinationTable
SELECT * FROM sourceTable

Two decimal places using printf( )

Try using a format like %d.%02d

int iAmount = 10050;
printf("The number with fake decimal point is %d.%02d", iAmount/100, iAmount%100);

Another approach is to type cast it to double before printing it using %f like this:

printf("The number with fake decimal point is %0.2f", (double)(iAmount)/100);

My 2 cents :)

How to create an integer-for-loop in Ruby?

Try Below Simple Ruby Magics :)

(1..x).each { |n| puts n }
x.times { |n| puts n }
1.upto(x) { |n| print n }

True/False vs 0/1 in MySQL

If you are into performance, then it is worth using ENUM type. It will probably be faster on big tables, due to the better index performance.

The way of using it (source: http://dev.mysql.com/doc/refman/5.5/en/enum.html):

CREATE TABLE shirts (
    name VARCHAR(40),
    size ENUM('x-small', 'small', 'medium', 'large', 'x-large')
);

But, I always say that explaining the query like this:

EXPLAIN SELECT * FROM shirts WHERE size='medium';

will tell you lots of information about your query and help on building a better table structure. For this end, it is usefull to let phpmyadmin Propose a table table structure - but this is more a long time optimisation possibility, when the table is already filled with lots of data.

Rotating a Vector in 3D Space

If you want to rotate a vector you should construct what is known as a rotation matrix.

Rotation in 2D

Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are

    x' = x cos ? - y sin ?
    y' = x sin ? + y cos ?

To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider

    Unit vector along X axis = <1, 0>
    x' = 1 cos 90 - 0 sin 90 = 0
    y' = 1 sin 90 + 0 cos 90 = 1
    New coordinates of the vector, <x', y'> = <0, 1>  ?  Y-axis

When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is

    |cos ?   -sin ?| |x| = |x cos ? - y sin ?| = |x'|
    |sin ?    cos ?| |y|   |x sin ? + y cos ?|   |y'|

Rotation in 3D

That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be

    |cos ?   -sin ?   0| |x|   |x cos ? - y sin ?|   |x'|
    |sin ?    cos ?   0| |y| = |x sin ? + y cos ?| = |y'|
    |  0       0      1| |z|   |        z        |   |z'|

around the Y-axis would be

    | cos ?    0   sin ?| |x|   | x cos ? + z sin ?|   |x'|
    |   0      1       0| |y| = |         y        | = |y'|
    |-sin ?    0   cos ?| |z|   |-x sin ? + z cos ?|   |z'|

around the X-axis would be

    |1     0           0| |x|   |        x        |   |x'|
    |0   cos ?    -sin ?| |y| = |y cos ? - z sin ?| = |y'|
    |0   sin ?     cos ?| |z|   |y sin ? + z cos ?|   |z'|

Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.

Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.

I hope this clarifies basic rotation.

Rotation not Revolution

The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.

Composition

I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).

Rotation around Arbitrary Vector

A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.

How does Java resolve a relative path in new File()?

Only slightly related to the question, but try to wrap your head around this one. So un-intuitive:

import java.nio.file.*;
class Main {
  public static void main(String[] args) {
    Path p1 = Paths.get("/personal/./photos/./readme.txt");
    Path p2 = Paths.get("/personal/index.html");
    Path p3 = p1.relativize(p2);
    System.out.println(p3); //prints  ../../../../index.html  !!
  }
}

How to get the process ID to kill a nohup process?

This works in Ubuntu

Type this to find out the PID

ps aux | grep java

All the running process regarding to java will be shown

In my case is

johnjoe      3315  9.1  4.0 1465240 335728 ?      Sl   09:42   3:19 java -jar batch.jar

Now kill it kill -9 3315

The zombie process finally stopped.

OpenCV & Python - Image too big to display

In opencv, cv.namedWindow() just creates a window object as you determine, but not resizing the original image. You can use cv2.resize(img, resolution) to solve the problem.

Here's what it displays, a 740 * 411 resolution image. The original image

image = cv2.imread("740*411.jpg")
cv2.imshow("image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Here, it displays a 100 * 200 resolution image after resizing. Remember the resolution parameter use column first then is row.

Image after resizing

image = cv2.imread("740*411.jpg")
image = cv2.resize(image, (200, 100))
cv2.imshow("image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Read XLSX file in Java

I had to do this in .NET and I couldn't find any API's out there. My solution was to unzip the .xlsx, and dive right into manipulating the XML. It's not so bad once you create your helper classes and such.

There are some "gotchas" like the nodes all have to be sorted according to the way excel expects them, that I didn't find in the official docs. Excel has its own date timestamping, so you'll need to make a conversion formula.

Split string into array

You can try this way:

let entry = prompt("Enter your name") 
let entryArray = entry.split('')
console.log(entryArray)

here is fiddle https://jsfiddle.net/swapanil/Lp1arvqc/17/

Array from dictionary keys in swift

From the official Array Apple documentation:

init(_:) - Creates an array containing the elements of a sequence.

Declaration

Array.init<S>(_ s: S) where Element == S.Element, S : Sequence

Parameters

s - The sequence of elements to turn into an array.

Discussion

You can use this initializer to create an array from any other type that conforms to the Sequence protocol...You can also use this initializer to convert a complex sequence or collection type back to an array. For example, the keys property of a dictionary isn’t an array with its own storage, it’s a collection that maps its elements from the dictionary only when they’re accessed, saving the time and space needed to allocate an array. If you need to pass those keys to a method that takes an array, however, use this initializer to convert that list from its type of LazyMapCollection<Dictionary<String, Int>, Int> to a simple [String].

func cacheImagesWithNames(names: [String]) {
    // custom image loading and caching
 }

let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302,
        "Gold": 50, "Cerise": 320]
let colorNames = Array(namedHues.keys)
cacheImagesWithNames(colorNames)

print(colorNames)
// Prints "["Gold", "Cerise", "Magenta", "Vermillion"]"

Angular get object from array by Id

getDimensions(id) {
    var obj = questions.filter(function(node) {
        return node.id==id;
    });

    return obj;   
}

How to add text at the end of each line in Vim?

The substitute command can be applied to a visual selection. Make a visual block over the lines that you want to change, and type :, and notice that the command-line is initialized like this: :'<,'>. This means that the substitute command will operate on the visual selection, like so:

:'<,'>s/$/,/

And this is a substitution that should work for your example, assuming that you really want the comma at the end of each line as you've mentioned. If there are trailing spaces, then you may need to adjust the command accordingly:

:'<,'>s/\s*$/,/

This will replace any amount of whitespace preceding the end of the line with a comma, effectively removing trailing whitespace.

The same commands can operate on a range of lines, e.g. for the next 5 lines: :,+5s/$/,/, or for the entire buffer: :%s/$/,/.

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

I faced the same problem, I added android support design dependencies to the app level build.gradle

Add following:

implementation 'com.android.support:design:27.1.0'

in build.gradle. Now its working for me.

EF 5 Enable-Migrations : No context type was found in the assembly

Worked for me:

 UnInstall-Package EntityFramework 
  • Restart Visual Studio

Install-Package EntityFramework

  • Build project

Put a Delay in Javascript

Use a AJAX function which will call a php page synchronously and then in that page you can put the php usleep() function which will act as a delay.

function delay(t){

var xmlhttp;

if (window.XMLHttpRequest)

{// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}

else

{// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

xmlhttp.open("POST","http://www.hklabs.org/files/delay.php?time="+t,false);

//This will call the page named delay.php and the response will be sent to a division with ID as "response"

xmlhttp.send();

document.getElementById("response").innerHTML=xmlhttp.responseText;

}

http://www.hklabs.org/articles/put-delay-in-javascript

Return JsonResult from web api without its properties

I had a similar problem (differences being I wanted to return an object that was already converted to a json string and my controller get returns a IHttpActionResult)

Here is how I solved it. First I declared a utility class

public class RawJsonActionResult : IHttpActionResult
{
    private readonly string _jsonString;

    public RawJsonActionResult(string jsonString)
    {
        _jsonString = jsonString;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var content = new StringContent(_jsonString);
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = content };
        return Task.FromResult(response);
    }
}

This class can then be used in your controller. Here is a simple example

public IHttpActionResult Get()
{
    var jsonString = "{\"id\":1,\"name\":\"a small object\" }";
    return new RawJsonActionResult(jsonString);
}

How To Auto-Format / Indent XML/HTML in Notepad++

Not exactly a solution but a workaround.

Notepad ++ doesn't provide any such feature by default. But you can use some online tools to autoformat text like https://www.freeformatter.com/xml-formatter.html.

It helps. :)

Spring MVC - How to get all request params in a map in Spring controller?

There are two interfaces

  1. org.springframework.web.context.request.WebRequest
  2. org.springframework.web.context.request.NativeWebRequest

Allows for generic request parameter access as well as request/session attribute access, without ties to the native Servlet/Portlet API.

Ex.:

@RequestMapping(value = "/", method = GET)
public List<T> getAll(WebRequest webRequest){
    Map<String, String[]> params = webRequest.getParameterMap();
    //...
}

P.S. There are Docs about arguments which can be used as Controller params.

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

Difference between r+ and w+ in fopen()

There are 2 differences, unlike r+, w+ will:

  • create the file if it does not already exist
  • first truncate it, i.e., will delete its contents

Deploying my application at the root in Tomcat

I know that my answer is kind of overlapping with some of the other answer, but this is a complete solution that has some advantages. This works on Tomcat 8:

  1. The main application is served from the root
  2. The deployment of war files through the web interface is maintained.
  3. The main application will run on port 80 while only the admins have access to the managment folders (I realize that *nix systems require superuser for binding to 80, but on windows this is not an issue).

This means that you only have to restart the tomcat once, and after updated war files can be deployed without a problem.

Step 1: In the server.xml file, find the connector entry and replace it with:

<Connector 
    port="8080"
    protocol="HTTP/1.1"
    connectionTimeout="20000"
    redirectPort="8443" />

<Connector
    port="80"
    protocol="HTTP/1.1"
    connectionTimeout="20000"
    redirectPort="8443" />

Step 2: Define contexts within the <Host ...> tag:

<Context path="/" docBase="CAS">
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
<Context path="/ROOT" docBase="ROOT">
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
<Context path="/manager" docBase="manager" privileged="true">
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
<Context path="/host-manager" docBase="host-manager" privileged="true">
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>

Note that I addressed all apps in the webapp folder. The first effectively switch the root and the main app from position. ROOT is now on http://example.com/ROOT and the the main application is on http://example.com/. The webapps that are password protected require the privileged="true" attribute.

When you deploy a CAS.war file that matches with the root (<Context path="/" docBase="CAS"> you have to reload that one in the admin panel as it does not refresh with the deployment.

Do not include the <Context path="/CAS" docBase="CAS"> in your contexts as it disables the manager option to deploy war files. This means that you can access the app in two ways: http://example.com/ and http://example.com/APP/

Step 3: In order to prevent unwanted access to the root and manager folder, add a valve to those context tags like this:

<Context path="/manager" docBase="manager" privileged="true">
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <Valve className="org.apache.catalina.valves.RemoteAddrValve"
        addConnectorPort="true"
        allow="143\.21\.2\.\d+;8080|127\.0\.0\.1;8080|::1;8080|0:0:0:0:0:0:0:1;8080"/>
</Context>

This essentially limits access to the admin web app folder to people from my own domain (fake IP address) and localhost when they use the default port 8080 and maintains the ability to dynamically deploy the war files through the web interface.

If you want to use this for multiple apps that are using different IP addresses, you can add the IP address to the connector (address="143.21.2.1").

If you want to run multiple web apps from the root, you can duplicate the Service tag (use a different name for the second) and change the docbase of the <Context path="/" docBase="CAS"> to for example <Context path="/" docBase="ICR">.

Responsive background image in div full width

I also tried this style for ionic hybrid app background. this is also having style for background blur effect.

.bg-image {
   position: absolute;
   background: url(../img/bglogin.jpg) no-repeat;
   height: 100%;
   width: 100%;
   background-size: cover;
   bottom: 0px;
   margin: 0 auto;
   background-position: 50%;


  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);

}

Swift Open Link in Safari

since iOS 10 you should use:

guard let url = URL(string: linkUrlString) else {
    return
}
    
if #available(iOS 10.0, *) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
    UIApplication.shared.openURL(url)
}

Check if a row exists, otherwise insert

INSERT INTO table ( column1, column2, column3 )
SELECT $column1, $column2, $column3
EXCEPT SELECT column1, column2, column3
FROM table

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

I was also facing same issue but able to fix it by putting async: true. I know it is by default true but it works when I write it explicitly

$.ajax({
   async: true,   // this will solve the problem
   type: "POST",
   url: "/Page/Method",
   contentType: "application/json",
   data: JSON.stringify({ ParameterName: paramValue }),
});

html select option separator

I elected to conditionally alternate color and background. Setting a sort order and with vue.js, I did something like this:

<style>
    .altgroup_1 {background:gray; color:white;}
    .altgroup_2{background:white; color:black;}
</style>

<option :class = {
    'altgroup_1': (country.sort_order > 25),
    'altgroup_2': (country.sort_order > 50 }"
    value="{{ country.iso_short }}">
    {{ country.short_name }}
</option

Declare a variable as Decimal

You can't declare a variable as Decimal - you have to use Variant (you can use CDec to populate it with a Decimal type though).

How do I get the position selected in a RecyclerView?

No need to have your ViewHolder implementing View.OnClickListener. You can get directly the clicked position by setting a click listener in the method onCreateViewHolder of RecyclerView.Adapter here is a sample of code :

public class ItemListAdapterRecycler extends RecyclerView.Adapter<ItemViewHolder>
{

    private final List<Item> items;

    public ItemListAdapterRecycler(List<Item> items)
    {
        this.items = items;
    }

    @Override
    public ItemViewHolder onCreateViewHolder(final ViewGroup parent, int viewType)
    {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false);

        view.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                int currentPosition = getClickedPosition(view);
                Log.d("DEBUG", "" + currentPosition);
            }
        });

        return new ItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ItemViewHolder itemViewHolder, int position)
    {
        ...
    }

    @Override
    public int getItemCount()
    {
        return items.size();
    }

    private int getClickedPosition(View clickedView)
    {
        RecyclerView recyclerView = (RecyclerView) clickedView.getParent();
        ItemViewHolder currentViewHolder = (ItemViewHolder) recyclerView.getChildViewHolder(clickedView);
        return currentViewHolder.getAdapterPosition();
    }

}

Kill process by name?

Get the process object using the Process.

>>> import psutil
>>> p = psutil.Process(23442)
>>> p
psutil.Process(pid=23442, name='python3.6', started='09:24:16')
>>> p.kill()
>>> 

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

I faced the same problem. I restarted the oracle service for that DB instance and the error is gone.

Hive ParseException - cannot recognize input near 'end' 'string'

I was using /Date=20161003 in the folder path while doing an insert overwrite and it was failing. I changed it to /Dt=20161003 and it worked

How to check cordova android version of a cordova/phonegap project?

After upgrading the Application. I observed different Cordova versions.

  1. Apache Cordova Cli version which is 6.0.0.
  2. Cordova Android version which is 5.1.0.
  3. Cordova IOS version which is 4.1.1.
  4. Docs version is which is 6.0.0, shown on the Cordova Docs website.

Now i am confused, On which version basis, Google Dev Console is giving warning?

Please migrate your app(s) to Apache Cordova v.4.1.1 or higher as soon as possible and increment the version number of the upgraded APK. Beginning May 9, 2016, Google Play will block publishing of any new apps or updates that use pre-4.1.1 versions of Apache Cordova.

The vulnerabilities were addressed in Apache Cordova 4.1.1. If you’re using a 3rd party library that bundles Apache Cordova, you’ll need to upgrade it to a version that bundles Apache Cordova 4.1.1 or later.

And before upgrading. Our Application versions were these.

  1. Apache Cordova Cli version which is 5.4.1.
  2. Cordova Android version which is 4.1.1.
  3. Cordova IOS version which is 3.9.1.
  4. Docs version is which is 5.4.1, shown on the Cordova Docs website.

How to remove item from a python list in a loop?

This stems from the fact that on deletion, the iteration skips one element as it semms only to work on the index.

Workaround could be:

x = ["ok", "jj", "uy", "poooo", "fren"]
for item in x[:]: # make a copy of x
    if len(item) != 2:
        print "length of %s is: %s" %(item, len(item))
        x.remove(item)

How to Call Controller Actions using JQuery in ASP.NET MVC

We can call Controller method using Javascript / Jquery very easily as follows:

Suppose following is the Controller method to be called returning an array of some class objects. Let the class is 'A'

public JsonResult SubMenu_Click(string param1, string param2)

    {
       A[] arr = null;
        try
        {
            Processing...
           Get Result and fill arr.

        }
        catch { }


        return Json(arr , JsonRequestBehavior.AllowGet);

    }

Following is the complex type (class)

 public class A
 {

  public string property1 {get ; set ;}

  public string property2 {get ; set ;}

 }

Now it was turn to call above controller method by JQUERY. Following is the Jquery function to call the controller method.

function callControllerMethod(value1 , value2) {
    var strMethodUrl = '@Url.Action("SubMenu_Click", "Home")?param1=value1 &param2=value2'
    $.getJSON(strMethodUrl, receieveResponse);
}


function receieveResponse(response) {

    if (response != null) {
        for (var i = 0; i < response.length; i++) {
           alert(response[i].property1);
        }
    }
}

In the above Jquery function 'callControllerMethod' we develop controller method url and put that in a variable named 'strMehodUrl' and call getJSON method of Jquery API.

receieveResponse is the callback function receiving the response or return value of the controllers method.

Here we made use of JSON , since we can't make use of the C# class object

directly into the javascript function , so we converted the result (arr) in controller method into JSON object as follows:

Json(arr , JsonRequestBehavior.AllowGet);

and returned that Json object.

Now in callback function of the Javascript / JQuery we can make use of this resultant JSON object and work accordingly to show response data on UI.

For more detaill click here

Read large files in Java

First, if your file contains binary data, then using BufferedReader would be a big mistake (because you would be converting the data to String, which is unnecessary and could easily corrupt the data); you should use a BufferedInputStream instead. If it's text data and you need to split it along linebreaks, then using BufferedReader is OK (assuming the file contains lines of a sensible length).

Regarding memory, there shouldn't be any problem if you use a decently sized buffer (I'd use at least 1MB to make sure the HD is doing mostly sequential reading and writing).

If speed turns out to be a problem, you could have a look at the java.nio packages - those are supposedly faster than java.io,

json_decode() expects parameter 1 to be string, array given

json_decode() is used to decode a json string to an array/data object. json_encode() creates a json string from an array or data. You are using the wrong function my friend, try json_encode();

How do I trim leading/trailing whitespace in a standard way?

#include "stdafx.h"
#include "malloc.h"
#include "string.h"

int main(int argc, char* argv[])
{

  char *ptr = (char*)malloc(sizeof(char)*30);
  strcpy(ptr,"            Hel  lo    wo           rl   d G    eo rocks!!!    by shahil    sucks b i          g       tim           e");

  int i = 0, j = 0;

  while(ptr[j]!='\0')
  {

      if(ptr[j] == ' ' )
      {
          j++;
          ptr[i] = ptr[j];
      }
      else
      {
          i++;
          j++;
          ptr[i] = ptr[j];
      }
  }


  printf("\noutput-%s\n",ptr);
        return 0;
}

React : difference between <Route exact path="/" /> and <Route path="/" />

In this example, nothing really. The exact param comes into play when you have multiple paths that have similar names:

For example, imagine we had a Users component that displayed a list of users. We also have a CreateUser component that is used to create users. The url for CreateUsers should be nested under Users. So our setup could look something like this:

<Switch>
  <Route path="/users" component={Users} />
  <Route path="/users/create" component={CreateUser} />
</Switch>

Now the problem here, when we go to http://app.com/users the router will go through all of our defined routes and return the FIRST match it finds. So in this case, it would find the Users route first and then return it. All good.

But, if we went to http://app.com/users/create, it would again go through all of our defined routes and return the FIRST match it finds. React router does partial matching, so /users partially matches /users/create, so it would incorrectly return the Users route again!

The exact param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url.

So in this case, we should add exact to our Users route so that it will only match on /users:

<Switch>
  <Route exact path="/users" component={Users} />
  <Route path="/users/create" component={CreateUser} />
</Switch>

The docs explain exact in detail and give other examples.

find without recursion

If you look for POSIX compliant solution:

cd DirsRoot && find . -type f -print -o -name . -o -prune

-maxdepth is not POSIX compliant option.

Using WGET to run a cronjob PHP

you can just use this code to hit the script using cron job using cpanel:

wget https://www.example.co.uk/unique-code

Index inside map() function

You will be able to get the current iteration's index for the map method through its 2nd parameter.

Example:

const list = [ 'h', 'e', 'l', 'l', 'o'];
list.map((currElement, index) => {
  console.log("The current iteration is: " + index);
  console.log("The current element is: " + currElement);
  console.log("\n");
  return currElement; //equivalent to list[index]
});

Output:

The current iteration is: 0 <br>The current element is: h

The current iteration is: 1 <br>The current element is: e

The current iteration is: 2 <br>The current element is: l

The current iteration is: 3 <br>The current element is: l 

The current iteration is: 4 <br>The current element is: o

See also: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Parameters

callback - Function that produces an element of the new Array, taking three arguments:

1) currentValue
The current element being processed in the array.

2) index
The index of the current element being processed in the array.

3) array
The array map was called upon.

Define static method in source-file with declaration in header-file in C++

Static member functions must refer to static variables of that class. So in your case,

static void CP_StringToPString( std::string& inString, unsigned char *outString);

Since your member function CP_StringToPstring is static, the parameters in that function, inString and outString should be declared as static too.

The static member functions does not refer to the object that it is working on but the variables your declared refers to its current object so it return error.

You could either remove the static from the member function or add static while declaring the parameters you used for the member function as static too.

Swift how to sort array of custom objects by property value

With Swift 5, Array has two methods called sorted() and sorted(by:). The first method, sorted(), has the following declaration:

Returns the elements of the collection, sorted.

func sorted() -> [Element]

The second method, sorted(by:), has the following declaration:

Returns the elements of the collection, sorted using the given predicate as the comparison between elements.

func sorted(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> [Element]

#1. Sort with ascending order for comparable objects

If the element type inside your collection conforms to Comparable protocol, you will be able to use sorted() in order to sort your elements with ascending order. The following Playground code shows how to use sorted():

class ImageFile: CustomStringConvertible, Comparable {

    let fileName: String
    let fileID: Int
    var description: String { return "ImageFile with ID: \(fileID)" }

    init(fileName: String, fileID: Int) {
        self.fileName = fileName
        self.fileID = fileID
    }

    static func ==(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID == rhs.fileID
    }

    static func <(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID < rhs.fileID
    }

}

let images = [
    ImageFile(fileName: "Car", fileID: 300),
    ImageFile(fileName: "Boat", fileID: 100),
    ImageFile(fileName: "Plane", fileID: 200)
]

let sortedImages = images.sorted()
print(sortedImages)

/*
 prints: [ImageFile with ID: 100, ImageFile with ID: 200, ImageFile with ID: 300]
 */

#2. Sort with descending order for comparable objects

If the element type inside your collection conforms to Comparable protocol, you will have to use sorted(by:) in order to sort your elements with a descending order.

class ImageFile: CustomStringConvertible, Comparable {

    let fileName: String
    let fileID: Int
    var description: String { return "ImageFile with ID: \(fileID)" }

    init(fileName: String, fileID: Int) {
        self.fileName = fileName
        self.fileID = fileID
    }

    static func ==(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID == rhs.fileID
    }

    static func <(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID < rhs.fileID
    }

}

let images = [
    ImageFile(fileName: "Car", fileID: 300),
    ImageFile(fileName: "Boat", fileID: 100),
    ImageFile(fileName: "Plane", fileID: 200)
]

let sortedImages = images.sorted(by: { (img0: ImageFile, img1: ImageFile) -> Bool in
    return img0 > img1
})
//let sortedImages = images.sorted(by: >) // also works
//let sortedImages = images.sorted { $0 > $1 } // also works
print(sortedImages)

/*
 prints: [ImageFile with ID: 300, ImageFile with ID: 200, ImageFile with ID: 100]
 */

#3. Sort with ascending or descending order for non-comparable objects

If the element type inside your collection DOES NOT conform to Comparable protocol, you will have to use sorted(by:) in order to sort your elements with ascending or descending order.

class ImageFile: CustomStringConvertible {

    let fileName: String
    let fileID: Int
    var description: String { return "ImageFile with ID: \(fileID)" }

    init(fileName: String, fileID: Int) {
        self.fileName = fileName
        self.fileID = fileID
    }

}

let images = [
    ImageFile(fileName: "Car", fileID: 300),
    ImageFile(fileName: "Boat", fileID: 100),
    ImageFile(fileName: "Plane", fileID: 200)
]

let sortedImages = images.sorted(by: { (img0: ImageFile, img1: ImageFile) -> Bool in
    return img0.fileID < img1.fileID
})
//let sortedImages = images.sorted { $0.fileID < $1.fileID } // also works
print(sortedImages)

/*
 prints: [ImageFile with ID: 300, ImageFile with ID: 200, ImageFile with ID: 100]
 */

Note that Swift also provides two methods called sort() and sort(by:) as counterparts of sorted() and sorted(by:) if you need to sort your collection in-place.

What is the functionality of setSoTimeout and how it works?

The JavaDoc explains it very well:

With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.

SO_TIMEOUT is the timeout that a read() call will block. If the timeout is reached, a java.net.SocketTimeoutException will be thrown. If you want to block forever put this option to zero (the default value), then the read() call will block until at least 1 byte could be read.

Conda command is not recognized on Windows 10

Even I got the same problem when I've first installed Anaconda. It said 'conda' command not found.

So I've just setup two values[added two new paths of Anaconda] system environment variables in the PATH variable which are: C:\Users\mshas\Anaconda2\ & C:\Users\mshas\Anaconda2\Scripts

Lot of people forgot to add the second variable which is "Scripts" just add that then 'conda' command works.

Docker container not starting (docker start)

What I need is to use Docker with MariaDb on different port /3301/ on my Ubuntu machine because I already had MySql installed and running on 3306.

To do this after half day searching did it using:

docker run -it -d -p 3301:3306 -v ~/mdbdata/mariaDb:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root --name mariaDb mariadb

This pulls the image with latest MariaDb, creates container called mariaDb, and run mysql on port 3301. All data of which is located in home directory in /mdbdata/mariaDb.

To login in mysql after that can use:

mysql -u root -proot -h 127.0.0.1 -P3301

Used sources are:

The answer of Iarks in this article /using -it -d was the key :) /

how-to-install-and-use-docker-on-ubuntu-16-04

installing-and-using-mariadb-via-docker

mariadb-and-docker-use-cases-part-1

Good luck all!

List names of all tables in a SQL Server 2012 schema

SELECT t1.name AS [Schema], t2.name AS [Table]
FROM sys.schemas t1
INNER JOIN sys.tables t2
ON t2.schema_id = t1.schema_id
ORDER BY t1.name,t2.name

What is stability in sorting algorithms and why is it important?

Stable sort will always return same solution (permutation) on same input.

For instance [2,1,2] will be sorted using stable sort as permutation [2,1,3] (first is index 2, then index 1 then index 3 in sorted output) That mean that output is always shuffled same way. Other non stable, but still correct permutation is [2,3,1].

Quick sort is not stable sort and permutation differences among same elements depends on algorithm for picking pivot. Some implementations pick up at random and that can make quick sort yielding different permutations on same input using same algorithm.

Stable sort algorithm is necessary deterministic.

Static Vs. Dynamic Binding in Java

There are three major differences between static and dynamic binding while designing the compilers and how variables and procedures are transferred to the runtime environment. These differences are as follows:

Static Binding: In static binding three following problems are discussed:

  • Definition of a procedure

  • Declaration of a name(variable, etc.)

  • Scope of the declaration

Dynamic Binding: Three problems that come across in the dynamic binding are as following:

  • Activation of a procedure

  • Binding of a name

  • Lifetime of a binding

Https to http redirect using htaccess

However, if your website does not have a security certificate, it's on a shared hosting environment, and you don't want to get the "warning" when your website is being requested through https, you can't redirect it using htaccess. The reason is that the warning message gets triggered before the request even goes through to the htaccess file, so you have to fix it on the server. Go to /etc/httpd/conf.d/ssl.conf and comment out the part about the virtual server 443. But the odds are that your hosting provider won't give you that much control. So you would have to either move to a different host or buy the SSL just so the warning does not trigger before your htaccess has a chance to redirect.

Can you style an html radio button to look like a checkbox?

appearance property doesn't work in all browser. You can do like the following-

_x000D_
_x000D_
input[type="radio"]{_x000D_
  display: none;_x000D_
}_x000D_
label:before{_x000D_
  content:url(http://strawberrycambodia.com/book/admin/templates/default/images/icons/16x16/checkbox.gif);_x000D_
}_x000D_
input[type="radio"]:checked+label:before{_x000D_
  content:url(http://www.treatment-abroad.ru/img/admin/icons/16x16/checkbox.gif);_x000D_
}
_x000D_
 _x000D_
  <input type="radio" name="gender" id="test1" value="male">_x000D_
  <label for="test1"> check 1</label>_x000D_
  <input type="radio" name="gender" value="female" id="test2">_x000D_
  <label for="test2"> check 2</label>_x000D_
  <input type="radio" name="gender" value="other" id="test3">_x000D_
  <label for="test3"> check 3</label>  
_x000D_
_x000D_
_x000D_

It works IE 8+ and other browsers

Disable Buttons in jQuery Mobile

I created a widget that can completely disable or present a read-only view of the content on your page. It disables all buttons, anchors, removes all click events, etc., and can re-enable them all back again. It even supports all jQuery UI widgets as well. I created it for an application I wrote at work. You're free to use it.

Check it out at ( http://www.dougestep.com/dme/jquery-disabler-widget ).

Swift - How to convert String to Double

I haven't seen the answer I was looking for. I just post in here mine in case it can help anyone. This answer is valid only if you don't need a specific format.

Swift 3

extension String {
    var toDouble: Double {
        return Double(self) ?? 0.0
    }
}

How to hide column of DataGridView when using custom DataSource?

I had the same problem

Here is the Solution that might work for you. It worked for me

    GridView1.DataBind();
if (GridView1.Columns.Count > 0)
    GridView1.Columns[0].Visible = false;
else
{
    GridView1.HeaderRow.Cells[0].Visible = false;
    foreach (GridViewRow gvr in GridView1.Rows)
    {
        gvr.Cells[0].Visible = false;
    }
}

Disable sorting for a particular column in jQuery DataTables

You can directry use .notsortable() method on column

 vm.dtOpt_product = DTOptionsBuilder.newOptions()
                .withOption('responsive', true)
        vm.dtOpt_product.withPaginationType('full_numbers');
        vm.dtOpt_product.withColumnFilter({
            aoColumns: [{
                    type: 'null'
                }, {
                    type: 'text',
                    bRegex: true,
                    bSmart: true
                }, {
                    type: 'text',
                    bRegex: true,
                    bSmart: true
                }, {
                    type: 'text',
                    bRegex: true,
                    bSmart: true
                }, {
                    type: 'select',
                    bRegex: false,
                    bSmart: true,
                    values: vm.dtProductTypes
                }]

        });

        vm.dtColDefs_product = [
            DTColumnDefBuilder.newColumnDef(0), DTColumnDefBuilder.newColumnDef(1),
            DTColumnDefBuilder.newColumnDef(2), DTColumnDefBuilder.newColumnDef(3).withClass('none'),
            DTColumnDefBuilder.newColumnDef(4), DTColumnDefBuilder.newColumnDef(5).notSortable()
        ];

How can I add NSAppTransportSecurity to my info.plist file?

try With this --- worked for me in Xcode-beta 4 7.0

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>yourdomain.com</key>
        <dict>
            <!--Include to allow subdomains-->
            <key>NSIncludesSubdomains</key>
            <true/>
            <!--Include to allow HTTP requests-->
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <!--Include to specify minimum TLS version-->
            <key>NSTemporaryExceptionMinimumTLSVersion</key>
            <string>TLSv1.1</string>
        </dict>
    </dict>
</dict>

Also one more option, if you want to disable ATS you can use this :

<key>NSAppTransportSecurity</key>  
 <dict>  
      <key>NSAllowsArbitraryLoads</key><true/>  
 </dict>

But this is not recommended at all. The server should have the SSL certificates and so that there is no privacy leaks.

print arraylist element?

If you want to print an arraylist with integer numbers, as an example you can use below code.

class Test{
    public static void main(String[] args){
        ArrayList<Integer> arraylist = new ArrayList<Integer>();

        for(int i=0; i<=10; i++){
            arraylist .add(i);
        }
       for (Integer n : arraylist ){
            System.out.println(n);
       }
   }
}

The output is above code:

0
1
2
3
4
5
6
7
8
9
10

How to increase the max upload file size in ASP.NET?

For IIS 7+, as well as adding the httpRuntime maxRequestLength setting you also need to add:

  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="52428800" /> <!--50MB-->
      </requestFiltering>
    </security>
  </system.webServer>

Or in IIS (7):

  • Select the website you want enable to accept large file uploads.
  • In the main window double click 'Request filtering'
  • Select "Edit Feature Settings"
  • Modify the "Maximum allowed content length (bytes)"

Converting a String to DateTime

DateTime.Parse

Syntax:

DateTime.Parse(String value)
DateTime.Parse(String value, IFormatProvider provider)
DateTime.Parse(String value, IFormatProvider provider, DateTypeStyles styles)

Example:

string value = "1 January 2019";
CultureInfo provider = new CultureInfo("en-GB");
DateTime.Parse(value, provider, DateTimeStyles.NoCurrentDateDefault););
  • Value: string representation of date and time.
  • Provider: object which provides culture specific info.
  • Styles: formatting options that customize string parsing for some date and time parsing methods. For instance, AllowWhiteSpaces is a value which helps to ignore all spaces present in string while it parse.

It's also worth remembering DateTime is an object that is stored as number internally in the framework, Format only applies to it when you convert it back to string.

  • Parsing converting a string to the internal number type.

  • Formatting converting the internal numeric value to a readable string.

I recently had an issue where I was trying to convert a DateTime to pass to Linq what I hadn't realised at the time was format is irrelevant when passing DateTime to a Linq Query.

DateTime SearchDate = DateTime.Parse(searchDate);
applicationsUsages = applicationsUsages.Where(x => DbFunctions.TruncateTime(x.dateApplicationSelected) == SearchDate.Date);

Full DateTime Documentation

iOS: Modal ViewController with transparent background

Of course you should set UIModalPresentationCurrentContext, but the place to set clearColor is very important too! You can't set background in viewDidLoad function, set it before the view did load like in the root view controller or in the init function of the controller that going to present!

actionController.view.backgroundColor = [UIColor clearColor];
[self presentViewController:actionController animated:YES completion:nil];

or

- (instancetype)init {

    self = [super initWithNibName:nil bundle:nil];

    if(self) {
        self.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        [self.view setBackgroundColor:[UIColor clearColor]];
    }

    return self;
}

The "backspace" escape character '\b': unexpected behavior?

Your result will vary depending on what kind of terminal or console program you're on, but yes, on most \b is a nondestructive backspace. It moves the cursor backward, but doesn't erase what's there.

So for the hello worl part, the code outputs

hello worl
          ^

...(where ^ shows where the cursor is) Then it outputs two \b characters which moves the cursor backward two places without erasing (on your terminal):

hello worl
        ^

Note the cursor is now on the r. Then it outputs d, which overwrites the r and gives us:

hello wodl
         ^

Finally, it outputs \n, which is a non-destructive newline (again, on most terminals, including apparently yours), so the l is left unchanged and the cursor is moved to the beginning of the next line.

Instagram API - How can I retrieve the list of people a user is following on Instagram

The REST API of Instagram has been discontinued. But you can use GraphQL to get the desired data. Here you can find an overview: https://developers.facebook.com/docs/instagram-api

disable Bootstrap's Collapse open/close animation

Maybe not a direct answer to the question, but a recent addition to the official documentation describes how jQuery can be used to disable transitions entirely just by:

$.support.transition = false

Setting the .collapsing CSS transitions to none as mentioned in the accepted answer removed the animation. But this — in Firefox and Chromium for me — creates an unwanted visual issue on collapse of the navbar.

For instance, visit the Bootstrap navbar example and add the CSS from the accepted answer:

.collapsing {
     -webkit-transition: none;
     transition: none;
}

What I currently see is when the navbar collapses, the bottom border of the navbar momentarily becomes two pixels instead of one, then disconcertingly jumps back to one. Using jQuery, this artifact doesn't appear.

How can I troubleshoot Python "Could not find platform independent libraries <prefix>"

My pycharm ce had the same error, was easy to fix it, if someone has that error, just uninstall and delete the folder, use ctrl+h if you can't find the folder in your documents, install the software again and should work again.

Remember to save the scratches folder before erasing the pycharm folder.

How to continue a Docker container which has exited

If you want to do it in multiple, easy-to-remember commands:

  1. list stopped containers:

docker ps -a

  1. copy the name or the container id of the container you want to attach to, and start the container with:

docker start -i <name/id>

The -i flag tells docker to attach to the container's stdin.

If the container wasn't started with an interactive shell to connect to, you need to do this to run a shell:

docker start <name/id>
docker exec -it <name/id> /bin/sh

The /bin/sh is the shell usually available with alpine-based images.

Reset identity seed after deleting records in SQL Server

It should be noted that IF all of the data is being removed from the table via the DELETE (i.e. no WHERE clause), then as long as a) permissions allow for it, and b) there are no FKs referencing the table (which appears to be the case here), using TRUNCATE TABLE would be preferred as it does a more efficient DELETE and resets the IDENTITY seed at the same time. The following details are taken from the MSDN page for TRUNCATE TABLE:

Compared to the DELETE statement, TRUNCATE TABLE has the following advantages:

  • Less transaction log space is used.

    The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction log.

  • Fewer locks are typically used.

    When the DELETE statement is executed using a row lock, each row in the table is locked for deletion. TRUNCATE TABLE always locks the table (including a schema (SCH-M) lock) and page but not each row.

  • Without exception, zero pages are left in the table.

    After a DELETE statement is executed, the table can still contain empty pages. For example, empty pages in a heap cannot be deallocated without at least an exclusive (LCK_M_X) table lock. If the delete operation does not use a table lock, the table (heap) will contain many empty pages. For indexes, the delete operation can leave empty pages behind, although these pages will be deallocated quickly by a background cleanup process.

If the table contains an identity column, the counter for that column is reset to the seed value defined for the column. If no seed was defined, the default value 1 is used. To retain the identity counter, use DELETE instead.

So the following:

DELETE FROM [MyTable];
DBCC CHECKIDENT ('[MyTable]', RESEED, 0);

Becomes just:

TRUNCATE TABLE [MyTable];

Please see the TRUNCATE TABLE documentation (linked above) for additional information on restrictions, etc.

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

I finally re-found the jupyter/IPython documentation that I was looking for.

I needed this:

from IPython.display import HTML, display

data = [[1,2,3],
        [4,5,6],
        [7,8,9],
        ]

display(HTML(
   '<table><tr>{}</tr></table>'.format(
       '</tr><tr>'.join(
           '<td>{}</td>'.format('</td><td>'.join(str(_) for _ in row)) for row in data)
       )
))

(I may have slightly mucked up the comprehensions, but display(HTML('some html here')) is what we needed)

Rails get index of "each" loop

The two answers are good. And I also suggest you a similar method:

<% @images.each.with_index do |page, index| %>
<% end %>

You might not see the difference between this and the accepted answer. Let me direct your eyes to these method calls: .each.with_index see how it's .each and then .with_index.

How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?

Copy the diff file to the root of your repository, and then do:

git apply yourcoworkers.diff

More information about the apply command is available on its man page.

By the way: A better way to exchange whole commits by file is the combination of the commands git format-patch on the sender and then git am on the receiver, because it also transfers the authorship info and the commit message.

If the patch application fails and if the commits the diff was generated from are actually in your repo, you can use the -3 option of apply that tries to merge in the changes.

It also works with Unix pipe as follows:

git diff d892531 815a3b5 | git apply

How to detect incoming calls, in an Android device?

@Gabe Sechan, thanks for your code. It works fine except the onOutgoingCallEnded(). It is never executed. Testing phones are Samsung S5 & Trendy. There are 2 bugs I think.

1: a pair of brackets is missing.

case TelephonyManager.CALL_STATE_IDLE: 
    // Went to idle-  this is the end of a call.  What type depends on previous state(s)
    if (lastState == TelephonyManager.CALL_STATE_RINGING) {
        // Ring but no pickup-  a miss
        onMissedCall(context, savedNumber, callStartTime);
    } else {
        // this one is missing
        if(isIncoming){
            onIncomingCallEnded(context, savedNumber, callStartTime, new Date());                       
        } else {
            onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());                                               
        }
    }
    // this one is missing
    break;

2: lastState is not updated by the state if it is at the end of the function. It should be replaced to the first line of this function by

public void onCallStateChanged(Context context, int state, String number) {
    int lastStateTemp = lastState;
    lastState = state;
    // todo replace all the "lastState" by lastStateTemp from here.
    if (lastStateTemp  == state) {
        //No change, debounce extras
        return;
    }
    //....
}

Additional I've put lastState and savedNumber into shared preference as you suggested.

Just tested it with above changes. Bug fixed at least on my phones.

Laravel update model with unique validation rule for attribute

I have BaseModel class, so I needed something more generic.

//app/BaseModel.php
public function rules()
{
    return $rules = [];
}
public function isValid($id = '')
{

    $validation = Validator::make($this->attributes, $this->rules($id));

    if($validation->passes()) return true;
    $this->errors = $validation->messages();
    return false;
}

In user class let's suppose I need only email and name to be validated:

//app/User.php
//User extends BaseModel
public function rules($id = '')
{
    $rules = [
                'name' => 'required|min:3',
                'email' => 'required|email|unique:users,email',
                'password' => 'required|alpha_num|between:6,12',
                'password_confirmation' => 'same:password|required|alpha_num|between:6,12',
            ];
    if(!empty($id))
    {
        $rules['email'].= ",$id";
        unset($rules['password']);
        unset($rules['password_confirmation']);
    }

    return $rules;
}

I tested this with phpunit and works fine.

//tests/models/UserTest.php 
public function testUpdateExistingUser()
{
    $user = User::find(1);
    $result = $user->id;
    $this->assertEquals(true, $result);
    $user->name = 'test update';
    $user->email = '[email protected]';
    $user->save();

    $this->assertTrue($user->isValid($user->id), 'Expected to pass');

}

I hope will help someone, even if for getting a better idea. Thanks for sharing yours as well. (tested on Laravel 5.0)

How do I remove version tracking from a project cloned from git?

All the data Git uses for information is stored in .git/, so removing it should work just fine. Of course, make sure that your working copy is in the exact state that you want it, because everything else will be lost. .git folder is hidden so make sure you turn on the Show hidden files, folders and disks option.

From there, you can run git init to create a fresh repository.

Make WPF Application Fullscreen (Cover startmenu)

When you're doing it by code the trick is to call

WindowStyle = WindowStyle.None;

first and then

WindowState = WindowState.Maximized;

to get it to display over the Taskbar.

How to embed HTML into IPython output?

Related: While constructing a class, def _repr_html_(self): ... can be used to create a custom HTML representation of its instances:

class Foo:
    def _repr_html_(self):
        return "Hello <b>World</b>!"

o = Foo()
o

will render as:

Hello World!

For more info refer to IPython's docs.

An advanced example:

from html import escape # Python 3 only :-)

class Todo:
    def __init__(self):
        self.items = []

    def add(self, text, completed):
        self.items.append({'text': text, 'completed': completed})

    def _repr_html_(self):
        return "<ol>{}</ol>".format("".join("<li>{} {}</li>".format(
            "?" if item['completed'] else "?",
            escape(item['text'])
        ) for item in self.items))

my_todo = Todo()
my_todo.add("Buy milk", False)
my_todo.add("Do homework", False)
my_todo.add("Play video games", True)

my_todo

Will render:

  1. ? Buy milk
  2. ? Do homework
  3. ? Play video games

Show current assembly instruction in GDB

GDB Dashboard

https://github.com/cyrus-and/gdb-dashboard

This GDB configuration uses the official GDB Python API to show us whatever we want whenever GDB stops after for example next, much like TUI.

However I have found that this implementation is a more robust and configurable alternative to the built-in GDB TUI mode as explained at: gdb split view with code

For example, we can configure GDB Dashboard to show disassembly, source, registers and stack with:

dashboard -layout source assembly registers stack

Here is what it looks like if you enable all available views instead:

enter image description here

Related questions:

Expression must have class type

Summary: Instead of a.f(); it should be a->f();

In main you have defined a as a pointer to object of A, so you can access functions using the -> operator.

An alternate, but less readable way is (*a).f()

a.f() could have been used to access f(), if a was declared as: A a;

CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

Centering both horizontally and vertically

Actually, having the height and width in percents makes centering it even easier. You just offset the left and top by half of the area not occupied by the div.

So if you height is 40%, 100% - 40% = 60%. So you want 30% above and below. Then top: 30% does the trick.

See the example here: http://dabblet.com/gist/5957545

Centering only horizontally

Use inline-block. The other answer here will not work for IE 8 and below, however. You must use a CSS hack or conditional styles for that. Here is the hack version:

See the example here: http://dabblet.com/gist/5957591

.inlineblock { 
    display: inline-block;
    zoom: 1;
    display*: inline; /* ie hack */
}

EDIT

By using media queries you can combine two techniques to achive the effect you want. The only complication is height. You use a nested div to switch between % width and

http://dabblet.com/gist/5957676

@media (max-width: 1000px) {
    .center{}
    .center-inner{left:25%;top:25%;position:absolute;width:50%;height:300px;background:#f0f;text-align:center;max-width:500px;max-height:500px;}
}
@media (min-width: 1000px) {
    .center{left:50%;top:25%;position:absolute;}
    .center-inner{width:500px;height:100%;margin-left:-250px;height:300px;background:#f0f;text-align:center;max-width:500px;max-height:500px;}
}

Rails 4 - Strong Parameters - Nested Objects

I found this suggestion useful in my case:

  def product_params
    params.require(:product).permit(:name).tap do |whitelisted|
      whitelisted[:data] = params[:product][:data]
    end
  end

Check this link of Xavier's comment on github.

This approach whitelists the entire params[:measurement][:groundtruth] object.

Using the original questions attributes:

  def product_params
    params.require(:measurement).permit(:name, :groundtruth).tap do |whitelisted|
      whitelisted[:groundtruth] = params[:measurement][:groundtruth]
    end
  end

React JS onClick event handler

_x000D_
_x000D_
class FrontendSkillList extends React.Component {_x000D_
  constructor() {_x000D_
    super();_x000D_
    this.state = { selectedSkill: {} };_x000D_
  }_x000D_
  render() {_x000D_
    return (_x000D_
      <ul>_x000D_
        {this.props.skills.map((skill, i) => (_x000D_
            <li_x000D_
              className={_x000D_
                this.state.selectedSkill.id === skill.id ? "selected" : ""_x000D_
              }_x000D_
              onClick={this.selectSkill.bind(this, skill)}_x000D_
              style={{ cursor: "pointer" }}_x000D_
              key={skill.id}_x000D_
            >_x000D_
            {skill.name}_x000D_
            </li>_x000D_
        ))}_x000D_
      </ul>_x000D_
    );_x000D_
  }_x000D_
_x000D_
  selectSkill(selected) {_x000D_
    if (selected.id !== this.state.selectedSkill.id) {_x000D_
      this.setState({ selectedSkill: selected });_x000D_
    } else {_x000D_
      this.setState({ selectedSkill: {} });_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
const data = [_x000D_
  { id: "1", name: "HTML5" },_x000D_
  { id: "2", name: "CSS3" },_x000D_
  { id: "3", name: "ES6 & ES7" }_x000D_
];_x000D_
const element = (_x000D_
  <div>_x000D_
    <h1>Frontend Skill List</h1>_x000D_
    <FrontendSkillList skills={data} />_x000D_
  </div>_x000D_
);_x000D_
ReactDOM.render(element, document.getElementById("root"));
_x000D_
.selected {_x000D_
  background-color: rgba(217, 83, 79, 0.8);_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

@user544079 Hope this demo can help :) I recommend changing background color by toggling classname.

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

My Mac OS didn't like that it didn't find the env variable set in the settings file:

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('MY_SERVER_ENV_VAR_NAME')

but after adding the env var to my local Mac OS dev environment, the error disappeared:

export MY_SERVER_ENV_VAR_NAME ='fake dev security key that is longer than 50 characters.'

In my case, I also needed to add the --settings param:

python3 manage.py check --deploy --settings myappname.settings.production

where production.py is a file containing production specific settings inside a settings folder.

Defining a `required` field in Bootstrap

To make a field required, use required or required="true"

I think required="required" has been deprecated in version 3 of bootstrap.

Pure JavaScript: a function like jQuery's isNumeric()

This should help:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

Very good link: Validate decimal numbers in JavaScript - IsNumeric()

Sending JWT token in the headers with Postman

I did as how moplin mentioned .But in my case service send the JWT in response headers ,as a value under the key "Authorization".

Authorization ?Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJpbWFsIiwiZXhwIjoxNDk4OTIwOTEyfQ.dYEbf4x5TGr_kTtwywKPI2S-xYhsp5RIIBdOa_wl9soqaFkUUKfy73kaMAv_c-6cxTAqBwtskOfr-Gm3QI0gpQ

What I did was ,make a Global variable in postman as

key->jwt
value->blahblah

in login request->Tests Tab, add

postman.clearGlobalVariable("jwt");
postman.setGlobalVariable("jwt", postman.getResponseHeader("Authorization"));

in other requests select the Headers tab and give

key->Authorization

value->{{jwt}}

Understanding REST: Verbs, error codes, and authentication

I noticed this question a couple of days late, but I feel that I can add some insight. I hope this can be helpful towards your RESTful venture.


Point 1: Am I understanding it right?

You understood right. That is a correct representation of a RESTful architecture. You may find the following matrix from Wikipedia very helpful in defining your nouns and verbs:


When dealing with a Collection URI like: http://example.com/resources/

  • GET: List the members of the collection, complete with their member URIs for further navigation. For example, list all the cars for sale.

  • PUT: Meaning defined as "replace the entire collection with another collection".

  • POST: Create a new entry in the collection where the ID is assigned automatically by the collection. The ID created is usually included as part of the data returned by this operation.

  • DELETE: Meaning defined as "delete the entire collection".


When dealing with a Member URI like: http://example.com/resources/7HOU57Y

  • GET: Retrieve a representation of the addressed member of the collection expressed in an appropriate MIME type.

  • PUT: Update the addressed member of the collection or create it with the specified ID.

  • POST: Treats the addressed member as a collection in its own right and creates a new subordinate of it.

  • DELETE: Delete the addressed member of the collection.


Point 2: I need more verbs

In general, when you think you need more verbs, it may actually mean that your resources need to be re-identified. Remember that in REST you are always acting on a resource, or on a collection of resources. What you choose as the resource is quite important for your API definition.

Activate/Deactivate Login: If you are creating a new session, then you may want to consider "the session" as the resource. To create a new session, use POST to http://example.com/sessions/ with the credentials in the body. To expire it use PUT or a DELETE (maybe depending on whether you intend to keep a session history) to http://example.com/sessions/SESSION_ID.

Change Password: This time the resource is "the user". You would need a PUT to http://example.com/users/USER_ID with the old and new passwords in the body. You are acting on "the user" resource, and a change password is simply an update request. It's quite similar to the UPDATE statement in a relational database.

My instinct would be to do a GET call to a URL like /api/users/1/activate_login

This goes against a very core REST principle: The correct usage of HTTP verbs. Any GET request should never leave any side effect.

For example, a GET request should never create a session on the database, return a cookie with a new Session ID, or leave any residue on the server. The GET verb is like the SELECT statement in a database engine. Remember that the response to any request with the GET verb should be cache-able when requested with the same parameters, just like when you request a static web page.


Point 3: How to return error messages and codes

Consider the 4xx or 5xx HTTP status codes as error categories. You can elaborate the error in the body.

Failed to Connect to Database: / Incorrect Database Login: In general you should use a 500 error for these types of errors. This is a server-side error. The client did nothing wrong. 500 errors are normally considered "retryable". i.e. the client can retry the same exact request, and expect it to succeed once the server's troubles are resolved. Specify the details in the body, so that the client will be able to provide some context to us humans.

The other category of errors would be the 4xx family, which in general indicate that the client did something wrong. In particular, this category of errors normally indicate to the client that there is no need to retry the request as it is, because it will continue to fail permanently. i.e. the client needs to change something before retrying this request. For example, "Resource not found" (HTTP 404) or "Malformed Request" (HTTP 400) errors would fall in this category.


Point 4: How to do authentication

As pointed out in point 1, instead of authenticating a user, you may want to think about creating a session. You will be returned a new "Session ID", along with the appropriate HTTP status code (200: Access Granted or 403: Access Denied).

You will then be asking your RESTful server: "Can you GET me the resource for this Session ID?".

There is no authenticated mode - REST is stateless: You create a session, you ask the server to give you resources using this Session ID as a parameter, and on logout you drop or expire the session.

How to filter array when object key value is in array

This is a fast solution with a temporary object.

_x000D_
_x000D_
var records = [{ "empid": 1, "fname": "X", "lname": "Y" }, { "empid": 2, "fname": "A", "lname": "Y" }, { "empid": 3, "fname": "B", "lname": "Y" }, { "empid": 4, "fname": "C", "lname": "Y" }, { "empid": 5, "fname": "C", "lname": "Y" }],_x000D_
    empid = [1, 4, 5],_x000D_
    object = {},_x000D_
    result;_x000D_
_x000D_
records.forEach(function (a) {_x000D_
    object[a.empid] = a;_x000D_
});_x000D_
_x000D_
result = empid.map(function (a) {_x000D_
    return object[a];_x000D_
});_x000D_
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
_x000D_
_x000D_
_x000D_

Running Facebook application on localhost

So I got this to work today. My URL is http://localhost:8888. The domain I gave facebook is localhost. I thought that it was not working because I was trying to pull data using the FB.api method. I kept on getting an "undefined" name and an image without a source, so definitely didn't have access to the Graph.

Later I realized that my problem was really that I was only passing a first argument of /me to FB.api, and I didn't have a token. So you'll need to use the FB.getLoginStatus function to get a token, which should be added to the /me argument.

href overrides ng-click in Angular.js

You should probably just use a button tag if you don't need a uri.

Regular expression - starting and ending with a character string

This should do it for you ^wp.*php$

Matches

wp-comments-post.php
wp.something.php
wp.php

Doesn't match

something-wp.php
wp.php.txt

How to change Android version and code version number?

Go in the build.gradle and set the version code and name inside the defaultConfig element

defaultConfig { minSdkVersion 9 targetSdkVersion 19 versionCode 1 versionName "1.0" }

Android Open External Storage directory(sdcard) for storing file

taking @rijul's answer forward, it doesn't work in marshmallow and above versions:

       //for pre-marshmallow versions
       String path = System.getenv("SECONDARY_STORAGE");

       // For Marshmallow, use getExternalCacheDirs() instead of System.getenv("SECONDARY_STORAGE")
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
           File[] externalCacheDirs = mContext.getExternalCacheDirs();
           for (File file : externalCacheDirs) {
               if (Environment.isExternalStorageRemovable(file)) {
                   // Path is in format /storage.../Android....
                   // Get everything before /Android
                   path = file.getPath().split("/Android")[0];
                   break;
               }
           }
       }


        // Android avd emulator doesn't support this variable name so using other one
        if ((null == path) || (path.length() == 0))
            path = Environment.getExternalStorageDirectory().getAbsolutePath();

In Angular, What is 'pathmatch: full' and what effect does it have?

While technically correct, the other answers would benefit from an explanation of Angular's URL-to-route matching. I don't think you can fully (pardon the pun) understand what pathMatch: full does if you don't know how the router works in the first place.


Let's first define a few basic things. We'll use this URL as an example: /users/james/articles?from=134#section.

  1. It may be obvious but let's first point out that query parameters (?from=134) and fragments (#section) do not play any role in path matching. Only the base url (/users/james/articles) matters.

  2. Angular splits URLs into segments. The segments of /users/james/articles are, of course, users, james and articles.

  3. The router configuration is a tree structure with a single root node. Each Route object is a node, which may have children nodes, which may in turn have other children or be leaf nodes.

The goal of the router is to find a router configuration branch, starting at the root node, which would match exactly all (!!!) segments of the URL. This is crucial! If Angular does not find a route configuration branch which could match the whole URL - no more and no less - it will not render anything.

E.g. if your target URL is /a/b/c but the router is only able to match either /a/b or /a/b/c/d, then there is no match and the application will not render anything.

Finally, routes with redirectTo behave slightly differently than regular routes, and it seems to me that they would be the only place where anyone would really ever want to use pathMatch: full. But we will get to this later.

Default (prefix) path matching

The reasoning behind the name prefix is that such a route configuration will check if the configured path is a prefix of the remaining URL segments. However, the router is only able to match full segments, which makes this naming slightly confusing.

Anyway, let's say this is our root-level router configuration:

const routes: Routes = [
  {
    path: 'products',
    children: [
      {
        path: ':productID',
        component: ProductComponent,
      },
    ],
  },
  {
    path: ':other',
    children: [
      {
        path: 'tricks',
        component: TricksComponent,
      },
    ],
  },
  {
    path: 'user',
    component: UsersonComponent,
  },
  {
    path: 'users',
    children: [
      {
        path: 'permissions',
        component: UsersPermissionsComponent,
      },
      {
        path: ':userID',
        children: [
          {
            path: 'comments',
            component: UserCommentsComponent,
          },
          {
            path: 'articles',
            component: UserArticlesComponent,
          },
        ],
      },
    ],
  },
];

Note that every single Route object here uses the default matching strategy, which is prefix. This strategy means that the router iterates over the whole configuration tree and tries to match it against the target URL segment by segment until the URL is fully matched. Here's how it would be done for this example:

  1. Iterate over the root array looking for a an exact match for the first URL segment - users.
  2. 'products' !== 'users', so skip that branch. Note that we are using an equality check rather than a .startsWith() or .includes() - only full segment matches count!
  3. :other matches any value, so it's a match. However, the target URL is not yet fully matched (we still need to match james and articles), thus the router looks for children.
  • The only child of :other is tricks, which is !== 'james', hence not a match.
  1. Angular then retraces back to the root array and continues from there.
  2. 'user' !== 'users, skip branch.
  3. 'users' === 'users - the segment matches. However, this is not a full match yet, thus we need to look for children (same as in step 3).
  • 'permissions' !== 'james', skip it.
  • :userID matches anything, thus we have a match for the james segment. However this is still not a full match, thus we need to look for a child which would match articles.
    1. We can see that :userID has a child route articles, which gives us a full match! Thus the application renders UserArticlesComponent.

Full URL (full) matching

Example 1

Imagine now that the users route configuration object looked like this:

{
  path: 'users',
  component: UsersComponent,
  pathMatch: 'full',
  children: [
    {
      path: 'permissions',
      component: UsersPermissionsComponent,
    },
    {
      path: ':userID',
      component: UserComponent,
      children: [
        {
          path: 'comments',
          component: UserCommentsComponent,
        },
        {
          path: 'articles',
          component: UserArticlesComponent,
        },
      ],
    },
  ],
}

Note the usage of pathMatch: full. If this were the case, steps 1-5 would be the same, however step 6 would be different:

  1. 'users' !== 'users/james/articles - the segment does not match because the path configuration users with pathMatch: full does not match the full URL, which is users/james/articles.
  2. Since there is no match, we are skipping this branch.
  3. At this point we reached the end of the router configuration without having found a match. The application renders nothing.

Example 2

What if we had this instead:

{
  path: 'users/:userID',
  component: UsersComponent,
  pathMatch: 'full',
  children: [
    {
      path: 'comments',
      component: UserCommentsComponent,
    },
    {
      path: 'articles',
      component: UserArticlesComponent,
    },
  ],
}

users/:userID with pathMatch: full matches only users/james thus it's a no-match once again, and the application renders nothing.

Example 3

Let's consider this:

{
  path: 'users',
  children: [
    {
      path: 'permissions',
      component: UsersPermissionsComponent,
    },
    {
      path: ':userID',
      component: UserComponent,
      pathMatch: 'full',
      children: [
        {
          path: 'comments',
          component: UserCommentsComponent,
        },
        {
          path: 'articles',
          component: UserArticlesComponent,
        },
      ],
    },
  ],
}

In this case:

  1. 'users' === 'users - the segment matches, but james/articles still remains unmatched. Let's look for children.
  • 'permissions' !== 'james' - skip.
  • :userID' can only match a single segment, which would be james. However, it's a pathMatch: full route, and it must match james/articles (the whole remaining URL). It's not able to do that and thus it's not a match (so we skip this branch)!
  1. Again, we failed to find any match for the URL and the application renders nothing.

As you may have noticed, a pathMatch: full configuration is basically saying this:

Ignore my children and only match me. If I am not able to match all of the remaining URL segments myself, then move on.

Redirects

Any Route which has defined a redirectTo will be matched against the target URL according to the same principles. The only difference here is that the redirect is applied as soon as a segment matches. This means that if a redirecting route is using the default prefix strategy, a partial match is enough to cause a redirect. Here's a good example:

const routes: Routes = [
  {
    path: 'not-found',
    component: NotFoundComponent,
  },
  {
    path: 'users',
    redirectTo: 'not-found',
  },
  {
    path: 'users/:userID',
    children: [
      {
        path: 'comments',
        component: UserCommentsComponent,
      },
      {
        path: 'articles',
        component: UserArticlesComponent,
      },
    ],
  },
];

For our initial URL (/users/james/articles), here's what would happen:

  1. 'not-found' !== 'users' - skip it.
  2. 'users' === 'users' - we have a match.
  3. This match has a redirectTo: 'not-found', which is applied immediately.
  4. The target URL changes to not-found.
  5. The router begins matching again and finds a match for not-found right away. The application renders NotFoundComponent.

Now consider what would happen if the users route also had pathMatch: full:

const routes: Routes = [
  {
    path: 'not-found',
    component: NotFoundComponent,
  },
  {
    path: 'users',
    pathMatch: 'full',
    redirectTo: 'not-found',
  },
  {
    path: 'users/:userID',
    children: [
      {
        path: 'comments',
        component: UserCommentsComponent,
      },
      {
        path: 'articles',
        component: UserArticlesComponent,
      },
    ],
  },
];
  1. 'not-found' !== 'users' - skip it.
  2. users would match the first segment of the URL, but the route configuration requires a full match, thus skip it.
  3. 'users/:userID' matches users/james. articles is still not matched but this route has children.
  • We find a match for articles in the children. The whole URL is now matched and the application renders UserArticlesComponent.

Empty path (path: '')

The empty path is a bit of a special case because it can match any segment without "consuming" it (so it's children would have to match that segment again). Consider this example:

const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'users',
        component: BadUsersComponent,
      }
    ]
  },
  {
    path: 'users',
    component: GoodUsersComponent,
  },
];

Let's say we are trying to access /users:

  • path: '' will always match, thus the route matches. However, the whole URL has not been matched - we still need to match users!
  • We can see that there is a child users, which matches the remaining (and only!) segment and we have a full match. The application renders BadUsersComponent.

Now back to the original question

The OP used this router configuration:

const routes: Routes = [
  {
    path: 'welcome',
    component: WelcomeComponent,
  },
  {
    path: '',
    redirectTo: 'welcome',
    pathMatch: 'full',
  },
  {
    path: '**',
    redirectTo: 'welcome',
    pathMatch: 'full',
  },
];

If we are navigating to the root URL (/), here's how the router would resolve that:

  1. welcome does not match an empty segment, so skip it.
  2. path: '' matches the empty segment. It has a pathMatch: 'full', which is also satisfied as we have matched the whole URL (it had a single empty segment).
  3. A redirect to welcome happens and the application renders WelcomeComponent.

What if there was no pathMatch: 'full'?

Actually, one would expect the whole thing to behave exactly the same. However, Angular explicitly prevents such a configuration ({ path: '', redirectTo: 'welcome' }) because if you put this Route above welcome, it would theoretically create an endless loop of redirects. So Angular just throws an error, which is why the application would not work at all! (https://angular.io/api/router/Route#pathMatch)

Actually, this does not make too much sense to me because Angular also has implemented a protection against such endless redirects - it only runs a single redirect per routing level! This would stop all further redirects (as you'll see in the example below).

What about path: '**'?

path: '**' will match absolutely anything (af/frewf/321532152/fsa is a match) with or without a pathMatch: 'full'.

Also, since it matches everything, the root path is also included, which makes { path: '', redirectTo: 'welcome' } completely redundant in this setup.

Funnily enough, it is perfectly fine to have this configuration:

const routes: Routes = [
  {
    path: '**',
    redirectTo: 'welcome'
  },
  {
    path: 'welcome',
    component: WelcomeComponent,
  },
];

If we navigate to /welcome, path: '**' will be a match and a redirect to welcome will happen. Theoretically this should kick off an endless loop of redirects but Angular stops that immediately (because of the protection I mentioned earlier) and the whole thing works just fine.

WARNING: sanitizing unsafe style value url

For anyone who is already doing what the warning suggests you do, before the upgrade to Angular 5, I had to map my SafeStyle types to string before using them in the templates. After Angular 5, this is no longer the case. I had to change my models to have an image: SafeStyle instead of image: string. I was already using the [style.background-image] property binding and bypassing security on the whole url.

Hope this helps someone.

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

When I was a little kid, I had a keen interest in computers (MSX back then), and consequently programming (all there was, was a variant of Basic). I lost that after I grew up, but I got back to it when I learned that Counter-Strike was just a mod made by some fans by modifying Half-Life code. That made me really interested in programming all over again!

It's not 10 lines of code, but if you show people the source code for some game, and then modify that and make it do something different, and demonstrate it to them live, it's reaaaaally gonna blow them away. Wow, this actually is not dark magic! You can do it!

Now a days, there are quite a few games you can do this with. I think the source code for all the Quake series (atleast I through III) is released. I know for a fact that you can create mods for Half-Life and Half-Life2, I'm sure other games like Unreal and FarCry also offer a similar ability.

Some simple things that could spark grate motivation:

  • Make a weapon super powerful (e.g., infinite ammo, higher damage, auto-aim .. etc.
  • Add an Anime-style movement (flying, dashing really fast, etc).

The modification itself shouldn't take too many lines of code, but the fact that it works is just amazing.

Create list of single item repeated N times

>>> [5] * 4
[5, 5, 5, 5]

Be careful when the item being repeated is a list. The list will not be cloned: all the elements will refer to the same list!

>>> x=[5]
>>> y=[x] * 4
>>> y
[[5], [5], [5], [5]]
>>> y[0][0] = 6
>>> y
[[6], [6], [6], [6]]

How to filter by object property in angularJS

The documentation has the complete answer. Anyway this is how it is done:

<input type="text" ng-model="filterValue">
<li ng-repeat="i in data | filter:{age:filterValue}:true"> {{i | json }}</li>

will filter only age in data array and true is for exact match.

For deep filtering,

<li ng-repeat="i in data | filter:{$:filterValue}:true"> {{i}}</li>

The $ is a special property for deep filter and the true is for exact match like above.

Calculating powers of integers

There some issues with pow method:

  1. We can replace (y & 1) == 0; with y % 2 == 0
    bitwise operations always are faster.

Your code always decrements y and performs extra multiplication, including the cases when y is even. It's better to put this part into else clause.

public static long pow(long x, int y) {
        long result = 1;
        while (y > 0) {
            if ((y & 1) == 0) {
                x *= x;
                y >>>= 1;
            } else {
                result *= x;
                y--;
            }
        }
        return result;
    }

How to find the foreach index?

Jonathan is correct. PHP arrays act as a map table mapping keys to values. in some cases you can get an index if your array is defined, such as

$var = array(2,5);

for ($i = 0; $i < count($var); $i++) {
    echo $var[$i]."\n";
}

your output will be

2
5

in which case each element in the array has a knowable index, but if you then do something like the following

$var = array_push($var,10);

for ($i = 0; $i < count($var); $i++) {
    echo $var[$i]."\n";
}

you get no output. This happens because arrays in PHP are not linear structures like they are in most languages. They are more like hash tables that may or may not have keys for all stored values. Hence foreach doesn't use indexes to crawl over them because they only have an index if the array is defined. If you need to have an index, make sure your arrays are fully defined before crawling over them, and use a for loop.

Windows recursive grep command-line

findstr can do recursive searches (/S) and supports some variant of regex syntax (/R).

C:\>findstr /?
Searches for strings in files.

FINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P] [/F:file]
        [/C:string] [/G:file] [/D:dir list] [/A:color attributes] [/OFF[LINE]]
        strings [[drive:][path]filename[ ...]]

  /B         Matches pattern if at the beginning of a line.
  /E         Matches pattern if at the end of a line.
  /L         Uses search strings literally.
  /R         Uses search strings as regular expressions.
  /S         Searches for matching files in the current directory and all
             subdirectories.
  /I         Specifies that the search is not to be case-sensitive.
  /X         Prints lines that match exactly.
  /V         Prints only lines that do not contain a match.
  /N         Prints the line number before each line that matches.
  /M         Prints only the filename if a file contains a match.
  /O         Prints character offset before each matching line.
  /P         Skip files with non-printable characters.
  /OFF[LINE] Do not skip files with offline attribute set.
  /A:attr    Specifies color attribute with two hex digits. See "color /?"
  /F:file    Reads file list from the specified file(/ stands for console).
  /C:string  Uses specified string as a literal search string.
  /G:file    Gets search strings from the specified file(/ stands for console).
  /D:dir     Search a semicolon delimited list of directories
  strings    Text to be searched for.
  [drive:][path]filename
             Specifies a file or files to search.

Use spaces to separate multiple search strings unless the argument is prefixed
with /C.  For example, 'FINDSTR "hello there" x.y' searches for "hello" or
"there" in file x.y.  'FINDSTR /C:"hello there" x.y' searches for
"hello there" in file x.y.

Regular expression quick reference:
  .        Wildcard: any character
  *        Repeat: zero or more occurrences of previous character or class
  ^        Line position: beginning of line
  $        Line position: end of line
  [class]  Character class: any one character in set
  [^class] Inverse class: any one character not in set
  [x-y]    Range: any characters within the specified range
  \x       Escape: literal use of metacharacter x
  \<xyz    Word position: beginning of word
  xyz\>    Word position: end of word

For full information on FINDSTR regular expressions refer to the online Command
Reference.

How to create a secure random AES key in Java?

I would use your suggested code, but with a slight simplification:

KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256); // for example
SecretKey secretKey = keyGen.generateKey();

Let the provider select how it plans to obtain randomness - don't define something that may not be as good as what the provider has already selected.

This code example assumes (as Maarten points out below) that you've configured your java.security file to include your preferred provider at the top of the list. If you want to manually specify the provider, just call KeyGenerator.getInstance("AES", "providerName");.

For a truly secure key, you need to be using a hardware security module (HSM) to generate and protect the key. HSM manufacturers will typically supply a JCE provider that will do all the key generation for you, using the code above.

Angular: date filter adds timezone, how to output UTC?

I just used getLocaleString() function for my application. It should adapt the timeformat common to the locale, so no +0200 etc. Ofcourse, there will be less possibility for controlling the width of your string then.

var str = (new Date(1400167800)).toLocaleString();

PHP Warning: PHP Startup: ????????: Unable to initialize module

Erase the module that can't be initialized and reinstall it.

GitHub - error: failed to push some refs to '[email protected]:myrepo.git'

In my case. I had the error because I forgot to make a commit after create a repository on github into an existing project. So I solved:

git add .
git commit -m"commentary"

Then I was able to type:

git push -u origin master

Intercept and override HTTP requests from WebView

Try this, I've used it in a personal wiki-like app:

webView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.startsWith("foo://")) {
            // magic
            return true;
        }
        return false;
    }
});

Run javascript function when user finishes typing instead of on key up?

Well, strictly speaking no, as the computer cannot guess when the user has finished typing. You could of course fire a timer on key up, and reset it on every subsequent key up. If the timer expires, the user hasn't typed for the timer duration - you could call that "finished typing".

If you expect users to make pauses while typing, there's no way to know when they are done.

(Unless of course you can tell from the data when they are done)

XPath:: Get following Sibling

You should be looking for the second tr that has the td that equals ' Color Digest ', then you need to look at either the following sibling of the first td in the tr, or the second td.

Try the following:

//tr[td='Color Digest'][2]/td/following-sibling::td[1]

or

//tr[td='Color Digest'][2]/td[2]

http://www.xpathtester.com/saved/76bb0bca-1896-43b7-8312-54f924a98a89

How to Import 1GB .sql file to WAMP/phpmyadmin

A phpMyAdmin feature called UploadDir permits to upload your file via another mechanism, then importing it from the server's file system. See http://docs.phpmyadmin.net/en/latest/faq.html#i-cannot-upload-big-dump-files-memory-http-or-timeout-problems.

Online code beautifier and formatter

What language?? There are different tools for almost every imaginable programming language, since they all have different syntactic rules and conventions.

Good ol' indent is a nice, customizable, command-line utility to format C and C++ programs.

Spring Boot without the web server

  • Through program :

    ConfigurableApplicationContext ctx =  new  SpringApplicationBuilder(YourApplicationMain.class)
    .web(WebApplicationType.NONE)
    .run(args);
    
  • Through application.properties file :

    spring.main.web-environment=false 
    
  • Through application.yml file :

    spring:
     main:
      web-environment:false
    

How to wrap text using CSS?

The better option if you cannot control user input, it is to establish the css property, overflow:hidden, so if the string is superior to the width, it will not deform the design.

Edited:

I like the answer: "word-wrap: break-word", and for those browsers that do not support it, for example, IE6 or IE7, I would use my solution.

How do I convert from stringstream to string in C++?

From memory, you call stringstream::str() to get the std::string value out.

Set database timeout in Entity Framework

For Database first Aproach:

We can still set it in a constructor, by override the ContextName.Context.tt T4 Template this way:

<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext
{
    public <#=code.Escape(container)#>()
        : base("name=<#=container.Name#>")
    {
        Database.CommandTimeout = 180;
<#
if (!loader.IsLazyLoadingEnabled(container))
{
#>
        this.Configuration.LazyLoadingEnabled = false;
<#
}

Database.CommandTimeout = 180; is the acutaly change.

The generated output is this:

public ContextName() : base("name=ContextName")
{
    Database.CommandTimeout = 180;
}

If you change your Database Model, this template stays, but the actualy class will be updated.

How do I automatically scroll to the bottom of a multiline text box?

I found a simple difference that hasn't been addressed in this thread.

If you're doing all the ScrollToCarat() calls as part of your form's Load() event, it doesn't work. I just added my ScrollToCarat() call to my form's Activated() event, and it works fine.

Edit

It's important to only do this scrolling the first time form's Activated event is fired (not on subsequent activations), or it will scroll every time your form is activated, which is something you probably don't want.

So if you're only trapping the Activated() event to scroll your text when your program loads, then you can just unsubscribe to the event inside the event handler itself, thusly:

Activated -= new System.EventHandler(this.Form1_Activated);

If you have other things you need to do each time your form is activated, you can set a bool to true the first time your Activated() event is fired, so you don't scroll on subsequent activations, but can still do the other things you need to do.

Also, if your TextBox is on a tab that isn't the SelectedTab, ScrollToCarat() will have no effect. So you need at least make it the selected tab while you're scrolling. You can wrap the code in a YourTab.SuspendLayout(); and YourTab.ResumeLayout(false); pair if your form flickers when you do this.

End of edit

Hope this helps!

Select the values of one property on all objects of an array in PowerShell

Caution, member enumeration only works if the collection itself has no member of the same name. So if you had an array of FileInfo objects, you couldn't get an array of file lengths by using

 $files.length # evaluates to array length

And before you say "well obviously", consider this. If you had an array of objects with a capacity property then

 $objarr.capacity

would work fine UNLESS $objarr were actually not an [Array] but, for example, an [ArrayList]. So before using member enumeration you might have to look inside the black box containing your collection.

(Note to moderators: this should be a comment on rageandqq's answer but I don't yet have enough reputation.)

How can I build multiple submit buttons django form?

It's an old question now, nevertheless I had the same issue and found a solution that works for me: I wrote MultiRedirectMixin.

from django.http import HttpResponseRedirect

class MultiRedirectMixin(object):
    """
    A mixin that supports submit-specific success redirection.
     Either specify one success_url, or provide dict with names of 
     submit actions given in template as keys
     Example: 
       In template:
         <input type="submit" name="create_new" value="Create"/>
         <input type="submit" name="delete" value="Delete"/>
       View:
         MyMultiSubmitView(MultiRedirectMixin, forms.FormView):
             success_urls = {"create_new": reverse_lazy('create'),
                               "delete": reverse_lazy('delete')}
    """
    success_urls = {}  

    def form_valid(self, form):
        """ Form is valid: Pick the url and redirect.
        """

        for name in self.success_urls:
            if name in form.data:
                self.success_url = self.success_urls[name]
                break

        return HttpResponseRedirect(self.get_success_url())

    def get_success_url(self):
        """
        Returns the supplied success URL.
        """
        if self.success_url:
            # Forcing possible reverse_lazy evaluation
            url = force_text(self.success_url)
        else:
            raise ImproperlyConfigured(
                _("No URL to redirect to. Provide a success_url."))
        return url

MySQL load NULL values from CSV data

Converted the input file to include \N for the blank column data using the below sed command in UNix terminal:

sed -i 's/,,/,\\N,/g' $file_name

and then use LOAD DATA INFILE command to load to mysql

Force IE compatibility mode off using tags

Insert as the very first item under the tag.

This forces IE to render the page in the physical version of IE, and it ignores the Browser "Mode setting". This can be set in the developer tools, try changing it to a older version of IE to test, this should be ignored and the page should look exactly the same.

Having trouble setting working directory

I just had this error message happen. When searching for why, I figured out that there's a related issue that can occur if you're not paying attention - the same error occurs if the directory you are trying to move into does not exist.

Transposing a 1D NumPy array

I am just consolidating the above post, hope it will help others to save some time:

The below array has (2, )dimension, it's a 1-D array,

b_new = np.array([2j, 3j])  

There are two ways to transpose a 1-D array:


slice it with "np.newaxis" or none.!

print(b_new[np.newaxis].T.shape)
print(b_new[None].T.shape)

other way of writing, the above without T operation.!

print(b_new[:, np.newaxis].shape)
print(b_new[:, None].shape)

Wrapping [ ] or using np.matrix, means adding a new dimension.!

print(np.array([b_new]).T.shape)
print(np.matrix(b_new).T.shape)

Calculating a 2D Vector's Cross Product

Implementation 1 returns the magnitude of the vector that would result from a regular 3D cross product of the input vectors, taking their Z values implicitly as 0 (i.e. treating the 2D space as a plane in the 3D space). The 3D cross product will be perpendicular to that plane, and thus have 0 X & Y components (thus the scalar returned is the Z value of the 3D cross product vector).

Note that the magnitude of the vector resulting from 3D cross product is also equal to the area of the parallelogram between the two vectors, which gives Implementation 1 another purpose. In addition, this area is signed and can be used to determine whether rotating from V1 to V2 moves in an counter clockwise or clockwise direction. It should also be noted that implementation 1 is the determinant of the 2x2 matrix built from these two vectors.

Implementation 2 returns a vector perpendicular to the input vector still in the same 2D plane. Not a cross product in the classical sense but consistent in the "give me a perpendicular vector" sense.

Note that 3D euclidean space is closed under the cross product operation--that is, a cross product of two 3D vectors returns another 3D vector. Both of the above 2D implementations are inconsistent with that in one way or another.

Hope this helps...

Fetching data from MySQL database to html dropdown list

To do this you want to loop through each row of your query results and use this info for each of your drop down's options. You should be able to adjust the code below fairly easily to meet your needs.

// Assume $db is a PDO object
$query = $db->query("YOUR QUERY HERE"); // Run your query

echo '<select name="DROP DOWN NAME">'; // Open your drop down box

// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
   echo '<option value="'.$row['something'].'">'.$row['something'].'</option>';
}

echo '</select>';// Close your drop down box

How to convert php array to utf8?

A more general function to encode an array is:

/**
 * also for multidemensional arrays
 *
 * @param array $array
 * @param string $sourceEncoding
 * @param string $destinationEncoding
 *
 * @return array
 */
function encodeArray(array $array, string $sourceEncoding, string $destinationEncoding = 'UTF-8'): array
{
    if($sourceEncoding === $destinationEncoding){
        return $array;
    }

    array_walk_recursive($array,
        function(&$array) use ($sourceEncoding, $destinationEncoding) {
            $array = mb_convert_encoding($array, $destinationEncoding, $sourceEncoding);
        }
    );

    return $array;
}

How to Install Font Awesome in Laravel Mix

npm install font-awesome --save

add ~/ before path

@import "~/font-awesome/scss/font-awesome.scss";

What is the javascript filename naming convention?

I'm not aware of any particular convention for javascript files as they aren't really unique on the web versus css files or html files or any other type of file like that. There are some "safe" things you can do that make it less likely you will accidentally run into a cross platform issue:

  1. Use all lowercase filenames. There are some operating systems that are not case sensitive for filenames and using all lowercase prevents inadvertently using two files that differ only in case that might not work on some operating systems.
  2. Don't use spaces in the filename. While this technically can be made to work there are lots of reasons why spaces in filenames can lead to problems.
  3. A hyphen is OK for a word separator. If you want to use some sort of separator for multiple words instead of a space or camelcase as in various-scripts.js, a hyphen is a safe and useful and commonly used separator.
  4. Think about using version numbers in your filenames. When you want to upgrade your scripts, plan for the effects of browser or CDN caching. The simplest way to use long term caching (for speed and efficiency), but immediate and safe upgrades when you upgrade a JS file is to include a version number in the deployed filename or path (like jQuery does with jquery-1.6.2.js) and then you bump/change that version number whenever you upgrade/change the file. This will guarantee that no page that requests the newer version is ever served the older version from a cache.

Parsing JSON string in Java

Here is the example of one Object, For your case you have to use JSONArray.

public static final String JSON_STRING="{\"employee\":{\"name\":\"Sachin\",\"salary\":56000}}";  
try{  
   JSONObject emp=(new JSONObject(JSON_STRING)).getJSONObject("employee");  
   String empname=emp.getString("name");  
   int empsalary=emp.getInt("salary");  

   String str="Employee Name:"+empname+"\n"+"Employee Salary:"+empsalary;  
   textView1.setText(str);  

}catch (Exception e) {e.printStackTrace();}  
   //Do when JSON has problem.
}

I don't have time but tried to give an idea. If you still can't do it, then I will help.