Programs & Examples On #Url mapping

A framework's URL mapping facility is the mechanism by which the framework interprets URLs.

Replacing objects in array

function getMatch(elem) {
    function action(ele, val) {
        if(ele === val){ 
            elem = arr2[i]; 
        }
    }

    for (var i = 0; i < arr2.length; i++) {
        action(elem.id, Object.values(arr2[i])[0]);
    }
    return elem;
}

var modified = arr1.map(getMatch);

Installing packages in Sublime Text 2

You may try to install Package Control first by following simple instructions available at Installation Guide (which is like 1. Open the Console, 2. Paste the code).

Then please check Package Docs Control Usage for Basic Functionality:

Package Control is driven by the Command Pallete. To open the pallete, press Ctrl+Shift+P (Win, Linux) or CMD+Shift+P (OS X). All Package Control commands begin with Package Control:, so start by typing Package.

The command pallete will now show a number of commands. Most users will be interested in the following:

Install Package

Show a list of all available packages that are available for install. This will include all of the packages from the default channel, plus any from repositories you have added.

Get the string value from List<String> through loop for display

Try following if your looking for while loop implementation.

List<String> myString = new ArrayList<String>();

// How you add your data in string list
myString.add("Test 1");
myString.add("Test 2");
myString.add("Test 3");
myString.add("Test 4");

int i = 0;
while (i < myString.size()) {
    System.out.println(myString.get(i));
    i++;
}

How to have Java method return generic list of any type?

You can simply cast to List and then check if every element can be casted to T.

public <T> List<T> asList(final Class<T> clazz) {
    List<T> values = (List<T>) this.value;
    values.forEach(clazz::cast);
    return values;
}

CSS to prevent child element from inheriting parent styles

Unfortunately, you're out of luck here.

There is inherit to copy a certain value from a parent to its children, but there is no property the other way round (which would involve another selector to decide which style to revert).

You will have to revert style changes manually:

div { color: green; }

form div { color: red; }

form div div.content { color: green; }

If you have access to the markup, you can add several classes to style precisely what you need:

form div.sub { color: red; }

form div div.content { /* remains green */ }

Edit: The CSS Working Group is up to something:

div.content {
  all: revert;
}

No idea, when or if ever this will be implemented by browsers.

Edit 2: As of March 2015 all modern browsers but Safari and IE/Edge have implemented it: https://twitter.com/LeaVerou/status/577390241763467264 (thanks, @Lea Verou!)

Edit 3: default was renamed to revert.

Is there an opposite to display:none?

you can use

display: normal;

It works as normal.... Its a small hacking in css ;)

How could I use requests in asyncio?

DISCLAMER: Following code creates different threads for each function.

This might be useful for some of the cases as it is simpler to use. But know that it is not async but gives illusion of async using multiple threads, even though decorator suggests that.

To make any function non blocking, simply copy the decorator and decorate any function with a callback function as parameter. The callback function will receive the data returned from the function.

import asyncio
import requests


def run_async(callback):
    def inner(func):
        def wrapper(*args, **kwargs):
            def __exec():
                out = func(*args, **kwargs)
                callback(out)
                return out

            return asyncio.get_event_loop().run_in_executor(None, __exec)

        return wrapper

    return inner


def _callback(*args):
    print(args)


# Must provide a callback function, callback func will be executed after the func completes execution !!
@run_async(_callback)
def get(url):
    return requests.get(url)


get("https://google.com")
print("Non blocking code ran !!")

swift UITableView set rowHeight

Make sure Your TableView Delegate are working as well. if not then in your story board or in .xib press and hold Control + right click on tableView drag and Drop to your Current ViewController. swift 2.0

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 60.0;
}

Cancel split window in Vim

The command :hide will hide the currently focused window. I think this is the functionality you are looking for.

In order to navigate between windows type Ctrl+w followed by a navigation key (h,j,k,l, or arrow keys)

For more information run :help window and :help hide in vim.

How do I set a cookie on HttpClient's HttpRequestMessage

Here's how you could set a custom cookie value for the request:

var baseAddress = new Uri("http://example.com");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
    var content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("foo", "bar"),
        new KeyValuePair<string, string>("baz", "bazinga"),
    });
    cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
    var result = await client.PostAsync("/test", content);
    result.EnsureSuccessStatusCode();
}

Entity Framework Code First - two Foreign Keys from same table

You can try this too:

public class Match
{
    [Key]
    public int MatchId { get; set; }

    [ForeignKey("HomeTeam"), Column(Order = 0)]
    public int? HomeTeamId { get; set; }
    [ForeignKey("GuestTeam"), Column(Order = 1)]
    public int? GuestTeamId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public virtual Team HomeTeam { get; set; }
    public virtual Team GuestTeam { get; set; }
}

When you make a FK column allow NULLS, you are breaking the cycle. Or we are just cheating the EF schema generator.

In my case, this simple modification solve the problem.

C# if/then directives for debug vs release

DEBUG/_DEBUG should be defined in VS already.

Remove the #define DEBUG in your code. Set preprocessors in the build configuration for that specific build.

The reason it prints "Mode=Debug" is because of your #define and then skips the elif.

The right way to check is:

#if DEBUG
    Console.WriteLine("Mode=Debug"); 
#else
    Console.WriteLine("Mode=Release"); 
#endif

Don't check for RELEASE.

How to find the length of an array list?

System.out.println(myList.size());

Since no elements are in the list

output => 0

myList.add("newString");  // use myList.add() to insert elements to the arraylist
System.out.println(myList.size());

Since one element is added to the list

output => 1

ASP.NET Web API application gives 404 when deployed at IIS 7

You may need to install Hotfix KB980368.

This article describes a update that enables certain Internet Information Services (IIS) 7.0 or IIS 7.5 handlers to handle requests whose URLs do not end with a period. Specifically, these handlers are mapped to "." request paths. Currently, a handler that is mapped to a "." request path handles only requests whose URLs end with a period. For example, the handler handles only requests whose URLs resemble the following URL:

http://www.example.com/ExampleSite/ExampleFile.

After you apply this update, handlers that are mapped to a "*." request path can handle requests whose URLs end with a period and requests whose URLs do not end with a period. For example, the handler can now handle requests that resemble the following URLs:

http://www.example.com/ExampleSite/ExampleFile

http://www.example.com/ExampleSite/ExampleFile.

After this patch is applied, ASP.NET 4 applications can handle requests for extensionless URLs. Therefore, managed HttpModules that run prior to handler execution will run. In some cases, the HttpModules can return errors for extensionless URLs. For example, an HttpModule that was written to expect only .aspx requests may now return errors when it tries to access the HttpContext.Session property.

How to delete all records from table in sqlite with Android?

To delete all the rows within the table you can use:

db.delete(TABLE_NAME, null, null);

How to measure time elapsed on Javascript?

The Date documentation states that :

The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC

Click on start button then on end button. It will show you the number of seconds between the 2 clicks.

The milliseconds diff is in variable timeDiff. Play with it to find seconds/minutes/hours/ or what you need

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = new Date();_x000D_
  var timeDiff = endTime - startTime; //in ms_x000D_
  // strip the ms_x000D_
  timeDiff /= 1000;_x000D_
_x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

OR another way of doing it for modern browser

Using performance.now() which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.

The time origin is a standard time which is considered to be the beginning of the current document's lifetime.

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = performance.now();_x000D_
  var timeDiff = endTime - startTime; //in ms _x000D_
  // strip the ms _x000D_
  timeDiff /= 1000; _x000D_
  _x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

How to implement a SQL like 'LIKE' operator in java?

You could turn '%string%' to contains(), 'string%' to startsWith() and '%string"' to endsWith().

You should also run toLowerCase() on both the string and pattern as LIKE is case-insenstive.

Not sure how you'd handle '%string%other%' except with a Regular Expression though.

If you're using Regular Expressions:

IE11 meta element Breaks SVG

I figured it out! The page was rendering using IE8 mode... had

<meta http-equiv="X-UA-Compatible" content="IE=8">

in the header... changed it to

<meta http-equiv="X-UA-Compatible" content="IE=9">

9 and it worked!

JavaScript OOP in NodeJS: how?

This is the best video about Object-Oriented JavaScript on the internet:

The Definitive Guide to Object-Oriented JavaScript

Watch from beginning to end!!

Basically, Javascript is a Prototype-based language which is quite different than the classes in Java, C++, C#, and other popular friends. The video explains the core concepts far better than any answer here.

With ES6 (released 2015) we got a "class" keyword which allows us to use Javascript "classes" like we would with Java, C++, C#, Swift, etc.

Screenshot from the video showing how to write and instantiate a Javascript class/subclass: enter image description here

Prevent flex items from stretching

You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.

To affect all flex-items of the container, choose this:
You have to set align-items: flex-start; to div and all flex-items of this container get the height of their content.

_x000D_
_x000D_
div {_x000D_
  align-items: flex-start;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}
_x000D_
<div>_x000D_
  <span>This is some text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start; to this flex-item. All other flex-items of the container aren't affected.

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
  background: tan;_x000D_
}_x000D_
span.only {_x000D_
  background: red;_x000D_
  align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
    background:green;_x000D_
}
_x000D_
<div>_x000D_
  <span class="only">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why is this happening to the span?
The default value of the property align-items is stretch. This is the reason why the span fill the height of the div.

Difference between baseline and flex-start?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start the flex-item will be set to the top of the container (without space).

_x000D_
_x000D_
div {_x000D_
  align-items: baseline;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
  font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
  <span class="fontsize">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can find more information about the difference between baseline and flex-start here:
What's the difference between flex-start and baseline?

How to set xampp open localhost:8080 instead of just localhost

The port that the Admin button references is configurable. In the XAMPP install folder there is a xampp-control.ini file. Changing the Apache entry under [ServicePorts] will affect the url the Admin button opens.

[ServicePorts]
Apache=8080

How to drop all tables from a database with one SQL query?

If anybody else had a problem with best answer's solution (including disabling foreign keys), here is another solution from me:

-- CLEAN DB
USE [DB_NAME]
    EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
    EXEC sp_MSForEachTable 'DELETE FROM ?'

    DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR
    SET @Cursor = CURSOR FAST_FORWARD FOR

    SELECT DISTINCT sql = 'ALTER TABLE [' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + ']'
    FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
    LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME
    OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql
    WHILE (@@FETCH_STATUS = 0)
      BEGIN
        Exec SP_EXECUTESQL @Sql
        FETCH NEXT 
        FROM @Cursor INTO @Sql
      END
    CLOSE @Cursor DEALLOCATE @Cursor
    GO

    EXEC sp_MSForEachTable 'DROP TABLE ?'
    GO

    EXEC sp_MSForEachTable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL'

Remove all subviews?

In objective-C, go ahead and create a category method off of the UIView class.

- (void)removeAllSubviews
{
    for (UIView *subview in self.subviews)
        [subview removeFromSuperview];
}

Custom ImageView with drop shadow

I manage to apply gradient border using this code..

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

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

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

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

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

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

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

    return bmp;
}

hope this helps !

Python write line by line to a text file

Well, the problem you have is wrong line ending/encoding for notepad. Notepad uses Windows' line endings - \r\n and you use \n.

Add a space (" ") after an element using :after

There can be a problem with "\00a0" in pseudo-elements because it takes the text-decoration of its defining element, so that, for example, if the defining element is underlined, then the white space of the pseudo-element is also underlined.

The easiest way to deal with this is to define the opacity of the pseudo-element to be zero, eg:

element:before{
  content: "_";
  opacity: 0;
}

Fragment MyFragment not attached to Activity

I've faced two different scenarios here:

1) When I want the asynchronous task to finish anyway: imagine my onPostExecute does store data received and then call a listener to update views so, to be more efficient, I want the task to finish anyway so I have the data ready when user cames back. In this case I usually do this:

@Override
protected void onPostExecute(void result) {
    // do whatever you do to save data
    if (this.getView() != null) {
        // update views
    }
}

2) When I want the asynchronous task only to finish when views can be updated: the case you're proposing here, the task only updates the views, no data storage needed, so it has no clue for the task to finish if views are not longer being showed. I do this:

@Override
protected void onStop() {
    // notice here that I keep a reference to the task being executed as a class member:
    if (this.myTask != null && this.myTask.getStatus() == Status.RUNNING) this.myTask.cancel(true);
    super.onStop();
}

I've found no problem with this, although I also use a (maybe) more complex way that includes launching tasks from the activity instead of the fragments.

Wish this helps someone! :)

How to use GOOGLEFINANCE(("CURRENCY:EURAUD")) function

Bear in mind that the GoogleFinance() function isn't working 100% in the new version of Google Sheets. For example, converting from USD to GBP using the formula GoogleFinance("CURRENCY:USDGBP") gives 0.603974 in the old version, but only 0.6 in the new one. Looks like there's a rounding error.

Foreign key constraints: When to use ON UPDATE and ON DELETE

Do not hesitate to put constraints on the database. You'll be sure to have a consistent database, and that's one of the good reasons to use a database. Especially if you have several applications requesting it (or just one application but with a direct mode and a batch mode using different sources).

With MySQL you do not have advanced constraints like you would have in postgreSQL but at least the foreign key constraints are quite advanced.

We'll take an example, a company table with a user table containing people from theses company

CREATE TABLE COMPANY (
     company_id INT NOT NULL,
     company_name VARCHAR(50),
     PRIMARY KEY (company_id)
) ENGINE=INNODB;

CREATE TABLE USER (
     user_id INT, 
     user_name VARCHAR(50), 
     company_id INT,
     INDEX company_id_idx (company_id),
     FOREIGN KEY (company_id) REFERENCES COMPANY (company_id) ON...
) ENGINE=INNODB;

Let's look at the ON UPDATE clause:

  • ON UPDATE RESTRICT : the default : if you try to update a company_id in table COMPANY the engine will reject the operation if one USER at least links on this company.
  • ON UPDATE NO ACTION : same as RESTRICT.
  • ON UPDATE CASCADE : the best one usually : if you update a company_id in a row of table COMPANY the engine will update it accordingly on all USER rows referencing this COMPANY (but no triggers activated on USER table, warning). The engine will track the changes for you, it's good.
  • ON UPDATE SET NULL : if you update a company_id in a row of table COMPANY the engine will set related USERs company_id to NULL (should be available in USER company_id field). I cannot see any interesting thing to do with that on an update, but I may be wrong.

And now on the ON DELETE side:

  • ON DELETE RESTRICT : the default : if you try to delete a company_id Id in table COMPANY the engine will reject the operation if one USER at least links on this company, can save your life.
  • ON DELETE NO ACTION : same as RESTRICT
  • ON DELETE CASCADE : dangerous : if you delete a company row in table COMPANY the engine will delete as well the related USERs. This is dangerous but can be used to make automatic cleanups on secondary tables (so it can be something you want, but quite certainly not for a COMPANY<->USER example)
  • ON DELETE SET NULL : handful : if you delete a COMPANY row the related USERs will automatically have the relationship to NULL. If Null is your value for users with no company this can be a good behavior, for example maybe you need to keep the users in your application, as authors of some content, but removing the company is not a problem for you.

usually my default is: ON DELETE RESTRICT ON UPDATE CASCADE. with some ON DELETE CASCADE for track tables (logs--not all logs--, things like that) and ON DELETE SET NULL when the master table is a 'simple attribute' for the table containing the foreign key, like a JOB table for the USER table.

Edit

It's been a long time since I wrote that. Now I think I should add one important warning. MySQL has one big documented limitation with cascades. Cascades are not firing triggers. So if you were over confident enough in that engine to use triggers you should avoid cascades constraints.

MySQL triggers activate only for changes made to tables by SQL statements. They do not activate for changes in views, nor by changes to tables made by APIs that do not transmit SQL statements to the MySQL Server

==> See below the last edit, things are moving on this domain

Triggers are not activated by foreign key actions.

And I do not think this will get fixed one day. Foreign key constraints are managed by the InnoDb storage and Triggers are managed by the MySQL SQL engine. Both are separated. Innodb is the only storage with constraint management, maybe they'll add triggers directly in the storage engine one day, maybe not.

But I have my own opinion on which element you should choose between the poor trigger implementation and the very useful foreign keys constraints support. And once you'll get used to database consistency you'll love PostgreSQL.

12/2017-Updating this Edit about MySQL:

as stated by @IstiaqueAhmed in the comments, the situation has changed on this subject. So follow the link and check the real up-to-date situation (which may change again in the future).

How to update primary key

When you find it necessary to update a primary key value as well as all matching foreign keys, then the entire design needs to be fixed.

It is tricky to cascade all the necessary foreign keys changes. It is a best practice to never update the primary key, and if you find it necessary, you should use a Surrogate Primary Key, which is a key not derived from application data. As a result its value is unrelated to the business logic and never needs to change (and should be invisible to the end user). You can then update and display some other column.

for example:

BadUserTable
UserID     varchar(20) primary key --user last name
other columns...

when you create many tables that have a FK to UserID, to track everything that the user has worked on, but that user then gets married and wants a ID to match their new last name, you are out of luck.

GoodUserTable
UserID    int identity(1,1) primary key
UserLogin varchar(20) 
other columns....

you now FK the Surrogate Primary Key to all the other tables, and display UserLogin when necessary, allow them to login using that value, and when they need to change it, you change it in one column of one row only.

When to use async false and async true in ajax function in jquery

  1. When async setting is set to false, a Synchronous call is made instead of an Asynchronous call.
  2. When the async setting of the jQuery AJAX function is set to true then a jQuery Asynchronous call is made. AJAX itself means Asynchronous JavaScript and XML and hence if you make it Synchronous by setting async setting to false, it will no longer be an AJAX call.
  3. for more information please refer this link

How to decrease prod bundle size?

Another way to reduce bundle, is to serve GZIP instead of JS. We went from 2.6mb to 543ko.

https://httpd.apache.org/docs/2.4/mod/mod_deflate.html

What's the difference between using CGFloat and float?

As @weichsel stated, CGFloat is just a typedef for either float or double. You can see for yourself by Command-double-clicking on "CGFloat" in Xcode — it will jump to the CGBase.h header where the typedef is defined. The same approach is used for NSInteger and NSUInteger as well.

These types were introduced to make it easier to write code that works on both 32-bit and 64-bit without modification. However, if all you need is float precision within your own code, you can still use float if you like — it will reduce your memory footprint somewhat. Same goes for integer values.

I suggest you invest the modest time required to make your app 64-bit clean and try running it as such, since most Macs now have 64-bit CPUs and Snow Leopard is fully 64-bit, including the kernel and user applications. Apple's 64-bit Transition Guide for Cocoa is a useful resource.

How to check for empty value in Javascript?

The counter in your for loop appears incorrect (or we're missing some code). Here's a working Fiddle.

This code:

//Where is counter[0] initialized?
for (i ; i < counter[0].value; i++)

Should be replaced with:

var timeTempCount = 5; //I'm not sure where you're getting this value so I set it.

for (var i = 0; i <= timeTempCount; i++)

Convert from days to milliseconds

You can use this utility class -

public class DateUtils
{
    public static final long SECOND_IN_MILLIS = 1000;
    public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;
    public static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;
    public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;
    public static final long WEEK_IN_MILLIS = DAY_IN_MILLIS * 7;
}

If you are working on Android framework then just import it (also named DateUtils) under package android.text.format

Jmeter - Run .jmx file through command line and get the summary report in a excel

You can run JMeter from the command line using the -n parameter for 'Non-GUI' and the -t parameter for the test plan file.

    jmeter -n -t "PATHTOJMXFILE"        

If you want to further customize the command line experience, I would direct you to the 'Getting Started' section of their documentation.

XSD - how to allow elements in any order any number of times?

In the schema you have in your question, child1 or child2 can appear in any order, any number of times. So this sounds like what you are looking for.

Edit: if you wanted only one of them to appear an unlimited number of times, the unbounded would have to go on the elements instead:

Edit: Fixed type in XML.

Edit: Capitalised O in maxOccurs

<xs:element name="foo">
   <xs:complexType>
     <xs:choice maxOccurs="unbounded">
       <xs:element name="child1" type="xs:int" maxOccurs="unbounded"/>
       <xs:element name="child2" type="xs:string" maxOccurs="unbounded"/>
     </xs:choice>
   </xs:complexType>
</xs:element>

How to cin to a vector

You probably want to read in more numbers, not only one. For this, you need a loop

int main()
{
  int input = 0;
  while(input != -1){
    vector<int> V;
    cout << "Enter your numbers to be evaluated: " << endl;
    cin >> input;
    V.push_back(input);
    write_vector(V);
  }
  return 0;
}

Note, with this version, it is not possible to add the number -1 as it is the "end signal". Type numbers as long as you like, it will be aborted when you type -1.

How to get Activity's content view?

this.getWindow().getDecorView().findViewById(android.R.id.content)

or

this.findViewById(android.R.id.content)

or

this.findViewById(android.R.id.content).getRootView()

Is there a Subversion command to reset the working copy?

Very quick and simple and does exactly what you want

svn status | awk '{if($2 !~ /(config|\.ini)/ && !system("test -e \"" $2 "\"")) {print $2; system("rm -Rf \"" $2 "\"");}}'

The /(config|.ini)/ is for my own purposes.

And might be a good idea to add --no-ignore to the svn command

How to get date representing the first day of a month?

Get First Day of Last Month

Select ADDDATE(LAST_DAY(ADDDATE(now(), INTERVAL -2 MONTH)), INTERVAL 1 DAY);

Get Last Day of Last Month

Select LAST_DAY(ADDDATE(now(), INTERVAL -1 MONTH));

Unpacking a list / tuple of pairs into two lists / tuples

list1 = (x[0] for x in source_list)
list2 = (x[1] for x in source_list)

ImportError: cannot import name

This can also happen if you've been working on your scripts and functions and have been moving them around (i.e. changed the location of the definition) which could have accidentally created a looping reference.

You may find that the situation is solved if you just reset the iPython kernal to clear any old assignments:

%reset

or menu->restart terminal

GridView Hide Column by code

Here i am binding the gridview with dataset like this-

GVAnswer.DataSource = DS.Tables[0];
GVAnswer.DataBind();

Then after

Then we count the number of rows like this in the for loop

for (int i = 0; i < GVAnswer.Rows.Count; i++)
{

}

Then after we find the header we want make visible false

GVAnswer.HeaderRow.Cells[2].Visible = false;

then after we make the visibility false of that particular cell.

The complete code is give like this

public void FillGVAnswer(int QuestionID) { try { OBJClsQuestionAnswer = new ClsQuestionAnswer(); DS = new DataSet(); DS = OBJClsQuestionAnswer.GetAnswers(QuestionID); GVAnswer.DataSource = DS.Tables[0]; GVAnswer.DataBind(); if (DS.Tables[0].Rows.Count > 0) { for (int i = 0; i < GVAnswer.Rows.Count; i++) { GVAnswer.HeaderRow.Cells[2].Visible = false; GVAnswer.HeaderRow.Cells[3].Visible = false; GVAnswer.HeaderRow.Cells[6].Visible = false; GVAnswer.HeaderRow.Cells[8].Visible = false; GVAnswer.HeaderRow.Cells[10].Visible = false; GVAnswer.HeaderRow.Cells[11].Visible = false; //GVAnswer.Rows[i].Cells[1].Visible = false; if (GVAnswer.Rows[i].Cells[4].Text == "T") { GVAnswer.Rows[i].Cells[4].Text = "Text"; } else { GVAnswer.Rows[i].Cells[4].Text = "Image"; } if (GVAnswer.Rows[i].Cells[5].Text == "View Image") { HtmlAnchor a = new HtmlAnchor(); a.HRef = "~/ImageHandler.aspx?ACT=AIMG&AID=" + GVAnswer.Rows[i].Cells[2].Text; a.Attributes.Add("rel", "lightbox"); a.InnerText = GVAnswer.Rows[i].Cells[5].Text; GVAnswer.Rows[i].Cells[5].Controls.Add(a); } if (GVAnswer.Rows[i].Cells[7].Text == "Yes") { j++; ViewState["CheckHasMulAns"] = j;// To Chek How Many answer Of a particulaer Question Is Right } GVAnswer.Rows[i].Cells[8].Visible = false; GVAnswer.Rows[i].Cells[3].Visible = false; GVAnswer.Rows[i].Cells[10].Visible = false; GVAnswer.Rows[i].Cells[6].Visible = false; GVAnswer.Rows[i].Cells[11].Visible = false; GVAnswer.Rows[i].Cells[2].Visible = false; } } } catch (Exception ex) { string err = ex.Message; if (ex.InnerException != null) { err = err + " :: Inner Exception :- " + ex.InnerException.Message; } string addInfo = "Error in getting Answers :: -> "; ClsExceptionPublisher objPub = new ClsExceptionPublisher(); objPub.Publish(err, addInfo); } }

Background service with location listener in android

Very easy no need create class extends LocationListener 1- Variable

private LocationManager mLocationManager;
private LocationListener mLocationListener;
private static double currentLat =0;
private static double currentLon =0;

2- onStartService()

@Override public void onStartService() {
    addListenerLocation();
}

3- Method addListenerLocation()

 private void addListenerLocation() {
    mLocationManager = (LocationManager)
            getSystemService(Context.LOCATION_SERVICE);
    mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            currentLat = location.getLatitude();
            currentLon = location.getLongitude();

            Toast.makeText(getBaseContext(),currentLat+"-"+currentLon, Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
            Location lastKnownLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if(lastKnownLocation!=null){
                currentLat = lastKnownLocation.getLatitude();
                currentLon = lastKnownLocation.getLongitude();
            }

        }

        @Override
        public void onProviderDisabled(String provider) {
        }
    };
    mLocationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 500, 10, mLocationListener);
}

4- onDestroy()

@Override
public void onDestroy() {
    super.onDestroy();
    mLocationManager.removeUpdates(mLocationListener);
}

Export DataTable to Excel with Open Xml SDK in c#

I tried accepted answer and got message saying generated excel file is corrupted when trying to open. I was able to fix it by doing few modifications like adding below line end of the code.

workbookPart.Workbook.Save();

I have posted full code @ Export DataTable to Excel with Open XML in c#

mysql is not recognised as an internal or external command,operable program or batch

In my case, I resolved it by adding this path C:\xampp\mysql\bin to system variables path and then restarted pash/cmd.

Note: Click me if you don't know how to set the path and system variables.

Serving static web resources in Spring Boot & Spring Security application

i had the same issue with my spring boot application, so I thought it will be nice if i will share with you guys my solution. I just simply configure the antMatchers to be suited to specific type of filles. In my case that was only js filles and js.map. Here is a code:

   @Configuration
   @EnableWebSecurity
   public class SecurityConfig extends WebSecurityConfigurerAdapter {

   @Override
   protected void configure(HttpSecurity http) throws Exception {
       http.authorizeRequests()
      .antMatchers("/index.html", "/", "/home", 
       "/login","/favicon.ico","/*.js","/*.js.map").permitAll()
      .anyRequest().authenticated().and().csrf().disable();
   }
  }

What is interesting. I find out that resources path like "resources/myStyle.css" in antMatcher didnt work for me at all. If you will have folder inside your resoruces folder just add it in antMatcher like "/myFolder/myFille.js"* and it should work just fine.

Autonumber value of last inserted row - MS Access / VBA

In your example, because you use CurrentDB to execute your INSERT you've made it harder for yourself. Instead, this will work:

  Dim query As String
  Dim newRow As Long  ' note change of data type
  Dim db As DAO.Database

  query = "INSERT INTO InvoiceNumbers (date) VALUES (" & NOW() & ");"
  Set db = CurrentDB
  db.Execute(query)
  newRow = db.OpenRecordset("SELECT @@IDENTITY")(0)
  Set db = Nothing

I used to do INSERTs by opening an AddOnly recordset and picking up the ID from there, but this here is a lot more efficient. And note that it doesn't require ADO.

How to avoid pressing Enter with getchar() for reading a single character only?

yes you can do this on windows too, here's the code below, using the conio.h library

#include <iostream> //basic input/output
#include <conio.h>  //provides non standard getch() function
using namespace std;

int main()
{  
  cout << "Password: ";  
  string pass;
  while(true)
  {
             char ch = getch();    

             if(ch=='\r'){  //when a carriage return is found [enter] key
             cout << endl << "Your password is: " << pass <<endl; 
             break;
             }

             pass+=ch;             
             cout << "*";
             }
  getch();
  return 0;
}

ExecutorService that interrupts tasks after a timeout

Using John W answer I created an implementation that correctly begin the timeout when the task starts its execution. I even write a unit test for it :)

However, it does not suit my needs since some IO operations do not interrupt when Future.cancel() is called (ie when Thread.interrupt() is called). Some examples of IO operation that may not be interrupted when Thread.interrupt() is called are Socket.connect and Socket.read (and I suspect most of IO operation implemented in java.io). All IO operations in java.nio should be interruptible when Thread.interrupt() is called. For example, that is the case for SocketChannel.open and SocketChannel.read.

Anyway if anyone is interested, I created a gist for a thread pool executor that allows tasks to timeout (if they are using interruptible operations...): https://gist.github.com/amanteaux/64c54a913c1ae34ad7b86db109cbc0bf

How to generate a core dump in Linux on a segmentation fault?

Ubuntu 19.04

All other answers themselves didn't help me. But the following sum up did the job

Create ~/.config/apport/settings with the following content:

[main]
unpackaged=true

(This tells apport to also write core dumps for custom apps)

check: ulimit -c. If it outputs 0, fix it with

ulimit -c unlimited

Just for in case restart apport:

sudo systemctl restart apport

Crash files are now written in /var/crash/. But you cannot use them with gdb. To use them with gdb, use

apport-unpack <location_of_report> <target_directory>

Further information:

  • Some answers suggest changing core_pattern. Be aware, that that file might get overwritten by the apport service on restarting.
  • Simply stopping apport did not do the job
  • The ulimit -c value might get changed automatically while you're trying other answers of the web. Be sure to check it regularly during setting up your core dump creation.

References:

Correct format specifier to print pointer or address?

You can use %x or %X or %p; all of them are correct.

  • If you use %x, the address is given as lowercase, for example: a3bfbc4
  • If you use %X, the address is given as uppercase, for example: A3BFBC4

Both of these are correct.

If you use %x or %X it's considering six positions for the address, and if you use %p it's considering eight positions for the address. For example:

Webpack.config how to just copy the index.html to the dist folder

You can add the index directly to your entry config and using a file-loader to load it

module.exports = {

  entry: [
    __dirname + "/index.html",
    .. other js files here
  ],

  module: {
    rules: [
      {
        test: /\.html/, 
        loader: 'file-loader?name=[name].[ext]', 
      },
      .. other loaders
    ]
  }

}

html text input onchange event

I used this line to listen for input events from javascript.
It is useful because it listens for text change and text pasted events.

myElement.addEventListener('input', e => { myEvent() });

Fastest way to tell if two files have the same contents in Unix/Linux?

Doing some testing with a Raspberry Pi 3B+ (I'm using an overlay file system, and need to sync periodically), I ran a comparison of my own for diff -q and cmp -s; note that this is a log from inside /dev/shm, so disk access speeds are a non-issue:

[root@mypi shm]# dd if=/dev/urandom of=test.file bs=1M count=100 ; time diff -q test.file test.copy && echo diff true || echo diff false ; time cmp -s test.file test.copy && echo cmp true || echo cmp false ; cp -a test.file test.copy ; time diff -q test.file test.copy && echo diff true || echo diff false; time cmp -s test.file test.copy && echo cmp true || echo cmp false
100+0 records in
100+0 records out
104857600 bytes (105 MB) copied, 6.2564 s, 16.8 MB/s
Files test.file and test.copy differ

real    0m0.008s
user    0m0.008s
sys     0m0.000s
diff false

real    0m0.009s
user    0m0.007s
sys     0m0.001s
cmp false
cp: overwrite âtest.copyâ? y

real    0m0.966s
user    0m0.447s
sys     0m0.518s
diff true

real    0m0.785s
user    0m0.211s
sys     0m0.573s
cmp true
[root@mypi shm]# pico /root/rwbscripts/utils/squish.sh

I ran it a couple of times. cmp -s consistently had slightly shorter times on the test box I was using. So if you want to use cmp -s to do things between two files....

identical (){
  echo "$1" and "$2" are the same.
  echo This is a function, you can put whatever you want in here.
}
different () {
  echo "$1" and "$2" are different.
  echo This is a function, you can put whatever you want in here, too.
}
cmp -s "$FILEA" "$FILEB" && identical "$FILEA" "$FILEB" || different "$FILEA" "$FILEB"

How to count instances of character in SQL Column

try this

declare @v varchar(250) = 'test.a,1  ;hheuw-20;'
-- LF   ;
select len(replace(@v,';','11'))-len(@v)

Read all files in a folder and apply a function to each data frame

On the contrary, I do think working with list makes it easy to automate such things.

Here is one solution (I stored your four dataframes in folder temp/).

filenames <- list.files("temp", pattern="*.csv", full.names=TRUE)
ldf <- lapply(filenames, read.csv)
res <- lapply(ldf, summary)
names(res) <- substr(filenames, 6, 30)

It is important to store the full path for your files (as I did with full.names), otherwise you have to paste the working directory, e.g.

filenames <- list.files("temp", pattern="*.csv")
paste("temp", filenames, sep="/")

will work too. Note that I used substr to extract file names while discarding full path.

You can access your summary tables as follows:

> res$`df4.csv`
       A              B        
 Min.   :0.00   Min.   : 1.00  
 1st Qu.:1.25   1st Qu.: 2.25  
 Median :3.00   Median : 6.00  
 Mean   :3.50   Mean   : 7.00  
 3rd Qu.:5.50   3rd Qu.:10.50  
 Max.   :8.00   Max.   :16.00  

If you really want to get individual summary tables, you can extract them afterwards. E.g.,

for (i in 1:length(res))
  assign(paste(paste("df", i, sep=""), "summary", sep="."), res[[i]])

enum - getting value of enum on string conversion

I implemented access using the following

class D(Enum):
    x = 1
    y = 2

    def __str__(self):
        return '%s' % self.value

now I can just do

print(D.x) to get 1 as result.

You can also use self.name in case you wanted to print x instead of 1.

Writing an input integer into a cell

When asking a user for a response to put into a cell using the InputBox method, there are usually three things that can happen¹.

  1. The user types something in and clicks OK. This is what you expect to happen and you will receive input back that can be returned directly to a cell or a declared variable.
  2. The user clicks Cancel, presses Esc or clicks × (Close). The return value is a boolean False. This should be accounted for.
  3. The user does not type anything in but clicks OK regardless. The return value is a zero-length string.

If you are putting the return value into a cell, your own logic stream will dictate what you want to do about the latter two scenarios. You may want to clear the cell or you may want to leave the cell contents alone. Here is how to handle the various outcomes with a variant type variable and a Select Case statement.

    Dim returnVal As Variant

    returnVal = InputBox(Prompt:="Type a value:", Title:="Test Data")

    'if the user clicked Cancel, Close or Esc the False
    'is translated to the variant as a vbNullString
    Select Case True
        Case Len(returnVal) = 0
            'no value but user clicked OK - clear the target cell
            Range("A2").ClearContents
        Case Else
            'returned a value with OK, save it
            Range("A2") = returnVal
    End Select

¹ There is a fourth scenario when a specific type of InputBox method is used. An InputBox can return a formula, cell range error or array. Those are special cases and requires using very specific syntax options. See the supplied link for more.

urllib2 and json

To read json response use json.loads(). Here is the sample.

import json
import urllib
import urllib2

post_params = {
    'foo' : bar
}

params = urllib.urlencode(post_params)
response = urllib2.urlopen(url, params)
json_response = json.loads(response.read())

Github Push Error: RPC failed; result=22, HTTP code = 413

I had this error (error: RPC failed; result=22, HTTP code = 413) when I tried to push my initial commit to a new BitBucket repository. The error occurred for me because the BitBucket repo had no master branch. If you are using SourceTree you can create a master branch on the origin by pressing the Git Flow button.

Convert 4 bytes to int

You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.

new BigInteger(bytes).intValue();

or to denote polarity:

new BigInteger(1, bytes).intValue();

How to read and write into file using JavaScript?

This Javascript function presents a complete "Save As" Dialog box to the user who runs this through the browser. The user presses OK and the file is saved.

Edit: The following code only works with IE Browser since Firefox and Chrome have considered this code a security problem and has blocked it from working.

// content is the data you'll write to file<br/>
// filename is the filename<br/>
// what I did is use iFrame as a buffer, fill it up with text
function save_content_to_file(content, filename)
{
    var dlg = false;
    with(document){
     ir=createElement('iframe');
     ir.id='ifr';
     ir.location='about.blank';
     ir.style.display='none';
     body.appendChild(ir);
      with(getElementById('ifr').contentWindow.document){
           open("text/plain", "replace");
           charset = "utf-8";
           write(content);
           close();
           document.charset = "utf-8";
           dlg = execCommand('SaveAs', false, filename+'.txt');
       }
       body.removeChild(ir);
     }
    return dlg;
}

Invoke the function:

save_content_to_file("Hello", "C:\\test");

RegEx match open tags except XHTML self-contained tags

I agree that the right tool to parse XML and especially HTML is a parser and not a regular expression engine. However, like others have pointed out, sometimes using a regex is quicker, easier, and gets the job done if you know the data format.

Microsoft actually has a section of Best Practices for Regular Expressions in the .NET Framework and specifically talks about Consider[ing] the Input Source.

Regular Expressions do have limitations, but have you considered the following?

The .NET framework is unique when it comes to regular expressions in that it supports Balancing Group Definitions.

For this reason, I believe you CAN parse XML using regular expressions. Note however, that it must be valid XML (browsers are very forgiving of HTML and allow bad XML syntax inside HTML). This is possible since the "Balancing Group Definition" will allow the regular expression engine to act as a PDA.

Quote from article 1 cited above:

.NET Regular Expression Engine

As described above properly balanced constructs cannot be described by a regular expression. However, the .NET regular expression engine provides a few constructs that allow balanced constructs to be recognized.

  • (?<group>) - pushes the captured result on the capture stack with the name group.
  • (?<-group>) - pops the top most capture with the name group off the capture stack.
  • (?(group)yes|no) - matches the yes part if there exists a group with the name group otherwise matches no part.

These constructs allow for a .NET regular expression to emulate a restricted PDA by essentially allowing simple versions of the stack operations: push, pop and empty. The simple operations are pretty much equivalent to increment, decrement and compare to zero respectively. This allows for the .NET regular expression engine to recognize a subset of the context-free languages, in particular the ones that only require a simple counter. This in turn allows for the non-traditional .NET regular expressions to recognize individual properly balanced constructs.

Consider the following regular expression:

(?=<ul\s+id="matchMe"\s+type="square"\s*>)
(?>
   <!-- .*? -->                  |
   <[^>]*/>                      |
   (?<opentag><(?!/)[^>]*[^/]>)  |
   (?<-opentag></[^>]*[^/]>)     |
   [^<>]*
)*
(?(opentag)(?!))

Use the flags:

  • Singleline
  • IgnorePatternWhitespace (not necessary if you collapse regex and remove all whitespace)
  • IgnoreCase (not necessary)

Regular Expression Explained (inline)

(?=<ul\s+id="matchMe"\s+type="square"\s*>) # match start with <ul id="matchMe"...
(?>                                        # atomic group / don't backtrack (faster)
   <!-- .*? -->                 |          # match xml / html comment
   <[^>]*/>                     |          # self closing tag
   (?<opentag><(?!/)[^>]*[^/]>) |          # push opening xml tag
   (?<-opentag></[^>]*[^/]>)    |          # pop closing xml tag
   [^<>]*                                  # something between tags
)*                                         # match as many xml tags as possible
(?(opentag)(?!))                           # ensure no 'opentag' groups are on stack

You can try this at A Better .NET Regular Expression Tester.

I used the sample source of:

<html>
<body>
<div>
   <br />
   <ul id="matchMe" type="square">
      <li>stuff...</li>
      <li>more stuff</li>
      <li>
          <div>
               <span>still more</span>
               <ul>
                    <li>Another &gt;ul&lt;, oh my!</li>
                    <li>...</li>
               </ul>
          </div>
      </li>
   </ul>
</div>
</body>
</html>

This found the match:

   <ul id="matchMe" type="square">
      <li>stuff...</li>
      <li>more stuff</li>
      <li>
          <div>
               <span>still more</span>
               <ul>
                    <li>Another &gt;ul&lt;, oh my!</li>
                    <li>...</li>
               </ul>
          </div>
      </li>
   </ul>

although it actually came out like this:

<ul id="matchMe" type="square">           <li>stuff...</li>           <li>more stuff</li>           <li>               <div>                    <span>still more</span>                    <ul>                         <li>Another &gt;ul&lt;, oh my!</li>                         <li>...</li>                    </ul>               </div>           </li>        </ul>

Lastly, I really enjoyed Jeff Atwood's article: Parsing Html The Cthulhu Way. Funny enough, it cites the answer to this question that currently has over 4k votes.

Why do we use web.xml?

It's the default configuration for a Java web application; it's required.

WicketFilter

is applied to every HTTP request that's sent to this web app.

How to define the basic HTTP authentication using cURL correctly?

as header

AUTH=$(echo -ne "$BASIC_AUTH_USER:$BASIC_AUTH_PASSWORD" | base64 --wrap 0)

curl \
  --header "Content-Type: application/json" \
  --header "Authorization: Basic $AUTH" \
  --request POST \
  --data  '{"key1":"value1", "key2":"value2"}' \
  https://example.com/

cannot find zip-align when publishing app

If you are using gradle just update ypur gradle plugin!

Change line in build.gradle from:

classpath 'com.android.tools.build:gradle:0.9.+'

to:

classpath 'com.android.tools.build:gradle:0.11.+'

It works for me.

Note that variable buildToolsVersion (for me "20.0.0") must match your version of build-tools.

Good luck :)

Vue.js get selected option on @change

Use v-model to bind the value of selected option's value. Here is an example.

<select name="LeaveType" @change="onChange($event)" class="form-control" v-model="key">
   <option value="1">Annual Leave/ Off-Day</option>
   <option value="2">On Demand Leave</option>
</select>
<script>
var vm = new Vue({
    data: {
        key: ""
    },
    methods: {
        onChange(event) {
            console.log(event.target.value)
        }
    }
}
</script>

More reference can been seen from here.

Regular expression to match DNS hostname or IP Address?

To match a valid IP address use the following regex:

(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}

instead of:

([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])(\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])){3}

Explanation

Many regex engine match the first possibility in the OR sequence. For instance, try the following regex:

10.48.0.200

Test

Test the difference between good vs bad

What is the difference between CSS and SCSS?

Variable definitions right:

$      => SCSS, SASS
--     => CSS
@      => LESS

All answers is good but question a little different than answers

"about Sass. How is SCSS different from CSS" : scss is well formed CSS3 syntax. uses sass preprocessor to create that.

and if I use SCSS instead of CSS will it work the same? yes. if your ide supports sass preprocessor. than it will work same.

Sass has two syntaxes. The most commonly used syntax is known as “SCSS” (for “Sassy CSS”), and is a superset of CSS3’s syntax. This means that every valid CSS3 stylesheet is valid SCSS as well. SCSS files use the extension .scss.

The second, older syntax is known as the indented syntax (or just “.sass”). Inspired by Haml’s terseness, it’s intended for people who prefer conciseness over similarity to CSS. Instead of brackets and semicolons, it uses the indentation of lines to specify blocks. Files in the indented syntax use the extension .sass.


  • Furher Information About:

What Is A CSS Preprocessor?

CSS in itself is devoid of complex logic and functionality which is required to write reusable and organized code. As a result, a developer is bound by limitations and would face extreme difficulty in code maintenance and scalability, especially when working on large projects involving extensive code and multiple CSS stylesheets. This is where CSS Preprocessors come to the rescue.

A CSS Preprocessor is a tool used to extend the basic functionality of default vanilla CSS through its own scripting language. It helps us to use complex logical syntax like – variables, functions, mixins, code nesting, and inheritance to name a few, supercharging your vanilla CSS. By using CSS Preprocessors, you can seamlessly automate menial tasks, build reusable code snippets, avoid code repetition and bloating and write nested code blocks that are well organized and easy to read. However, browsers can only understand native vanilla CSS code and will be unable to interpret the CSS Preprocessor syntax. Therefore, the complex and advanced Preprocessor syntax needs to be first compiled into native CSS syntax which can then be interpreted by the browsers to avoid cross browser compatibility issues. While different Preprocessors have their own unique syntaxes, eventually all of them are compiled to the same native CSS code.

Moving forward in the article, we will take a look at the 3 most popular CSS Preprocessors currently being used by developers around the world i.e Sass, LESS, and Stylus. Before you decide the winner between Sass vs LESS vs Stylus, let us get to know them in detail first.

Sass – Syntactically Awesome Style Sheets

Sass is the acronym for “Syntactically Awesome Style Sheets”. Sass is not only the most popular CSS Preprocessor in the world but also one of the oldest, launched in 2006 by Hampton Catlin and later developed by Natalie Weizenbaum. Although Sass is written in Ruby language, a Precompiler LibSass allows Sass to be parsed in other languages and decouple it from Ruby. Sass has a massive active community and extensive learning resources available on the net for beginners. Thanks to its maturity, stability and powerful logical prowess, Sass has established itself to the forefront of CSS Preprocessor ahead of its rival peers.

Sass can be written in 2 syntaxes either using Sass or SCSS. What is the difference between the two? Let’s find out.

Syntax Declaration: Sass vs SCSS

  • SCSS stands for Sassy CSS. Unlike Sass, SCSS is not based on indentation.
  • .sass extension is used as original syntax for Sass, while SCSS offers a newer syntax with .scss extension.
  • Unlike Sass, SCSS has curly braces and semicolons, just like CSS.
  • Contrary to SCSS, Sass is difficult to read as it is quite deviant from CSS. Which is why SCSS it the more recommended Sass syntax as it is easier to read and closely resembles Native CSS while at the same time enjoying with power of Sass.

Consider the example below with Sass vs SCSS syntax along with Compiled CSS code.

Sass SYNTAX
    $font-color: #fff
    $bg-color: #00f

    #box
      color: $font-color
      background: $bg-color

SCSS SYNTAX
    $font-color: #fff;
    $bg-color: #00f;

    #box{
      color: $font-color;
      background: $bg-color;
    }

In both cases, be it Sass or SCSS, the compiled CSS code will be the same –

#box {
      color: #fff;
      background: #00f;

Usage of Sass

Arguably the most Popular front end framework Bootstrap is written in Sass. Up until version 3, Bootstrap was written in LESS but bootstrap 4 adopted Sass and boosted its popularity. A few of the big companies using Sass are – Zapier, Uber, Airbnb and Kickstarter.

LESS – Leaner Style Sheets

LESS is an acronym for “Leaner Stylesheets”. It was released in 2009 by Alexis Sellier, 3 years after the initial launch of Sass in 2006. While Sass is written in Ruby, LESS is written JavaScript. In fact, LESS is a JavaScript library that extends the functionality of native vanilla CSS with mixins, variables, nesting and rule set loop. Sass vs LESS has been a heated debate. It is no surprise that LESS is the strongest competitor to Sass and has the second-largest user base. However, When bootstrap dumped LESS in favor of Sass with the launch of Bootstrap 4, LESS has waned in popularity. One of the few disadvantages of LESS over Sass is that it does not support functions. Unlike Sass, LESS uses @ to declare variables which might cause confusion with @media and @keyframes. However, One key advantage of LESS over Sass and Stylus or any other preprocessors, is the ease of adding it in your project. You can do that either by using NPM or by incorporating Less.js file. Syntax Declaration: LESS Uses .less extension. Syntax of LESS is quite similar to SCSS with the exception that for declaring variables, instead of $ sign, LESS uses @.

@font-color: #fff;
    @bg-color: #00f

    #box{
      color: @font-color;
      background: @bg-color;
    }

COMPILED CSS
    #box {
        color: #fff;
        background: #00f;
      }

Usage Of LESS The popular Bootstrap framework until the launch of version 4 was written in LESS. However, another popular framework called SEMANTIC UI is still written in LESS. Among the big companies using Sass are – Indiegogo, Patreon, and WeChat

Stylus

The stylus was launched in 2010 by former Node JS developer TJ Holowaychuk, nearly 4 years after the release of Sass and 1 year after the release of LESS. The stylus is written Node JS and fits perfectly with JS stack. The stylus was heavily influenced by the logical prowess of the Sass and simplicity of LESS. Even though Stylus is still popular with Node JS developers, it hasn’t managed to carve out a sizeable share for itself. One advantage of Stylus over Sass or LESS, is that it is armed with extremely powerful built-in functions and is capable of handling heavy computing.

Syntax Declaration: Stylus Uses .styl extension. Stylus offers a great deal of flexibility in writing syntax, supports native CSS as well as allows omission of brackets colons and semicolons. Also, note that Stylus does not use @ or $ symbols for defining variables. Instead, Stylus uses the assignment operators to indicate a variable declaration.

STYLUS SYNTAX WRITTEN LIKE NATIVE CSS

font-color = #fff;
bg-color = #00f;

#box {
    color: font-color;
    background: bg-color;
}

OR

STYLUS SYNTAX WITHOUT CURLY BRACES

font-color = #fff;
bg-color = #00f;

#box 
    color: font-color;
    background: bg-color;

OR

STYLUS SYNTAX WITHOUT COLONS AND SEMICOLONS

font-color = #fff
bg-color = #00f

#box 
    color font-color
    background bg-color

CLEAR SCREEN - Oracle SQL Developer shortcut?

In the Oracle SQL-plus:

shift+del

What is the meaning of {...this.props} in Reactjs

It's called spread attributes and its aim is to make the passing of props easier.

Let us imagine that you have a component that accepts N number of properties. Passing these down can be tedious and unwieldy if the number grows.

<Component x={} y={} z={} />

Thus instead you do this, wrap them up in an object and use the spread notation

var props = { x: 1, y: 1, z:1 };
<Component {...props} />

which will unpack it into the props on your component, i.e., you "never" use {... props} inside your render() function, only when you pass the props down to another component. Use your unpacked props as normal this.props.x.

How do we use runOnUiThread in Android?

We use Worker Thread to make Apps smoother and avoid ANR's. We may need to update UI after the heavy process in worker Tread. The UI can only be updated from UI Thread. In such cases, we use Handler or runOnUiThread both have a Runnable run method that executes in UI Thread. The onClick method runs in UI thread so don't need to use runOnUiThread here.

Using Kotlin

While in Activity,

this.runOnUiThread {
      // Do stuff
}

From Fragment,

activity?.runOnUiThread {
      // Do stuff
}

Using Java,

this.runOnUiThread(new Runnable() {
     void run() {
         // Do stuff
     }
});

What does FETCH_HEAD in Git mean?

FETCH_HEAD is a short-lived ref, to keep track of what has just been fetched from the remote repository.

Actually, ... not always considering that, with Git 2.29 (Q4 2020), "git fetch"(man) learned --no-write-fetch-head option to avoid writing the FETCH_HEAD file.

See commit 887952b (18 Aug 2020) by Junio C Hamano (gitster).
(Merged by Junio C Hamano -- gitster -- in commit b556050, 24 Aug 2020)

fetch: optionally allow disabling FETCH_HEAD update

Signed-off-by: Derrick Stolee

If you run fetch but record the result in remote-tracking branches, and either if you do nothing with the fetched refs (e.g. you are merely mirroring) or if you always work from the remote-tracking refs (e.g. you fetch and then merge origin/branchname separately), you can get away with having no FETCH_HEAD at all.

Teach "git fetch"(man) a command line option "--[no-]write-fetch-head".

  • The default is to write FETCH_HEAD, and the option is primarily meant to be used with the "--no-" prefix to override this default, because there is no matching fetch.writeFetchHEAD configuration variable to flip the default to off (in which case, the positive form may become necessary to defeat it).

Note that under "--dry-run" mode, FETCH_HEAD is never written; otherwise you'd see list of objects in the file that you do not actually have.

Passing --write-fetch-head does not force [git fetch](https://github.com/git/git/blob/887952b8c680626f4721cb5fa57704478801aca4/Documentation/git-fetch.txt)<sup>([man](https://git-scm.com/docs/git-fetch))</sup> to write the file.

fetch-options now includes in its man page:

--[no-]write-fetch-head

Write the list of remote refs fetched in the FETCH_HEAD file directly under $GIT_DIR.
This is the default.

Passing --no-write-fetch-head from the command line tells Git not to write the file.
Under --dry-run option, the file is never written.


Consider also, still with Git 2.29 (Q4 2020), the FETCH_HEAD is now always read from the filesystem regardless of the ref backend in use, as its format is much richer than the normal refs, and written directly by "git fetch"(man) as a plain file..

See commit e811530, commit 5085aef, commit 4877c6c, commit e39620f (19 Aug 2020) by Han-Wen Nienhuys (hanwen).
(Merged by Junio C Hamano -- gitster -- in commit 98df75b, 27 Aug 2020)

refs: read FETCH_HEAD and MERGE_HEAD generically

Signed-off-by: Han-Wen Nienhuys

The FETCH_HEAD and MERGE_HEAD refs must be stored in a file, regardless of the type of ref backend. This is because they can hold more than just a single ref.

To accomodate them for alternate ref backends, read them from a file generically in refs_read_raw_ref().


With Git 2.29 (Q4 2020), Updates to on-demand fetching code in lazily cloned repositories.

See commit db3c293 (02 Sep 2020), and commit 9dfa8db, commit 7ca3c0a, commit 5c3b801, commit abcb7ee, commit e5b9421, commit 2b713c2, commit cbe566a (17 Aug 2020) by Jonathan Tan (jhowtan).
(Merged by Junio C Hamano -- gitster -- in commit b4100f3, 03 Sep 2020)

fetch: no FETCH_HEAD display if --no-write-fetch-head

Signed-off-by: Jonathan Tan

887952b8c6 ("fetch: optionally allow disabling FETCH_HEAD update", 2020-08-18, Git v2.29.0 -- merge listed in batch #10) introduced the ability to disable writing to FETCH_HEAD during fetch, but did not suppress the "<source> -> FETCH_HEAD" message when this ability is used.

This message is misleading in this case, because FETCH_HEAD is not written.

Also, because "fetch" is used to lazy-fetch missing objects in a partial clone, this significantly clutters up the output in that case since the objects to be fetched are potentially numerous.

Therefore, suppress this message when --no-write-fetch-head is passed (but not when --dry-run is set).

Move to next item using Java 8 foreach loop in stream

Using return; will work just fine. It will not prevent the full loop from completing. It will only stop executing the current iteration of the forEach loop.

Try the following little program:

public static void main(String[] args) {
    ArrayList<String> stringList = new ArrayList<>();
    stringList.add("a");
    stringList.add("b");
    stringList.add("c");

    stringList.stream().forEach(str -> {
        if (str.equals("b")) return; // only skips this iteration.

        System.out.println(str);
    });
}

Output:

a
c

Notice how the return; is executed for the b iteration, but c prints on the following iteration just fine.

Why does this work?

The reason the behavior seems unintuitive at first is because we are used to the return statement interrupting the execution of the whole method. So in this case, we expect the main method execution as a whole to be halted.

However, what needs to be understood is that a lambda expression, such as:

str -> {
    if (str.equals("b")) return;

    System.out.println(str);
}

... really needs to be considered as its own distinct "method", completely separate from the main method, despite it being conveniently located within it. So really, the return statement only halts the execution of the lambda expression.

The second thing that needs to be understood is that:

stringList.stream().forEach()

... is really just a normal loop under the covers that executes the lambda expression for every iteration.

With these 2 points in mind, the above code can be rewritten in the following equivalent way (for educational purposes only):

public static void main(String[] args) {
    ArrayList<String> stringList = new ArrayList<>();
    stringList.add("a");
    stringList.add("b");
    stringList.add("c");

    for(String s : stringList) {
        lambdaExpressionEquivalent(s);
    }
}

private static void lambdaExpressionEquivalent(String str) {
    if (str.equals("b")) {
        return;
    }

    System.out.println(str);
}

With this "less magic" code equivalent, the scope of the return statement becomes more apparent.

JQuery ajax call default timeout value

As an aside, when trying to diagnose a similar bug I realised that jquery's ajax error callback returns a status of "timeout" if it failed due to a timeout.

Here's an example:

$.ajax({
    url: "/ajax_json_echo/",
    timeout: 500,
    error: function(jqXHR, textStatus, errorThrown) {
        alert(textStatus); // this will be "timeout"
    }
});

Here it is on jsfiddle.

Using Ansible set_fact to create a dictionary from register results

I think I got there in the end.

The task is like this:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}"
  with_items: "{{ people.results }}"

It loops through each of the dicts (item) in the people.results array, each time creating a new dict like {Bob: "male"}, and combine()s that new dict in the genders array, which ends up like:

{
    "Bob": "male",
    "Thelma": "female"
}

It assumes the keys (the name in this case) will be unique.


I then realised I actually wanted a list of dictionaries, as it seems much easier to loop through using with_items:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default([]) + [ {'name': item.item.name, 'gender': item.stdout} ] }}"
  with_items: "{{ people.results }}"

This keeps combining the existing list with a list containing a single dict. We end up with a genders array like this:

[
    {'name': 'Bob', 'gender': 'male'},
    {'name': 'Thelma', 'gender': 'female'}
]

Copying and pasting data using VBA code

'So from this discussion i am thinking this should be the code then.

Sub Button1_Click()
    Dim excel As excel.Application
    Dim wb As excel.Workbook
    Dim sht As excel.Worksheet
    Dim f As Object

    Set f = Application.FileDialog(3)
    f.AllowMultiSelect = False
    f.Show

    Set excel = CreateObject("excel.Application")
    Set wb = excel.Workbooks.Open(f.SelectedItems(1))
    Set sht = wb.Worksheets("Data")

    sht.Activate
    sht.Columns("A:G").Copy
    Range("A1").PasteSpecial Paste:=xlPasteValues


    wb.Close
End Sub

'Let me know if this is correct or a step was missed. Thx.

How to get the last row of an Oracle a table

SELECT * FROM 
  MY_TABLE
WHERE 
  <your filters>
ORDER BY PRIMARY_KEY DESC FETCH FIRST ROW ONLY

Reading a simple text file

Here is a simple class that handles both raw and asset files :

public class ReadFromFile {

public static String raw(Context context, @RawRes int id) {
    InputStream is = context.getResources().openRawResource(id);
    int size = 0;
    try {
        size = is.available();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
    return readFile(size, is);
}

public static String asset(Context context, String fileName) {
    InputStream is = null;
    int size = 0;
    try {
        is = context.getAssets().open(fileName);
        AssetFileDescriptor fd = null;
        fd = context.getAssets().openFd(fileName);
        size = (int) fd.getLength();
        fd.close();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
    return readFile(size, is);
}


private static String readFile(int size, InputStream is) {
    try {
        byte buffer[] = new byte[size];
        is.read(buffer);
        is.close();
        return new String(buffer);
    } catch (Exception e) {
        e.printStackTrace();
        return "";
    }
}

}

For example :

ReadFromFile.raw(context, R.raw.textfile);

And for asset files :

ReadFromFile.asset(context, "file.txt");

Oracle find a constraint

maybe this can help..

SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";

How to include NA in ifelse?

You can't really compare NA with another value, so using == would not work. Consider the following:

NA == NA
# [1] NA

You can just change your comparison from == to %in%:

ifelse(is.na(test$time) | test$type %in% "A", NA, "1")
# [1] NA  "1" NA  "1"

Regarding your other question,

I could get this to work with my existing code if I could somehow change the result of is.na(test$type) to return FALSE instead of TRUE, but I'm not sure how to do that.

just use ! to negate the results:

!is.na(test$time)
# [1]  TRUE  TRUE FALSE  TRUE

CronJob not running

I want to add 2 points that I learned:

  1. Cron config files put in /etc/cron.d/ should not contain a dot (.). Otherwise, it won't be read by cron.
  2. If the user running your command is not in /etc/shadow. It won't be allowed to schedule cron.

Refs:

  1. http://manpages.ubuntu.com/manpages/xenial/en/man8/cron.8.html
  2. https://help.ubuntu.com/community/CronHowto

DateTimeFormat in TypeScript

This should work...

var displayDate = new Date().toLocaleDateString();

alert(displayDate);

But I suspect you are trying it on something else, for example:

var displayDate = Date.now.toLocaleDateString(); // No!

alert(displayDate);

SQL Column definition : default value and not null redundant?

I would say not.

If the column does accept null values, then there's nothing to stop you inserting a null value into the field. As far as I'm aware, the default value only applies on creation of a new row.

With not null set, then you can't insert a null value into the field as it'll throw an error.

Think of it as a fail safe mechanism to prevent nulls.

Angular ng-repeat Error "Duplicates in a repeater are not allowed."

I was having an issue in my project where I was using ng-repeat track by $index but the products were not getting reflecting when data comes from database. My code is as below:

<div ng-repeat="product in productList.productList track by $index">
  <product info="product"></product>
 </div>

In the above code, product is a separate directive to display the product.But i came to know that $index causes issue when we pass data out from the scope. So the data losses and DOM can not be updated.

I found the solution by using product.id as a key in ng-repeat like below:

<div ng-repeat="product in productList.productList track by product.id">
  <product info="product"></product>
 </div>

But the above code again fails and throws the below error when more than one product comes with same id:

angular.js:11706 Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater

So finally i solved the problem by making dynamic unique key of ng-repeat like below:

<div ng-repeat="product in productList.productList track by (product.id + $index)">
  <product info="product"></product>
 </div>

This solved my problem and hope this will help you in future.

How to change the font color in the textbox in C#?

Assuming WinForms, the ForeColor property allows to change all the text in the TextBox (not just what you're about to add):

TextBox.ForeColor = Color.Red;

To only change the color of certain words, look at RichTextBox.

Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings

Since PHP 5.5, there is a separate php.ini file for CLI interface. If You use symfony console from command line, then this specific php.ini is used.

In Ubuntu 13.10 check file:

/etc/php5/cli/php.ini

BAT file to open CMD in current directory

The simplest command to do this:
start

You can always run this in command line to open new command line window in the same location. Or you can place it in your .bat file.

Way to insert text having ' (apostrophe) into a SQL table

INSERT INTO exampleTbl VALUES('he doesn''t work for me')

If you're adding a record through ASP.NET, you can use the SqlParameter object to pass in values so you don't have to worry about the apostrophe's that users enter in.

How do I display a ratio in Excel in the format A:B?

Below is the formula I use. I had a problem using GCD, because I use fairly large numbers to calculate the ratios from, and I found ratios such as "209:1024" to be less useful than simply rounding so it displays either "1:" or ":1". I also prefer not to use macros, if at all possible. Below is the result.

=IF(A1>B1,((ROUND(A1/B1,0))&":"&(B1/B1)),((A1/A1)&":"&(ROUND(B1/A1,0))))

Some of the formula is unnecessary (e.g., "A1/A1"), but I included it to show the logic behind it. Also, you can toggle how much rounding occurs by playing with the setting on each ROUND function.

Reset textbox value in javascript

This worked for me:

$("#searchField").focus(function()
{ 
    this.value = ''; 
});

ORA-28040: No matching authentication protocol exception

This except for adding the following to sqlnet.ora

SQLNET.ALLOWED_LOGON_VERSION_CLIENT = 8
SQLNET.ALLOWED_LOGON_VERSION_SERVER = 8

If you get "ORA-01017: invalid username/password; logon denied" error, then you need to re-create your password.

How to determine total number of open/active connections in ms sql server 2005

As @jwalkerjr mentioned, you should be disposing of connections in code (if connection pooling is enabled, they are just returned to the connection pool). The prescribed way to do this is using the 'using' statement:

// Execute stored proc to read data from repository
using (SqlConnection conn = new SqlConnection(this.connectionString))
{
    using (SqlCommand cmd = conn.CreateCommand())
    {
        cmd.CommandText = "LoadFromRepository";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@ID", fileID);

        conn.Open();
        using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
        {
            if (rdr.Read())
            {
                filename = SaveToFileSystem(rdr, folderfilepath);
            }
        }
    }
}

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

"Case" can return single value only, but you can use complex type:

create type foo as (a int, b text);
select (case 1 when 1 then (1,'qq')::foo else (2,'ww')::foo end).*;

Memory errors and list limits?

The MemoryError exception that you are seeing is the direct result of running out of available RAM. This could be caused by either the 2GB per program limit imposed by Windows (32bit programs), or lack of available RAM on your computer. (This link is to a previous question).

You should be able to extend the 2GB by using 64bit copy of Python, provided you are using a 64bit copy of windows.

The IndexError would be caused because Python hit the MemoryError exception before calculating the entire array. Again this is a memory issue.

To get around this problem you could try to use a 64bit copy of Python or better still find a way to write you results to file. To this end look at numpy's memory mapped arrays.

You should be able to run you entire set of calculation into one of these arrays as the actual data will be written disk, and only a small portion of it held in memory.

How to return the output of stored procedure into a variable in sql server

With the Return statement from the proc, I needed to assign the temp variable and pass it to another stored procedure. The value was getting assigned fine but when passing it as a parameter, it lost the value. I had to create a temp table and set the variable from the table (SQL 2008)

From this: 
declare @anID int
exec @anID = dbo.StoredProc_Fetch @ID, @anotherID, @finalID
exec dbo.ADifferentStoredProc @anID (no value here)

To this:
declare @t table(id int) 
declare @anID int
insert into @t exec dbo.StoredProc_Fetch @ID, @anotherID, @finalID
set @anID= (select Top 1 * from @t)

java.sql.SQLException: Incorrect string value: '\xF0\x9F\x91\xBD\xF0\x9F...'

I had kind of the same problem and after going carefully against all charsets and finding that they were all right, I realized that the bugged property I had in my class was annotated as @Column instead of @JoinColumn (javax.presistence; hibernate) and it was breaking everything up.

Get form data in ReactJS

In many events in javascript, we have event which give an object including what event happened and what are the values, etc...

That's what we use with forms in ReactJs as well...

So in your code you set the state to the new value... something like this:

class UserInfo extends React.Component {

  constructor(props) {
    super(props);
    this.handleLogin = this.handleLogin.bind(this);
  }

  handleLogin(e) {
    e.preventDefault();
    for (const field in this.refs) {
      this.setState({this.refs[field]: this.refs[field].value});
    }
  }

  render() {
    return (
        <div>
          <form onSubmit={this.handleLogin}>
            <input ref="email" type="text" name="email" placeholder="Email" />
            <input ref="password" type="password" name="password" placeholder="Password" />
            <button type="button">Login</button>
          </form>
        </div>
    );
  }
}

export default UserInfo;

Also this is the form example in React v.16, just as reference for the form you creating in the future:

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

How do I remove/delete a folder that is not empty?

You can use os.system command for simplicity:

import os
os.system("rm -rf dirname")

As obvious, it actually invokes system terminal to accomplish this task.

AttributeError: 'module' object has no attribute 'urlretrieve'

A Python 2+3 compatible solution is:

import sys

if sys.version_info[0] >= 3:
    from urllib.request import urlretrieve
else:
    # Not Python 3 - today, it is most likely to be Python 2
    # But note that this might need an update when Python 4
    # might be around one day
    from urllib import urlretrieve

# Get file from URL like this:
urlretrieve("http://www-scf.usc.edu/~chiso/oldspice/m-b1-hello.mp3")

Get custom product attributes in Woocommerce

The answer to "Any idea for getting all attributes at once?" question is just to call function with only product id:

$array=get_post_meta($product->id);

key is optional, see http://codex.wordpress.org/Function_Reference/get_post_meta

What is the SQL command to return the field names of a table?

If you just want the column names, then

select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'tablename'

On MS SQL Server, for more information on the table such as the types of the columns, use

sp_help 'tablename'

Click event doesn't work on dynamically generated elements

Use the .on() method with delegated events

$('#staticParent').on('click', '.dynamicElement', function() {
    // Do something on an existent or future .dynamicElement
});

The .on() method allows you to delegate any desired event handler to:
current elements or future elements added to the DOM at a later time.

P.S: Don't use .live()! From jQuery 1.7+ the .live() method is deprecated.

How do I get the SharedPreferences from a PreferenceActivity in Android?

having to pass context around everywhere is really annoying me. the code becomes too verbose and unmanageable. I do this in every project instead...

public class global {
    public static Activity globalContext = null;

and set it in the main activity create

@Override
public void onCreate(Bundle savedInstanceState) {
    Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
            global.sdcardPath,
            ""));
    super.onCreate(savedInstanceState);

    //Start 
    //Debug.startMethodTracing("appname.Trace1");

    global.globalContext = this;

also all preference keys should be language independent, I'm shocked nobody has mentioned that.

getText(R.string.yourPrefKeyName).toString()

now call it very simply like this in one line of code

global.globalContext.getSharedPreferences(global.APPNAME_PREF, global.MODE_PRIVATE).getBoolean("isMetric", true);

How should I call 3 functions in order to execute them one after the other?

Since you tagged it with javascript, I would go with a timer control since your function names are 3, 5, and 8 seconds. So start your timer, 3 seconds in, call the first, 5 seconds in call the second, 8 seconds in call the third, then when it's done, stop the timer.

Normally in Javascript what you have is correct for the functions are running one after another, but since it looks like you're trying to do timed animation, a timer would be your best bet.

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

This is weird, but in my case whenever I wanted to retype the access id and the key by typing aws configure.

Adding the id access end up always with a mess in the access id entry in the file located ~/.aws/credentials(see the picture) The messed access id

I have removed this mess and left only the access id. And the error resolved.

Open Google Chrome from VBA/Excel

shell("C:\Users\USERNAME\AppData\Local\Google\Chrome\Application\Chrome.exe -url http:google.ca")

Javascript Cookie with no expiration date

All cookies expire as per the cookie specification, Maximum value you can set is

 2^31 - 1 = 2147483647 = 2038-01-19 04:14:07

So Maximum cookie life time is

$.cookie('subscripted_24', true, { expires: 2147483647 });

Get the generated SQL statement from a SqlCommand object?

If your database was Oracle and the sql text contains dynamic variables named like :1,:2 ,... then you can use:

string query = cmd.CommandText;
int i = 1;
foreach (OracleParameter p in cmd.Parameters)
  {
    query = query.Replace(":"+i.ToString(),((p.Value==null)?"":p.Value.ToString()));
    i++;
  }

Is it possible to pass parameters programmatically in a Microsoft Access update query?

I just tested this and it works in Access 2010.

Say you have a SELECT query with parameters:

PARAMETERS startID Long, endID Long;
SELECT Members.*
FROM Members
WHERE (((Members.memberID) Between [startID] And [endID]));

You run that query interactively and it prompts you for [startID] and [endID]. That works, so you save that query as [MemberSubset].

Now you create an UPDATE query based on that query:

UPDATE Members SET Members.age = [age]+1
WHERE (((Members.memberID) In (SELECT memberID FROM [MemberSubset])));

You run that query interactively and again you are prompted for [startID] and [endID] and it works well, so you save it as [MemberSubsetUpdate].

You can run [MemberSubsetUpdate] from VBA code by specifying [startID] and [endID] values as parameters to [MemberSubsetUpdate], even though they are actually parameters of [MemberSubset]. Those parameter values "trickle down" to where they are needed, and the query does work without human intervention:

Sub paramTest()
    Dim qdf As DAO.QueryDef
    Set qdf = CurrentDb.QueryDefs("MemberSubsetUpdate")
    qdf!startID = 1  ' specify
    qdf!endID = 2    '     parameters
    qdf.Execute
    Set qdf = Nothing
End Sub

Getting the error "Missing $ inserted" in LaTeX

It's actually the underscores. Use \_ instead, or include the underscore package.

How to convert Moment.js date to users local timezone?

Here's what I did:

var timestamp = moment.unix({{ time }});
var utcOffset = moment().utcOffset();
var local_time = timestamp.add(utcOffset, "minutes");
var dateString = local_time.fromNow();

Where {{ time }} is the utc timestamp.

Margin-Top not working for span element?

span element is display:inline; by default you need to make it inline-block or block

Change your CSS to be like this

span.first_title {
    margin-top: 20px;
    margin-left: 12px;
    font-weight: bold;
    font-size:24px;
    color: #221461;
    /*The change*/
    display:inline-block; /*or display:block;*/
}

PHP Redirect with POST data

function post(path, params, method) {
    method = method || "post"; // Set method to post by default if not specified.



    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
}

Example:

 post('url', {name: 'Johnny Bravo'});

Print Currency Number Format in PHP

The easiest answer is number_format().

echo "$ ".number_format($value, 2);

If you want your application to be able to work with multiple currencies and locale-aware formatting (1.000,00 for some of us Europeans for example), it becomes a bit more complex.

There is money_format() but it doesn't work on Windows and relies on setlocale(), which is rubbish in my opinion, because it requires the installation of (arbitrarily named) locale packages on server side.

If you want to seriously internationalize your application, consider using a full-blown internationalization library like Zend Framework's Zend_Locale and Zend_Currency.

Create a pointer to two-dimensional array

You could also add an offset if you want to use negative indexes:

uint8_t l_matrix[10][20];
uint8_t (*matrix_ptr)[20] = l_matrix+5;
matrix_ptr[-4][1]=7;

If your compiler gives an error or warning you could use:

uint8_t (*matrix_ptr)[20] = (uint8_t (*)[20]) l_matrix;

Remove table row after clicking table row delete button

you can do it like this:

<script>
    function SomeDeleteRowFunction(o) {
     //no clue what to put here?
     var p=o.parentNode.parentNode;
         p.parentNode.removeChild(p);
    }
    </script>

    <table>
       <tr>
           <td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)"></td>
       </tr>
       <tr>
           <td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)"></td>
       </tr>
       <tr>
           <td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)"></td>
       </tr>
    </table>

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

i am using like this.. its easy to understand first argument is mapStateToProps and second argument is mapDispatchToProps in the end connect with function/class.

const mapStateToProps = (state) => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter)
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch(toggleTodo(id))
    }
  }
}

export default connect(mapStateToProps,mapDispatchToProps)(TodoList);

Can anyone explain me StandardScaler?

StandardScaler performs the task of Standardization. Usually a dataset contains variables that are different in scale. For e.g. an Employee dataset will contain AGE column with values on scale 20-70 and SALARY column with values on scale 10000-80000.
As these two columns are different in scale, they are Standardized to have common scale while building machine learning model.

How to force browser to download file?

You are setting the response headers after writing the contents of the file to the output stream. This is quite late in the response lifecycle to be setting headers. The correct sequence of operations should be to set the headers first, and then write the contents of the file to the servlet's outputstream.

Therefore, your method should be written as follows (this won't compile as it is a mere representation):

response.setContentType("application/force-download");
response.setContentLength((int)f.length());
        //response.setContentLength(-1);
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-Disposition","attachment; filename=\"" + "xxx\"");//fileName);
...
...
File f= new File(fileName);

InputStream in = new FileInputStream(f);
BufferedInputStream bin = new BufferedInputStream(in);
DataInputStream din = new DataInputStream(bin);

while(din.available() > 0){
    out.print(din.readLine());
    out.print("\n");
}

The reason for the failure is that it is possible for the actual headers sent by the servlet would be different from what you are intending to send. After all, if the servlet container does not know what headers (which appear before the body in the HTTP response), then it may set appropriate headers to ensure that the response is valid; setting the headers after the file has been written is therefore futile and redundant as the container might have already set the headers. You could confirm this by looking at the network traffic using Wireshark or a HTTP debugging proxy like Fiddler or WebScarab.

You may also refer to the Java EE API documentation for ServletResponse.setContentType to understand this behavior:

Sets the content type of the response being sent to the client, if the response has not been committed yet. The given content type may include a character encoding specification, for example, text/html;charset=UTF-8. The response's character encoding is only set from the given content type if this method is called before getWriter is called.

This method may be called repeatedly to change content type and character encoding. This method has no effect if called after the response has been committed.

...

MySQL JOIN with LIMIT 1 on joined table

SELECT c.id, c.title, p.id AS product_id, p.title
FROM categories AS c
JOIN products AS p ON c.id = p.category_id
GROUP BY c.id

This will return the first data in products (equals limit 1)

Reading e-mails from Outlook with Python through MAPI

I had the same problem you did - didn't find much that worked. The following code, however, works like a charm.

import win32com.client

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
                                    # the inbox. You can change that number to reference
                                    # any other folder
messages = inbox.Items
message = messages.GetLast()
body_content = message.body
print body_content

Right way to convert data.frame to a numeric matrix, when df also contains strings?

I manually filled NAs by exporting the CSV then editing it and reimporting, as below.

Perhaps one of you experts might explain why this procedure worked so well (the first file had columns with data of types char, INT and num (floating point numbers)), which all became char type after STEP 1; but at the end of STEP 3 R correctly recognized the datatype of each column).

# STEP 1:
MainOptionFile <- read.csv("XLUopt_XLUstk_v3.csv",
                            header=T, stringsAsFactors=FALSE)
#... STEP 2:
TestFrame <- subset(MainOptionFile, str_locate(option_symbol,"120616P00034000") > 0)
write.csv(TestFrame, file = "TestFrame2.csv")
# ...
# STEP 3:
# I made various amendments to `TestFrame2.csv`, including replacing all missing data cells with appropriate numbers. I then read that amended data frame back into R as follows:    
XLU_34P_16Jun12 <- read.csv("TestFrame2_v2.csv",
                            header=T,stringsAsFactors=FALSE)

On arrival back in R, all columns had their correct measurement levels automatically recognized by R!

Jetty: HTTP ERROR: 503/ Service Unavailable

None of these answers worked for me.

I had to remove all deployed java web app:

  • Windows/Show View/Other...
  • Go the the Server folder and select "Servers"
  • Right-click on the J2EE Preview at localhost
  • Click to Add and Remove... Click Remove all

Then run the project on the server

The Error is gone!

You will have to stop the server before deploying another project because it will not be found by the server. Otherwise you will get a 404 error

SMTP server response: 530 5.7.0 Must issue a STARTTLS command first

Blockquote

I then modified the php.ini file to use it (commented out the other lines):

[mail function]
; For Win32 only.
; SMTP = smtp.gmail.com
; smtp_port = 25

; For Win32 only.
; sendmail_from = <e-mail username>@gmail.com

; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

Ignore the "For Unix only" comment, as this version of sendmail works for Windows.

You then have to configure the "sendmail.ini" file in the directory where sendmail was installed:

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=25
error_logfile=error.log
debug_logfile=debug.log
auth_username=<username>
auth_password=<password>
force_sender=<e-mail username>@gmail.com

http://byitcurious.blogspot.com.br/2009/04/solving-must-issue-starttls-command.html

> Blockquote

How do I increase the capacity of the Eclipse output console?

For CDT users / C/C++ build, also adjust the setting

in Window > Preferences

under C/C++ > Build > Console (!)

(This time in number of lines.)

This also affects the "CDT Global Build Console".

Disable spell-checking on HTML textfields

An IFrame WILL "trigger" the spell checker (if it has content-editable set to true) just as a textfield, at least in Chrome.

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

Spring Security Documentation mentions the reason for blocking // in the request.

For example, it could contain path-traversal sequences (like /../) or multiple forward slashes (//) which could also cause pattern-matches to fail. Some containers normalize these out before performing the servlet mapping, but others don’t. To protect against issues like these, FilterChainProxy uses an HttpFirewall strategy to check and wrap the request. Un-normalized requests are automatically rejected by default, and path parameters and duplicate slashes are removed for matching purposes.

So there are two possible solutions -

  1. remove double slash (preferred approach)
  2. Allow // in Spring Security by customizing the StrictHttpFirewall using the below code.

Step 1 Create custom firewall that allows slash in URL.

@Bean
public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
    StrictHttpFirewall firewall = new StrictHttpFirewall();
    firewall.setAllowUrlEncodedSlash(true);    
    return firewall;
}

Step 2 And then configure this bean in websecurity

@Override
public void configure(WebSecurity web) throws Exception {
    //@formatter:off
    super.configure(web);
    web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
....
}

Step 2 is an optional step, Spring Boot just needs a bean to be declared of type HttpFirewall and it will auto-configure it in filter chain.

Spring Security 5.4 Update

In Spring security 5.4 and above (Spring Boot >= 2.4.0), we can get rid of too many logs complaining about the request rejected by creating the below bean.

import org.springframework.security.web.firewall.RequestRejectedHandler;
import org.springframework.security.web.firewall.HttpStatusRequestRejectedHandler;

@Bean
RequestRejectedHandler requestRejectedHandler() {
   return new HttpStatusRequestRejectedHandler();
}

I cannot start SQL Server browser

I'm trying to setup rf online game to be played offline using MS SQL server 2019 and ended up with the same problem. The SQL Browser service won't start. Almost all answers in this post have been tried but the outcome is disappointing. I've got a weird idea to try start the SQL browser service manually and then change it to automatic after it runs. Luckily it works. So, just simply right click on SQL Server Browser ==> Properties ==>Service==>Start Mode==>Manual. After apply the changes right click on the SQL Server Browser again and start the service. After the service run change the start mode to automatic. Make sure the information provided on log on as: are correct.

Javascript Debugging line by line using Google Chrome

Assuming you're running on a Windows machine...

  1. Hit the F12 key
  2. Select the Scripts, or Sources, tab in the developer tools
  3. Click the little folder icon in the top level
  4. Select your JavaScript file
  5. Add a breakpoint by clicking on the line number on the left (adds a little blue marker)
  6. Execute your JavaScript

Then during execution debugging you can do a handful of stepping motions...

  • F8 Continue: Will continue until the next breakpoint
  • F10 Step over: Steps over next function call (won't enter the library)
  • F11 Step into: Steps into the next function call (will enter the library)
  • Shift + F11 Step out: Steps out of the current function

Update

After reading your updated post; to debug your code I would recommend temporarily using the jQuery Development Source Code. Although this doesn't directly solve your problem, it will allow you to debug more easily. For what you're trying to achieve I believe you'll need to step-in to the library, so hopefully the production code should help you decipher what's happening.

"date(): It is not safe to rely on the system's timezone settings..."

I had this error running php-fpm in a chroot jail. I tried creating etc/php.ini and /usr/share/zoneinfo in the chroot directory, but it just didn't work. I even tried strace-ing the php-fpm daemons to see what file they were missing - nothing jumped out.

So in case Google brings you here because you get this error when using php-fpm configured for chroot, you can probably fix it by adding this line to /etc/php-fpm.d/www.conf in the ENV section:

env[TZ] = America/New_York

A php-fpm restart is normally required for it to take effect. Hope this helps somebody out there.

Git Pull vs Git Rebase

git pull and git rebase are not interchangeable, but they are closely connected.

git pull fetches the latest changes of the current branch from a remote and applies those changes to your local copy of the branch. Generally this is done by merging, i.e. the local changes are merged into the remote changes. So git pull is similar to git fetch & git merge.

Rebasing is an alternative to merging. Instead of creating a new commit that combines the two branches, it moves the commits of one of the branches on top of the other.

You can pull using rebase instead of merge (git pull --rebase). The local changes you made will be rebased on top of the remote changes, instead of being merged with the remote changes.

Atlassian has some excellent documentation on merging vs. rebasing.

How do operator.itemgetter() and sort() work?

Looks like you're a little bit confused about all that stuff.

operator is a built-in module providing a set of convenient operators. In two words operator.itemgetter(n) constructs a callable that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it.

So, you can't use key=a[x][1] there, because python has no idea what x is. Instead, you could use a lambda function (elem is just a variable name, no magic there):

a.sort(key=lambda elem: elem[1])

Or just an ordinary function:

def get_second_elem(iterable):
    return iterable[1]

a.sort(key=get_second_elem)

So, here's an important note: in python functions are first-class citizens, so you can pass them to other functions as a parameter.

Other questions:

  1. Yes, you can reverse sort, just add reverse=True: a.sort(key=..., reverse=True)
  2. To sort by more than one column you can use itemgetter with multiple indices: operator.itemgetter(1,2), or with lambda: lambda elem: (elem[1], elem[2]). This way, iterables are constructed on the fly for each item in list, which are than compared against each other in lexicographic(?) order (first elements compared, if equal - second elements compared, etc)
  3. You can fetch value at [3,2] using a[2,1] (indices are zero-based). Using operator... It's possible, but not as clean as just indexing.

Refer to the documentation for details:

  1. operator.itemgetter explained
  2. Sorting list by custom key in Python

LINQ - Full Outer Join

I'm guessing @sehe's approach is stronger, but until I understand it better, I find myself leap-frogging off of @MichaelSander's extension. I modified it to match the syntax and return type of the built-in Enumerable.Join() method described here. I appended the "distinct" suffix in respect to @cadrell0's comment under @JeffMercado's solution.

public static class MyExtensions {

    public static IEnumerable<TResult> FullJoinDistinct<TLeft, TRight, TKey, TResult> (
        this IEnumerable<TLeft> leftItems, 
        IEnumerable<TRight> rightItems, 
        Func<TLeft, TKey> leftKeySelector, 
        Func<TRight, TKey> rightKeySelector,
        Func<TLeft, TRight, TResult> resultSelector
    ) {

        var leftJoin = 
            from left in leftItems
            join right in rightItems 
              on leftKeySelector(left) equals rightKeySelector(right) into temp
            from right in temp.DefaultIfEmpty()
            select resultSelector(left, right);

        var rightJoin = 
            from right in rightItems
            join left in leftItems 
              on rightKeySelector(right) equals leftKeySelector(left) into temp
            from left in temp.DefaultIfEmpty()
            select resultSelector(left, right);

        return leftJoin.Union(rightJoin);
    }

}

In the example, you would use it like this:

var test = 
    firstNames
    .FullJoinDistinct(
        lastNames,
        f=> f.ID,
        j=> j.ID,
        (f,j)=> new {
            ID = f == null ? j.ID : f.ID, 
            leftName = f == null ? null : f.Name,
            rightName = j == null ? null : j.Name
        }
    );

In the future, as I learn more, I have a feeling I'll be migrating to @sehe's logic given it's popularity. But even then I'll have to be careful, because I feel it is important to have at least one overload that matches the syntax of the existing ".Join()" method if feasible, for two reasons:

  1. Consistency in methods helps save time, avoid errors, and avoid unintended behavior.
  2. If there ever is an out-of-the-box ".FullJoin()" method in the future, I would imagine it will try to keep to the syntax of the currently existing ".Join()" method if it can. If it does, then if you want to migrate to it, you can simply rename your functions without changing the parameters or worrying about different return types breaking your code.

I'm still new with generics, extensions, Func statements, and other features, so feedback is certainly welcome.

EDIT: Didn't take me long to realize there was a problem with my code. I was doing a .Dump() in LINQPad and looking at the return type. It was just IEnumerable, so I tried to match it. But when I actually did a .Where() or .Select() on my extension I got an error: "'System Collections.IEnumerable' does not contain a definition for 'Select' and ...". So in the end I was able to match the input syntax of .Join(), but not the return behavior.

EDIT: Added "TResult" to the return type for the function. Missed that when reading the Microsoft article, and of course it makes sense. With this fix, it now seems the return behavior is in line with my goals after all.

What does %>% function mean in R?

%...% operators

%>% has no builtin meaning but the user (or a package) is free to define operators of the form %whatever% in any way they like. For example, this function will return a string consisting of its left argument followed by a comma and space and then it's right argument.

"%,%" <- function(x, y) paste0(x, ", ", y)

# test run

"Hello" %,% "World"
## [1] "Hello, World"

The base of R provides %*% (matrix mulitiplication), %/% (integer division), %in% (is lhs a component of the rhs?), %o% (outer product) and %x% (kronecker product). It is not clear whether %% falls in this category or not but it represents modulo.

expm The R package, expm, defines a matrix power operator %^%. For an example see Matrix power in R .

operators The operators R package has defined a large number of such operators such as %!in% (for not %in%). See http://cran.r-project.org/web/packages/operators/operators.pdf

igraph This package defines %--% , %->% and %<-% to select edges.

lubridate This package defines %m+% and %m-% to add and subtract months and %--% to define an interval. igraph also defines %--% .

Pipes

magrittr In the case of %>% the magrittr R package has defined it as discussed in the magrittr vignette. See http://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html

magittr has also defined a number of other such operators too. See the Additional Pipe Operators section of the prior link which discusses %T>%, %<>% and %$% and http://cran.r-project.org/web/packages/magrittr/magrittr.pdf for even more details.

dplyr The dplyr R package used to define a %.% operator which is similar; however, it has been deprecated and dplyr now recommends that users use %>% which dplyr imports from magrittr and makes available to the dplyr user. As David Arenburg has mentioned in the comments this SO question discusses the differences between it and magrittr's %>% : Differences between %.% (dplyr) and %>% (magrittr)

pipeR The R package, pipeR, defines a %>>% operator that is similar to magrittr's %>% and can be used as an alternative to it. See http://renkun.me/pipeR-tutorial/

The pipeR package also has defined a number of other such operators too. See: http://cran.r-project.org/web/packages/pipeR/pipeR.pdf

postlogic The postlogic package defined %if% and %unless% operators.

wrapr The R package, wrapr, defines a dot pipe %.>% that is an explicit version of %>% in that it does not do implicit insertion of arguments but only substitutes explicit uses of dot on the right hand side. This can be considered as another alternative to %>%. See https://winvector.github.io/wrapr/articles/dot_pipe.html

Bizarro pipe. This is not really a pipe but rather some clever base syntax to work in a way similar to pipes without actually using pipes. It is discussed in http://www.win-vector.com/blog/2017/01/using-the-bizarro-pipe-to-debug-magrittr-pipelines-in-r/ The idea is that instead of writing:

1:8 %>% sum %>% sqrt
## [1] 6

one writes the following. In this case we explicitly use dot rather than eliding the dot argument and end each component of the pipeline with an assignment to the variable whose name is dot (.) . We follow that with a semicolon.

1:8 ->.; sum(.) ->.; sqrt(.)
## [1] 6

Update Added info on expm package and simplified example at top. Added postlogic package.

How can I correctly format currency using jquery?

Expanding upon Melu's answer you can do this to functionalize the code and handle negative amounts.

Sample Output:
$5.23
-$5.23

function formatCurrency(total) {
    var neg = false;
    if(total < 0) {
        neg = true;
        total = Math.abs(total);
    }
    return (neg ? "-$" : '$') + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString();
}

Effective way to find any file's Encoding

I'd try the following steps:

1) Check if there is a Byte Order Mark

2) Check if the file is valid UTF8

3) Use the local "ANSI" codepage (ANSI as Microsoft defines it)

Step 2 works because most non ASCII sequences in codepages other that UTF8 are not valid UTF8.

Javascript/jQuery detect if input is focused

If you can use JQuery, then using the JQuery :focus selector will do the needful

$(this).is(':focus');

Add string in a certain position in Python

I think the above answers are fine, but I would explain that there are some unexpected-but-good side effects to them...

def insert(string_s, insert_s, pos_i=0):
    return string_s[:pos_i] + insert_s + string_s[pos_i:]

If the index pos_i is very small (too negative), the insert string gets prepended. If too long, the insert string gets appended. If pos_i is between -len(string_s) and +len(string_s) - 1, the insert string gets inserted into the correct place.

Callback functions in Java

A method is not (yet) a first-class object in Java; you can't pass a function pointer as a callback. Instead, create an object (which usually implements an interface) that contains the method you need and pass that.

Proposals for closures in Java—which would provide the behavior you are looking for—have been made, but none will be included in the upcoming Java 7 release.

What is a constant reference? (not a reference to a constant)

The statement icr=y; does not make the reference refer to y; it assigns the value of y to the variable that icr refers to, i.

References are inherently const, that is you can't change what they refer to. There are 'const references' which are really 'references to const', that is you can't change the value of the object they refer to. They are declared const int& or int const& rather than int& const though.

Run multiple python scripts concurrently

With Bash:

python script1.py &
python script2.py &

That's the entire script. It will run the two Python scripts at the same time.

Python could do the same thing itself but it would take a lot more typing and is a bad choice for the problem at hand.

I think it's possible though that you are taking the wrong approach to solving your problem, and I'd like to hear what you're getting at.

What is the difference between .NET Core and .NET Standard Class Library project types?

.NET Standard: Think of it as a big standard library. When using this as a dependency you can only make libraries (.DLLs), not executables. A library made with .NET standard as a dependency can be added to a Xamarin.Android, a Xamarin.iOS, a .NET Core Windows/OS X/Linux project.

.NET Core: Think of it as the continuation of the old .NET framework, just it's opensource and some stuff is not yet implemented and others got deprecated. It extends the .NET standard with extra functions, but it only runs on desktops. When adding this as a dependency you can make runnable applications on Windows, Linux and OS X. (Although console only for now, no GUIs). So .NET Core = .NET Standard + desktop specific stuff.

Also UWP uses it and the new ASP.NET Core uses it as a dependency too.

how to make password textbox value visible when hover an icon

<html>
<head>
</head>
<body>
<script>
function demo(){
    var d=document.getElementById('s1');
    var e=document.getElementById('show_f').value;
    var f=document.getElementById('show_f').type; 

    if(d.value=="show"){
        var f= document.getElementById('show_f').type="text";
        var g=document.getElementById('show_f').value=e;
        d.value="Hide";

    } else{
        var f= document.getElementById('show_f').type="password";
        var g=document.getElementById('show_f').value=e;
        d.value="show";
     }     
  }   
</script>   

<form method='post'>
Password: <input type='password' name='pass_f' maxlength='30' id='show_f'><input type="button" onclick="demo()" id="s1" value="show" style="height:25px; margin-left:5px;margin-top:3px;"><br><br>
<input type='submit' name='sub' value='Submit Now'>

</form>
</body>
</html>

Automating running command on Linux from Windows using PuTTY

Here is a totally out of the box solution.

  1. Install AutoHotKey (ahk)
  2. Map the script to a key (e.g. F9)
  3. In the ahk script, a) Ftp the commands (.ksh) file to the linux machine

    b) Use plink like below. Plink should be installed if you have putty.

plink sessionname -l username -pw password test.ksh

or

plink -ssh example.com -l username -pw password test.ksh

All the steps will be performed in sequence whenever you press F9 in windows.

Username and password in command for git push

According to the Git documentation, the last argument of the git push command can be the repository that you want to push to:

    git push [--all | --mirror | --tags] [-n | --dry-run] [--receive-pack=<git-receive-pack>]
             [--repo=<repository>] [-f | --force] [--prune] [-v | --verbose] [-u | --set-upstream]
             [<repository> [<refspec>…]]

And the repository parameter can be either a URL or a remote name.

So you can specify username and password the same way as you do in your example of clone command.

Finding the direction of scrolling in a UIScrollView?

This is what it worked for me (in Objective-C):

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView{

        NSString *direction = ([scrollView.panGestureRecognizer translationInView:scrollView.superview].y >0)?@"up":@"down";
        NSLog(@"%@",direction);
    }

Save matplotlib file to a directory

Here's the piece of code that saves plot to the selected directory. If the directory does not exist, it is created.

import os
import matplotlib.pyplot as plt

script_dir = os.path.dirname(__file__)
results_dir = os.path.join(script_dir, 'Results/')
sample_file_name = "sample"

if not os.path.isdir(results_dir):
    os.makedirs(results_dir)

plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.savefig(results_dir + sample_file_name)

Hexadecimal To Decimal in Shell Script

The error as reported appears when the variables are null (or empty):

$ unset var3 var4; var5=$(($var4-$var3))
bash: -: syntax error: operand expected (error token is "-")

That could happen because the value given to bc was incorrect. That might well be that bc needs UPPERcase values. It needs BFCA3000, not bfca3000. That is easily fixed in bash, just use the ^^ expansion:

var3=bfca3000; var3=`echo "ibase=16; ${var1^^}" | bc`

That will change the script to this:

#!/bin/bash

var1="bfca3000"
var2="efca3250"

var3="$(echo "ibase=16; ${var1^^}" | bc)"
var4="$(echo "ibase=16; ${var2^^}" | bc)"

var5="$(($var4-$var3))"

echo "Diference $var5"

But there is no need to use bc [1], as bash could perform the translation and substraction directly:

#!/bin/bash

var1="bfca3000"
var2="efca3250"

var5="$(( 16#$var2 - 16#$var1 ))"

echo "Diference $var5"

[1]Note: I am assuming the values could be represented in 64 bit math, as the difference was calculated in bash in your original script. Bash is limited to integers less than ((2**63)-1) if compiled in 64 bits. That will be the only difference with bc which does not have such limit.

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

In my case, it was working in x86 but not in x64.

It quite ridiculous, but in x64 the following change had to be added before it would work:

x86 -> szDsn = "DRIVER={MICROSOFT ACCESS DRIVER (*.mdb)};
x64 -> szDsn = "DRIVER={MICROSOFT ACCESS DRIVER (*.mdb, *.accdb)};

Note the addition of *.accdb.

How do I remove objects from an array in Java?

Arrgh, I can't get the code to show up correctly. Sorry, I got it working. Sorry again, I don't think I read the question properly.

String  foo[] = {"a","cc","a","dd"},
remove = "a";
boolean gaps[] = new boolean[foo.length];
int newlength = 0;

for (int c = 0; c<foo.length; c++)
{
    if (foo[c].equals(remove))
    {
        gaps[c] = true;
        newlength++;
    }
    else 
        gaps[c] = false;

    System.out.println(foo[c]);
}

String newString[] = new String[newlength];

System.out.println("");

for (int c1=0, c2=0; c1<foo.length; c1++)
{
    if (!gaps[c1])
    {
        newString[c2] = foo[c1];
        System.out.println(newString[c2]);
        c2++;
    }
}

Trying to load local JSON file to show data in a html page using JQuery

I would try to save my object as .txt file and then fetch it like this:

 $.get('yourJsonFileAsString.txt', function(data) {
   console.log( $.parseJSON( data ) );
 }); 

.NET - Get protocol, host, and port

Request.Url will return you the Uri of the request. Once you have that, you can retrieve pretty much anything you want. To get the protocol, call the Scheme property.

Sample:

Uri url = Request.Url;
string protocol = url.Scheme;

Hope this helps.

How to use doxygen to create UML class diagrams from C++ source

I think you will need to edit the doxys file and set GENERATE_UML (something like that) to true. And you need to have dot/graphviz installed.

How can I get the class name from a C++ object?

use typeid(class).name

// illustratory code assuming all includes/namespaces etc

#include <iostream>
#include <typeinfo>
using namespace std;

struct A{};
int main(){
   cout << typeid(A).name();
}

It is important to remember that this gives an implementation defined names.

As far as I know, there is no way to get the name of the object at run time reliably e.g. 'A' in your code.

EDIT 2:

#include <typeinfo>
#include <iostream>
#include <map>
using namespace std; 

struct A{
};
struct B{
};

map<const type_info*, string> m;

int main(){
    m[&typeid(A)] = "A";         // Registration here
    m[&typeid(B)] = "B";         // Registration here

    A a;
    cout << m[&typeid(a)];
}

Implementing a simple file download servlet

And to send a largFile

byte[] pdfData = getPDFData();

String fileType = "";

res.setContentType("application/pdf");

httpRes.setContentType("application/.pdf");
httpRes.addHeader("Content-Disposition", "attachment; filename=IDCards.pdf");
httpRes.setStatus(HttpServletResponse.SC_OK);
OutputStream out = res.getOutputStream();
System.out.println(pdfData.length);
         
out.write(pdfData);
System.out.println("sendDone");
out.flush();

Android Studio : unmappable character for encoding UTF-8

In Android Studio resolved it by

  1. Navigate to File > Editor > File Encodings.
  2. In global encoding set the encoding to ISO-8859-1
  3. In Project encoding set the encoding to UTF-8 and the same case to Default encoding for properties files.
  4. Rebuild project.

Redirecting to a page after submitting form in HTML

You need to use the jQuery AJAX or XMLHttpRequest() for post the data to the server. After data posting you can redirect your page to another page by window.location.href.

Example:

 var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      window.location.href = 'https://website.com/my-account';
    }
  };
  xhttp.open("POST", "demo_post.asp", true);
  xhttp.send();

jQuery: How to capture the TAB keypress within a Textbox

Edit: Since your element is dynamically inserted, you have to use delegated on() as in your example, but you should bind it to the keydown event, because as @Marc comments, in IE the keypress event doesn't capture non-character keys:

$("#parentOfTextbox").on('keydown', '#textbox', function(e) { 
  var keyCode = e.keyCode || e.which; 

  if (keyCode == 9) { 
    e.preventDefault(); 
    // call custom function here
  } 
});

Check an example here.

How to deal with INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES without uninstall?

Just delete the old build from the device and reinstall the same. Because device.keystore is already exist in the device so just uninstall the build and reinstall the APK thats all..

Thanks

What is the best way to check for Internet connectivity using .NET?

I am having issue on those method on my 3g Router/modem, because if internet is disconnected the router redirects the page to its response page, so you still get a steam and your code think there is internet. Apples (or others) have a hot-spot-dedection page which always returns a certain response. The following sample returns "Success" response. So you will be exactly sure you could connect the internet and get real response !

public static bool CheckForInternetConnection()
{
    try
    {       
        using (var webClient = new WebClient())
        using (var stream = webClient.OpenRead("http://captive.apple.com/hotspot-detect.html"))
        {
            if (stream != null)
            {
                //return true;
                stream.ReadTimeout = 1000;
                using (var reader = new StreamReader(stream, Encoding.UTF8, false))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (line == "<HTML><HEAD><TITLE>Success</TITLE></HEAD><BODY>Success</BODY></HTML>")
                        {
                            return true;
                        }
                        Console.WriteLine(line);
                    }
                }

            }
            return false;
        }
    }
    catch
    {

    }
    return false;
}

Why is volatile needed in C?

The Wiki say everything about volatile:

And the Linux kernel's doc also make a excellent notation about volatile:

How Can I Override Style Info from a CSS Class in the Body of a Page?

  • Id's are prior to classnames.
  • Tag attribue 'style=' is prior to CSS selectors.
  • !important word is prior to first two rules.
  • More specific CSS selectors are prior to less specific. More specific will be applied.

for example:

  • .divclass .spanclass is more specific than .spanclass
  • .divclass.divclass is more specific than .divclass
  • #divId .spanclass has ID that's why it is more specific than .divClass .spanClass
  • <div id="someDiv" style="color:red;"> has attribute and beats #someDiv{color:blue}
  • style: #someDiv{color:blue!important} will be applied over attribute style="color:red"

How to create a pivot query in sql server without aggregate function

SELECT *
FROM
(
SELECT [Period], [Account], [Value]
FROM TableName
) AS source
PIVOT
(
    MAX([Value])
    FOR [Period] IN ([2000], [2001], [2002])
) as pvt

Another way,

SELECT ACCOUNT,
      MAX(CASE WHEN Period = '2000' THEN Value ELSE NULL END) [2000],
      MAX(CASE WHEN Period = '2001' THEN Value ELSE NULL END) [2001],
      MAX(CASE WHEN Period = '2002' THEN Value ELSE NULL END) [2002]
FROM tableName
GROUP BY Account

Adding a new entry to the PATH variable in ZSH

OPTION 1: Add this line to ~/.zshrc:

export "PATH=$HOME/pear/bin:$PATH"

After that you need to run source ~/.zshrc in order your changes to take affect OR close this window and open a new one

OPTION 2: execute it inside the terminal console to add this path only to the current terminal window session. When you close the window/session, it will be lost.

Get Return Value from Stored procedure in asp.net

You need a parameter with Direction set to ParameterDirection.ReturnValue in code but no need to add an extra parameter in SP. Try this

  SqlParameter returnParameter = cmd.Parameters.Add("RetVal", SqlDbType.Int);
  returnParameter.Direction = ParameterDirection.ReturnValue;
  cmd.ExecuteNonQuery();

  int id = (int) returnParameter.Value;

How to delete from a table where ID is in a list of IDs?

delete from t
where id in (1, 4, 6, 7)

How to Lock/Unlock screen programmatically?

The androidmanifest.xml and policies.xml files on the sample page are invisible in my browser due to it trying to format the XML files as HTML. I'm only posting this for reference for the convenience of others, this is sourced from the sample page.

Thanks all for this helpful question!

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.kns"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".LockScreenActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".MyAdmin"
                android:permission="android.permission.BIND_DEVICE_ADMIN">
            <meta-data android:name="android.app.device_admin"
                       android:resource="@xml/policies" />
            <intent-filter>
                <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
            </intent-filter>
        </receiver>

    </application>
</manifest>

policies.xml

<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <limit-password />
        <watch-login />
        <reset-password />
        <force-lock />
        <wipe-data />
    </uses-policies>
</device-admin>

Capture Signature using HTML5 and iPad

A canvas element with some JavaScript would work great.

In fact, Signature Pad (a jQuery plugin) already has this implemented.

port forwarding in windows

I've solved it, it can be done executing:

netsh interface portproxy add v4tov4 listenport=4422 listenaddress=192.168.1.111 connectport=80 connectaddress=192.168.0.33

To remove forwarding:

netsh interface portproxy delete v4tov4 listenport=4422 listenaddress=192.168.1.111

Official docs

Move layouts up when soft keyboard is shown?

similar issue i was facing with my layout which consist scroll view inside. Whenever i try to select text in EditText,Copy/Cut/Paste action bar gets moved up with below code as such it does not resize layout

android:windowSoftInputMode="adjustPan"

By modifying it to as below

1) AndroidManifest.xml

android:windowSoftInputMode="stateVisible|adjustResize"

2) style.xml file ,in activity style

<item name="android:windowActionBarOverlay">true</item>

It worked.!!!!!!!!!!!!

How to launch Safari and open URL from iOS app

Here's what I did:

  1. I created an IBAction in the header .h files as follows:

    - (IBAction)openDaleDietrichDotCom:(id)sender;
    
  2. I added a UIButton on the Settings page containing the text that I want to link to.

  3. I connected the button to IBAction in File Owner appropriately.

  4. Then implement the following:

Objective-C

- (IBAction)openDaleDietrichDotCom:(id)sender {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.daledietrich.com"]];
}

Swift

(IBAction in viewController, rather than header file)

if let link = URL(string: "https://yoursite.com") {
  UIApplication.shared.open(link)
}

React Native android build failed. SDK location not found

You must write correct full path. Don't use '~/Library/Android/sdk'

vi ~/.bashrc

export ANDROID_HOME=/Users/{UserName}/Library/Android/sdk
export PATH=${PATH}:${ANDROID_HOME}/tools
export PATH=${PATH}:${ANDROID_HOME}/platform-tools

source ~/.bashrc

Struct with template variables in C++

The syntax is wrong. The typedef should be removed.

How do I specify unique constraint for multiple columns in MySQL?

I have a MySQL table:

CREATE TABLE `content_html` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_box_elements` int(11) DEFAULT NULL,
  `id_router` int(11) DEFAULT NULL,
  `content` mediumtext COLLATE utf8_czech_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_box_elements` (`id_box_elements`,`id_router`)
);

and the UNIQUE KEY works just as expected, it allows multiple NULL rows of id_box_elements and id_router.

I am running MySQL 5.1.42, so probably there was some update on the issue discussed above. Fortunately it works and hopefully it will stay that way.

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

use maven it will download all the required jar files for you.

in this case you need the below jar files:

slf4j-log4j12-1.6.1.jar slf4j-api-1.6.1.jar

These jars will also depend on the cassandra version which you are running. There are dependencies with cassandra version , jar version and jdk version you use.

You can use : jdk1.6 with : cassandra 1.1.12 and the above jars.

Is there a PowerShell "string does not contain" cmdlet or syntax?

If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains:

Get-Content $FileName | foreach-object { `
   if ($arrayofStringsNotInterestedIn -notcontains $_) { $) }

or better (IMO)

Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_}

Remove Safari/Chrome textinput/textarea glow

This is the solution for people that do care about accessibility.

Please, don't use outline:none; for disabling the focus outline. You are killing accessibility of the web if you do this. There is a accessible way of doing this.

Check out this article that I've written to explain how to remove the border in an accessible way.

The idea in short is to only show the outline border when we detect a keyboard user. Once a user starts using his mouse we disable the outline. As a result you get the best of the two.

Get the first element of an array

This is not so simple response in the real world. Suppose that we have these examples of possible responses that you can find in some libraries.

$array1 = array();
$array2 = array(1,2,3,4);
$array3 = array('hello'=>'world', 'foo'=>'bar');
$array4 = null;

var_dump('reset1', reset($array1));
var_dump('reset2', reset($array2));
var_dump('reset3', reset($array3));
var_dump('reset4', reset($array4)); // Warning

var_dump('array_shift1', array_shift($array1));
var_dump('array_shift2', array_shift($array2));
var_dump('array_shift3', array_shift($array3));
var_dump('array_shift4', array_shift($array4)); // Warning

var_dump('each1', each($array1));
var_dump('each2', each($array2));
var_dump('each3', each($array3));
var_dump('each4', each($array4)); // Warning

var_dump('array_values1', array_values($array1)[0]); // Notice
var_dump('array_values2', array_values($array2)[0]);
var_dump('array_values3', array_values($array3)[0]);
var_dump('array_values4', array_values($array4)[0]); // Warning

var_dump('array_slice1', array_slice($array1, 0, 1));
var_dump('array_slice2', array_slice($array2, 0, 1));
var_dump('array_slice3', array_slice($array3, 0, 1));
var_dump('array_slice4', array_slice($array4, 0, 1)); // Warning

list($elm) = $array1; // Notice
var_dump($elm);
list($elm) = $array2;
var_dump($elm);
list($elm) = $array3; // Notice
var_dump($elm);
list($elm) = $array4;
var_dump($elm);

Like you can see, we have several 'one line' solutions that work well in some cases, but not in all.

In my opinion, you have should that handler only with arrays.

Now talking about performance, assuming that we have always array, like this:

$elm = empty($array) ? null : ...($array);

...you would use without errors:
$array[count($array)-1];
array_shift
reset
array_values
array_slice

array_shift is faster than reset, that is more fast than [count()-1], and these three are faster than array_values and array_slice.

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

I just needed to parse a nested dictionary, like

{
    "x": {
        "a": 1,
        "b": 2,
        "c": 3
    }
}

where JsonConvert.DeserializeObject doesn't help. I found the following approach:

var dict = JObject.Parse(json).SelectToken("x").ToObject<Dictionary<string, int>>();

The SelectToken lets you dig down to the desired field. You can even specify a path like "x.y.z" to step further down into the JSON object.

How to generate a random number in C++?

Can get full Randomer class code for generating random numbers from here!

If you need random numbers in different parts of the project you can create a separate class Randomer to incapsulate all the random stuff inside it.

Something like that:

class Randomer {
    // random seed by default
    std::mt19937 gen_;
    std::uniform_int_distribution<size_t> dist_;

public:
    /*  ... some convenient ctors ... */ 

    Randomer(size_t min, size_t max, unsigned int seed = std::random_device{}())
        : gen_{seed}, dist_{min, max} {
    }

    // if you want predictable numbers
    void SetSeed(unsigned int seed) {
        gen_.seed(seed);
    }

    size_t operator()() {
        return dist_(gen_);
    }
};

Such a class would be handy later on:

int main() {
    Randomer randomer{0, 10};
    std::cout << randomer() << "\n";
}

You can check this link as an example how i use such Randomer class to generate random strings. You can also use Randomer if you wish.

bootstrap button shows blue outline when clicked

Try

.btn-primary:focus { 
  box-shadow: none !important; 
}

How to use the switch statement in R functions?

This is a more general answer to the missing "Select cond1, stmt1, ... else stmtelse" connstruction in R. It's a bit gassy, but it works an resembles the switch statement present in C

while (TRUE) {
  if (is.na(val)) {
    val <- "NULL"
    break
  }
  if (inherits(val, "POSIXct") || inherits(val, "POSIXt")) {
    val <- paste0("#",  format(val, "%Y-%m-%d %H:%M:%S"), "#")
    break
  }
  if (inherits(val, "Date")) {
    val <- paste0("#",  format(val, "%Y-%m-%d"), "#")
    break
  }
  if (is.numeric(val)) break
  val <- paste0("'", gsub("'", "''", val), "'")
  break
}

Linq select to new object

var x = from t in types
        group t by t.Type into grouped
        select new { type = grouped.Key,
                     count = grouped.Count() };

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

Unfortunately, no. This feature is not available for facebook albums.

Increasing the JVM maximum heap size for memory intensive applications

32-bit Java is limited to approximately 1.4 to 1.6 GB.

Oracle 32 bit heap FAQ

Quote

The maximum theoretical heap limit for the 32-bit JVM is 4G. Due to various additional constraints such as available swap, kernel address space usage, memory fragmentation, and VM overhead, in practice the limit can be much lower. On most modern 32-bit Windows systems the maximum heap size will range from 1.4G to 1.6G. On 32-bit Solaris kernels the address space is limited to 2G. On 64-bit operating systems running the 32-bit VM, the max heap size can be higher, approaching 4G on many Solaris systems.

Comparing the contents of two files in Sublime Text

You can actually compare files natively right in Sublime Text.

  1. Navigate to the folder containing them through Open Folder... or in a project
  2. Select the two files (ie, by holding Ctrl on Windows or ? on macOS) you want to compare in the sidebar
  3. Right click and select the Diff files... option.

How to convert an Instant to a date format?

If you want to convert an Instant to a Date:

Date myDate = Date.from(instant);

And then you can use SimpleDateFormat for the formatting part of your question:

SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
String formattedDate = formatter.format(myDate);

How to delete columns in pyspark dataframe

You can delete column like this:

df.drop("column Name).columns

In your case :

df.drop("id").columns

If you want to drop more than one column you can do:

dfWithLongColName.drop("ORIGIN_COUNTRY_NAME", "DEST_COUNTRY_NAME")

Warning: X may be used uninitialized in this function

When you use Vector *one you are merely creating a pointer to the structure but there is no memory allocated to it.

Simply use one = (Vector *)malloc(sizeof(Vector)); to declare memory and instantiate it.

Property [title] does not exist on this collection instance

You Should Used Collection keyword in Controller. Like Here..

public function ApiView(){
    return User::collection(Profile::all());
}

Here, User is Resource Name and Profile is Model Name. Thank You.

Create a dictionary with list comprehension

You can create a new dict for each pair and merge it with the previous dict:

reduce(lambda p, q: {**p, **{q[0]: q[1]}}, bla bla bla, {})

Obviously this approaches requires reduce from functools.

Add class to an element in Angular 4

you can try this without any java script you can do that just by using CSS

img:active,
img:focus,
img:hover{ 
border: 10px solid red !important
}

of if your case is to add any other css class by clicking you can use query selector like

<img id="image1" ng-click="changeClass(id)" >
<img id="image2" ng-click="changeClass(id)" >
<img id="image3" ng-click="changeClass(id)" >
<img id="image3" ng-click="changeClass(id)" >

in controller first search for any image with red border and remove it then by passing the image id add the border class to that image

$scope.changeClass = function(id){
angular.element(document.querySelector('.some-class').removeClass('.some-class');
angular.element(document.querySelector(id)).addClass('.some-class');
}

CSS div element - how to show horizontal scroll bars only?

you can also make it overflow: auto and give a maximum fixed height and width that way, when the text or whatever is in there, overflows it'll show only the required scrollbar