Programs & Examples On #Jssh

The JavaScript Shell server for Mozilla (JSSh) is an extension for Mozilla browsers which allows remote users to execute JavaScript in the running browser.

Setting up MySQL and importing dump within Dockerfile

edit: I had misunderstand the question here. My following answer explains how to run sql commands at container creation time, but not at image creation time as desired by OP.

I'm not quite fond of Kuhess's accepted answer as the sleep 5 seems a bit hackish to me as it assumes that the mysql db daemon has correctly loaded within this time frame. That's an assumption, no guarantee. Also if you use a provided mysql docker image, the image itself already takes care about starting up the server; I would not interfer with this with a custom /usr/bin/mysqld_safe.

I followed the other answers around here and copied bash and sql scripts into the folder /docker-entrypoint-initdb.d/ within the docker container as this is clearly the intended way by the mysql image provider. Everything in this folder is executed once the db daemon is ready, hence you should be able rely on it.

As an addition to the others - since no other answer explicitely mentions this: besides sql scripts you can also copy bash scripts into that folder which might give you more control.

This is what I had needed for example as I also needed to import a dump, but the dump alone was not sufficient as it did not provide which database it should import into. So in my case I have a script named db_custom_init.sh with this content:

mysql -u root -p$MYSQL_ROOT_PASSWORD -e 'create database my_database_to_import_into'
mysql -u root -p$MYSQL_ROOT_PASSWORD my_database_to_import_into < /home/db_dump.sql

and this Dockerfile copying that script:

FROM mysql/mysql-server:5.5.62
ENV MYSQL_ROOT_PASSWORD=XXXXX
COPY ./db_dump.sql /home/db_dump.sql
COPY ./db_custom_init.sh /docker-entrypoint-initdb.d/

Image convert to Base64

_x000D_
_x000D_
function readFile() {_x000D_
  _x000D_
  if (this.files && this.files[0]) {_x000D_
    _x000D_
    var FR= new FileReader();_x000D_
    _x000D_
    FR.addEventListener("load", function(e) {_x000D_
      document.getElementById("img").src       = e.target.result;_x000D_
      document.getElementById("b64").innerHTML = e.target.result;_x000D_
    }); _x000D_
    _x000D_
    FR.readAsDataURL( this.files[0] );_x000D_
  }_x000D_
  _x000D_
}_x000D_
_x000D_
document.getElementById("inp").addEventListener("change", readFile);
_x000D_
<input id="inp" type='file'>_x000D_
<p id="b64"></p>_x000D_
<img id="img" height="150">
_x000D_
_x000D_
_x000D_

(P.S: A base64 encoded image (String) 4/3 the size of the original image data)

Check this answer for multiple images upload.

Browser support: http://caniuse.com/#search=file%20api
More info here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader

How to change sender name (not email address) when using the linux mail command for autosending mail?

You can use the "-r" option to set the sender address:

mail -r [email protected] -s ...

In case you also want to include your real name in the from-field, you can use the following format

mail -r "[email protected] (My Name)" -s "My Subject" ...

Disable ONLY_FULL_GROUP_BY

The MySQL documentation also specifies the following methods:

  • Set sql-mode="<modes>" in an option file such as my.cnf (Unix operating systems) or my.ini (Windows).
  • To set the SQL mode at server startup via the command line, use the --sql-mode="<modes>" option.

*Where <modes> is a list of different modes separated by commas.

To clear the SQL mode explicitly, set it to an empty string using --sql-mode="" on the command line, or sql-mode="" in an option file.

I added the sql-mode="" option to /etc/my.cnf and it worked.

This SO solution discusses ways to find out which my.cnf file is being used by MySQL.

Don't forget to restart MySQL after making changes.

Splitting a continuous variable into equal sized groups

Or see cut_number from the ggplot2 package, e.g.

das$wt_2 <- as.numeric(cut_number(das$wt,3))

Note that cut(...,3) divides the range of the original data into three ranges of equal lengths; it doesn't necessarily result in the same number of observations per group if the data are unevenly distributed (you can replicate what cut_number does by using quantile appropriately, but it's a nice convenience function). On the other hand, Hmisc::cut2() using the g= argument does split by quantiles, so is more or less equivalent to ggplot2::cut_number. I might have thought that something like cut_number would have made its way into dplyr by so far, but as far as I can tell it hasn't.

Objective-C Static Class Level variables

(Strictly speaking not an answer to the question, but in my experience likely to be useful when looking for class variables)

A class method can often play many of the roles a class variable would in other languages (e.g. changed configuration during tests):

@interface MyCls: NSObject
+ (NSString*)theNameThing;
- (void)doTheThing;
@end
@implementation
+ (NSString*)theNameThing { return @"Something general"; }
- (void)doTheThing {
  [SomeResource changeSomething:[self.class theNameThing]];
}
@end

@interface MySpecialCase: MyCls
@end
@implementation
+ (NSString*)theNameThing { return @"Something specific"; }
@end

Now, an object of class MyCls calls Resource:changeSomething: with the string @"Something general" upon a call to doTheThing:, but an object derived from MySpecialCase with the string @"Something specific".

Changing background color of selected item in recyclerview

My Solution

With my solution I'm not using notifyDataSetChanged(), because annoying whenever item is clicked, all the items from list got refreshed. To tackle this problem, I used notifyItemChanged(position); This will only change the selected item.

Below I have added the code of my omBindViewHolder.

private int previousPosition = -1;
private SingleViewItemBinding previousView;

@Override
public void onBindViewHolder(@NonNull final ItemViewHolder holder, final int position) {
    holder.viewBinding.setItem(itemList.get(position));
    holder.viewBinding.rlContainerMain.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            clickRecyclerView.clickRecyclerItem(position, 0);

            previousPosition = position;
            notifyItemChanged(position);

            if(previousView != null){
                previousView.rlContainerMain.setBackgroundColor(
                        ContextCompat.getColor(context, R.color.colorGrayLight));

            }
        }
    });

    if(position == previousPosition){
        previousView = holder.viewBinding;

        holder.viewBinding.rlContainerMain.setBackgroundColor(
                ContextCompat.getColor(context, R.color.colorPrimary));

    }
    else {
        holder.viewBinding.rlContainerMain.setBackgroundColor(
                ContextCompat.getColor(context, R.color.colorGrayLight));

    }

}

java.sql.SQLException: Exhausted Resultset

If you reset the result set to the top, using rs.absolute(1) you won't get exhaused result set.

while (rs.next) {
    System.out.println(rs.getString(1));
}
rs.absolute(1);
System.out.println(rs.getString(1));

You can also use rs.first() instead of rs.absolute(1), it does the same.

Full screen background image in an activity

Another option is to add a single image (not necessarily big) in the drawables (let's name it backgroung.jpg), create an ImageView iv_background at the root of your xml without a "src" attribute. Then in the onCreate method of the corresponding activity:

    /* create a full screen window */
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.your_activity);

    /* adapt the image to the size of the display */
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    Bitmap bmp = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(
      getResources(),R.drawable.background),size.x,size.y,true);

    /* fill the background ImageView with the resized image */
    ImageView iv_background = (ImageView) findViewById(R.id.iv_background);
    iv_background.setImageBitmap(bmp);

No cropping, no many different sized images. Hope it helps!

Auto height div with overflow and scroll when needed

Try this:
CSS:

#content {
  margin: 0 auto;
  border: 1px solid red;
  width:800px;
  position:absolute;
  bottom:0px;
  top:0px;
  overflow:auto
}

HTML:

<body>
<div id="content">
...content goes here...
</div>
<body>

If you don't like absolute positioning in this case, just can play with making a parent and child div to this one, both with position:relative.

EDIT: Below should work (I just put the css inline for the moment):

<div style="margin:0 auto; width:800px; height:100%; overflow:hidden">
<div style="border: 1px solid red; width:800px; position:absolute; bottom:0px; top:0px; overflow:auto">
...content goes here...
</div>
</div>

Which method performs better: .Any() vs .Count() > 0?

It depends, how big is the data set and what are your performance requirements?

If it's nothing gigantic use the most readable form, which for myself is any, because it's shorter and readable rather than an equation.

How to choose between Hudson and Jenkins?

For those who have mentioned a reconciliation as a potential future for Hudson and Jenkins, with the fact that Jenkins will be joining SPI, it is unlikely at this point they will reconcile.

How to set a radio button in Android

If you want to do it in code, you can call the check member of RadioGroup:

radioGroup.check(R.id.radioButtonId);

This will check the button you specify and uncheck the others.

Get last 30 day records from today date in SQL Server

This Should Work Fine

SELECT * FROM product 
WHERE pdate BETWEEN datetime('now', '-30 days') AND datetime('now', 'localtime')

Get MD5 hash of big files in Python

You need to read the file in chunks of suitable size:

def md5_for_file(f, block_size=2**20):
    md5 = hashlib.md5()
    while True:
        data = f.read(block_size)
        if not data:
            break
        md5.update(data)
    return md5.digest()

NOTE: Make sure you open your file with the 'rb' to the open - otherwise you will get the wrong result.

So to do the whole lot in one method - use something like:

def generate_file_md5(rootdir, filename, blocksize=2**20):
    m = hashlib.md5()
    with open( os.path.join(rootdir, filename) , "rb" ) as f:
        while True:
            buf = f.read(blocksize)
            if not buf:
                break
            m.update( buf )
    return m.hexdigest()

The update above was based on the comments provided by Frerich Raabe - and I tested this and found it to be correct on my Python 2.7.2 windows installation

I cross-checked the results using the 'jacksum' tool.

jacksum -a md5 <filename>

http://www.jonelo.de/java/jacksum/

How to count digits, letters, spaces for a string in Python?

Following code replaces any nun-numeric character with '', allowing you to count number of such characters with function len.

import re
len(re.sub("[^0-9]", "", my_string))

Alphabetical:

import re
len(re.sub("[^a-zA-Z]", "", my_string))

More info - https://docs.python.org/3/library/re.html

If using maven, usually you put log4j.properties under java or resources?

If your log4j.properties or log4j.xml file not found under src/main/resources use this PropertyConfigurator.configure("log4j.xml");

   PropertyConfigurator.configure("log4j.xml");
   Logger logger = LoggerFactory.getLogger(MyClass.class);
   logger.error(message);

Pushing from local repository to GitHub hosted remote

This worked for my GIT version 1.8.4:

  1. From the local repository folder, right click and select 'Git Commit Tool'.
  2. There, select the files you want to upload, under 'Unstaged Changes' and click 'Stage Changed' button. (You can initially click on 'Rescan' button to check what files are modified and not uploaded yet.)
  3. Write a Commit Message and click 'Commit' button.
  4. Now right click in the folder again and select 'Git Bash'.
  5. Type: git push origin master and enter your credentials. Done.

iCheck check if checkbox is checked

Use this code for iCheck:

$('.i-checks').iCheck({
    checkboxClass: 'icheckbox_square-green',
    radioClass: 'iradio_square-green',
}).on('ifChanged', function(e) {
    // Get the field name
    var isChecked = e.currentTarget.checked;

    if (isChecked == true) {

    }
});

How do I align views at the bottom of the screen?

I used the solution Janusz posted, but I added padding to the last View since the top part of my layout was a ScrollView.

The ScrollView will be partly hidden as it grows with content. Using android:paddingBottom on the last View helps show all the content in the ScrollView.

grep using a character vector with multiple patterns

Not sure whether this answer has already appeared...

For the particular pattern in the question, you can just do it with a single grep() call,

grep("A[169]", myfile$Letter)

How to disable/enable select field using jQuery?

You would like to use code like this:

<form>
  <input type="checkbox" id="pizza" name="pizza" value="yes">
  <label for="pizza">I would like to order a</label>
  <select id="pizza_kind" name="pizza_kind">
    <option>(choose one)</option>
    <option value="margaritha">Margaritha</option>
    <option value="hawai">Hawai</option>
  </select>
  pizza.
</form>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
  var update_pizza = function () {
    if ($("#pizza").is(":checked")) {
        $('#pizza_kind').prop('disabled', false);
    }
    else {
        $('#pizza_kind').prop('disabled', 'disabled');
    }
  };
  $(update_pizza);
  $("#pizza").change(update_pizza);
</script>

?Here is working example

How to know user has clicked "X" or the "Close" button?

How to detect if the form closed by click on X button or by calling Close() in code?

You cannot rely on close reason of the form closing event args, because if the user click X button on title bar or close the form using Alt + F4 or use system menu to close the form or the form get closed by calling Close() method, all all above cases, the close reason will be Closed by User which is not desired result.

To distinguish if the form closed by X button or by Close method, you can use either of the following options:

  • Handle WM_SYSCOMMAND and check for SC_CLOSE and set a flag.
  • Check the StackTrace to see if any of the frames contain Close method call.

Example 1 - Handle WM_SYSCOMMAND

public bool ClosedByXButtonOrAltF4 {get; private set;}
private const int SC_CLOSE = 0xF060;
private const int WM_SYSCOMMAND = 0x0112;
protected override void WndProc(ref Message msg)
{
    if (msg.Msg == WM_SYSCOMMAND && msg.WParam.ToInt32() == SC_CLOSE)
        ClosedByXButtonOrAltF4 = true;
    base.WndProc(ref msg);
}
protected override void OnShown(EventArgs e)
{
    ClosedByXButtonOrAltF4 = false;
}   
protected override void OnFormClosing(FormClosingEventArgs e)
{
    if (ClosedByXButtonOrAltF4)
        MessageBox.Show("Closed by X or Alt+F4");
    else
        MessageBox.Show("Closed by calling Close()");
}

Example 2 - Checking StackTrace

protected override void OnFormClosing(FormClosingEventArgs e)
{
    if (new StackTrace().GetFrames().Any(x => x.GetMethod().Name == "Close"))
        MessageBox.Show("Closed by calling Close()");
    else
        MessageBox.Show("Closed by X or Alt+F4");
}

JUnit Testing private variables?

First of all, you are in a bad position now - having the task of writing tests for the code you did not originally create and without any changes - nightmare! Talk to your boss and explain, it is not possible to test the code without making it "testable". To make code testable you usually do some important changes;

Regarding private variables. You actually never should do that. Aiming to test private variables is the first sign that something wrong with the current design. Private variables are part of the implementation, tests should focus on behavior rather of implementation details.

Sometimes, private field are exposed to public access with some getter. I do that, but try to avoid as much as possible (mark in comments, like 'used for testing').

Since you have no possibility to change the code, I don't see possibility (I mean real possibility, not like Reflection hacks etc.) to check private variable.

Android EditText Hint

et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {

            et.setHint(temp +" Characters");
        }
    });

Adding space/padding to a UILabel

I edited a little in the accepted answer. There is a problem when leftInset and rightInset increase, a part of text will be disappeared, b/c the width of label will be narrowed but the height does not increase as figure:

padding label with wrong intrinsic content size

To resolve this problem you need to re-calculate height of text as follow:

@IBDesignable class PaddingLabel: UILabel {

  @IBInspectable var topInset: CGFloat = 20.0
  @IBInspectable var bottomInset: CGFloat = 20.0
  @IBInspectable var leftInset: CGFloat = 20.0
  @IBInspectable var rightInset: CGFloat = 20.0

  override func drawTextInRect(rect: CGRect) {
    let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
    super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
  }

  override func intrinsicContentSize() -> CGSize {
    var intrinsicSuperViewContentSize = super.intrinsicContentSize()

    let textWidth = frame.size.width - (self.leftInset + self.rightInset)
    let newSize = self.text!.boundingRectWithSize(CGSizeMake(textWidth, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: self.font], context: nil)
    intrinsicSuperViewContentSize.height = ceil(newSize.size.height) + self.topInset + self.bottomInset

    return intrinsicSuperViewContentSize
  }
}

and result:

padding label with right intrinsic content size

I hope to help some people in the same situation as me.

Multiple line code example in Javadoc comment

Try replacing "code" with "pre". The pre tag in HTML marks the text as preformatted and all linefeeds and spaces will appear exactly as you type them.

What is Python used for?

Why should you learn Python Programming Language?

Python offers a stepping stone into the world of programming. Even though Python Programming Language has been around for 25 years, it is still rising in popularity. Some of the biggest advantage of Python are it's

  • Easy to Read & Easy to Learn
  • Very productive or small as well as big projects
  • Big libraries for many things

enter image description here

What is Python Programming Language used for?

As a general purpose programming language, Python can be used for multiple things. Python can be easily used for small, large, online and offline projects. The best options for utilizing Python are web development, simple scripting and data analysis. Below are a few examples of what Python will let you do:

Web Development:

You can use Python to create web applications on many levels of complexity. There are many excellent Python web frameworks including, Pyramid, Django and Flask, to name a few.

Data Analysis:

Python is the leading language of choice for many data scientists. Python has grown in popularity, within this field, due to its excellent libraries including; NumPy and Pandas and its superb libraries for data visualisation like Matplotlib and Seaborn.

Machine Learning:

What if you could predict customer satisfaction or analyse what factors will affect household pricing or to predict stocks over the next few days, based on previous years data? There are many wonderful libraries implementing machine learning algorithms such as Scikit-Learn, NLTK and TensorFlow.

Computer Vision:

You can do many interesting things such as Face detection, Color detection while using Opencv and Python.

Internet Of Things With Raspberry Pi:

Raspberry Pi is a very tiny and affordable computer which was developed for education and has gained enormous popularity among hobbyists with do-it-yourself hardware and automation. You can even build a robot and automate your entire home. Raspberry Pi can be used as the brain for your robot in order to perform various actions and/or react to the environment. The coding on a Raspberry Pi can be performed using Python. The Possibilities are endless!

Game Development:

Create a video game using module Pygame. Basically, you use Python to write the logic of the game. PyGame applications can run on Android devices.

Web Scraping:

If you need to grab data from a website but the site does not have an API to expose data, use Python to scraping data.

Writing Scripts:

If you're doing something manually and want to automate repetitive stuff, such as emails, it's not difficult to automate once you know the basics of this language.

Browser Automation:

Perform some neat things such as opening a browser and posting a Facebook status, you can do it with Selenium with Python.

GUI Development:

Build a GUI application (desktop app) using Python modules Tkinter, PyQt to support it.

Rapid Prototyping:

Python has libraries for just about everything. Use it to quickly built a (lower-performance, often less powerful) prototype. Python is also great for validating ideas or products for established companies and start-ups alike.

Python can be used in so many different projects. If you're a programmer looking for a new language, you want one that is growing in popularity. As a newcomer to programming, Python is the perfect choice for learning quickly and easily.

Prevent Sequelize from outputting SQL to the console on execution of query?

Here is my answer:

Brief: I was using typeorm as a ORM library. So, to set the query logging level I have used the following option instead of directly setting the logging option as false.

Solution: File name - ormconfig.ts

{
    'type': process.env.DB_DRIVER,
    'host': process.env.DB_HOST,
    'port': process.env.DB_PORT,
    'username': process.env.DB_USER,
    'password': process.env.DB_PASS,
    'database': process.env.DB_NAME,
    'migrations': [process.env.MIGRATIONS_ENTITIES],
    'synchronize': false,
    'logging': process.env.DB_QUERY_LEVEL,
    'entities': [
        process.env.ORM_ENTITIES
    ],
    'cli': {
        'migrationsDir': 'migrations'
     }
}

And, in the envrionment variable set the DB_QUERY_LEVEL as ["query", "error"].

Result: As a result it will log only when the query has error else it won't.

Ref link: typeorm db query logging doc

Hope this helps! Thanks.

Group by in LINQ

You can also Try this:

var results= persons.GroupBy(n => new { n.PersonId, n.car})
                .Select(g => new {
                               g.Key.PersonId,
                               g.Key.car)}).ToList();

How to use ArgumentCaptor for stubbing?

The line

when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);

would do the same as

when(someObject.doSomething(Matchers.any())).thenReturn(true);

So, using argumentCaptor.capture() when stubbing has no added value. Using Matchers.any() shows better what really happens and therefor is better for readability. With argumentCaptor.capture(), you can't read what arguments are really matched. And instead of using any(), you can use more specific matchers when you have more information (class of the expected argument), to improve your test.

And another problem: If using argumentCaptor.capture() when stubbing it becomes unclear how many values you should expect to be captured after verification. We want to capture a value during verification, not during stubbing because at that point there is no value to capture yet. So what does the argument captors capture method capture during stubbing? It capture anything because there is nothing to be captured yet. I consider it to be undefined behavior and I don't want to use undefined behavior.

Nginx - Customizing 404 page

You use the error_page property in the nginx config.

For example, if you intend to set the 404 error page to /404.html, use

error_page 404 /404.html;

Setting the 500 error page to /500.html is just as easy as:

error_page 500 /500.html;

how to set mongod --dbpath

Create a directory db in home, inside db another directory data

cd 
mkdir db
cd db
mkdir data

then type this command--

mongod --dbpath ~/db/data

Bootstrap 3.0: How to have text and input on same line?

In Bootstrap 4 for Horizontal element you can use .row with .col-*-* classes to specify the width of your labels and controls. see this link.

And if you want to display a series of labels, form controls, and buttons on a single horizontal row you can use .form-inline for more info this link

Invalid use side-effecting operator Insert within a function

There is an exception (I'm using SQL 2014) when you are only using Insert/Update/Delete on Declared-Tables. These Insert/Update/Delete statements cannot contain an OUTPUT statement. The other restriction is that you are not allowed to do a MERGE, even into a Declared-Table. I broke up my Merge statements, that didn't work, into Insert/Update/Delete statements that did work.

The reason I didn't convert it to a stored-procedure is that the table-function was faster (even without the MERGE) than the stored-procedure. This is despite the stored-procedure allowing me to use Temp-Tables that have statistics. I needed the table-function to be very fast, since it is called 20-K times/day. This table function never updates the database.

I also noticed that the NewId() and RAND() SQL functions are not allowed in a function.

Font size of TextView in Android application changes on changing font size from native settings

Override getResources() in Activity.

Set TextView's size in sp as usual like android:textSize="32sp"

override fun getResources(): Resources {
    return super.getResources().apply {
        configuration.fontScale = 1F
        updateConfiguration(configuration, displayMetrics)
    }
}

How do I connect to a Websphere Datasource with a given JNDI name?

For those like me, only needing information on how to connect to a (DB2) WAS Data Source from Java using JNDI lookup (Used IBM Websphere 8.5.5 & DB2 Universal JDBC Driver Provider with implementation class: com.ibm.db2.jcc.DB2ConnectionPoolDataSource):

public DataSource getJndiDataSource() throws NamingException {
    DataSource datasource = null;
    InitialContext context = new InitialContext();
    // Tomcat/Possibly others: java:comp/env/jdbc/myDatasourceJndiName
    datasource = (DataSource) context.lookup("jdbc/myDatasourceJndiName");
    return datasource;
}

Download Excel file via AJAX MVC

  $.ajax({
    global: false,
    url: SitePath + "/User/ExportTeamMembersInExcel",
    "data": { 'UserName': UserName, 'RoleId': RoleId, UserIds: AppraseeId },
    "type": "POST",
    "dataType": "JSON",
   "success": function (result) {
        debugger
        var bytes = new Uint8Array(result.FileContents);
        var blob = new Blob([bytes], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = "myFileName.xlsx";
        link.click();
      },
    "error": function () {
        alert("error");
    }
})


[HttpPost]
    public JsonResult ExportTeamMembersInExcel(string UserName, long? RoleId, string[] UserIds)
    {
        MemoryStream stream = new MemoryStream();
        FileContentResult robj;
        DataTable data = objuserservice.ExportTeamToExcel(UserName, RoleId, UserIds);
        using (XLWorkbook wb = new XLWorkbook())
        {
            wb.Worksheets.Add(data, "TeamMembers");
            using (stream)
            {
                wb.SaveAs(stream);
            }
        }
        robj = File(stream.ToArray(), System.Net.Mime.MediaTypeNames.Application.Octet, "TeamMembers.xlsx");
        return Json(robj, JsonRequestBehavior.AllowGet);
    }

Deep copy, shallow copy, clone

  • Deep copy: Clone this object and every reference to every other object it has
  • Shallow copy: Clone this object and keep its references
  • Object clone() throws CloneNotSupportedException: It is not specified whether this should return a deep or shallow copy, but at the very least: o.clone() != o

How to inject a Map using the @Value Spring Annotation?

I believe Spring Boot supports loading properties maps out of the box with @ConfigurationProperties annotation.

According that docs you can load properties:

my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com

into bean like this:

@ConfigurationProperties(prefix="my")
public class Config {

    private List<String> servers = new ArrayList<String>();

    public List<String> getServers() {
        return this.servers;
    }
}

I used @ConfigurationProperties feature before, but without loading into map. You need to use @EnableConfigurationProperties annotation to enable this feature.

Cool stuff about this feature is that you can validate your properties.

How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options

Explanation:

From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

TypeError: 'dict_keys' object does not support indexing

You're passing the result of somedict.keys() to the function. In Python 3, dict.keys doesn't return a list, but a set-like object that represents a view of the dictionary's keys and (being set-like) doesn't support indexing.

To fix the problem, use list(somedict.keys()) to collect the keys, and work with that.

GSON - Date format

As M.L. pointed out, JsonSerializer works here. However, if you are formatting database entities, use java.sql.Date to register you serializer. Deserializer is not needed.

Gson gson = new GsonBuilder()
   .registerTypeAdapter(java.sql.Date.class, ser).create();

This bug report might be related: http://code.google.com/p/google-gson/issues/detail?id=230. I use version 1.7.2 though.

Read lines from a text file but skip the first two lines

Open sFileName For Input As iFileNum

Dim LineNum As Long
LineNum = 0

Do While Not EOF(iFileNum)
  LineNum = LineNum + 1
  Line Input #iFileNum, Fields
  If LineNum > 2 Then
    DoStuffWith(Fields)
  End If
Loop

What is dynamic programming?

The key bits of dynamic programming are "overlapping sub-problems" and "optimal substructure". These properties of a problem mean that an optimal solution is composed of the optimal solutions to its sub-problems. For instance, shortest path problems exhibit optimal substructure. The shortest path from A to C is the shortest path from A to some node B followed by the shortest path from that node B to C.

In greater detail, to solve a shortest-path problem you will:

  • find the distances from the starting node to every node touching it (say from A to B and C)
  • find the distances from those nodes to the nodes touching them (from B to D and E, and from C to E and F)
  • we now know the shortest path from A to E: it is the shortest sum of A-x and x-E for some node x that we have visited (either B or C)
  • repeat this process until we reach the final destination node

Because we are working bottom-up, we already have solutions to the sub-problems when it comes time to use them, by memoizing them.

Remember, dynamic programming problems must have both overlapping sub-problems, and optimal substructure. Generating the Fibonacci sequence is not a dynamic programming problem; it utilizes memoization because it has overlapping sub-problems, but it does not have optimal substructure (because there is no optimization problem involved).

Jquery date picker z-index issue

Based in marksyzm answer, this worked for me:

$('input').datepicker({
    beforeShow:function(input) {
        $(input).css({
            "position": "relative",
            "z-index": 999999
        });
    }
});

How to extract an assembly from the GAC?

just navigate to C:\Windows find the [assembly] folder right click and select add to archive

wait a little

vola you have an archive file containing all the assemblies in your GAC

return results from a function (javascript, nodejs)

function routeToRoom(userId, passw, cb) {
    var roomId = 0;
    var nStore = require('nstore/lib/nstore').extend(require('nstore/lib/nstore/query')());
    var users = nStore.new('data/users.db', function() {
        users.find({
            user: userId,
            pass: passw
        }, function(err, results) {
            if (err) {
                roomId = -1;
            } else {
                roomId = results.creationix.room;
            }
            cb(roomId);
        });
    });
}
routeToRoom("alex", "123", function(id) {
    console.log(id);    
});

You need to use callbacks. That's how asynchronous IO works. Btw sys.puts is deprecated

A weighted version of random.choice

Since Python 3.6 there is a method choices from the random module.

Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.0.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import random

In [2]: random.choices(
...:     population=[['a','b'], ['b','a'], ['c','b']],
...:     weights=[0.2, 0.2, 0.6],
...:     k=10
...: )

Out[2]:
[['c', 'b'],
 ['c', 'b'],
 ['b', 'a'],
 ['c', 'b'],
 ['c', 'b'],
 ['b', 'a'],
 ['c', 'b'],
 ['b', 'a'],
 ['c', 'b'],
 ['c', 'b']]

Note that random.choices will sample with replacement, per the docs:

Return a k sized list of elements chosen from the population with replacement.

Note for completeness of answer:

When a sampling unit is drawn from a finite population and is returned to that population, after its characteristic(s) have been recorded, before the next unit is drawn, the sampling is said to be "with replacement". It basically means each element may be chosen more than once.

If you need to sample without replacement, then as @ronan-paixão's brilliant answer states, you can use numpy.choice, whose replace argument controls such behaviour.

Jquery asp.net Button Click Event via ajax

I found myself wanting to do this and I reviewed the above answers and did a hybrid approach of them. It got a little tricky, but here is what I did:

My button already worked with a server side post. I wanted to let that to continue to work so I left the "OnClick" the same, but added a OnClientClick:

OnClientClick="if (!OnClick_Submit()) return false;"

Here is my full button element in case it matters:

<asp:Button UseSubmitBehavior="false" runat="server" Class="ms-ButtonHeightWidth jiveSiteSettingsSubmit" OnClientClick="if (!OnClick_Submit()) return false;" OnClick="BtnSave_Click" Text="<%$Resources:wss,multipages_okbutton_text%>" id="BtnOK" accesskey="<%$Resources:wss,okbutton_accesskey%>" Enabled="true"/>

If I inspect the onclick attribute of the HTML button at runtime it actually looks like this:

if (!OnClick_Submit()) return false;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$PlaceHolderMain$ctl03$RptControls$BtnOK", "", true, "", "", false, true))

Then in my Javascript I added the OnClick_Submit method. In my case I needed to do a check to see if I needed to show a dialog to the user. If I show the dialog I return false causing the event to stop processing. If I don't show the dialog I return true causing the event to continue processing and my postback logic to run as it used to.

function OnClick_Submit() {
    var initiallyActive = initialState.socialized && initialState.activityEnabled;
    var socialized = IsSocialized();
    var enabled = ActivityStreamsEnabled();

    var displayDialog;

    // Omitted the setting of displayDialog for clarity

    if (displayDialog) {
        $("#myDialog").dialog('open');
        return false;
    }
    else {
        return true;
    }
}

Then in my Javascript code that runs when the dialog is accepted, I do the following depending on how the user interacted with the dialog:

$("#myDialog").dialog('close');
__doPostBack('message', '');

The "message" above is actually different based on what message I want to send.

But wait, there's more!

Back in my server-side code, I changed OnLoad from:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e)
    if (IsPostBack)
    {
        return;
    }

    // OnLoad logic removed for clarity
}

To:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e)
    if (IsPostBack)
    {
        switch (Request.Form["__EVENTTARGET"])
        {
            case "message1":
                // We did a __doPostBack with the "message1" command provided
                Page.Validate();
                BtnSave_Click(this, new CommandEventArgs("message1", null));
                break;

            case "message2":
                // We did a __doPostBack with the "message2" command provided
                Page.Validate();
                BtnSave_Click(this, new CommandEventArgs("message2", null));
                break;
            }
            return;
    }

    // OnLoad logic removed for clarity
}

Then in BtnSave_Click method I do the following:

CommandEventArgs commandEventArgs = e as CommandEventArgs;
string message = (commandEventArgs == null) ? null : commandEventArgs.CommandName;

And finally I can provide logic based on whether or not I have a message and based on the value of that message.

Foreach in a Foreach in MVC View

Try this:

It looks like you are looping for every product each time, now this is looping for each product that has the same category ID as the current category being looped

<div id="accordion1" style="text-align:justify">
@using (Html.BeginForm())
{
    foreach (var category in Model.Categories)
    {
        <h3><u>@category.Name</u></h3>

        <div>
            <ul>    
                @foreach (var product in Model.Product.Where(m=> m.CategoryID= category.CategoryID)
                {
                    <li>
                        @product.Title
                        @if (System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal("/admin", User, "GET"))
                        {
                            @Html.Raw(" - ")  
                            @Html.ActionLink("Edit", "Edit", new { id = product.ID })
                        }
                        <ul>
                            <li>
                                @product.Description
                            </li>
                        </ul>
                    </li>
                }
            </ul>
        </div>
    }
}  

$.ajax - dataType

as per docs:

  • "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
  • "text": A plain text string.

Most efficient way to check if a file is empty in Java on Windows

Why not just use:

File file = new File("test.txt");

if (file.length() == 0) {
    // file empty
} else {
    // not empty
}

Is there something wrong with it?

Select a random sample of results from a query result

This in not a perfect answer but will get much better performance.

SELECT  *
FROM    (
    SELECT  *
    FROM    mytable sample (0.01)
    ORDER BY
            dbms_random.value
    )
WHERE rownum <= 1000

Sample will give you a percent of your actual table, if you really wanted a 1000 rows you would need to adjust that number. More often I just need an arbitrary number of rows anyway so I don't limit my results. On my database with 2 million rows I get 2 seconds vs 60 seconds.

select * from mytable sample (0.01)

Postfix is installed but how do I test it?

To check whether postfix is running or not

sudo postfix status

If it is not running, start it.

sudo postfix start

Then telnet to localhost port 25 to test the email id

ehlo localhost
mail from: root@localhost
rcpt to: your_email_id
data
Subject: My first mail on Postfix

Hi,
Are you there?
regards,
Admin
.

Do not forget the . at the end, which indicates end of line

How do I install a custom font on an HTML site

Yes, you can use the CSS feature named @font-face. It has only been officially approved in CSS3, but been proposed and implemented in CSS2 and has been supported in IE for quite a long time.

You declare it in the CSS like this:

 @font-face { font-family: Delicious; src: url('Delicious-Roman.otf'); } 
 @font-face { font-family: Delicious; font-weight: bold; src: url('Delicious-Bold.otf');}

Then, you can just reference it like the other standard fonts:

 h3 { font-family: Delicious, sans-serif; }

So, in this case,

<html>
   <head>
    <style>
      @font-face { font-family: JuneBug; src: url('JUNEBUG.TTF'); } 
      h1 {
         font-family: JuneBug
      }
    </style>
   </head>
   <body>
      <h1>Hey, June</h1>
   </body>
</html>

And you just need to put the JUNEBUG.TFF in the same location as the html file.

I downloaded the font from the dafont.com website:

http://www.dafont.com/junebug.font

Select <a> which href ends with some string

Just in case you don't want to import a big library like jQuery to accomplish something this trivial, you can use the built-in method querySelectorAll instead. Almost all selector strings used for jQuery work with DOM methods as well:

const anchors = document.querySelectorAll('a[href$="ABC"]');

Or, if you know that there's only one matching element:

const anchor = document.querySelector('a[href$="ABC"]');

You may generally omit the quotes around the attribute value if the value you're searching for is alphanumeric, eg, here, you could also use

a[href$=ABC]

but quotes are more flexible and generally more reliable.

How to style SVG with external CSS?

@leo here is the angularJS version, thanks again

G.directive ( 'imgInlineSvg', function () {

return {
    restrict : 'C',
    scope : true,
    link : function ( scope, elem, attrs ) {

        if ( attrs.src ) {

            $ ( attrs ).each ( function () {
                var imgID    = attrs.class;
                var imgClass = attrs.class;
                var imgURL   = attrs.src;

                $.get ( imgURL, function ( data ) {

                    var $svg = $ ( data ).find ( 'svg' );
                    if ( typeof imgID !== 'undefined' ) {
                        $svg = $svg.attr ( 'id', imgID );
                    }

                    if ( typeof imgClass !== 'undefined' ) {
                        $svg = $svg.attr ( 'class', imgClass + ' replaced-svg' );
                    }

                    $svg = $svg.removeAttr ( 'xmlns:a' );

                    elem.replaceWith ( $svg );

                } );

            } );
        }

    }

}

} );

What do these three dots in React do?

... (three dots in Javascript) is called the Spread Syntax or Spread Operator. This allows an iterable such as an array expression or string to be expanded or an object expression to be expanded wherever placed. This is not specific to React. It is a Javascript operator.

All these answers here are helpful, but I want to list down the mostly used practical Use Cases of the Spread Syntax (Spread Operator).

1. Combine Arrays (Concatenate Arrays)

There are a variety of ways to combine arrays, but the spread operator allows you to place this at any place in an array. If you'd like to combine two arrays and place elements at any point within the array, you can do as follows:

var arr1 = ['two', 'three'];
var arr2 = ['one', ...arr1, 'four', 'five'];

// arr2 = ["one", "two", "three", "four", "five"]

2. Copying Arrays

When we wanted a copy of an array, we used to have the Array.prototypr.slice() method. But, you can do the same with the spread operator.

var arr = [1,2,3];
var arr2 = [...arr];
// arr2 = [1,2,3]

3. Calling Functions without Apply

In ES5, to pass an array of two numbers to the doStuff() function, you often use the Function.prototype.apply() method as follows:

function doStuff (x, y, z) { }
var args = [0, 1, 2];

// Call the function, passing args
doStuff.apply(null, args);

However, by using the spread operator, you can pass an array into the function.

doStuff(...args);

4. Destructuring Arrays

You can use destructuring and the rest operator together to extract the information into variables as you'd like them:

let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
console.log(x); // 1
console.log(y); // 2
console.log(z); // { a: 3, b: 4 }

5. Function Arguments as Rest Parameters

ES6 also has the three dots ( ...) which is a rest parameter that collects all remaining arguments of a function into an array.

function f(a, b, ...args) {
  console.log(args);
}

f(1,2,3,4,5);
// [ 3, 4, 5 ]

6. Using Math Functions

Any function where spread is used as the argument can be used by functions that can accept any number of arguments.

let numbers = [9, 4, 7, 1];
Math.min(...numbers); // 1

7. Combining Two Objects

You can use the spread operator to combine two objects. This is an easy and cleaner way to do it.

var carType = {
  model: 'Toyota',
  yom: '1995'
};

var carFuel = 'Petrol';

var carData = {
  ...carType,
  carFuel
}

console.log(carData); 
// {
//  model: 'Toyota',
//  yom: '1995',
//  carFuel = 'Petrol'
// }

8. Separate a String into Separate Characters

You can use the spread operator to spread a string into separate characters.

let chars = ['A', ...'BC', 'D'];
console.log(chars); // ["A", "B", "C", "D"]

You can think of more ways to use the Spread Operator. What I have listed here are the popular use cases of it.

Decode Hex String in Python 3

The answers from @unbeli and @Niklas are good, but @unbeli's answer does not work for all hex strings and it is desirable to do the decoding without importing an extra library (codecs). The following should work (but will not be very efficient for large strings):

>>> result = bytes.fromhex((lambda s: ("%s%s00" * (len(s)//2)) % tuple(s))('4a82fdfeff00')).decode('utf-16-le')
>>> result == '\x4a\x82\xfd\xfe\xff\x00'
True

Basically, it works around having invalid utf-8 bytes by padding with zeros and decoding as utf-16.

Nexus 5 USB driver

I just wanted to bring a small contribution, because I have been able to debug on my Nexus 5 device on Windows 8, without doing all of this.

When I plugged it, there was no yellow exclamation mark within the device manager. So for me, the drivers was OK. But the device was not listed within my eclipse ddms. After a little bit of searching, It was just an option to change in the device settings. By default, the Nexus 5 usb computer connection is in MTP mode (Media Device).

What you have to do is:

  1. Unplug the device from the computer
  2. Go to Settings -> Storage.
  3. In the ActionBar, click the option menu and choose "USB computer connection".
  4. Check "Camera (PTP)" connection.
  5. Plug the device and you should have a popup on the device allowing you to accept the computer's incoming connection, or something like that.
  6. Finally you should see it now in the ddms and voilà.

I hope this will help!

Do conditional INSERT with SQL?

If you're looking to do an "upsert" one of the most efficient ways currently in SQL Server for single rows is this:

UPDATE myTable ...


IF @@ROWCOUNT=0
    INSERT INTO myTable ....

You can also use the MERGE syntax if you're doing this with sets of data rather than single rows.

If you want to INSERT and not UPDATE then you can just write your single INSERT statement and use WHERE NOT EXISTS (SELECT ...)

How do I get the current time zone of MySQL?

My PHP framework uses

SET LOCAL time_zone='Whatever'

on after connect, where 'Whatever' == date_default_timezone_get()

Not my solution, but this ensures SYSTEM timezone of MySQL server is always the same as PHP's one

So, yes, PHP is strongly envolved and can affect it

403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied

Try this

 <allow  users="?" />

Now you are using <deny users="?" /> that means you are not allowing authenticated user to use your site.

authorization Element

Python: Writing to and Reading from serial port

a piece of code who work with python to read rs232 just in case somedoby else need it

ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()

Word wrap for a label in Windows Forms

If the dimensions of the button need to be kept unchanged:

myButton.Text = "word\r\nwrapped"

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `songs` where `id` = 5 limit 1)

protected $primaryKey = 'SongID';

After adding to my model to tell the primary key because it was taking id(SongID) by default

How can I drop all the tables in a PostgreSQL database?

You need to drop tables and sequences, here is what worked for me

psql -qAtX -c "select 'DROP TABLE IF EXISTS ' || quote_ident(table_schema) || '.' || quote_ident(table_name) || ' CASCADE;' FROM information_schema.tables where table_type = 'BASE TABLE' and not table_schema ~ '^(information_schema|pg_.*)$'" | psql -qAtX
psql -qAtX -c "select 'DROP SEQUENCE IF EXISTS ' || quote_ident(relname) || ' CASCADE;' from pg_statio_user_sequences;" | psql -qAtX

before you run the command you might need to sudo/su to the postgres user or (export connection details PGHOST, PGPORT, PGUSER and PGPASSWORD) and then export PGDATABASE=yourdatabase

Convert a CERT/PEM certificate to a PFX certificate

openssl pkcs12 -inkey bob_key.pem -in bob_cert.cert -export -out bob_pfx.pfx

How to use onClick with divs in React.js

Your box doesn't have a size. If you set the width and height, it works just fine:

_x000D_
_x000D_
var Box = React.createClass({_x000D_
    getInitialState: function() {_x000D_
        return {_x000D_
            color: 'black'_x000D_
        };_x000D_
    },_x000D_
_x000D_
    changeColor: function() {_x000D_
        var newColor = this.state.color == 'white' ? 'black' : 'white';_x000D_
        this.setState({_x000D_
            color: newColor_x000D_
        });_x000D_
    },_x000D_
_x000D_
    render: function() {_x000D_
        return (_x000D_
            <div>_x000D_
                <div_x000D_
                    style = {{_x000D_
                        background: this.state.color,_x000D_
                        width: 100,_x000D_
                        height: 100_x000D_
                    }}_x000D_
                    onClick = {this.changeColor}_x000D_
                >_x000D_
                </div>_x000D_
            </div>_x000D_
        );_x000D_
    }_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
  <Box />,_x000D_
  document.getElementById('box')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id='box'></div>
_x000D_
_x000D_
_x000D_

Shortcut to create properties in Visual Studio?

After typing "prop" + Tab + Tab as suggested by Amra, you can immediately type the property's type (which will replace the default int), type another tab and type the property name (which will replace the default MyProperty). Finish by pressing Enter.

Is there a "previous sibling" selector?

Consider the order property of flex and grid layouts.

I'll focus on flexbox in the examples below, but the same concepts apply to Grid.


With flexbox, a previous sibling selector can be simulated.

In particular, the flex order property can move elements around the screen.

Here's an example:

You want element A to turn red when element B is hovered.

<ul>
    <li>A</li>
    <li>B</li>
</ul>

STEPS

  1. Make the ul a flex container.

    ul { display: flex; }
    

  1. Reverse the order of siblings in the mark-up.

    <ul>
       <li>B</li>
       <li>A</li>
    </ul>
    

  1. Use a sibling selector to target Element A (~ or + will do) .

    li:hover + li { background-color: red; }
    

  1. Use the flex order property to restore the order of siblings on the visual display.

    li:last-child { order: -1; }
    

...and voilà! A previous sibling selector is born (or at least simulated).

Here's the full code:

_x000D_
_x000D_
ul {_x000D_
    display: flex;_x000D_
}_x000D_
_x000D_
li:hover + li {_x000D_
    background-color: red;_x000D_
}_x000D_
_x000D_
li:last-child {_x000D_
    order: -1;_x000D_
}_x000D_
_x000D_
/* non-essential decorative styles */_x000D_
li {_x000D_
    height: 200px;_x000D_
    width: 200px;_x000D_
    background-color: aqua;_x000D_
    margin: 5px;_x000D_
    list-style-type: none;_x000D_
    cursor: pointer;_x000D_
}
_x000D_
<ul>_x000D_
    <li>B</li>_x000D_
    <li>A</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

From the flexbox spec:

5.4. Display Order: the order property

Flex items are, by default, displayed and laid out in the same order as they appear in the source document. The order property can be used to change this ordering.

The order property controls the order in which flex items appear within the flex container, by assigning them to ordinal groups. It takes a single <integer> value, which specifies which ordinal group the flex item belongs to.

The initial order value for all flex items is 0.

Also see order in the CSS Grid Layout spec.


Examples of "previous sibling selectors" created with the flex order property.

_x000D_
_x000D_
.container { display: flex; }_x000D_
_x000D_
.box5 { order: 1; }    _x000D_
.box5:hover + .box4 { background-color: orangered; font-size: 1.5em; }_x000D_
_x000D_
.box6 { order: -4; }_x000D_
.box7 { order: -3; }_x000D_
.box8 { order: -2; }_x000D_
.box9 { order: -1; }_x000D_
.box9:hover ~ :not(.box12):nth-child(-1n+5) { background-color: orangered;_x000D_
                                              font-size: 1.5em; }_x000D_
.box12 { order: 2; }_x000D_
.box12:hover ~ :nth-last-child(-1n+2) { background-color: orangered;_x000D_
                                        font-size: 1.5em; }_x000D_
.box21 { order: 1; }_x000D_
.box21:hover ~ .box { background-color: orangered; font-size: 1.5em; }_x000D_
_x000D_
/* non-essential decorative styles */_x000D_
.container {_x000D_
    padding: 5px;_x000D_
    background-color: #888;_x000D_
}_x000D_
.box {_x000D_
    height: 50px;_x000D_
    width: 75px;_x000D_
    margin: 5px;_x000D_
    background-color: lightgreen;_x000D_
    display: flex;_x000D_
    justify-content: center;_x000D_
    align-items: center;_x000D_
    text-align: center;_x000D_
    cursor: pointer;_x000D_
}
_x000D_
<p>_x000D_
Using the flex <code>order</code> property to construct a previous sibling selector_x000D_
</p>_x000D_
_x000D_
<div class="container">_x000D_
    <div class="box box1"><span>1</span></div>_x000D_
    <div class="box box2"><span>2</span></div>_x000D_
    <div class="box box3"><span>3</span></div>_x000D_
    <div class="box box5"><span>HOVER ME</span></div>_x000D_
    <div class="box box4"><span>4</span></div>_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
_x000D_
<div class="container">_x000D_
    <div class="box box9"><span>HOVER ME</span></div>_x000D_
    <div class="box box12"><span>HOVER ME</span></div>_x000D_
    <div class="box box6"><span>6</span></div>_x000D_
    <div class="box box7"><span>7</span></div>_x000D_
    <div class="box box8"><span>8</span></div>_x000D_
    <div class="box box10"><span>10</span></div>_x000D_
    <div class="box box11"><span>11</span></div>_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
_x000D_
<div class="container">_x000D_
    <div class="box box21"><span>HOVER ME</span></div>_x000D_
    <div class="box box13"><span>13</span></div>_x000D_
    <div class="box box14"><span>14</span></div>_x000D_
    <div class="box box15"><span>15</span></div>_x000D_
    <div class="box box16"><span>16</span></div>_x000D_
    <div class="box box17"><span>17</span></div>_x000D_
    <div class="box box18"><span>18</span></div>_x000D_
    <div class="box box19"><span>19</span></div>_x000D_
    <div class="box box20"><span>20</span></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jsFiddle


A Side Note – Two Outdated Beliefs about CSS

Flexbox is shattering long-held beliefs about CSS.

One such belief is that a previous sibling selector is not possible in CSS.

To say this belief is widespread would be an understatement. Here's a sampling of related questions on Stack Overflow alone:

As described above, this belief is not entirely true. A previous sibling selector can be simulated in CSS using the flex order property.

The z-index Myth

Another long-standing belief has been that z-index works only on positioned elements.

In fact, the most current version of the spec – the W3C Editor's Draft – still asserts this to be true:

9.9.1 Specifying the stack level: the z-index property

z-index

  • Value: auto | | inherit
  • Initial: auto
  • Applies to: positioned elements
  • Inherited: no
  • Percentages: N/A
  • Media: visual
  • Computed value: as specified

(emphasis added)

In reality, however, this information is obsolete and inaccurate.

Elements that are flex items or grid items can create stacking contexts even when position is static.

4.3. Flex Item Z-Ordering

Flex items paint exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and z-index values other than auto create a stacking context even if position is static.

5.4. Z-axis Ordering: the z-index property

The painting order of grid items is exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and z-index values other than auto create a stacking context even if position is static.

Here's a demonstration of z-index working on non-positioned flex items: https://jsfiddle.net/m0wddwxs/

How to make --no-ri --no-rdoc the default for gem install?

Step by steps:

To create/edit the .gemrc file from the terminal:

vi  ~/.gemrc

You will open a editor called vi. paste in:

gem: --no-ri --no-rdoc

click 'esc'-button.

type in:

:exit

You can check if everything is correct with this command:

sudo /Applications/TextEdit.app/Contents/MacOS/TextEdit ~/.gemrc

Python "string_escape" vs "unicode_escape"

Within the range 0 = c < 128, yes the ' is the only difference for CPython 2.6.

>>> set(unichr(c).encode('unicode_escape') for c in range(128)) - set(chr(c).encode('string_escape') for c in range(128))
set(["'"])

Outside of this range the two types are not exchangeable.

>>> '\x80'.encode('string_escape')
'\\x80'
>>> '\x80'.encode('unicode_escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can’t decode byte 0x80 in position 0: ordinal not in range(128)

>>> u'1'.encode('unicode_escape')
'1'
>>> u'1'.encode('string_escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: escape_encode() argument 1 must be str, not unicode

On Python 3.x, the string_escape encoding no longer exists, since str can only store Unicode.

How do you convert a JavaScript date to UTC?

Looking at your question its clear that you just want to send the date range to your backend for further post processing.

I am assuming you are conforming to the standard data guidelines which expect the data to be in a particular format. For example, I use ODATA which is a RESTfull API which expects date time objects to be in the format:-

YYYY-MM-DDT00:00:00.

That can be easily achieved via the snippet posted below(Please change the format as per your requirement).

var mydate;//assuming this is my date object which I want to expose var UTCDateStr = mydate.getUTCFullYear() + "-" + mydate.getUTCMonth() + "-" + mydate.getUTCDate() + "T00:00:00";

If on the other hand, you are in my situation wherein you have received a date from your backend, and the browser converts that to your local date. You on the other hand are interested in the UTC date then you can perform the following:-

var mydate;//assuming this is my date object which I want to expose var UTCDate = new Date(mydate);/*create a copy of your date object. Only needed if you for some reason need the original local date*/ UTCDate.setTime(UTCDate.getTime() + UTCDate.getTimezoneOffset() * 60 * 1000);

The code snippet above basically adds/subtracts the time added/subtracted by the browser based on the timezone.

For example if I am in EST(GMT-5) and my Service returns a date time object = Wed Aug 17 2016 00:00:00 GMT-0500 my browser automatically subtracts the timezone offset(5hrs) to get my local time. So if I try to fetch the time I get Wed Aug 16 2016 19:00:00 GMT-0500. This causes a lot of problems. There are a lot of libraries out there which will definitely make this easier but I wanted to share the pure JS approach.

For more info please have a look at: http://praveenlobo.com/blog/how-to-convert-javascript-local-date-to-utc-and-utc-to-local-date/ where in I got my inspiration.

Hope this helps!

Binary Search Tree - Java Implementation

Here is my simple binary search tree implementation in Java SE 1.8:

public class BSTNode
{
    int data;
    BSTNode parent;
    BSTNode left;
    BSTNode right;

    public BSTNode(int data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
        this.parent = null;
    }

    public BSTNode()
    {
    }
}

public class BSTFunctions
{
    BSTNode ROOT;

    public BSTFunctions()
    {
        this.ROOT = null;
    }

    void insertNode(BSTNode node, int data)
    {
        if (node == null)
        {
            node = new BSTNode(data);
            ROOT = node;
        }
        else if (data < node.data && node.left == null)
        {
            node.left = new BSTNode(data);
            node.left.parent = node;
        }
        else if (data >= node.data && node.right == null)
        {
            node.right = new BSTNode(data);
            node.right.parent = node;
        }
        else
        {
            if (data < node.data)
            {
                insertNode(node.left, data);
            }
            else
            {
                insertNode(node.right, data);
            }
        }
    }

    public boolean search(BSTNode node, int data)
    {
        if (node == null)
        {
            return false;
        }
        else if (node.data == data)
        {
            return true;
        }
        else
        {
            if (data < node.data)
            {
                return search(node.left, data);
            }
            else
            {
                return search(node.right, data);
            }
        }
    }

    public void printInOrder(BSTNode node)
    {
        if (node != null)
        {
            printInOrder(node.left);
            System.out.print(node.data + " - ");
            printInOrder(node.right);
        }
    }

    public void printPostOrder(BSTNode node)
    {
        if (node != null)
        {
            printPostOrder(node.left);
            printPostOrder(node.right);
            System.out.print(node.data + " - ");
        }
    }

    public void printPreOrder(BSTNode node)
    {
        if (node != null)
        {
            System.out.print(node.data + " - ");
            printPreOrder(node.left);
            printPreOrder(node.right);
        }
    }

    public static void main(String[] args)
    {
        BSTFunctions f = new BSTFunctions();
        /**
         * Insert
         */
        f.insertNode(f.ROOT, 20);
        f.insertNode(f.ROOT, 5);
        f.insertNode(f.ROOT, 25);
        f.insertNode(f.ROOT, 3);
        f.insertNode(f.ROOT, 7);
        f.insertNode(f.ROOT, 27);
        f.insertNode(f.ROOT, 24);

        /**
         * Print
         */
        f.printInOrder(f.ROOT);
        System.out.println("");
        f.printPostOrder(f.ROOT);
        System.out.println("");
        f.printPreOrder(f.ROOT);
        System.out.println("");

        /**
         * Search
         */
        System.out.println(f.search(f.ROOT, 27) ? "Found" : "Not Found");
        System.out.println(f.search(f.ROOT, 10) ? "Found" : "Not Found");
    }
}

And the output is:

3 - 5 - 7 - 20 - 24 - 25 - 27 - 
3 - 7 - 5 - 24 - 27 - 25 - 20 - 
20 - 5 - 3 - 7 - 25 - 24 - 27 - 
Found
Not Found

Serializing enums with Jackson

In Spring Boot 2, the easiest way is to declare in your application.properties:

spring.jackson.serialization.WRITE_ENUMS_USING_TO_STRING=true
spring.jackson.deserialization.READ_ENUMS_USING_TO_STRING=true

and define the toString() method of your enums.

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug

For Windows Services using WCF, I ended the WFC host process and it worked. I hate it when this happens, and it happens randomly at times.

How to Update/Drop a Hive Partition?

in addition, you can drop multiple partitions from one statement (Dropping multiple partitions in Impala/Hive).

Extract from above link:

hive> alter table t drop if exists partition (p=1),partition (p=2),partition(p=3);
Dropped the partition p=1
Dropped the partition p=2
Dropped the partition p=3
OK

EDIT 1:

Also, you can drop bulk using a condition sign (>,<,<>), for example:

Alter table t 
drop partition (PART_COL>1);

How do I do pagination in ASP.NET MVC?

Well, what is the data source? Your action could take a few defaulted arguments, i.e.

ActionResult Search(string query, int startIndex, int pageSize) {...}

defaulted in the routes setup so that startIndex is 0 and pageSize is (say) 20:

        routes.MapRoute("Search", "Search/{query}/{startIndex}",
                        new
                        {
                            controller = "Home", action = "Search",
                            startIndex = 0, pageSize = 20
                        });

To split the feed, you can use LINQ quite easily:

var page = source.Skip(startIndex).Take(pageSize);

(or do a multiplication if you use "pageNumber" rather than "startIndex")

With LINQ-toSQL, EF, etc - this should "compose" down to the database, too.

You should then be able to use action-links to the next page (etc):

<%=Html.ActionLink("next page", "Search", new {
                query, startIndex = startIndex + pageSize, pageSize }) %>

'was not declared in this scope' error

You need to declare y and c outside the scope of the if/else statement. A variable is only valid inside the scope it is declared (and a scope is marked with { })

#include <iostream> 
using namespace std; 
//Using the Gaussian algorithm 
int dayofweek(int date, int month, int year ){ 
int d=date; 
int y, c;
if (month==1||month==2) 
        {y=((year-1)%100);c=(year-1)/100;} 
else 
        {y=year%100;c=year/100;} 
int m=(month+9)%12+1; 
int product=(d+(2.6*m-0.2)+y+y/4+c/4-2*c); 
return product%7; 
} 

int main(){ 
cout<<dayofweek(19,1,2054); 
return 0; 
} 

Is it possible only to declare a variable without assigning any value in Python?

It is a good question and unfortunately bad answers as var = None is already assigning a value, and if your script runs multiple times it is overwritten with None every time.

It is not the same as defining without assignment. I am still trying to figure out how to bypass this issue.

javascript, is there an isObject function like isArray?

You can use typeof operator.

if( (typeof A === "object" || typeof A === 'function') && (A !== null) )
{
    alert("A is object");
}

Note that because typeof new Number(1) === 'object' while typeof Number(1) === 'number'; the first syntax should be avoided.

How to convert a string to ASCII

For Any String try this:

string s = Console.ReadLine();
foreach( char c in s)
{
    Console.WriteLine(System.Convert.ToInt32(c));
}
Console.ReadKey();

SQL Server Service not available in service list after installation of SQL Server Management Studio

You need to start the SQL Server manually. Press

windows + R

type

sqlservermanager12.msc

right click ->Start

Service configuration does not display SQL Server?

Set folder browser dialog start location

Found on dotnet-snippets.de

With reflection this works and sets the real RootFolder!

using System;
using System.Reflection;
using System.Windows.Forms;

namespace YourNamespace
{
    public class RootFolderBrowserDialog
    {

        #region Public Properties

        /// <summary>
        ///   The description of the dialog.
        /// </summary>
        public string Description { get; set; } = "Chose folder...";

        /// <summary>
        ///   The ROOT path!
        /// </summary>
        public string RootPath { get; set; } = "";

        /// <summary>
        ///   The SelectedPath. Here is no initialization possible.
        /// </summary>
        public string SelectedPath { get; private set; } = "";

        #endregion Public Properties

        #region Public Methods

        /// <summary>
        ///   Shows the dialog...
        /// </summary>
        /// <returns>OK, if the user selected a folder or Cancel, if no folder is selected.</returns>
        public DialogResult ShowDialog()
        {
            var shellType = Type.GetTypeFromProgID("Shell.Application");
            var shell = Activator.CreateInstance(shellType);
            var folder = shellType.InvokeMember(
                             "BrowseForFolder", BindingFlags.InvokeMethod, null,
                             shell, new object[] { 0, Description, 0, RootPath, });
            if (folder is null)
            {
                return DialogResult.Cancel;
            }
            else
            {
                var folderSelf = folder.GetType().InvokeMember(
                                     "Self", BindingFlags.GetProperty, null,
                                     folder, null);
                SelectedPath = folderSelf.GetType().InvokeMember(
                                   "Path", BindingFlags.GetProperty, null,
                                   folderSelf, null) as string;
                // maybe ensure that SelectedPath is set
                return DialogResult.OK;
            }
        }

        #endregion Public Methods

    }
}

Where does Git store files?

It will create your repository in the .git folder in the current directory.

How to enable Ad Hoc Distributed Queries

The following command may help you..

EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO

VB.Net: Dynamically Select Image from My.Resources

Sometimes you must change the name (or check to get it automatically from compiler).

Example:

Filename = amp2-rot.png

It is not working as:

PictureBoxName.Image = resources.GetObject("amp2-rot.png")

It works, just as amp2_rot for me:

 PictureBox_L1.Image = My.Resources.Resource.amp2_rot

How do you determine the size of a file in C?

Matt's solution should work, except that it's C++ instead of C, and the initial tell shouldn't be necessary.

unsigned long fsize(char* file)
{
    FILE * f = fopen(file, "r");
    fseek(f, 0, SEEK_END);
    unsigned long len = (unsigned long)ftell(f);
    fclose(f);
    return len;
}

Fixed your brace for you, too. ;)

Update: This isn't really the best solution. It's limited to 4GB files on Windows and it's likely slower than just using a platform-specific call like GetFileSizeEx or stat64.

How to replace a character with a newline in Emacs?

Switch to text-mode

M-x text-mode

Highlight block to indent

Indent

C+M \

Switch back to whatever mode..

How to print matched regex pattern using awk?

If you know what column the text/pattern you're looking for (e.g. "yyy") is in, you can just check that specific column to see if it matches, and print it.

For example, given a file with the following contents, (called asdf.txt)

xxx yyy zzz

to only print the second column if it matches the pattern "yyy", you could do something like this:

awk '$2 ~ /yyy/ {print $2}' asdf.txt

Note that this will also match basically any line where the second column has a "yyy" in it, like these:

xxx yyyz zzz
xxx zyyyz

Remove useless zero digits from decimals in PHP

you could just use the floatval function

echo floatval('125.00');
// 125

echo floatval('966.70');
// 966.7

echo floatval('844.011');
// 844.011

Email Address Validation in Android on EditText

Try this:

if (!emailRegistration.matches("[a-zA-Z0-9._-]+@[a-z]+\.[a-z]+")) {
 editTextEmail.setError("Invalid Email Address");
}

A top-like utility for monitoring CUDA activity on a GPU

You can use the monitoring program glances with its GPU monitoring plug-in:

  • open source
  • to install: sudo apt-get install -y python-pip; sudo pip install glances[gpu]
  • to launch: sudo glances

enter image description here

It also monitors the CPU, disk IO, disk space, network, and a few other things:

enter image description here

Stash just a single file

Just in case you actually mean 'discard changes' whenever you use 'git stash' (and don't really use git stash to stash it temporarily), in that case you can use

git checkout -- <file>

Note that git stash is just a quicker and simple alternative to branching and doing stuff.

How Can I Truncate A String In jQuery?

From: jQuery text truncation (read more style)

Try this:

var title = "This is your title";

var shortText = jQuery.trim(title).substring(0, 10)
    .split(" ").slice(0, -1).join(" ") + "...";

And you can also use a plugin:

As a extension of String

String.prototype.trimToLength = function(m) {
  return (this.length > m) 
    ? jQuery.trim(this).substring(0, m).split(" ").slice(0, -1).join(" ") + "..."
    : this;
};

Use as

"This is your title".trimToLength(10);

Displaying one div on top of another

There are many ways to do it, but this is pretty simple and avoids issues with disrupting inline content positioning. You might need to adjust for margins/padding, too.

#backdrop, #curtain {
  height: 100px;
  width: 200px;
}

#curtain {
  position: relative;
  top: -100px;
}

Make browser window blink in task Bar

Why not take the approach that GMail uses and show the number of messages in the page title?

Sometimes users don't want to be distracted when a new message arrives.

Can I have two JavaScript onclick events in one element?

The HTML

<a href="#" id="btn">click</a>

And the javascript

// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
    if (window.addEventListener) {
        return function(target, type, listener){
            target.addEventListener(type, listener, false);
        };
    }
    else {
        return function(object, sEvent, fpNotify){
            object.attachEvent("on" + sEvent, fpNotify);
        };
    }
}());

// find the element
var el = document.getElementById("btn");

// add the first listener
on(el, "click", function(){
    alert("foo");
});

// add the second listener
on(el, "click", function(){
    alert("bar");
});

This will alert both 'foo' and 'bar' when clicked.

How to open mail app from Swift

I'm not sure if you want to switch to the mail app itself or just open and send an email. For the latter option linked to a button IBAction:

    import UIKit
    import MessageUI

    class ViewController: UIViewController, MFMailComposeViewControllerDelegate {

    @IBAction func launchEmail(sender: AnyObject) {

    var emailTitle = "Feedback"
    var messageBody = "Feature request or bug report?"
    var toRecipents = ["[email protected]"]
    var mc: MFMailComposeViewController = MFMailComposeViewController()
    mc.mailComposeDelegate = self
    mc.setSubject(emailTitle)
    mc.setMessageBody(messageBody, isHTML: false)
    mc.setToRecipients(toRecipents)

    self.presentViewController(mc, animated: true, completion: nil)
    }

    func mailComposeController(controller:MFMailComposeViewController, didFinishWithResult result:MFMailComposeResult, error:NSError) {
        switch result {
        case MFMailComposeResultCancelled:
            print("Mail cancelled")
        case MFMailComposeResultSaved:
            print("Mail saved")
        case MFMailComposeResultSent:
            print("Mail sent")
        case MFMailComposeResultFailed:
            print("Mail sent failure: \(error?.localizedDescription)")
        default:
            break
        }
        self.dismissViewControllerAnimated(true, completion: nil)
    }

    }

How to change letter spacing in a Textview?

This answer is based on Pedro's answer but adjusted so it also works if text attribute is already set:

package nl.raakict.android.spc.widget;
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ScaleXSpan;
import android.util.AttributeSet;
import android.widget.TextView;


public class LetterSpacingTextView extends TextView {
    private float letterSpacing = LetterSpacing.BIGGEST;
    private CharSequence originalText = "";


    public LetterSpacingTextView(Context context) {
        super(context);
    }

    public LetterSpacingTextView(Context context, AttributeSet attrs){
        super(context, attrs);
        originalText = super.getText();
        applyLetterSpacing();
        this.invalidate();
    }

    public LetterSpacingTextView(Context context, AttributeSet attrs, int defStyle){
        super(context, attrs, defStyle);
    }

    public float getLetterSpacing() {
        return letterSpacing;
    }

    public void setLetterSpacing(float letterSpacing) {
        this.letterSpacing = letterSpacing;
        applyLetterSpacing();
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        originalText = text;
        applyLetterSpacing();
    }

    @Override
    public CharSequence getText() {
        return originalText;
    }

    private void applyLetterSpacing() {
        if (this == null || this.originalText == null) return;
        StringBuilder builder = new StringBuilder();
        for(int i = 0; i < originalText.length(); i++) {
            String c = ""+ originalText.charAt(i);
            builder.append(c.toLowerCase());
            if(i+1 < originalText.length()) {
                builder.append("\u00A0");
            }
        }
        SpannableString finalText = new SpannableString(builder.toString());
        if(builder.toString().length() > 1) {
            for(int i = 1; i < builder.toString().length(); i+=2) {
                finalText.setSpan(new ScaleXSpan((letterSpacing+1)/10), i, i+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        super.setText(finalText, BufferType.SPANNABLE);
    }

    public class LetterSpacing {
        public final static float NORMAL = 0;
        public final static float NORMALBIG = (float)0.025;
        public final static float BIG = (float)0.05;
        public final static float BIGGEST = (float)0.2;
    }
}

If you want to use it programatically:

LetterSpacingTextView textView = new LetterSpacingTextView(context);
textView.setSpacing(10); //Or any float. To reset to normal, use 0 or LetterSpacingTextView.Spacing.NORMAL
textView.setText("My text");
//Add the textView in a layout, for instance:
((LinearLayout) findViewById(R.id.myLinearLayout)).addView(textView);

Equivalent of typedef in C#

Here is the code for it, enjoy!, I picked that up from the dotNetReference type the "using" statement inside the namespace line 106 http://referencesource.microsoft.com/#mscorlib/microsoft/win32/win32native.cs

using System;
using System.Collections.Generic;
namespace UsingStatement
{
    using Typedeffed = System.Int32;
    using TypeDeffed2 = List<string>;
    class Program
    {
        static void Main(string[] args)
        {
        Typedeffed numericVal = 5;
        Console.WriteLine(numericVal++);

        TypeDeffed2 things = new TypeDeffed2 { "whatever"};
        }
    }
}

How to run Rake tasks from within Rake tasks?

If you need the task to behave as a method, how about using an actual method?

task :build => [:some_other_tasks] do
  build
end

task :build_all do
  [:debug, :release].each { |t| build t }
end

def build(type = :debug)
  # ...
end

If you'd rather stick to rake's idioms, here are your possibilities, compiled from past answers:

  • This always executes the task, but it doesn't execute its dependencies:

    Rake::Task["build"].execute
    
  • This one executes the dependencies, but it only executes the task if it has not already been invoked:

    Rake::Task["build"].invoke
    
  • This first resets the task's already_invoked state, allowing the task to then be executed again, dependencies and all:

    Rake::Task["build"].reenable
    Rake::Task["build"].invoke
    
  • Note that dependencies already invoked are not automatically re-executed unless they are re-enabled. In Rake >= 10.3.2, you can use the following to re-enable those as well:

    Rake::Task["build"].all_prerequisite_tasks.each(&:reenable)
    

How do I implement Toastr JS?

Add CDN Files of toastr.css and toastr.js

<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/css/toastr.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/js/toastr.js"></script>

function toasterOptions() {
    toastr.options = {
        "closeButton": false,
        "debug": false,
        "newestOnTop": false,
        "progressBar": true,
        "positionClass": "toast-top-center",
        "preventDuplicates": true,
        "onclick": null,
        "showDuration": "100",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "show",
        "hideMethod": "hide"
    };
};


toasterOptions();
toastr.error("Error Message from toastr");

Best way to test if a row exists in a MySQL table

Or you can insert raw sql part to conditions so I have 'conditions'=>array('Member.id NOT IN (SELECT Membership.member_id FROM memberships AS Membership)')

All possible array initialization syntaxes

Just a note

The following arrays:

string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = { "A" , "B" };
string[] array4 = new[] { "A", "B" };

Will be compiled to:

string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = new string[] { "A", "B" };
string[] array4 = new string[] { "A", "B" };

Monad in plain English? (For the OOP programmer with no FP background)

I'll try to make the shortest definition I can manage using OOP terms:

A generic class CMonadic<T> is a monad if it defines at least the following methods:

class CMonadic<T> { 
    static CMonadic<T> create(T t);  // a.k.a., "return" in Haskell
    public CMonadic<U> flatMap<U>(Func<T, CMonadic<U>> f); // a.k.a. "bind" in Haskell
}

and if the following laws apply for all types T and their possible values t

left identity:

CMonadic<T>.create(t).flatMap(f) == f(t)

right identity

instance.flatMap(CMonadic<T>.create) == instance

associativity:

instance.flatMap(f).flatMap(g) == instance.flatMap(t => f(t).flatMap(g))

Examples:

A List monad may have:

List<int>.create(1) --> [1]

And flatMap on the list [1,2,3] could work like so:

intList.flatMap(x => List<int>.makeFromTwoItems(x, x*10)) --> [1,10,2,20,3,30]

Iterables and Observables can also be made monadic, as well as Promises and Tasks.

Commentary:

Monads are not that complicated. The flatMap function is a lot like the more commonly encountered map. It receives a function argument (also known as delegate), which it may call (immediately or later, zero or more times) with a value coming from the generic class. It expects that passed function to also wrap its return value in the same kind of generic class. To help with that, it provides create, a constructor that can create an instance of that generic class from a value. The return result of flatMap is also a generic class of the same type, often packing the same values that were contained in the return results of one or more applications of flatMap to the previously contained values. This allows you to chain flatMap as much as you want:

intList.flatMap(x => List<int>.makeFromTwo(x, x*10))
       .flatMap(x => x % 3 == 0 
                   ? List<string>.create("x = " + x.toString()) 
                   : List<string>.empty())

It just so happens that this kind of generic class is useful as a base model for a huge number of things. This (together with the category theory jargonisms) is the reason why Monads seem so hard to understand or explain. They're a very abstract thing and only become obviously useful once they're specialized.

For example, you can model exceptions using monadic containers. Each container will either contain the result of the operation or the error that has occured. The next function (delegate) in the chain of flatMap callbacks will only be called if the previous one packed a value in the container. Otherwise if an error was packed, the error will continue to propagate through the chained containers until a container is found that has an error handler function attached via a method called .orElse() (such a method would be an allowed extension)

Notes: Functional languages allow you to write functions that can operate on any kind of a monadic generic class. For this to work, one would have to write a generic interface for monads. I don't know if its possible to write such an interface in C#, but as far as I know it isn't:

interface IMonad<T> { 
    static IMonad<T> create(T t); // not allowed
    public IMonad<U> flatMap<U>(Func<T, IMonad<U>> f); // not specific enough,
    // because the function must return the same kind of monad, not just any monad
}

Calling an executable program using awk

It really depends :) One of the handy linux core utils (info coreutils) is xargs. If you are using awk you probably have a more involved use-case in mind - your question is not very detailled.

printf "1 2\n3 4" | awk '{ print $2 }' | xargs touch

Will execute touch 2 4. Here touch could be replaced by your program. More info at info xargs and man xargs (really, read these). I believe you would like to replace touch with your program.

Breakdown of beforementioned script:

printf "1 2\n3 4"
# Output:
1 2
3 4

# The pipe (|) makes the output of the left command the input of
# the right command (simplified)
printf "1 2\n3 4" | awk '{ print $2 }'
# Output (of the awk command):
2
4

# xargs will execute a command with arguments. The arguments
# are made up taking the input to xargs (in this case the output
# of the awk command, which is "2 4".
printf "1 2\n3 4" | awk '{ print $2 }' | xargs touch
# No output, but executes: `touch 2 4` which will create (or update
# timestamp if the files already exist) files with the name "2" and "4"

Update In the original answer, I used echo instead of printf. However, printf is the better and more portable alternative as was pointed out by a comment (where great links with discussions can be found).

Why am I getting the message, "fatal: This operation must be run in a work tree?"

Just in case what happened to me is happening to somebody else, I need to say this:
I was in my .git directory within my project when I was getting this error.
I searched and scoured for answers, but nothing worked.
All I had to do was get back to the right directory ( cd .. ).
It was kind of a face-palm moment for me.
In case there's anyone else out there as silly as me, I hope you found this answer helpful.

ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"

Your program does not know what precision for decimal numbers to use so it throws:

java.lang.ArithmeticException: Non-terminating decimal expansion

Solution to bypass exception:

MathContext precision = new MathContext(int setPrecisionYouWant); // example 2
BigDecimal a = new BigDecimal("1.6",precision);
BigDecimal b = new BigDecimal("9.2",precision);
a.divide(b) // result = 0.17

How to call a Python function from Node.js

Easiest way I know of is to use "child_process" package which comes packaged with node.

Then you can do something like:

const spawn = require("child_process").spawn;
const pythonProcess = spawn('python',["path/to/script.py", arg1, arg2, ...]);

Then all you have to do is make sure that you import sys in your python script, and then you can access arg1 using sys.argv[1], arg2 using sys.argv[2], and so on.

To send data back to node just do the following in the python script:

print(dataToSendBack)
sys.stdout.flush()

And then node can listen for data using:

pythonProcess.stdout.on('data', (data) => {
    // Do something with the data returned from python script
});

Since this allows multiple arguments to be passed to a script using spawn, you can restructure a python script so that one of the arguments decides which function to call, and the other argument gets passed to that function, etc.

Hope this was clear. Let me know if something needs clarification.

how to convert a string date to date format in oracle10g

You can convert a string to a DATE using the TO_DATE function, then reformat the date as another string using TO_CHAR, i.e.:

SELECT TO_CHAR(
         TO_DATE('15/August/2009,4:30 PM'
                ,'DD/Month/YYYY,HH:MI AM')
       ,'DD-MM-YYYY')
FROM DUAL;

15-08-2009

For example, if your table name is MYTABLE and the varchar2 column is MYDATESTRING:

SELECT TO_CHAR(
         TO_DATE(MYDATESTRING
                ,'DD/Month/YYYY,HH:MI AM')
       ,'DD-MM-YYYY')
FROM MYTABLE;

Returning binary file from controller in ASP.NET Web API

You can try the following code snippet

httpResponseMessage.Content.Headers.Add("Content-Type", "application/octet-stream");

Hope it will work for you.

How to convert text column to datetime in SQL

In SQL Server , cast text as datetime

select cast('5/21/2013 9:45:48' as datetime)

What is the "realm" in basic authentication

A realm can be seen as an area (not a particular page, it could be a group of pages) for which the credentials are used; this is also the string that will be shown when the browser pops up the login window, e.g.

Please enter your username and password for <realm name>:

When the realm changes, the browser may show another popup window if it doesn't have credentials for that particular realm.

"unrecognized selector sent to instance" error in Objective-C

Basics: Dynamic Invocation

The objective C is a dynamic language which invokes methods by looking at runtime for methods in classes. For example, if there is Class A including method DoSomething(arg1, arg2). If you try to call the method using correct arguments on an object of Class A everything will work fine. However, if the arguments are not passes properly, for example, you called the method with one argument only then the the run-time will treat this as a method call for a different method. Eventually, run-time will fail to find the method (DoSomething with one argument) and will through this exception "unrecognized selector sent to instance".

Solution

Please check what signature for @selector is expected. Usually it is, as you described in the code

-(IBAction)numberButtonClick:(id)sender{

How to get all files under a specific directory in MATLAB?

With little modification but almost similar approach to get the full file path of each sub folder

dataFolderPath = 'UCR_TS_Archive_2015/';

dirData = dir(dataFolderPath);      %# Get the data for the current directory
dirIndex = [dirData.isdir];  %# Find the index for directories
fileList = {dirData(~dirIndex).name}';  %'# Get a list of the files
if ~isempty(fileList)
    fileList = cellfun(@(x) fullfile(dataFolderPath,x),...  %# Prepend path to files
        fileList,'UniformOutput',false);
end
subDirs = {dirData(dirIndex).name};  %# Get a list of the subdirectories
validIndex = ~ismember(subDirs,{'.','..'});  %# Find index of subdirectories
%#   that are not '.' or '..'
for iDir = find(validIndex)                  %# Loop over valid subdirectories
    nextDir = fullfile(dataFolderPath,subDirs{iDir});    %# Get the subdirectory path
    getAllFiles = dir(nextDir);
    for k = 1:1:size(getAllFiles,1)
        validFileIndex = ~ismember(getAllFiles(k,1).name,{'.','..'});
        if(validFileIndex)
            filePathComplete = fullfile(nextDir,getAllFiles(k,1).name);
            fprintf('The Complete File Path: %s\n', filePathComplete);
        end
    end
end  

How to convert a color integer to a hex String in Android?

With this method Integer.toHexString, you can have an Unknown color exception for some colors when using Color.parseColor.

And with this method String.format("#%06X", (0xFFFFFF & intColor)), you'll lose alpha value.

So I recommend this method:

public static String ColorToHex(int color) {
        int alpha = android.graphics.Color.alpha(color);
        int blue = android.graphics.Color.blue(color);
        int green = android.graphics.Color.green(color);
        int red = android.graphics.Color.red(color);

        String alphaHex = To00Hex(alpha);
        String blueHex = To00Hex(blue);
        String greenHex = To00Hex(green);
        String redHex = To00Hex(red);

        // hexBinary value: aabbggrr
        StringBuilder str = new StringBuilder("#");
        str.append(alphaHex);
        str.append(blueHex);
        str.append(greenHex);
        str.append(redHex );

        return str.toString();
    }

    private static String To00Hex(int value) {
        String hex = "00".concat(Integer.toHexString(value));
        return hex.substring(hex.length()-2, hex.length());
    }

Remove json element

For those of you who came here looking for how to remove an object from a JSON array based on object value:

_x000D_
_x000D_
let users = [{"name": "Ben"},{"name": "Tim"},{"name": "Harry"}];

 for (let [i, user] of users.entries()) {
    if (user.name == "Tim") {
        users.splice(i, 1);
    }
 }
_x000D_
_x000D_
_x000D_

User Tim is now removed from JSON array users.

Bash script to cd to directory with spaces in pathname

I found the solution below on this page:

x="test\ me"  
eval cd $x

A combination of \ in a double-quoted text constant and an eval before cd makes it work like a charm!

When is it appropriate to use UDP instead of TCP?

UDP does have less overhead and is good for doing things like streaming real time data like audio or video, or in any case where it is ok if data is lost.

How to drop columns by name in a data frame

You can also try the dplyr package:

R> df <- data.frame(x=1:5, y=2:6, z=3:7, u=4:8)
R> df
  x y z u
1 1 2 3 4
2 2 3 4 5
3 3 4 5 6
4 4 5 6 7
5 5 6 7 8
R> library(dplyr)
R> dplyr::select(df2, -c(x, y))  # remove columns x and y
  z u
1 3 4
2 4 5
3 5 6
4 6 7
5 7 8

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

Got this from a network filter (LuLu on macOS) blocking traffic to/from Docker-related processes.

PDO get the last ID inserted

You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).

Like this $lid = $conn->lastInsertId();

Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php

In android how to set navigation drawer header image and name programmatically in class file?

As mentioned in the bug 190226, Since version 23.1.0 getting header layout view with: navigationView.findViewById(R.id.navigation_header_text) no longer works.

A workaround is to inflate the headerview programatically and find view by ID from the inflated header view.

For example:

View headerView = navigationView.inflateHeaderView(R.layout.navigation_header);
headerView.findViewById(R.id.navigation_header_text);

Ideally there should be a method getHeaderView() but it has already been proposed, let's see and wait for it to be released in the feature release of design support library.

Check if file is already open

I don't think you'll ever get a definitive solution for this, the operating system isn't necessarily going to tell you if the file is open or not.

You might get some mileage out of java.nio.channels.FileLock, although the javadoc is loaded with caveats.

System.Drawing.Image to stream C#

public static Stream ToStream(this Image image)
{
     var stream = new MemoryStream();

     image.Save(stream, image.RawFormat);
     stream.Position = 0;

     return stream;
 }

jQuery bind to Paste Event, how to get the content of the paste

How about this: http://jsfiddle.net/5bNx4/

Please use .on if you are using jq1.7 et al.

Behaviour: When you type anything or paste anything on the 1st textarea the teaxtarea below captures the cahnge.

Rest I hope it helps the cause. :)

Helpful link =>

How do you handle oncut, oncopy, and onpaste in jQuery?

Catch paste input

code

$(document).ready(function() {
    var $editor    = $('#editor');
    var $clipboard = $('<textarea />').insertAfter($editor);

    if(!document.execCommand('StyleWithCSS', false, false)) {
        document.execCommand('UseCSS', false, true);
    }

    $editor.on('paste, keydown', function() {
        var $self = $(this);            
        setTimeout(function(){ 
            var $content = $self.html();             
            $clipboard.val($content);
        },100);
     });
});

Using the value in a cell as a cell reference in a formula?

Use INDIRECT()

=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))

How to avoid 'cannot read property of undefined' errors?

What you are doing raises an exception (and rightfully so).

You can always do

try{
   window.a.b.c
}catch(e){
   console.log("YO",e)
}

But I wouldn't, instead think of your use case.

Why are you accessing data, 6 levels nested that you are unfamiliar of? What use case justifies this?

Usually, you'd like to actually validate what sort of object you're dealing with.

Also, on a side note you should not use statements like if(a.b) because it will return false if a.b is 0 or even if it is "0". Instead check if a.b !== undefined

What is the difference between print and puts?

puts call the to_s of each argument and adds a new line to each string, if it does not end with new line. print just output each argument by calling their to_s.

for example: puts "one two": one two

{new line}

puts "one two\n": one two

{new line} #puts will not add a new line to the result, since the string ends with a new line

print "one two": one two

print "one two\n": one two

{new line}

And there is another way to output: p

For each object, directly writes obj.inspect followed by a newline to the program’s standard output.

It is helpful to output debugging message. p "aa\n\t": aa\n\t

Multiline string literal in C#

The problem with using string literal I find is that it can make your code look a bit "weird" because in order to not get spaces in the string itself, it has to be completely left aligned:

    var someString = @"The
quick
brown
fox...";

Yuck.

So the solution I like to use, which keeps everything nicely aligned with the rest of your code is:

var someString = String.Join(
    Environment.NewLine,
    "The",
    "quick",
    "brown",
    "fox...");

And of course, if you just want to logically split up lines of an SQL statement like you are and don't actually need a new line, you can always just substitute Environment.NewLine for " ".

Fit image to table cell [Pure HTML]

It's all about display: block :)

Updated:

Ok so you have the table, tr and td tags:

<table>
  <tr>
    <td>
      <!-- your image goes here -->
    </td>
  </tr>
</table>

Lets say your table or td (whatever define your width) has property width: 360px;. Now, when you try to replace the html comment with the actual image and set that image property for example width: 100%; which should fully fill out the td cell you will face the problem.

The problem is that your table cell (td) isn't properly filled with the image. You'll notice the space at the bottom of the cell which your image doesn't cover (it's like 5px of padding).

How to solve this in a simpliest way?

You are working with the tables, right? You just need to add the display property to your image so that it has the following:

img {
  width: 100%;
  display: block;
}

making a paragraph in html contain a text from a file

I would use javascript for this.

var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://my.remote.url/myremotefile.txt", true);
txtFile.onreadystatechange = function() {
  if (txtFile.readyState === 4 && txtFile.status == 200) {
     allText = txtFile.responseText;
  }
document.getElementById('your div id').innerHTML = allText;

This is just a code sample, would need tweaking for all browsers, etc.

How to convert base64 string to image?

Return converted image without saving:

from PIL import Image
import cv2

# Take in base64 string and return cv image
def stringToRGB(base64_string):
    imgdata = base64.b64decode(str(base64_string))
    image = Image.open(io.BytesIO(imgdata))
    return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)

How to quickly check if folder is empty (.NET)?

Since you are going to work with a DirectoryInfo object anyway, I'd go with an extension

public static bool IsEmpty(this DirectoryInfo directoryInfo)
{
    return directoryInfo.GetFileSystemInfos().Count() == 0;
}

Sort a single String in Java

Convert to array of chars ? Sort ? Convert back to String:

String s = "edcba";
char[] c = s.toCharArray();        // convert to array of chars 
java.util.Arrays.sort(c);          // sort
String newString = new String(c);  // convert back to String
System.out.println(newString);     // "abcde"

Put quotes around a variable string in JavaScript

I think, the best and easy way for you, to put value inside quotes is:

JSON.stringify(variable or value)

How to get all options in a drop-down list by Selenium WebDriver using C#?

To get all the dropdown values you can use List.

List<string> lstDropDownValues = new List<string>();
int iValuescount = driver.FindElement(By.Xpath("\html\....\select\option"))

for(int ivalue = 1;ivalue<=iValuescount;ivalue++)
 {
  string strValue = driver.FindElement(By.Xpath("\html\....\select\option["+ ivalue +"]"));
  lstDropDownValues.Add(strValue); 
 }

How do you write a migration to rename an ActiveRecord model and its table in Rails?

Here's an example:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def self.up
    rename_table :old_table_name, :new_table_name
  end

  def self.down
    rename_table :new_table_name, :old_table_name
  end
end

I had to go and rename the model declaration file manually.

Edit:

In Rails 3.1 & 4, ActiveRecord::Migration::CommandRecorder knows how to reverse rename_table migrations, so you can do this:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def change
    rename_table :old_table_name, :new_table_name
  end 
end

(You still have to go through and manually rename your files.)

How to take complete backup of mysql database using mysqldump command line utility

On MySQL 5.7 its work for me, I'm using CentOS7.

For taking Dump.

Command :

mysqldump -u user_name -p database_name -R -E > file_name.sql

Exemple :

mysqldump -u root -p mr_sbc_clean -R -E > mr_sbc_clean_dump.sql

For deploying Dump.

Command :

mysql -u user_name -p database_name < file_name.sql

Exemple :

mysql -u root -p mr_sbc_clean_new < mr_sbc_clean_dump.sql

Changing Underline color

There's now a new css3 property for this: text-decoration-color

So you can now have text in one color and a text-decoration underline - in a different color... without needing an extra 'wrap' element

_x000D_
_x000D_
p {_x000D_
  text-decoration: underline;_x000D_
  -webkit-text-decoration-color: red; /* safari still uses vendor prefix */_x000D_
  text-decoration-color: red;_x000D_
}
_x000D_
<p>black text with red underline in one element - no wrapper elements here!</p>
_x000D_
_x000D_
_x000D_

Codepen

NB:

1) Browser Support is limited at the moment to Firefox and Chrome (fully supported as of V57) and Safari

2) You could also use the text-decoration shorthand property which looks like this:

<text-decoration-line> || <text-decoration-style> || <text-decoration-color>

...so using the text-decoration shorthand - the example above would simply be:

p {
  text-decoration: underline red;
}

_x000D_
_x000D_
p {_x000D_
  text-decoration: underline red;_x000D_
}
_x000D_
<p>black text with red underline in one element - no wrapper elements here!</p>
_x000D_
_x000D_
_x000D_

docker : invalid reference format

The first argument after the "run" that is not a flag or parameter to a flag is parsed as an image name. When that parsing fails, it tells you the reference format, aka image name (but could be an image id, pinned image, or other syntax) is invalid. In your command:

 docker run -p 8888:8888 -v `pwd`/../src:/src -v `pwd`/../data:/data -w /src supervisely_anpr --rm -it bash

The image name "supervisely_anpr" is valid, so you need to look earlier in the command. In this case, the error is most likely from pwd outputting a path with a space in it. Everything after the space is no longer a parameter to -v and docker tries to parse it as the image name. The fix is to quote the volume parameters when you cannot guarantee it is free of spaces or other special characters.

When you do that, you'll encounter the next error, "executable not found". Everything after the image name is parsed as the command to run inside the container. In your case, it will try to run the command --rm -it bash which will almost certainly fail since --rm will no exist as a binary inside your image. You need to reorder the parameters to resolve that:

 docker run --rm -it -p 8888:8888 -v "`pwd`/../src:/src" -v "`pwd`/../data:/data" -w /src supervisely_anpr  bash

I've got some more details on these two errors and causes in my slides here: https://sudo-bmitch.github.io/presentations/dc2018/faq-stackoverflow-lightning.html#29

Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

Sharing this for other people. In my case, we were working on a shared MVC solution, and using a common module for tables that we use for dropdowns. I got the error when I updated the Entity model by adding a new table. It turns out that when I updated the the EDMX, it probably updated my rights access on the database, which resulted to not having access to that certain table giving me no mapping specified.

Just re-adding and giving access to my user solved the problem.

Basic communication between two fragments

I recently created a library that uses annotations to generate those type casting boilerplate code for you. https://github.com/zeroarst/callbackfragment

Here is an example. Click a TextView on DialogFragment triggers a callback to MainActivity in onTextClicked then grab the MyFagment instance to interact with.

public class MainActivity extends AppCompatActivity implements MyFragment.FragmentCallback, MyDialogFragment.DialogListener {

private static final String MY_FRAGM = "MY_FRAGMENT";
private static final String MY_DIALOG_FRAGM = "MY_DIALOG_FRAGMENT";

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

    getSupportFragmentManager().beginTransaction()
        .add(R.id.lo_fragm_container, MyFragmentCallbackable.create(), MY_FRAGM)
        .commit();

    findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MyDialogFragmentCallbackable.create().show(getSupportFragmentManager(), MY_DIALOG_FRAGM);
        }
    });
}

Toast mToast;

@Override
public void onClickButton(MyFragment fragment) {
    if (mToast != null)
        mToast.cancel();
    mToast = Toast.makeText(this, "Callback from " + fragment.getTag() + " to " + this.getClass().getSimpleName(), Toast.LENGTH_SHORT);
    mToast.show();
}

@Override
public void onTextClicked(MyDialogFragment fragment) {
    MyFragment myFragm = (MyFragment) getSupportFragmentManager().findFragmentByTag(MY_FRAGM);
    if (myFragm != null) {
        myFragm.updateText("Callback from " + fragment.getTag() + " to " + myFragm.getTag());
    }
}

}

Build a basic Python iterator

Inspired by Matt Gregory's answer here is a bit more complicated iterator that will return a,b,...,z,aa,ab,...,zz,aaa,aab,...,zzy,zzz

    class AlphaCounter:
    def __init__(self, low, high):
        self.current = low
        self.high = high

    def __iter__(self):
        return self

    def __next__(self): # Python 3: def __next__(self)
        alpha = ' abcdefghijklmnopqrstuvwxyz'
        n_current = sum([(alpha.find(self.current[x])* 26**(len(self.current)-x-1)) for x in range(len(self.current))])
        n_high = sum([(alpha.find(self.high[x])* 26**(len(self.high)-x-1)) for x in range(len(self.high))])
        if n_current > n_high:
            raise StopIteration
        else:
            increment = True
            ret = ''
            for x in self.current[::-1]:
                if 'z' == x:
                    if increment:
                        ret += 'a'
                    else:
                        ret += 'z'
                else:
                    if increment:
                        ret += alpha[alpha.find(x)+1]
                        increment = False
                    else:
                        ret += x
            if increment:
                ret += 'a'
            tmp = self.current
            self.current = ret[::-1]
            return tmp

for c in AlphaCounter('a', 'zzz'):
    print(c)

Trying to fire the onload event on script tag

I faced a similar problem, trying to test if jQuery is already present on a page, and if not force it's load, and then execute a function. I tried with @David Hellsing workaround, but with no chance for my needs. In fact, the onload instruction was immediately evaluated, and then the $ usage inside this function was not yet possible (yes, the huggly "$ is not a function." ^^).

So, I referred to this article : https://developer.mozilla.org/fr/docs/Web/Events/load and attached a event listener to my script object.

var script = document.createElement('script');
script.type = "text/javascript";
script.addEventListener("load", function(event) {
    console.log("script loaded :)");
    onjqloaded();
});
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);

For my needs, it works fine now. Hope this can help others :)

Jenkins vs Travis-CI. Which one would you use for a Open Source project?

Travis-ci and Jenkins, while both are tools for continuous integration are very different.

Travis is a hosted service (free for open source) while you have to host, install and configure Jenkins.

Travis does not have jobs as in Jenkins. The commands to run to test the code are taken from a file named .travis.yml which sits along your project code. This makes it easy to have different test code per branch since each branch can have its own version of the .travis.yml file.

You can have a similar feature with Jenkins if you use one of the following plugins:

  • Travis YML Plugin - warning: does not seem to be popular, probably not feature complete in comparison to the real Travis.
  • Jervis - a modification of Jenkins to make it read create jobs from a .jervis.yml file found at the root of project code. If .jervis.yml does not exist, it will fall back to using .travis.yml file instead.

There are other hosted services you might also consider for continuous integration (non exhaustive list):


How to choose ?

You might want to stay with Jenkins because you are familiar with it or don't want to depend on 3rd party for your continuous integration system. Else I would drop Jenkins and go with one of the free hosted CI services as they save you a lot of trouble (host, install, configure, prepare jobs)

Depending on where your code repository is hosted I would make the following choices:

  • in-house ? Jenkins or gitlab-ci
  • Github.com ? Travis-CI

To setup Travis-CI on a github project, all you have to do is:

  • add a .travis.yml file at the root of your project
  • create an account at travis-ci.com and activate your project

The features you get are:

  • Travis will run your tests for every push made on your repo
  • Travis will run your tests on every pull request contributors will make

Could not load file or assembly 'EntityFramework' after downgrading EF 5.0.0.0 --> 4.3.1.0

While Building a Project, if in the project properties it shows that it is build under Target.NET Framework 4.5, update it to 4.6 or 4.6.1. Then the build will be able to locate Entity Framework 6.0 in the Web.config file. This approach solved my problem. Selecting Target framework from Project Properties

Where to get this Java.exe file for a SQL Developer installation

You need to install JAVA SDK and give the path upto bin directory which contains the java.exe file.

example - c:/programfiles/java/jdk/bin

Graphical DIFF programs for linux

Kompare is fine for diff, but I use dirdiff. Although it looks ugly, dirdiff can do 3-way merge - and you can get everything done inside the tool (both diff and merge).

How do I configure git to ignore some files locally?

Both --assume-unchanged and --skip-worktree are NOT A CORRECT WAY to ignore files locally... Kindly check this answer and the notes in the documentation of git update-index. Files that for any reason keep changing frequently (and/or change from a clone to another) and their changes should not be committed, then these files SHOULD NOT be tracked in the first place.

However, the are two proper ways to ignore files locally (both work with untracked files). Either to put files names in .git/info/exclude file which is the local alternative of .gitignore but specific to the current clone. Or to use a global .gitignore (which should be properly used only for common auxiliary files e.g. pyz, pycache, etc) and the file will be ignored in any git repo in your machine.

To make the above as kind of automated (adding to exclude or global .gitignore), you can use the following commands (add to your bash-profile):

  • Per clone local exclude (Note that you should be in the root of the repository when calling the command because of using the relative path), change ##FILE-NAME## to .git/info/exclude
  • Global .gitignore, first make global .gitignore here then change ##FILE-NAME## to ~/.gitignore

Linux

alias git-ignore='echo $1 >> ##FILE-NAME##'
alias git-show-ignored='cat ##FILE-NAME##'
git-unignore(){
  GITFILETOUNIGNORE=${1//\//\\\/}
  sed -i "/$GITFILETOUNIGNORE/d" ##FILE-NAME##
  unset GITFILETOUNIGNORE
}

MacOS (you need the .bak for sed inplace modifications (i.e. you are forced to add a file extension to inplace sed. i.e. make a backup before replacing something), therefore to delete the .bak file I added rm filename.bak)

alias git-ignore='echo $1 >> ##FILE-NAME##'
alias git-show-ignored='cat ##FILE-NAME##'
git-unignore(){
  GITFILETOUNIGNORE=${1//\//\\\/}
  sed -i.bak "/$GITFILETOUNIGNORE/d" ##FILE-NAME##
  rm ##FILE-NAME##.bak
  unset GITFILETOUNIGNORE
}

Then you can do:

git-ignore example_file.txt
git-unignore example_file.txt

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

I miss the Visual Basic's With statement when moving to C#, so here it goes:

public static void With<T>(this T obj, Action<T> act) { act(obj); }

And here's how to use it in C#:

someVeryVeryLonggggVariableName.With(x => {
    x.Int = 123;
    x.Str = "Hello";
    x.Str2 = " World!";
});

Saves a lot of typing!

Compare this to:

someVeryVeryLonggggVariableName.Int = 123;
someVeryVeryLonggggVariableName.Str = "Hello";
someVeryVeryLonggggVariableName.Str2 = " World!";

put in codeplex project

How to select a div element in the code-behind page?

id + runat="server" leads to accessible at the server

Trigger to fire only if a condition is met in SQL Server

Given that a WHERE clause did not work, maybe this will:

CREATE TRIGGER 
    [dbo].[SystemParameterInsertUpdate]
ON 
    [dbo].[SystemParameter]
FOR INSERT, UPDATE 
AS
  BEGIN
    SET NOCOUNT ON

      If (SELECT Attribute FROM INSERTED) LIKE 'NoHist_%'
      Begin
          Return
      End

      INSERT INTO SystemParameterHistory 
      (
        Attribute,
        ParameterValue,
        ParameterDescription,
        ChangeDate
      )
    SELECT
      Attribute,
      ParameterValue,
      ParameterDescription,
      ChangeDate
    FROM Inserted AS I
END

How do I compare strings in Java?

Function:

public float simpleSimilarity(String u, String v) {
    String[] a = u.split(" ");
    String[] b = v.split(" ");

    long correct = 0;
    int minLen = Math.min(a.length, b.length);

    for (int i = 0; i < minLen; i++) {
        String aa = a[i];
        String bb = b[i];
        int minWordLength = Math.min(aa.length(), bb.length());

        for (int j = 0; j < minWordLength; j++) {
            if (aa.charAt(j) == bb.charAt(j)) {
                correct++;
            }
        }
    }

    return (float) (((double) correct) / Math.max(u.length(), v.length()));
}

Test:

String a = "This is the first string.";

String b = "this is not 1st string!";

// for exact string comparison, use .equals

boolean exact = a.equals(b);

// For similarity check, there are libraries for this
// Here I'll try a simple example I wrote

float similarity = simple_similarity(a,b);

How to make the web page height to fit screen height

Try:

#content{ background-color:#F3F3F3; margin:auto;width:70%;height:77%;}
#footer{width:100%;background-color:#666666;height:22%;}

(77% and 22% roughly preserves the proportions of content and footer and should not cause scrolling)

PostgreSQL Exception Handling

To catch the error message and its code:

do $$       
begin

    create table yyy(a int);
    create table yyy(a int); -- this will cause an error

exception when others then 

    raise notice 'The transaction is in an uncommittable state. '
                 'Transaction was rolled back';

    raise notice '% %', SQLERRM, SQLSTATE;

end; $$ 
language 'plpgsql';

Haven't found the line number yet

UPDATE April, 16, 2019

As suggested by Diego Scaravaggi, for Postgres 9.2 and up, use GET STACKED DIAGNOSTICS:

do language plpgsql $$
declare
    v_state   TEXT;
    v_msg     TEXT;
    v_detail  TEXT;
    v_hint    TEXT;
    v_context TEXT;
begin

    create table yyy(a int);
    create table yyy(a int); -- this will cause an error

exception when others then 

    get stacked diagnostics
        v_state   = returned_sqlstate,
        v_msg     = message_text,
        v_detail  = pg_exception_detail,
        v_hint    = pg_exception_hint,
        v_context = pg_exception_context;

    raise notice E'Got exception:
        state  : %
        message: %
        detail : %
        hint   : %
        context: %', v_state, v_msg, v_detail, v_hint, v_context;

    raise notice E'Got exception:
        SQLSTATE: % 
        SQLERRM: %', SQLSTATE, SQLERRM;     

    raise notice '%', message_text; -- invalid. message_text is contextual to GET STACKED DIAGNOSTICS only

end; $$;

Result:

NOTICE:  Got exception:
        state  : 42P07
        message: relation "yyy" already exists
        detail : 
        hint   : 
        context: SQL statement "create table yyy(a int)"
PL/pgSQL function inline_code_block line 11 at SQL statement
NOTICE:  Got exception:
        SQLSTATE: 42P07 
        SQLERRM: relation "yyy" already exists

ERROR:  column "message_text" does not exist
LINE 1: SELECT message_text
               ^
QUERY:  SELECT message_text
CONTEXT:  PL/pgSQL function inline_code_block line 33 at RAISE
SQL state: 42703

Aside from GET STACKED DIAGNOSTICS is SQL standard-compliant, its diagnostics variables (e.g., message_text) are contextual to GSD only. So if you have a field named message_text in your table, there's no chance that GSD can interfere with your field's value.

Still no line number though.

Why does Math.Round(2.5) return 2 instead of 3?

This post has the answer you are looking for:

http://weblogs.asp.net/sfurman/archive/2003/03/07/3537.aspx

Basically this is what it says:

Return Value

The number nearest value with precision equal to digits. If value is halfway between two numbers, one of which is even and the other odd, then the even number is returned. If the precision of value is less than digits, then value is returned unchanged.

The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding. If digits is zero, this kind of rounding is sometimes called rounding toward zero.

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

According Spring 4 MVC ResponseEntity.BodyBuilder and ResponseEntity Enhancements Example it could be written as:

....
   return ResponseEntity.ok().build();
....
   return ResponseEntity.noContent().build();

UPDATE:

If returned value is Optional there are convinient method, returned ok() or notFound():

return ResponseEntity.of(optional)

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

In Ubuntu by default, the system will not allow you to occupy privileged ports [ 0 to 1023], other than specifying the port as 80, you need to run XAMP with sudo.

How can I style a PHP echo text?

You can style it by the following way:

echo "<p style='color:red;'>" . $ip['cityName'] . "</p>";
echo "<p style='color:red;'>" . $ip['countryName'] . "</p>";

How to compare values which may both be null in T-SQL

What if you want to do a comparison for values that ARE NOT equal? Just using a "NOT" in front of the previously mentioned comparisons does not work. The best I could come up with is:

(Field1 <> Field2) OR (NULLIF(Field1, Field2) IS NOT NULL) OR (NULLIF(Field2, Field1) IS NOT NULL)

How to get the indices list of all NaN value in numpy array?

Since x!=x returns the same boolean array with np.isnan(x) (because np.nan!=np.nan would return True), you could also write:

np.argwhere(x!=x)

However, I still recommend writing np.argwhere(np.isnan(x)) since it is more readable. I just try to provide another way to write the code in this answer.

Setting background-image using jQuery CSS property

You'll want to include double quotes (") before and after the imageUrl like this:

$('myOjbect').css('background-image', 'url("' + imageUrl + '")');

This way, if the image has spaces it will still be set as a property.

How to check the multiple permission at single request in Android M?

Based on vedval i have this solution.

public boolean checkForPermission(final String[] permissions, final int permRequestCode) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return true;
    }
    final List<String> permissionsNeeded = new ArrayList<>();
    for (int i = 0; i < permissions.length; i++) {
        final String perm = permissions[i];
        if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
            if (shouldShowRequestPermissionRationale(permissions[i])) {
                Snackbar.make(phrase, R.string.permission_location, Snackbar.LENGTH_INDEFINITE)
                        .setAction(android.R.string.ok, new View.OnClickListener() {
                            @Override
                            @TargetApi(Build.VERSION_CODES.M)
                            public void onClick(View v) {
                                permissionsNeeded.add(perm);
                            }
                        });
            } else {
                // add the request.
                permissionsNeeded.add(perm);
            }
        }
    }

    if (permissionsNeeded.size() > 0) {
        // go ahead and request permissions
        requestPermissions(permissionsNeeded.toArray(new String[permissionsNeeded.size()]), permRequestCode);
        return false;
    } else {
        // no permission need to be asked so all good...we have them all.
        return true;
    }
}

/**
 * Callback received when a permissions request has been completed.
 */
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    if (requestCode == REQUEST_READ_LOCATION) {
        int i = 0;
        for (String permission : permissions ){
            if ( permission.equals(Manifest.permission.ACCESS_FINE_LOCATION) && grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                initLocationManager();
            }
            i++;
        }

    }
}

Breaking out of a for loop in Java

public class Test {

public static void main(String args[]) {

  for(int x = 10; x < 20; x = x+1) {
     if(x==15)
         break;
     System.out.print("value of x : " + x );
     System.out.print("\n");
  }
}
}

How to set the project name/group/version, plus {source,target} compatibility in the same file?

I set the artifact baseName so it is independent of the build project name, which allows me to achieve what you want:

jar {
    baseName "core"
}

With this property set, even if my project name is "foo", when I run gradle install, the artifact is published with the name core instead of foo.

Compare two data.frames to find the rows in data.frame 1 that are not present in data.frame 2

It is certainly not efficient for this particular purpose, but what I often do in these situations is to insert indicator variables in each data.frame and then merge:

a1$included_a1 <- TRUE
a2$included_a2 <- TRUE
res <- merge(a1, a2, all=TRUE)

missing values in included_a1 will note which rows are missing in a1. similarly for a2.

One problem with your solution is that the column orders must match. Another problem is that it is easy to imagine situations where the rows are coded as the same when in fact are different. The advantage of using merge is that you get for free all error checking that is necessary for a good solution.

vector vs. list in STL

One special capability of std::list is splicing (linking or moving part of or a whole list into a different list).

Or perhaps if your contents are very expensive to copy. In such a case it might be cheaper, for example, to sort the collection with a list.

Also note that if the collection is small (and the contents are not particularly expensive to copy), a vector might still outperform a list, even if you insert and erase anywhere. A list allocates each node individually, and that might be much more costly than moving a few simple objects around.

I don't think there are very hard rules. It depends on what you mostly want to do with the container, as well as on how large you expect the container to be and the contained type. A vector generally trumps a list, because it allocates its contents as a single contiguous block (it is basically a dynamically allocated array, and in most circumstances an array is the most efficient way to hold a bunch of things).

How to make layout with rounded corners..?

Here's a copy of a XML file to create a drawable with a white background, black border and rounded corners:

 <?xml version="1.0" encoding="UTF-8"?> 
    <shape xmlns:android="http://schemas.android.com/apk/res/android"> 
        <solid android:color="#ffffffff"/>    

        <stroke android:width="3dp"
                android:color="#ff000000"
                />

        <padding android:left="1dp"
                 android:top="1dp"
                 android:right="1dp"
                 android:bottom="1dp"
                 /> 

        <corners android:bottomRightRadius="7dp" android:bottomLeftRadius="7dp" 
         android:topLeftRadius="7dp" android:topRightRadius="7dp"/> 
    </shape>

save it as a xml file in the drawable directory, Use it like you would use any drawable background(icon or resource file) using its resource name (R.drawable.your_xml_name)

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

If you use the Angular CLI to create your components, let's say CarComponent, it attaches app to the selector name (i.e app-car) and this throws the above error when you reference the component in the parent view. Therefore you either have to change the selector name in the parent view to let's say <app-car></app-car> or change the selector in the CarComponent to selector: 'car'

How do I create a comma-separated list using a SQL query?

From next version of SQL Server you will be able to do

SELECT r.name,
       STRING_AGG(a.name, ',')
FROM   RESOURCES r
       JOIN APPLICATIONSRESOURCES ar
         ON ar.resource_id = r.id
       JOIN APPLICATIONS a
         ON a.id = ar.app_id
GROUP  BY r.name 

For previous versions of the product there are quite a wide variety of different approaches to this problem. An excellent review of them is in the article: Concatenating Row Values in Transact-SQL.

  • Concatenating values when the number of items are not known

    • Recursive CTE method
    • The blackbox XML methods
    • Using Common Language Runtime
    • Scalar UDF with recursion
    • Table valued UDF with a WHILE loop
    • Dynamic SQL
    • The Cursor approach
      .
  • Non-reliable approaches

    • Scalar UDF with t-SQL update extension
    • Scalar UDF with variable concatenation in SELECT

What is the iBeacon Bluetooth Profile

For an iBeacon with ProximityUUID E2C56DB5-DFFB-48D2-B060-D0F5A71096E0, major 0, minor 0, and calibrated Tx Power of -59 RSSI, the transmitted BLE advertisement packet looks like this:

d6 be 89 8e 40 24 05 a2 17 6e 3d 71 02 01 1a 1a ff 4c 00 02 15 e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 00 00 00 00 c5 52 ab 8d 38 a5

This packet can be broken down as follows:

d6 be 89 8e # Access address for advertising data (this is always the same fixed value)
40 # Advertising Channel PDU Header byte 0.  Contains: (type = 0), (tx add = 1), (rx add = 0)
24 # Advertising Channel PDU Header byte 1.  Contains:  (length = total bytes of the advertising payload + 6 bytes for the BLE mac address.)
05 a2 17 6e 3d 71 # Bluetooth Mac address (note this is a spoofed address)
02 01 1a 1a ff 4c 00 02 15 e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 00 00 00 00 c5 # Bluetooth advertisement
52 ab 8d 38 a5 # checksum

The key part of that packet is the Bluetooth Advertisement, which can be broken down like this:

02 # Number of bytes that follow in first AD structure
01 # Flags AD type
1A # Flags value 0x1A = 000011010  
   bit 0 (OFF) LE Limited Discoverable Mode
   bit 1 (ON) LE General Discoverable Mode
   bit 2 (OFF) BR/EDR Not Supported
   bit 3 (ON) Simultaneous LE and BR/EDR to Same Device Capable (controller)
   bit 4 (ON) Simultaneous LE and BR/EDR to Same Device Capable (Host)
1A # Number of bytes that follow in second (and last) AD structure
FF # Manufacturer specific data AD type
4C 00 # Company identifier code (0x004C == Apple)
02 # Byte 0 of iBeacon advertisement indicator
15 # Byte 1 of iBeacon advertisement indicator
e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 # iBeacon proximity uuid
00 00 # major 
00 00 # minor 
c5 # The 2's complement of the calibrated Tx Power

Any Bluetooth LE device that can be configured to send a specific advertisement can generate the above packet. I have configured a Linux computer using Bluez to send this advertisement, and iOS7 devices running Apple's AirLocate test code pick it up as an iBeacon with the fields specified above. See: Use BlueZ Stack As A Peripheral (Advertiser)

This blog has full details about the reverse engineering process.

Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo

We can eliminate the unnecessary file read/write by using text. My complete solution is the following:

proc1 = ['/bin/bash', '-c', 
  "/usr/bin/git ls-remote --heads ssh://repo_url.git"].execute()
proc2 = ['/bin/bash', '-c', 
  "/usr/bin/awk ' { gsub(/refs\\/heads\\//, \"\"); print \$2 }' "].execute()
all = proc1 | proc2

choices = all.text
return choices.split().toList();

Swift addsubview and remove it

Thanks for help. This is the solution: I created the subview and i add a gesture to remove it

@IBAction func infoView(sender: UIButton) {
    var testView: UIView = UIView(frame: CGRectMake(0, 0, 320, 568))
    testView.backgroundColor = UIColor.blueColor()
    testView.alpha = 0.5
    testView.tag = 100
    testView.userInteractionEnabled = true
    self.view.addSubview(testView)

    let aSelector : Selector = "removeSubview"
    let tapGesture = UITapGestureRecognizer(target:self, action: aSelector)
    testView.addGestureRecognizer(tapGesture)
}

func removeSubview(){
    println("Start remove sibview")
    if let viewWithTag = self.view.viewWithTag(100) {
        viewWithTag.removeFromSuperview()
    }else{
        println("No!")
    }
}

Update:

Swift 3+

@IBAction func infoView(sender: UIButton) {
    let testView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 568))
    testView.backgroundColor = .blue
    testView.alpha = 0.5
    testView.tag = 100
    testView.isUserInteractionEnabled = true
    self.view.addSubview(testView)

    let aSelector : Selector = #selector(GasMapViewController.removeSubview)
    let tapGesture = UITapGestureRecognizer(target:self, action: aSelector)
    testView.addGestureRecognizer(tapGesture)
}

func removeSubview(){
    print("Start remove sibview")
    if let viewWithTag = self.view.viewWithTag(100) {
        viewWithTag.removeFromSuperview()
    }else{
        print("No!")
    }
}

Giving my function access to outside variable

Global $myArr;
$myArr = array();

function someFuntion(){
    global $myArr;

    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
}

Be forewarned, generally people stick away from globals as it has some downsides.

You could try this

function someFuntion($myArr){
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
    return $myArr;
}
$myArr = someFunction($myArr);

That would make it so you aren't relying on Globals.

Daemon not running. Starting it now on port 5037

Reference link: http://www.programering.com/a/MTNyUDMwATA.html

Steps I followed 1) Execute the command adb nodaemon server in command prompt Output at command prompt will be: The following error occurred cannot bind 'tcp:5037' The original ADB server port binding failed

2) Enter the following command query which using port 5037 netstat -ano | findstr "5037" The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288

3) View the task manager, close all adb.exe

4) Restart eclipse or other IDE

The above steps worked for me.

How do I get the currently-logged username from a Windows service in .NET?

This is a WMI query to get the user name:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();
string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];

You will need to add System.Management under References manually.

Which JRE am I using?

  1. Open up your:
    • command prompt if you're using Windows
    • terminal if you're using mac or Linux
  2. Type in:

    java -version // This will check your JRE version
    javac -version // This will check your Java compiler version if you installed the JDK
    
  3. Grab a cup of coffee and you're done! You don't need to add the .exe to the java -version if everything is installed correctly.

How do I escape ampersands in batch files?

You can enclose it in quotes, if you supply a dummy first argument.

Note that you need to supply a dummy first argument in this case, as start will treat the first argument as a title for the new console windows, if it is quoted. So the following should work (and does here):

start "" "http://www.google.com/search?client=opera&rls=en&q=escape+ampersand&sourceid=opera&ie=utf-8&oe=utf-8"

How To limit the number of characters in JTextField?

import java.awt.KeyboardFocusManager;
import javax.swing.InputVerifier;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;

/**
 *
 * @author Igor
 */
public class CustomLengthTextField extends JTextField {

    protected boolean upper = false;
    protected int maxlength = 0;

    public CustomLengthTextField() {
        this(-1);
    }

    public CustomLengthTextField(int length, boolean upper) {
        this(length, upper, null);
    }

    public CustomLengthTextField(int length, InputVerifier inpVer) {
        this(length, false, inpVer);
    }

    /**
     *
     * @param length - maksimalan length
     * @param upper - turn it to upercase
     * @param inpVer - InputVerifier
     */
    public CustomLengthTextField(int length, boolean upper, InputVerifier inpVer) {
        super();
        this.maxlength = length;
        this.upper = upper;
        if (length > 0) {
            AbstractDocument doc = (AbstractDocument) getDocument();
            doc.setDocumentFilter(new DocumentSizeFilter());
        }
        setInputVerifier(inpVer);
    }

    public CustomLengthTextField(int length) {
        this(length, false);
    }

    public void setMaxLength(int length) {
        this.maxlength = length;
    }

    class DocumentSizeFilter extends DocumentFilter {

        public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)
                throws BadLocationException {

            //This rejects the entire insertion if it would make
            //the contents too long. Another option would be
            //to truncate the inserted string so the contents
            //would be exactly maxCharacters in length.
            if ((fb.getDocument().getLength() + str.length()) <= maxlength) {
                super.insertString(fb, offs, str, a);
            }
        }

        public void replace(FilterBypass fb, int offs,
                int length,
                String str, AttributeSet a)
                throws BadLocationException {

            if (upper) {
                str = str.toUpperCase();
            }

            //This rejects the entire replacement if it would make
            //the contents too long. Another option would be
            //to truncate the replacement string so the contents
            //would be exactly maxCharacters in length.
            int charLength = fb.getDocument().getLength() + str.length() - length;

            if (charLength <= maxlength) {
                super.replace(fb, offs, length, str, a);
                if (charLength == maxlength) {
                    focusNextComponent();
                }
            } else {
                focusNextComponent();
            }
        }

        private void focusNextComponent() {
            if (CustomLengthTextField.this == KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()) {
                KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent();
            }
        }
    }
}

What is the @Html.DisplayFor syntax for?

After looking for an answer for myself for some time, i could find something. in general if we are using it for just one property it appears same even if we do a "View Source" of generated HTML Below is generated HTML for example, when i want to display only Name property for my class

    <td>
    myClassNameProperty
    </td>
   <td>
    myClassNameProperty, This is direct from Item
    </td>

This is the generated HTML from below code

<td>
@Html.DisplayFor(modelItem=>item.Genre.Name)            
</td>

<td>
@item.Genre.Name, This is direct from Item
</td>

At the same time now if i want to display all properties in one statement for my class "Genre" in this case, i can use @Html.DisplayFor() to save on my typing, for least

i can write @Html.DisplayFor(modelItem=>item.Genre) in place of writing a separate statement for each property of Genre as below

@item.Genre.Name
@item.Genre.Id
@item.Genre.Description

and so on depending on number of properties.

How to build a Debian/Ubuntu package from source?

Here is a tutorial for building a Debian package.

Basically, you need to:

  1. Set up your folder structure
  2. Create a control file
  3. Optionally create postinst or prerm scripts
  4. Run dpkg-deb

I usually do all of this in my Makefile so I can just type make to spit out the binary and package it in one go.

How can a divider line be added in an Android RecyclerView?

  class ItemOffsetDecoration(
        context: Context,
        private val paddingLeft: Int,
        private val paddingRight: Int
    ) : RecyclerView.ItemDecoration() {
        private var mDivider: Drawable? = null

        init {
            mDivider = ContextCompat.getDrawable(context, R.drawable.divider_medium)
        }

        override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
            val left = parent.paddingLeft + paddingLeft
            val right = parent.width - parent.paddingRight - paddingRight
            val childCount = parent.childCount
            for (i in 0 until childCount) {
                val child = parent.getChildAt(i)
                val params = child.layoutParams as RecyclerView.LayoutParams
                val top = child.bottom + params.bottomMargin
                val bottom = top + (mDivider?.intrinsicHeight ?: 0)

                mDivider?.let {
                    it.setBounds(left, top, right, bottom)
                    it.draw(c)
                }
            }
        }
    }

You just need to specify a color in R.drawable.divider_medium

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/black" />
    <size
        android:height="1dp"
        android:width="1dp" />

</shape>

and add it to your recyclerView

recyclerView.addItemDecoration(
                        ItemOffsetDecoration(
                            this,
                            resources.getDimension(resources.getDimension(R.dimen.dp_70).roundToInt()).roundToInt(),
                            0
                        )
                    )

refernce this

Replacing H1 text with a logo image: best method for SEO and accessibility?

I think you'd be interested in the H1 debate. It's a debate about whether to use the h1 element for the page's title or for the logo.

Personally I'd go with your first suggestion, something along these lines:

<div id="header">
    <a href="http://example.com/"><img src="images/logo.png" id="site-logo" alt="MyCorp" /></a>
</div>

<!-- or alternatively (with css in a stylesheet ofc-->
<div id="header">
    <div id="logo" style="background: url('logo.png'); display: block; 
        float: left; width: 100px; height: 50px;">
        <a href="#" style="display: block; height: 50px; width: 100px;">
            <span style="visibility: hidden;">Homepage</span>
        </a>
    </div>
    <!-- with css in a stylesheet: -->
    <div id="logo"><a href="#"><span>Homepage</span></a></div>
</div>


<div id="body">
    <h1>About Us</h1>
    <p>MyCorp has been dealing in narcotics for over nine-thousand years...</p>
</div>

Of course this depends on whether your design uses page titles but this is my stance on this issue.

Laravel Eloquent: Ordering results of all()

In addition, just to buttress the former answers, it could be sorted as well either in descending desc or ascending asc orders by adding either as the second parameter.

$results = Project::orderBy('created_at', 'desc')->get();

github: server certificate verification failed

To me a simple

sudo apt-get update

solved the issue. It was a clock issue and with this command it resets to the current date/time and everything worked

How can I recover a lost commit in Git?

Sadly git is so unrelable :( I just lost 2 days of work :(

It's best to manual backup anything before doing commit. I just did "git commit" and git just destroy all my changes without saying anything.

I learned my lesson - next time backup first and only then commit. Never trust git for anything.

Svn switch from trunk to branch

  • Short version of (correct) tzaman answer will be (for fresh SVN)

    svn switch ^/branches/v1p2p3
    
  • --relocate switch is deprecated anyway, when it needed you'll have to use svn relocate command

  • Instead of creating snapshot-branch (ReadOnly) you can use tags (conventional RO labels for history)

On Windows, the caret character (^) must be escaped:

svn switch ^^/branches/v1p2p3

Xcode couldn't find any provisioning profiles matching

Requirements:

  1. Unique name (across all Apple Apps)
  2. Have to sign in while your phone is connected (mine had a large warning here)

Worked great without restart on Xcode 10

Settings

How to create a BKS (BouncyCastle) format Java Keystore that contains a client certificate chain

command line:

keytool -genseckey -alias aliasName -keystore truststore.bks -providerclass org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath /path/to/jar/bcprov-jdk16-1.46.jar -storetype BKS

How do I create a file at a specific path?

The file path "c:\Test\blah" will have a tab character for the `\T'. You need to use either:

"C:\\Test"

or

r"C:\Test"

Twitter bootstrap remote modal shows same content every time

Adding an $(this).html(''); to clear visible data as well, and it works pretty fine

How can I get a JavaScript stack trace when I throw an exception?

It is easier to get a stack trace on Firefox than it is on IE but fundamentally here is what you want to do:

Wrap the "problematic" piece of code in a try/catch block:

try {
    // some code that doesn't work
    var t = null;
    var n = t.not_a_value;
}
    catch(e) {
}

If you will examine the contents of the "error" object it contains the following fields:

e.fileName : The source file / page where the issue came from e.lineNumber : The line number in the file/page where the issue arose e.message : A simple message describing what type of error took place e.name : The type of error that took place, in the example above it should be 'TypeError' e.stack : Contains the stack trace that caused the exception

I hope this helps you out.

How to assign an action for UIImageView object in Swift

Swift4 Code

Try this some new extension methods:

import UIKit

extension UIView {

    fileprivate struct AssociatedObjectKeys {
        static var tapGestureRecognizer = "MediaViewerAssociatedObjectKey_mediaViewer"
    }

    fileprivate typealias Action = (() -> Void)?


    fileprivate var tapGestureRecognizerAction: Action? {
        set {
            if let newValue = newValue {
                // Computed properties get stored as associated objects
                objc_setAssociatedObject(self, &AssociatedObjectKeys.tapGestureRecognizer, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
            }
        }
        get {
            let tapGestureRecognizerActionInstance = objc_getAssociatedObject(self, &AssociatedObjectKeys.tapGestureRecognizer) as? Action
            return tapGestureRecognizerActionInstance
        }
    }


    public func addTapGestureRecognizer(action: (() -> Void)?) {
        self.isUserInteractionEnabled = true
        self.tapGestureRecognizerAction = action
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture))
        self.addGestureRecognizer(tapGestureRecognizer)
    }


    @objc fileprivate func handleTapGesture(sender: UITapGestureRecognizer) {
        if let action = self.tapGestureRecognizerAction {
            action?()
        } else {
            print("no action")
        }
    }

}

Now whenever we want to add a UITapGestureRecognizer to a UIView or UIView subclass like UIImageView, we can do so without creating associated functions for selectors!

Usage:

 profile_ImageView.addTapGestureRecognizer {
        print("image tapped")
    }