Programs & Examples On #User activity

Index was outside the bounds of the Array. (Microsoft.SqlServer.smo)

I found an issue with Diagram and Schema in SQL-Server 2016 that could be useful to the subject. I was editing diagram (related to, and with lot of tables of, the "sales" schema) and added a new table, BUT forgot to declare it schema, so it was with the default "dbo". Then when I returned to, and opened up, the schema "sales" and tried to add an existent table... Bluf! THAT Triggered exactly the same error described in that thread. I even tried the workaround (drag the table) but it didn't work. Suddenly I noticed that the schema was incorrect, I updated it, tried again, and Eureka! the problem was immediately away... Regards.

How to use vim in the terminal?

if you want to open all your .cpp files with one command, and have the window split in as many tiles as opened files, you can use:

vim -o $(find name ".cpp")

if you want to include a template in the place you are, you can use:

:r ~/myHeaderTemplate 

will import the file "myHeaderTemplate in the place the cursor was before starting the command.

you can conversely select visually some code and save it to a file

  1. select visually,
  2. add w ~/myPartialfile.txt

when you select visualy, after type ":" in order to enter a command, you'll see "'<,'>" appear after the ":"

'<,'>w ~/myfile $

^ if you add "~/myfile" to the command, the selected part of the file will be saved to myfile.

if you're editing a file an want to copy it :

:saveas newFileWithNewName 

How to create a readonly textbox in ASP.NET MVC3 Razor

With credits to the previous answer by @Bronek and @Shimmy:

This is like I have done the same thing in ASP.NET Core:

<input asp-for="DisabledField" disabled="disabled" />
<input asp-for="DisabledField" class="hidden" />

The first input is readonly and the second one passes the value to the controller and is hidden. I hope it will be useful for someone working with ASP.NET Core.

SELECT * WHERE NOT EXISTS

You didn't join the table in your query.

Your original query will always return nothing unless there are no records at all in eotm_dyn, in which case it will return everything.

Assuming these tables should be joined on employeeID, use the following:

SELECT  *
FROM    employees e
WHERE   NOT EXISTS
        (
        SELECT  null 
        FROM    eotm_dyn d
        WHERE   d.employeeID = e.id
        )

You can join these tables with a LEFT JOIN keyword and filter out the NULL's, but this will likely be less efficient than using NOT EXISTS.

Is there a way to create interfaces in ES6 / Node 4?

In comments debiasej wrote the mentioned below article explains more about design patterns (based on interfaces, classes):

http://loredanacirstea.github.io/es6-design-patterns/

Design patterns book in javascript may also be useful for you:

http://addyosmani.com/resources/essentialjsdesignpatterns/book/

Design pattern = classes + interface or multiple inheritance

An example of the factory pattern in ES6 JS (to run: node example.js):

"use strict";

// Types.js - Constructors used behind the scenes

// A constructor for defining new cars
class Car {
  constructor(options){
    console.log("Creating Car...\n");
    // some defaults
    this.doors = options.doors || 4;
    this.state = options.state || "brand new";
    this.color = options.color || "silver";
  }
}

// A constructor for defining new trucks
class Truck {
  constructor(options){
    console.log("Creating Truck...\n");
    this.state = options.state || "used";
    this.wheelSize = options.wheelSize || "large";
    this.color = options.color || "blue";
  }
}


// FactoryExample.js

// Define a skeleton vehicle factory
class VehicleFactory {}

// Define the prototypes and utilities for this factory

// Our default vehicleClass is Car
VehicleFactory.prototype.vehicleClass = Car;

// Our Factory method for creating new Vehicle instances
VehicleFactory.prototype.createVehicle = function ( options ) {

  switch(options.vehicleType){
    case "car":
      this.vehicleClass = Car;
      break;
    case "truck":
      this.vehicleClass = Truck;
      break;
    //defaults to VehicleFactory.prototype.vehicleClass (Car)
  }

  return new this.vehicleClass( options );

};

// Create an instance of our factory that makes cars
var carFactory = new VehicleFactory();
var car = carFactory.createVehicle( {
            vehicleType: "car",
            color: "yellow",
            doors: 6 } );

// Test to confirm our car was created using the vehicleClass/prototype Car

// Outputs: true
console.log( car instanceof Car );

// Outputs: Car object of color "yellow", doors: 6 in a "brand new" state
console.log( car );

var movingTruck = carFactory.createVehicle( {
                      vehicleType: "truck",
                      state: "like new",
                      color: "red",
                      wheelSize: "small" } );

// Test to confirm our truck was created with the vehicleClass/prototype Truck

// Outputs: true
console.log( movingTruck instanceof Truck );

// Outputs: Truck object of color "red", a "like new" state
// and a "small" wheelSize
console.log( movingTruck );

Convert pandas Series to DataFrame

Rather than create 2 temporary dfs you can just pass these as params within a dict using the DataFrame constructor:

pd.DataFrame({'email':sf.index, 'list':sf.values})

There are lots of ways to construct a df, see the docs

Apply function to pandas groupby

Regarding the issue with 'size', size is not a function on a dataframe, it is rather a property. So instead of using size(), plain size should work

Apart from that, a method like this should work

 def doCalculation(df):
    groupCount = df.size
    groupSum = df['my_labels'].notnull().sum()

    return groupCount / groupSum

dataFrame.groupby('my_labels').apply(doCalculation)

How do I configure HikariCP in my Spring Boot app in my application.properties files?

you can't use dataSourceClassName approach in application.properties configurations as said by @Andy Wilkinson. if you want to have dataSourceClassName anyway you can use Java Config as:

@Configuration
@ComponentScan
class DataSourceConfig {

 @Value("${spring.datasource.username}")
private String user;

@Value("${spring.datasource.password}")
private String password;

@Value("${spring.datasource.url}")
private String dataSourceUrl;

@Value("${spring.datasource.dataSourceClassName}")
private String dataSourceClassName;

@Value("${spring.datasource.poolName}")
private String poolName;

@Value("${spring.datasource.connectionTimeout}")
private int connectionTimeout;

@Value("${spring.datasource.maxLifetime}")
private int maxLifetime;

@Value("${spring.datasource.maximumPoolSize}")
private int maximumPoolSize;

@Value("${spring.datasource.minimumIdle}")
private int minimumIdle;

@Value("${spring.datasource.idleTimeout}")
private int idleTimeout;

@Bean
public DataSource primaryDataSource() {
    Properties dsProps = new Properties();
    dsProps.put("url", dataSourceUrl);
    dsProps.put("user", user);
    dsProps.put("password", password);
    dsProps.put("prepStmtCacheSize",250);
    dsProps.put("prepStmtCacheSqlLimit",2048);
    dsProps.put("cachePrepStmts",Boolean.TRUE);
    dsProps.put("useServerPrepStmts",Boolean.TRUE);

    Properties configProps = new Properties();
       configProps.put("dataSourceClassName", dataSourceClassName);
       configProps.put("poolName",poolName);
       configProps.put("maximumPoolSize",maximumPoolSize);
       configProps.put("minimumIdle",minimumIdle);
       configProps.put("minimumIdle",minimumIdle);
       configProps.put("connectionTimeout", connectionTimeout);
       configProps.put("idleTimeout", idleTimeout);
       configProps.put("dataSourceProperties", dsProps);

   HikariConfig hc = new HikariConfig(configProps);
   HikariDataSource ds = new HikariDataSource(hc);
   return ds;
   }
  } 

reason you cannot use dataSourceClassName because it will throw and exception

Caused by: java.lang.IllegalStateException: both driverClassName and dataSourceClassName are specified, one or the other should be used.

which mean spring boot infers from spring.datasource.url property the Driver and at the same time setting the dataSourceClassName creates this exception. To make it right your application.properties should look something like this for HikariCP datasource:

# hikariCP 
  spring.jpa.databasePlatform=org.hibernate.dialect.MySQLDialect
  spring.datasource.url=jdbc:mysql://localhost:3306/exampledb
  spring.datasource.username=root
  spring.datasource.password=
  spring.datasource.poolName=SpringBootHikariCP
  spring.datasource.maximumPoolSize=5
  spring.datasource.minimumIdle=3
  spring.datasource.maxLifetime=2000000
  spring.datasource.connectionTimeout=30000
  spring.datasource.idleTimeout=30000
  spring.datasource.pool-prepared-statements=true
  spring.datasource.max-open-prepared-statements=250

Note: Please check if there is any tomcat-jdbc.jar or commons-dbcp.jar in your classpath added most of the times by transitive dependency. If these are present in classpath Spring Boot will configure the Datasource using default connection pool which is tomcat. HikariCP will only be used to create the Datasource if there is no other provider in classpath. there is a fallback sequence from tomcat -> to HikariCP -> to Commons DBCP.

WebApi's {"message":"an error has occurred"} on IIS7, not in IIS Express

If you have <deployment retail="true"/> in your .NET Framework's machine.config, you won't see detailed error messages. Make sure that setting is false, or not present.

Convert JsonObject to String

There is an inbuilt method to convert a JSONObject to a String. Why don't you use that:

JSONObject json = new JSONObject();

json.toString();

what is this value means 1.845E-07 in excel?

1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.

1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.

C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.

You can specify a format string if you don't want to use the e-notation.

Vertical align middle with Bootstrap responsive grid

.row {
    letter-spacing: -.31em;
    word-spacing: -.43em;
}
.col-md-4 {
    float: none;
    display: inline-block;
    vertical-align: middle;
}

Note: .col-md-4 could be any grid column, its just an example here.

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

I haven't done web design for iOS but from what I recall seeing in the WWDC sessions and in documentation, the search bar in Mobile Safari, and navigation bars across the OS, will now automatically resize and shrink to show more of your content.

You can test this in Safari on an iPhone and notice that, when you scroll down to see more contents on a page, the navigation/search bar is hidden automatically.

Perhaps leaving the address bar/navigation bar as is, and not creating a full-screen experience, is what's best. I don't see Apple doing that anytime soon. And at most they are not automatically controlling when the address bar shows/hides.

Sure, you are losing screen real estate, specially on an iPhone 4 or 4S, but there doesn't seem to be an alternative as of Beta 4.

android get all contacts

//GET CONTACTLIST WITH ALL FIELD...       

public ArrayList < ContactItem > getReadContacts() {
         ArrayList < ContactItem > contactList = new ArrayList < > ();
         ContentResolver cr = getContentResolver();
         Cursor mainCursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
         if (mainCursor != null) {
          while (mainCursor.moveToNext()) {
           ContactItem contactItem = new ContactItem();
           String id = mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts._ID));
           String displayName = mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

           Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(id));
           Uri displayPhotoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);

           //ADD NAME AND CONTACT PHOTO DATA...
           contactItem.setDisplayName(displayName);
           contactItem.setPhotoUrl(displayPhotoUri.toString());

           if (Integer.parseInt(mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
            //ADD PHONE DATA...
            ArrayList < PhoneContact > arrayListPhone = new ArrayList < > ();
            Cursor phoneCursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] {
             id
            }, null);
            if (phoneCursor != null) {
             while (phoneCursor.moveToNext()) {
              PhoneContact phoneContact = new PhoneContact();
              String phone = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
              phoneContact.setPhone(phone);
              arrayListPhone.add(phoneContact);
             }
            }
            if (phoneCursor != null) {
             phoneCursor.close();
            }
            contactItem.setArrayListPhone(arrayListPhone);


            //ADD E-MAIL DATA...
            ArrayList < EmailContact > arrayListEmail = new ArrayList < > ();
            Cursor emailCursor = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] {
             id
            }, null);
            if (emailCursor != null) {
             while (emailCursor.moveToNext()) {
              EmailContact emailContact = new EmailContact();
              String email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
              emailContact.setEmail(email);
              arrayListEmail.add(emailContact);
             }
            }
            if (emailCursor != null) {
             emailCursor.close();
            }
            contactItem.setArrayListEmail(arrayListEmail);

            //ADD ADDRESS DATA...
            ArrayList < PostalAddress > arrayListAddress = new ArrayList < > ();
            Cursor addrCursor = getContentResolver().query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null, ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = ?", new String[] {
             id
            }, null);
            if (addrCursor != null) {
             while (addrCursor.moveToNext()) {
              PostalAddress postalAddress = new PostalAddress();
              String city = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
              String state = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
              String country = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
              postalAddress.setCity(city);
              postalAddress.setState(state);
              postalAddress.setCountry(country);
              arrayListAddress.add(postalAddress);
             }
            }
            if (addrCursor != null) {
             addrCursor.close();
            }
            contactItem.setArrayListAddress(arrayListAddress);
           }
           contactList.add(contactItem);
          }
         }
         if (mainCursor != null) {
          mainCursor.close();
         }
         return contactList;
        }



    //MODEL...
        public class ContactItem {

            private String displayName;
            private String photoUrl;
            private ArrayList<PhoneContact> arrayListPhone = new ArrayList<>();
            private ArrayList<EmailContact> arrayListEmail = new ArrayList<>();
            private ArrayList<PostalAddress> arrayListAddress = new ArrayList<>();


            public String getDisplayName() {
                return displayName;
            }

            public void setDisplayName(String displayName) {
                this.displayName = displayName;
            }

            public String getPhotoUrl() {
                return photoUrl;
            }

            public void setPhotoUrl(String photoUrl) {
                this.photoUrl = photoUrl;
            }

            public ArrayList<PhoneContact> getArrayListPhone() {
                return arrayListPhone;
            }

            public void setArrayListPhone(ArrayList<PhoneContact> arrayListPhone) {
                this.arrayListPhone = arrayListPhone;
            }

            public ArrayList<EmailContact> getArrayListEmail() {
                return arrayListEmail;
            }

            public void setArrayListEmail(ArrayList<EmailContact> arrayListEmail) {
                this.arrayListEmail = arrayListEmail;
            }

            public ArrayList<PostalAddress> getArrayListAddress() {
                return arrayListAddress;
            }

            public void setArrayListAddress(ArrayList<PostalAddress> arrayListAddress) {
                this.arrayListAddress = arrayListAddress;
            }
        }

        public class EmailContact
        {
            private String email = "";

            public String getEmail() {
                return email;
            }

            public void setEmail(String email) {
                this.email = email;
            }
        }

        public class PhoneContact
        {
            private String phone="";

            public String getPhone()
            {
                return phone;
            }

            public void setPhone(String phone) {
                this.phone = phone;
            }
        }


        public class PostalAddress
        {
            private String city="";
            private String state="";
            private String country="";

            public String getCity() {
                return city;
            }

            public void setCity(String city) {
                this.city = city;
            }

            public String getState() {
                return state;
            }

            public void setState(String state) {
                this.state = state;
            }

            public String getCountry() {
                return country;
            }

            public void setCountry(String country) {
                this.country = country;
            }
        }

How do you connect localhost in the Android emulator?

Use 10.0.2.2 to access your actual machine.

As you've learned, when you use the emulator, localhost (127.0.0.1) refers to the device's own loopback service, not the one on your machine as you may expect.

You can use 10.0.2.2 to access your actual machine, it is an alias set up to help in development.

For loop example in MySQL

Assume you have one table with name 'table1'. It contain one column 'col1' with varchar type. Query to crate table is give below

CREATE TABLE `table1` (
    `col1` VARCHAR(50) NULL DEFAULT NULL
)

Now if you want to insert number from 1 to 50 in that table then use following stored procedure

DELIMITER $$  
CREATE PROCEDURE ABC()

   BEGIN
      DECLARE a INT Default 1 ;
      simple_loop: LOOP         
         insert into table1 values(a);
         SET a=a+1;
         IF a=51 THEN
            LEAVE simple_loop;
         END IF;
   END LOOP simple_loop;
END $$

To call that stored procedure use

CALL `ABC`()

SVN check out linux

You can use checkout or co

$ svn co http://example.com/svn/app-name directory-name

Some short codes:-

  1. checkout (co)
  2. commit (ci)
  3. copy (cp)
  4. delete (del, remove,rm)
  5. diff (di)

What is "stdafx.h" used for in Visual Studio?

"Stdafx.h" is a precompiled header.It include file for standard system include files and for project-specific include files that are used frequently but are changed infrequently.which reduces compile time and Unnecessary Processing.

Precompiled Header stdafx.h is basically used in Microsoft Visual Studio to let the compiler know the files that are once compiled and no need to compile it from scratch. You can read more about it

http://www.cplusplus.com/articles/1TUq5Di1/

https://docs.microsoft.com/en-us/cpp/ide/precompiled-header-files?view=vs-2017

Resize external website content to fit iFrame width

Tip for 1 website resizing the height. But you can change to 2 websites.

Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.

  • local (iframe) page: just insert a code snippet
  • remote (external) page: you need a "body onload" and a "div" that holds all contents. And body needs to be styled to "margin:0"

Local:

<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>

<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
  if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>

You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).

Remote:

You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).

<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>

So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.

The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".

Hope this helps. Sorry for my english.

How to write a confusion matrix in Python?

A numpy-only solution for any number of classes that doesn't require looping:

import numpy as np

classes = 3
true = np.random.randint(0, classes, 50)
pred = np.random.randint(0, classes, 50)

np.bincount(true * classes + pred).reshape((classes, classes))

How to keep an iPhone app running on background fully operational

May be the link will Help bcz u might have to implement the code in Appdelegate in app run in background method .. Also consult the developer.apple.com site for application class Here is link for runing app in background

CSS Div width percentage and padding without breaking layout

You can also use the CSS calc() function to subtract the width of your padding from the percentage of your container's width.

An example:

width: calc((100%) - (32px))

Just be sure to make the subtracted width equal to the total padding, not just one half. If you pad both sides of the inner div with 16px, then you should subtract 32px from the final width, assuming that the example below is what you want to achieve.

_x000D_
_x000D_
.outer {_x000D_
  width: 200px;_x000D_
  height: 120px;_x000D_
  background-color: black;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  height: 40px;_x000D_
  top: 30px;_x000D_
  position: relative;_x000D_
  padding: 16px;_x000D_
  background-color: teal;_x000D_
}_x000D_
_x000D_
#inner-1 {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#inner-2 {_x000D_
  width: calc((100%) - (32px));_x000D_
}
_x000D_
<div class="outer" id="outer-1">_x000D_
  <div class="inner" id="inner-1"> width of 100% </div>_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div class="outer" id="outer-2">_x000D_
  <div class="inner" id="inner-2"> width of 100% - 16px </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the difference between mocking and spying when using Mockito?

The answer is in the documentation:

Real partial mocks (Since 1.8.0)

Finally, after many internal debates & discussions on the mailing list, partial mock support was added to Mockito. Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks.

Before release 1.8 spy() was not producing real partial mocks and it was confusing for some users. Read more about spying: here or in javadoc for spy(Object) method.

callRealMethod() was introduced after spy(), but spy() was left there of course, to ensure backward compatibility.

Otherwise, you're right: all the methods of a spy are real unless stubbed. All the methods of a mock are stubbed unless callRealMethod() is called. In general, I would prefer using callRealMethod(), because it doesn't force me to use the doXxx().when() idiom instead of the traditional when().thenXxx()

Calling an API from SQL Server stored procedure

I'd recommend using a CLR user defined function, if you already know how to program in C#, then the code would be;

using System.Data.SqlTypes;
using System.Net;

public partial class UserDefinedFunctions
{
 [Microsoft.SqlServer.Server.SqlFunction]
 public static SqlString http(SqlString url)
 {
  var wc = new WebClient();
  var html = wc.DownloadString(url.Value);
  return new SqlString (html);
 }
}

And here's installation instructions; https://blog.dotnetframework.org/2019/09/17/make-a-http-request-from-sqlserver-using-a-clr-udf/

How can I check if my Element ID has focus?

If you want to use jquery $("..").is(":focus").

You can take a look at this stack

Loop through an array in JavaScript

If you want a terse way to write a fast loop and you can iterate in reverse:

for (var i=myArray.length;i--;){
  var item=myArray[i];
}

This has the benefit of caching the length (similar to for (var i=0, len=myArray.length; i<len; ++i) and unlike for (var i=0; i<myArray.length; ++i)) while being fewer characters to type.

There are even some times when you ought to iterate in reverse, such as when iterating over a live NodeList where you plan on removing items from the DOM during iteration.

How to join on multiple columns in Pyspark?

You should use & / | operators and be careful about operator precedence (== has lower precedence than bitwise AND and OR):

df1 = sqlContext.createDataFrame(
    [(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
    ("x1", "x2", "x3"))

df2 = sqlContext.createDataFrame(
    [(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x3"))

df = df1.join(df2, (df1.x1 == df2.x1) & (df1.x2 == df2.x2))
df.show()

## +---+---+---+---+---+---+
## | x1| x2| x3| x1| x2| x3|
## +---+---+---+---+---+---+
## |  2|  b|3.0|  2|  b|0.0|
## +---+---+---+---+---+---+

gdb: how to print the current line or find the current line number?

Keep in mind that gdb is a powerful command -capable of low level instructions- so is tied to assembly concepts.

What you are looking for is called de instruction pointer, i.e:

The instruction pointer register points to the memory address which the processor will next attempt to execute. The instruction pointer is called ip in 16-bit mode, eip in 32-bit mode,and rip in 64-bit mode.

more detail here

all registers available on gdb execution can be shown with:

(gdb) info registers

with it you can find which mode your program is running (looking which of these registers exist)

then (here using most common register rip nowadays, replace with eip or very rarely ip if needed):

(gdb)info line *$rip

will show you line number and file source

(gdb) list *$rip

will show you that line with a few before and after

but probably

(gdb) frame

should be enough in many cases.

Can I change the checkbox size using CSS?

I think the simplest solution is re-style the checkbox as some users suggest. The CSS below is working for me, only requires a few lines of CSS, and answers the OP question:

input[type=checkbox] {
    -webkit-appearance: none;
    -moz-appearance: none;
    vertical-align: middle;
    width: 14px; 
    height: 14px;
    font-size: 14px;
    background-color: #eee;
}

input[type=checkbox]:checked:after {
    position: relative;
    bottom: 3px;
    left: 1px;
    color: blue;
    content: "\2713"; /* check mark */
}

As mentioned in this post, the zoom property seems not to work on Firefox, and transforms may cause undesired effects.

Tested on Chrome and Firefox, should work for all modern browsers. Just change the properties (colors, size, bottom, left, etc.) to your needs. Hope it helps!

Finding the 'type' of an input element

If you want to check the type of input within form, use the following code:

<script>
    function getFind(obj) {
    for (i = 0; i < obj.childNodes.length; i++) {
        if (obj.childNodes[i].tagName == "INPUT") {
            if (obj.childNodes[i].type == "text") {
                alert("this is Text Box.")
            }
            if (obj.childNodes[i].type == "checkbox") {
                alert("this is CheckBox.")
            }
            if (obj.childNodes[i].type == "radio") {
                alert("this is Radio.")
            }
        }
        if (obj.childNodes[i].tagName == "SELECT") {
            alert("this is Select")
        }
    }
}
</script>     

<script>    
    getFind(document.myform);  
</script>

How to download file from database/folder using php

here is the code to download file with how much % it is downloaded

<?php
$ch = curl_init();
$downloadFile = fopen( 'file name here', 'w' );
curl_setopt($ch, CURLOPT_URL, "file link here");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_BUFFERSIZE, 65536);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'downloadProgress'); 
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt( $ch, CURLOPT_FILE, $downloadFile );
curl_exec($ch);
curl_close($ch);

function downloadProgress ($resource, $download_size, $downloaded_size, $upload_size, $uploaded_size) {

    if($download_size!=0){
    $percen= (($downloaded_size/$download_size)*100);
    echo $percen."<br>";

}

}
?>

How to copy to clipboard in Vim?

For Ubuntu - July 2018

Use the register "+ to copy to the system clipboard (i.e. "+y instead of y).

Likewise you can paste from "+ to get text from the system clipboard (i.e. "+p instead of p).

You have to also make sure that vim is compiled with support for the clipboard. Try:

vim --version | grep .xterm_clipboard -o 

and if it's -xterm_clipboard (a minus prefix) then you do not have support.

Here are some instructions for swapping out with a working version of vim that has clipboard support.

  • $ sudo apt-get purge vim
  • $ sudo apt-get autoremove (removes any extraneous vim dependency packages from system)
  • $ sudo apt-get install vim-gnome (or sudo apt-get install vim-gtk3 for newer Ubuntu versions)

Check again with vim --version | grep .xterm_clipboard -o and you can confirm the clipboard is now available (ie. +xterm_clipboard)

Good luck.

How to fix Ora-01427 single-row subquery returns more than one row in select?

Use the following query:

SELECT E.I_EmpID AS EMPID,
       E.I_EMPCODE AS EMPCODE,
       E.I_EmpName AS EMPNAME,
       REPLACE(TO_CHAR(A.I_REQDATE, 'DD-Mon-YYYY'), ' ', '') AS FROMDATE,
       REPLACE(TO_CHAR(A.I_ENDDATE, 'DD-Mon-YYYY'), ' ', '') AS TODATE,
       TO_CHAR(NOD) AS NOD,
       DECODE(A.I_DURATION,
              'FD',
              'FullDay',
              'FN',
              'ForeNoon',
              'AN',
              'AfterNoon') AS DURATION,
       L.I_LeaveType AS LEAVETYPE,
       REPLACE(TO_CHAR((SELECT max(C.I_WORKDATE)
                         FROM T_COMPENSATION C
                        WHERE C.I_COMPENSATEDDATE = A.I_REQDATE
                          AND C.I_EMPID = A.I_EMPID),
                       'DD-Mon-YYYY'),
               ' ',
               '') AS WORKDATE,
       A.I_REASON AS REASON,
       AP.I_REJECTREASON AS REJECTREASON
  FROM T_LEAVEAPPLY A
 INNER JOIN T_EMPLOYEE_MS E
    ON A.I_EMPID = E.I_EmpID
   AND UPPER(E.I_IsActive) = 'YES'
   AND A.I_STATUS = '1'
 INNER JOIN T_LeaveType_MS L
    ON A.I_LEAVETYPEID = L.I_LEAVETYPEID
  LEFT OUTER JOIN T_APPROVAL AP
    ON A.I_REQDATE = AP.I_REQDATE
   AND A.I_EMPID = AP.I_EMPID
   AND AP.I_APPROVALSTATUS = '1'
 WHERE E.I_EMPID <> '22'
 ORDER BY A.I_REQDATE DESC

The trick is to force the inner query return only one record by adding an aggregate function (I have used max() here). This will work perfectly as far as the query is concerned, but, honestly, OP should investigate why the inner query is returning multiple records by examining the data. Are these multiple records really relevant business wise?

How to create a responsive image that also scales up in Bootstrap 3

Sure things!

.img-responsive is the right way to make images responsive with bootstrap 3 You can add some height rule for the picture you want to make responsive, because with responsibility, width changes along the height, fix it and there you are.

How do I find a particular value in an array and return its index?

#include <vector>
#include <algorithm>

int main()
{
     int arr[5] = {4, 1, 3, 2, 6};
     int x = -1;
     std::vector<int> testVector(arr, arr + sizeof(arr) / sizeof(int) );

     std::vector<int>::iterator it = std::find(testVector.begin(), testVector.end(), 3);
     if (it != testVector.end())
     {
          x = it - testVector.begin();
     }
     return 0;
}

Or you can just build a vector in a normal way, without creating it from an array of ints and then use the same solution as shown in my example.

How can I count the number of elements of a given value in a matrix?

Here's a list of all the ways I could think of to counting unique elements:

M = randi([1 7], [1500 1]);

Option 1: tabulate

t = tabulate(M);
counts1 = t(t(:,2)~=0, 2);

Option 2: hist/histc

counts2_1 = hist( M, numel(unique(M)) );
counts2_2 = histc( M, unique(M) );

Option 3: accumarray

counts3 = accumarray(M, ones(size(M)), [], @sum);
%# or simply: accumarray(M, 1);

Option 4: sort/diff

[MM idx] = unique( sort(M) );
counts4 = diff([0;idx]);

Option 5: arrayfun

counts5 = arrayfun( @(x)sum(M==x), unique(M) );

Option 6: bsxfun

counts6 = sum( bsxfun(@eq, M, unique(M)') )';

Option 7: sparse

counts7 = full(sparse(M,1,1));

How do I 'git diff' on a certain directory?

Not only you can add a path, but you can add git diff --relative to get result relative to that folder.

git -C a/folder diff --relative

And with Git 2.28 (Q3 2020), the commands in the "diff" family learned to honor the "diff.relative" configuration variable.

See commit c28ded8 (22 May 2020) by Laurent Arnoud (spk).
(Merged by Junio C Hamano -- gitster -- in commit e34df9a, 02 Jun 2020)

diff: add config option relative

Signed-off-by: Laurent Arnoud
Acked-by: Ðoàn Tr?n Công Danh

The diff.relative boolean option set to true shows only changes in the current directory/value specified by the path argument of the relative option and shows pathnames relative to the aforementioned directory.

Teach --no-relative to override earlier --relative

Add for git-format-patch(1) options documentation --relative and --no-relative

The documentation now includes:

diff.relative:

If set to 'true', 'git diff' does not show changes outside of the directory and show pathnames relative to the current directory.

For loop in multidimensional javascript array

You can do something like this:

var cubes = [
 [1, 2, 3],
 [4, 5, 6],    
 [7, 8, 9],
];

for(var i = 0; i < cubes.length; i++) {
    var cube = cubes[i];
    for(var j = 0; j < cube.length; j++) {
        display("cube[" + i + "][" + j + "] = " + cube[j]);
    }
}

Working jsFiddle:

The output of the above:

cube[0][0] = 1
cube[0][1] = 2
cube[0][2] = 3
cube[1][0] = 4
cube[1][1] = 5
cube[1][2] = 6
cube[2][0] = 7
cube[2][1] = 8
cube[2][2] = 9

stale element reference: element is not attached to the page document

According to @Abhishek Singh's you need to understand the problem:

What is the line which gives exception ?? The reason for this is because the element to which you have referred is removed from the DOM structure

and you can not refer to it anymore (imagine what element's ID has changed).

Follow the code:

class TogglingPage {
  @FindBy(...)
  private WebElement btnTurnOff;

  @FindBy(...)
  private WebElement btnTurnOn;

  TogglingPage turnOff() {
    this.btnTurnOff.isDisplayed();  
    this.btnTurnOff.click();          // when clicked, button should swap into btnTurnOn
    this.btnTurnOn.isDisplayed();
    this.btnTurnOn.click();           // when clicked, button should swap into btnTurnOff
    this.btnTurnOff.isDisplayed();    // throws an exception
    return new TogglingPage();
  }
}

Now, let us wonder why?

  1. btnTurnOff was found by a driver - ok
  2. btnTurnOff was replaced by btnTurnOn - ok
  3. btnTurnOn was found by a driver. - ok
  4. btnTurnOn was replaced by btnTurnOff - ok
  5. we call this.btnTurnOff.isDisplayed(); on the element which does not exist anymore in Selenium sense - you can see it, it works perfectly, but it is a different instance of the same button.

Possible fix:

  TogglingPage turnOff() {
    this.btnTurnOff.isDisplayed();  
    this.btnTurnOff.click();

    TogglingPage newPage = new TogglingPage();
    newPage.btnTurnOn.isDisplayed();
    newPage.btnTurnOn.click();

    TogglingPage newerPage = new TogglingPage();
    newerPage.btnTurnOff.isDisplayed();    // ok
    return newerPage;
  }

Remove pandas rows with duplicate indices

This adds the index as a dataframe column, drops duplicates on that, then removes the new column:

df = df.reset_index().drop_duplicates(subset='index', keep='last').set_index('index').sort_index()

Note that the use of .sort_index() above at the end is as needed and is optional.

Timeout jQuery effects

Update: As of jQuery 1.4 you can use the .delay( n ) method. http://api.jquery.com/delay/

$('.notice').fadeIn().delay(2000).fadeOut('slow'); 

Note: $.show() and $.hide() by default are not queued, so if you want to use $.delay() with them, you need to configure them that way:

$('.notice')
    .show({duration: 0, queue: true})
    .delay(2000)
    .hide({duration: 0, queue: true});

You could possibly use the Queue syntax, this might work:

jQuery(function($){ 

var e = $('.notice'); 
e.fadeIn(); 
e.queue(function(){ 
  setTimeout(function(){ 
    e.dequeue(); 
  }, 2000 ); 
}); 
e.fadeOut('fast'); 

}); 

or you could be really ingenious and make a jQuery function to do it.

(function($){ 

  jQuery.fn.idle = function(time)
  { 
      var o = $(this); 
      o.queue(function()
      { 
         setTimeout(function()
         { 
            o.dequeue(); 
         }, time);
      });
  };
})(jQuery);

which would ( in theory , working on memory here ) permit you do to this:

$('.notice').fadeIn().idle(2000).fadeOut('slow'); 

Table border left and bottom

Give a class .border-lb and give this CSS

.border-lb {border: 1px solid #ccc; border-width: 0 0 1px 1px;}

And the HTML

<table width="770">
  <tr>
    <td class="border-lb">picture (border only to the left and bottom ) </td>
    <td>text</td>
  </tr>
  <tr>
    <td>text</td>
    <td class="border-lb">picture (border only to the left and bottom) </td>
  </tr>
</table>

Screenshot

Fiddle: http://jsfiddle.net/FXMVL/

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

Interesting enough, this error also occurs, at time of opening when the .XLS? file is incorrectly formed or require repairs.

A hard to find error is to many rows on a .xls (old excel) file.

Test it: manually open the affected file with excel desktop .

I use automation to process a few hundred files daily, when this error show up, I notify the owner via mail and save the unprocessed file on a temporary location.

Python - How do you run a .py file?

On windows platform, you have 2 choices:

  1. In a command line terminal, type

    c:\python23\python xxxx.py

  2. Open the python editor IDLE from the menu, and open xxxx.py, then press F5 to run it.

For your posted code, the error is at this line:

def main(url, out_folder="C:\asdf\"):

It should be:

def main(url, out_folder="C:\\asdf\\"):

Peak signal detection in realtime timeseries data

This problem looks similar to one I encountered in a hybrid/embedded systems course, but that was related to detecting faults when the input from a sensor is noisy. We used a Kalman filter to estimate/predict the hidden state of the system, then used statistical analysis to determine the likelihood that a fault had occurred. We were working with linear systems, but nonlinear variants exist. I remember the approach being surprisingly adaptive, but it required a model of the dynamics of the system.

How does `scp` differ from `rsync`?

scp is best for one file.
OR a combination of tar & compression for smaller data sets like source code trees with small resources (ie: images, sqlite etc).


Yet, when you begin dealing with larger volumes say:

  • media folders (40 GB)
  • database backups (28 GB)
  • mp3 libraries (100 GB)

It becomes impractical to build a zip/tar.gz file to transfer with scp at this point do to the physical limits of the hosted server.

As an exercise, you can do some gymnastics like piping tar into ssh and redirecting the results into a remote file. (saving the need to build a swap or temporary clone aka zip or tar.gz)

However,

rsync simplify's this process and allows you to transfer data without consuming any additional disc space.

Also,

Continuous (cron?) updates use minimal changes vs full cloned copies speed up large data migrations over time.

tl;dr
scp == small scale (with room to build compressed files on the same drive)
rsync == large scale (with the necessity to backup large data and no room left)

What should every programmer know about security?

when you are building any enterprise or any of your own software,you should just think like a hacker.as we know hackers are also not expert in all the things,but when they find any vulnerability they start digging into it by gathering information about all the things and finally attack on our software.so for preventing such attacks we should follow some well known rules like:

  • always try to break your codes(use cheatsheets & google the things for more informations).
  • be updated for security flaws in your programming field.
  • and as mentioned above never trust in any type of user or automated inputs.
  • use opensource applications(their most security flaws are known and solved).

you can find more security resource on the following links:

for more information google about your application vendor security flows.

iOS: present view controller programmatically

If you are using Storyboard and your "add" viewController is in storyboard then set an identifier for your "add" viewcontroller in settings so you can do something like this:

UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"NameOfYourStoryBoard" 
                                                     bundle:nil];
AddTaskViewController *add = 
           [storyboard instantiateViewControllerWithIdentifier:@"viewControllerIdentifier"];

[self presentViewController:add 
                   animated:YES 
                 completion:nil];

if you do not have your "add" viewController in storyboard or a nib file and want to create the whole thing programmaticaly then appDocs says:

If you cannot define your views in a storyboard or a nib file, override the loadView method to manually instantiate a view hierarchy and assign it to the view property.

Importing larger sql files into MySQL

Had a similar problem, but in Windows. I was trying to figure out how to open a large MySql sql file in Windows, and these are the steps I had to take:

  • Go to the download website (http://dev.mysql.com/downloads/).
  • Download the MySQL Community Server and install it (select the developer or full install, so it will install client and server tools).
  • Open MySql Command Line Client from the Start menu.
  • Enter your password used in install.
  • In the prompt, mysql>, enter:

    CREATE DATABASE database_name;

    USE database_name;

    SOURCE myfile.sql

That should import your large file.

"Non-static method cannot be referenced from a static context" error

setLoanItem is an instance method, meaning you need an instance of the Media class in order to call it. You're attempting to call it on the Media type itself.

You may want to look into some basic object-oriented tutorials to see how static/instance members work.

Hibernate error: ids for this class must be manually assigned before calling save():

Resolved this problem using a Sequence ID defined in Oracle database.

ORACLE_DB_SEQ_ID is defined as a sequence for the table. Also look at the console to see the Hibernate SQL that is used to verify.

@Id
@Column(name = "MY_ID", unique = true, nullable = false)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "id_Sequence")
@SequenceGenerator(name = "id_Sequence", sequenceName = "ORACLE_DB_SEQ_ID")
Long myId;

Difference between text and varchar (character varying)

character varying(n), varchar(n) - (Both the same). value will be truncated to n characters without raising an error.

character(n), char(n) - (Both the same). fixed-length and will pad with blanks till the end of the length.

text - Unlimited length.

Example:

Table test:
   a character(7)
   b varchar(7)

insert "ok    " to a
insert "ok    " to b

We get the results:

a        | (a)char_length | b     | (b)char_length
----------+----------------+-------+----------------
"ok     "| 7              | "ok"  | 2

"SyntaxError: Unexpected token < in JSON at position 0"

Those who are using create-react-app and trying to fetch local json files.

As in create-react-app, webpack-dev-server is used to handle the request and for every request it serves the index.html. So you are getting

SyntaxError: Unexpected token < in JSON at position 0.

To solve this, you need to eject the app and modify the webpack-dev-server configuration file.

You can follow the steps from here.

ASP.NET MVC Bundle not rendering script files on staging server. It works on development server

Based on your comments, we need to go over how the Bundling mechanism works in MVC.

Edit: Based on the comment below by VSDev, you need to ensure WebGrease is installed into your project. NuGet would be the easiest was to install this package.

When you set a bundle configuration (Example not from above to illustrate)

bundles.Add(new ScriptBundle("~/bundles/mainJs")
      .Include("~/Scripts/mainSite.js")
      .Include("~/Scripts/helperStuff.js");

You then, in your views, call something like @Scripts.Render("~/bundles/mainJs"). When your web.config is set into a debug compilation OR you explicitly turn off bundling using the following line in your BundleConfig.cs file

BundleTable.EnableOptimizations = false;

Then, in your view, you will see the following rendered out

<script src="/Scripts/mainSite.js" type="text/javascript"></script>
<script src="/Scripts/helperStuff.js" type="text/javascript"></script>

These are the individual items that made up our bundle, uncompressed and listed individually. The reason these list out individually in debug mode is so that you can debug your scripts and see them as you wrote them (actual variable names, etc).

Now, when we are not in a debug compilation and have not turned off the EnableOptimizations feature, MVC will combine those files in our bundles, compress (minify) them and output only a single script tag.

<script src="/bundles/mainJs?v=someBigLongNumber" type="text/javascript"></script>

Notice that the source is the same as the name of the bundle from the bundle configurations. Also, the number after the ?v= will change anytime you change a file in that bundle. This is to help prevent caching of old js and css files by the client browsers.

Your scripts are still there and being outputted, but they are being compressed and combined into a single file called /bundles/mainJs. This feature is present to

A) compress the files and reduce information being transmitted and,

B) reduce the number of calls to a website to retrieve the necessary content to render the page.

Nothing is missing, it sounds like everything is working as intended. In a production site, the minification makes these files almost impossible to read, thus why the minification does not take affect while debugging.

As to why the jQuery UI is still being a single JS file, ensure someone didn't hard code that into your layout view. As for the JS errors, it could be errors that are present on your development box or perhaps something did not compress correctly (however, in all of my MVC development, I have not seen a JS error because of bad minification).

Subset of rows containing NA (missing) values in a chosen column of a data frame

NA is a special value in R, do not mix up the NA value with the "NA" string. Depending on the way the data was imported, your "NA" and "NULL" cells may be of various type (the default behavior is to convert "NA" strings to NA values, and let "NULL" strings as is).

If using read.table() or read.csv(), you should consider the "na.strings" argument to do clean data import, and always work with real R NA values.

An example, working in both cases "NULL" and "NA" cells :

DF <- read.csv("file.csv", na.strings=c("NA", "NULL"))
new_DF <- subset(DF, is.na(DF$Var2))

Getting hold of the outer class object from the inner class object

You could (but you shouldn't) use reflection for the job:

import java.lang.reflect.Field;

public class Outer {
    public class Inner {
    }

    public static void main(String[] args) throws Exception {

        // Create the inner instance
        Inner inner = new Outer().new Inner();

        // Get the implicit reference from the inner to the outer instance
        // ... make it accessible, as it has default visibility
        Field field = Inner.class.getDeclaredField("this$0");
        field.setAccessible(true);

        // Dereference and cast it
        Outer outer = (Outer) field.get(inner);
        System.out.println(outer);
    }
}

Of course, the name of the implicit reference is utterly unreliable, so as I said, you shouldn't :-)

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

I had same issue with the following version 12.0.3:

Could not load file or assembly 'Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified.

This issue was only in my Test project (xUnit) and was caused by lack of newtonsoft.json in this project.

What is important, I was testing code from another project where library was attached and works properly.

START_STICKY and START_NOT_STICKY

KISS answer

Difference:

START_STICKY

the system will try to re-create your service after it is killed

START_NOT_STICKY

the system will not try to re-create your service after it is killed


Standard example:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

"The specified Android SDK Build Tools version (26.0.0) is ignored..."

Open app/build.gradle file

Change buildToolsVersion to buildToolsVersion "26.0.2"

change compile 'com.android.support:appcompat to compile 'com.android.support:appcompat-v7:26.0.2'

Get checkbox values using checkbox name using jquery

You should include the brackets as well . . .

<input type="checkbox" name="bla[]" value="1" />

therefore referencing it should be as be name='bla[]'

$(document).ready( function () { 

   $("input[name='bla[]']").each( function () {
       alert( $(this).val() );
   });

});

Purpose of installing Twitter Bootstrap through npm?

  1. The point of using CDN is that it is faster, first of all, because it is a distributed network, but secondly, because the static files are being cached by the browsers and chances are high that, for example, the CDN's jquery library that your site uses had already been downloaded by the user's browser, and therefore the file had been cached, and therefore no unnecessary download is taking place. That being said, it is still a good idea to provide a fallback.

    Now, the point of bootstrap's npm package

    is that it provides bootstrap's javascript file as a module. As has been mentioned above, this makes it possible to require it using browserify, which is the most likely use case and, as I understand it, the main reason for bootstrap being published on npm.

  2. How to use it

    Imagine the following project structure:

    project
    |-- node_modules
    |-- public
    |   |-- css
    |   |-- img
    |   |-- js
    |   |-- index.html
    |-- package.json
    
    

In your index.html you can reference both css and js files like this:

<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
<script src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>

Which is the simplest way, and correct for the .css files. But it is much better to include the bootstrap.js file like this somewhere in your public/js/*.js files:

var bootstrap = require('bootstrap');

And you include this code only in those javascript files where you actually need bootstrap.js. Browserify takes care of including this file for you.

Now, the drawback is that you now have your front-end files as node_modules dependencies, and the node_modules folder is usually not checked in with git. I think this is the most controversial part, with many opinions and solutions.


UPDATE March 2017

Almost two years have passed since I wrote this answer and an update is in place.

Now the generally accepted way is to use a bundler like webpack (or another bundler of choice) to bundle all your assets in a build step.

Firstly, it allows you to use commonjs syntax just like browserify, so to include bootstrap js code in your project you do the same:

const bootstrap = require('bootstrap');

As for the css files, webpack has so called "loaders". They allow you write this in your js code:

require('bootstrap/dist/css/bootstrap.css');

and the css files will be "magically" included in your build. They will be dynamically added as <style /> tags when your app runs, but you can configure webpack to export them as a separate css file. You can read more about that in webpack's documentation.

In conclusion.

  1. You should "bundle" your app code with a bundler
  2. You shouldn't commit neither node_modules nor the dynamically built files to git. You can add a build script to npm which should be used to deploy files on server. Anyway, this can be done in different ways depending on your preferred build process.

if block inside echo statement?

You can always use the ( <condition> ? <value if true> : <value if false> ) syntax (it's called the ternary operator - thanks to Mark for remining me :) ).

If <condition> is true, the statement would be evaluated as <value if true>. If not, it would be evaluated as <value if false>

For instance:

$fourteen = 14;
$twelve = 12;
echo "Fourteen is ".($fourteen > $twelve ? "more than" : "not more than")." twelve";

This is the same as:

$fourteen = 14;
$twelve = 12;
if($fourteen > 12) {
  echo "Fourteen is more than twelve";
}else{
  echo "Fourteen is not more than twelve";
}

Check if a number is a perfect square

This response doesn't pertain to your stated question, but to an implicit question I see in the code you posted, ie, "how to check if something is an integer?"

The first answer you'll generally get to that question is "Don't!" And it's true that in Python, typechecking is usually not the right thing to do.

For those rare exceptions, though, instead of looking for a decimal point in the string representation of the number, the thing to do is use the isinstance function:

>>> isinstance(5,int)
True
>>> isinstance(5.0,int)
False

Of course this applies to the variable rather than a value. If I wanted to determine whether the value was an integer, I'd do this:

>>> x=5.0
>>> round(x) == x
True

But as everyone else has covered in detail, there are floating-point issues to be considered in most non-toy examples of this kind of thing.

Converting List<String> to String[] in Java

You want

String[] strarray = strlist.toArray(new String[0]);

See here for the documentation and note that you can also call this method in such a way that it populates the passed array, rather than just using it to work out what type to return. Also note that maybe when you print your array you'd prefer

System.out.println(Arrays.toString(strarray));

since that will print the actual elements.

How to Validate a DateTime in C#?

Here's another variation of the solution that returns true if the string can be converted to a DateTime type, and false otherwise.

public static bool IsDateTime(string txtDate)
{
    DateTime tempDate;
    return DateTime.TryParse(txtDate, out tempDate);
}

Getting All Variables In Scope

In ECMAScript 6 it's more or less possible by wrapping the code inside a with statement with a proxy object. Note it requires non-strict mode and it's bad practice.

_x000D_
_x000D_
function storeVars(target) {_x000D_
  return new Proxy(target, {_x000D_
    has(target, prop) { return true; },_x000D_
    get(target, prop) { return (prop in target ? target : window)[prop]; }_x000D_
  });_x000D_
}_x000D_
var vars = {}; // Outer variable, not stored._x000D_
with(storeVars(vars)) {_x000D_
  var a = 1;   // Stored in vars_x000D_
  var b = 2;   // Stored in vars_x000D_
  (function() {_x000D_
    var c = 3; // Inner variable, not stored._x000D_
  })();_x000D_
}_x000D_
console.log(vars);
_x000D_
_x000D_
_x000D_

The proxy claims to own all identifiers referenced inside with, so variable assignments are stored in the target. For lookups, the proxy retrieves the value from the proxy target or the global object (not the parent scope). let and const variables are not included.

Inspired by this answer by Bergi.

Group By Multiple Columns

Since C# 7 you can also use value tuples:

group x by (x.Column1, x.Column2)

or

.GroupBy(x => (x.Column1, x.Column2))

Why do python lists have pop() but not push()

Because "append" existed long before "pop" was thought of. Python 0.9.1 supported list.append in early 1991. By comparison, here's part of a discussion on comp.lang.python about adding pop in 1997. Guido wrote:

To implement a stack, one would need to add a list.pop() primitive (and no, I'm not against this particular one on the basis of any principle). list.push() could be added for symmetry with list.pop() but I'm not a big fan of multiple names for the same operation -- sooner or later you're going to read code that uses the other one, so you need to learn both, which is more cognitive load.

You can also see he discusses the idea of if push/pop/put/pull should be at element [0] or after element [-1] where he posts a reference to Icon's list:

I stil think that all this is best left out of the list object implementation -- if you need a stack, or a queue, with particular semantics, write a little class that uses a lists

In other words, for stacks implemented directly as Python lists, which already supports fast append(), and del list[-1], it makes sense that list.pop() work by default on the last element. Even if other languages do it differently.

Implicit here is that most people need to append to a list, but many fewer have occasion to treat lists as stacks, which is why list.append came in so much earlier.

Choosing line type and color in Gnuplot 4.0

Here is the syntax:

  set terminal pdf {monochrome|color|colour}
                   {{no}enhanced}
                   {fname "<font>"} {fsize <fontsize>}
                   {font "<fontname>{,<fontsize>}"}
                   {linewidth <lw>} {rounded|butt}
                   {solid|dashed} {dl <dashlength>}}
                   {size <XX>{unit},<YY>{unit}}

and an example:

set terminal pdfcairo monochrome enhanced font "Times-New-Roman,12" dashed

A valid provisioning profile for this executable was not found for debug mode

I had a certificate that expired (which generated the error).
Step 1. Go to developer.apple.com, login, and go to IOS provisioning portal

Step 2. Go to certificates (which is now empty), and follow the instructions listed to create a new certificate (open keychain on your computer, create a signing request, save it to disk, upload it to apple)

Step 3. Download and install the files created by apple to your keychain

Step 4. Problem: all of your previous provisioning profiles were associated with your OLD certificate, so you need to go back to developer.apple.com->IOS provising portal-> provisioning profiles and 'modify' each profile you care about. You will see that your identity is no longer assicated with the profile, so just click the check box

Step 5. Download all the profiles you changed

Step 6. Plugin your phone and drag and drop the .mobileprovision file onto xcode icon in the dock bar to install them on the device

What is Parse/parsing?

Parsing can be considered as a synonym of "Breaking down into small pieces" and then analysing what is there or using it in a modified way. In Java, Strings are parsed into Decimal, Octal, Binary, Hexadecimal, etc. It is done if your application is taking input from the user in the form of string but somewhere in your application you want to use that input in the form of an integer or of double type. It is not same as type casting. For type casting the types used should be compatible in order to caste but nothing such in parsing.

Aligning a float:left div to center?

.contentWrapper {
    float: left;
    clear: both;
    margin-left: 10%;
    margin-right: 10%;
}

.repeater {
    height: 9em;
    width: 9em;
    float: left;
    margin: 0.2em;
    position: relative;
    text-align: center;
    cursor: pointer;
}

How can I change from SQL Server Windows mode to mixed mode (SQL Server 2008)?

From this: http://weblogs.sqlteam.com/peterl/archive/2008/06/19/How-to-change-authentication-mode-in-SQL-Server.aspx

One can catch that you may change it through windows registry key

(SQLEXPRESS instance):

"Software\Microsoft\Microsoft SQL Server\SQLEXPRESS\LoginMode" = 2

... and restart service

Making WPF applications look Metro-styled, even in Windows 7? (Window Chrome / Theming / Theme)

Take a look at this WPF metro-styled window with optional glowing borders.

This is a stand-alone application using no other libraries than Microsoft.Windows.Shell (included) to create metro-styled windows with optional glowing borders.

Supports Windows all the way back to XP (.NET4).

How to remove the URL from the printing page?

<style type="text/css" media="print">
  @page {
    size: auto;  
    margin: 0;  
  }
</style>
//now set manual padding to body
<style>
  body{
    padding-left: 1.3cm;
    padding-right: 1.3cm; 
    padding-top: 1.1cm;
  }
</style>

What is the OAuth 2.0 Bearer Token exactly?

Bearer Token
A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

The Bearer Token is created for you by the Authentication server. When a user authenticates your application (client) the authentication server then goes and generates for you a Token. Bearer Tokens are the predominant type of access token used with OAuth 2.0. A Bearer token basically says "Give the bearer of this token access".

The Bearer Token is normally some kind of opaque value created by the authentication server. It isn't random; it is created based upon the user giving you access and the client your application getting access.

In order to access an API for example you need to use an Access Token. Access tokens are short lived (around an hour). You use the bearer token to get a new Access token. To get an access token you send the Authentication server this bearer token along with your client id. This way the server knows that the application using the bearer token is the same application that the bearer token was created for. Example: I can't just take a bearer token created for your application and use it with my application it wont work because it wasn't generated for me.

Google Refresh token looks something like this: 1/mZ1edKKACtPAb7zGlwSzvs72PvhAbGmB8K1ZrGxpcNM

copied from comment: I don't think there are any restrictions on the bearer tokens you supply. Only thing I can think of is that its nice to allow more than one. For example a user can authenticate the application up to 30 times and the old bearer tokens will still work. oh and if one hasn't been used for say 6 months I would remove it from your system. It's your authentication server that will have to generate them and validate them so how it's formatted is up to you.

Update:

A Bearer Token is set in the Authorization header of every Inline Action HTTP Request. For example:

POST /rsvp?eventId=123 HTTP/1.1
Host: events-organizer.com
Authorization: Bearer AbCdEf123456
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/1.0 (KHTML, like Gecko; Gmail Actions)

rsvpStatus=YES

The string "AbCdEf123456" in the example above is the bearer authorization token. This is a cryptographic token produced by the authentication server. All bearer tokens sent with actions have the issue field, with the audience field specifying the sender domain as a URL of the form https://. For example, if the email is from [email protected], the audience is https://example.com.

If using bearer tokens, verify that the request is coming from the authentication server and is intended for the the sender domain. If the token doesn't verify, the service should respond to the request with an HTTP response code 401 (Unauthorized).

Bearer Tokens are part of the OAuth V2 standard and widely adopted by many APIs.

RecyclerView expand/collapse items

Not saying this is the best approach, but it seems to work for me.

The full code may be found at: Example code at: https://github.com/dbleicher/recyclerview-grid-quickreturn

First off, add the expanded area to your cell/item layout, and make the enclosing cell layout animateLayoutChanges="true". This will ensure that the expand/collapse is animated:

<LinearLayout
    android:id="@+id/llCardBack"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:animateLayoutChanges="true"
    android:padding="4dp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center|fill_horizontal"
        android:padding="10dp"
        android:gravity="center"
        android:background="@android:color/holo_green_dark"
        android:text="This is a long title to show wrapping of text in the view."
        android:textColor="@android:color/white"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/tvSubTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center|fill_horizontal"
        android:background="@android:color/holo_purple"
        android:padding="6dp"
        android:text="My subtitle..."
        android:textColor="@android:color/white"
        android:textSize="12sp" />

    <LinearLayout
        android:id="@+id/llExpandArea"
        android:visibility="gone"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="6dp"
            android:text="Item One" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="6dp"
            android:text="Item Two" />

    </LinearLayout>
</LinearLayout>

Then, make your RV Adapter class implement View.OnClickListener so that you can act on the item being clicked. Add an int field to hold the position of the one expanded view, and initialize it to a negative value:

private int expandedPosition = -1;

Finally, implement your ViewHolder, onBindViewHolder() methods and override the onClick() method. You will expand the view in onBindViewHolder if it's position is equal to "expandedPosition", and hide it if not. You set the value of expandedPosition in the onClick listener:

@Override
public void onBindViewHolder(RVAdapter.ViewHolder holder, int position) {

    int colorIndex = randy.nextInt(bgColors.length);
    holder.tvTitle.setText(mDataset.get(position));
    holder.tvTitle.setBackgroundColor(bgColors[colorIndex]);
    holder.tvSubTitle.setBackgroundColor(sbgColors[colorIndex]);

    if (position == expandedPosition) {
        holder.llExpandArea.setVisibility(View.VISIBLE);
    } else {
        holder.llExpandArea.setVisibility(View.GONE);
    }
}

@Override
public void onClick(View view) {
    ViewHolder holder = (ViewHolder) view.getTag();
    String theString = mDataset.get(holder.getPosition());

    // Check for an expanded view, collapse if you find one
    if (expandedPosition >= 0) {
        int prev = expandedPosition;
        notifyItemChanged(prev);
    }
    // Set the current position to "expanded"
    expandedPosition = holder.getPosition();
    notifyItemChanged(expandedPosition);

    Toast.makeText(mContext, "Clicked: "+theString, Toast.LENGTH_SHORT).show();
}

/**
 * Create a ViewHolder to represent your cell layout
 * and data element structure
 */
public static class ViewHolder extends RecyclerView.ViewHolder {
    TextView tvTitle;
    TextView tvSubTitle;
    LinearLayout llExpandArea;

    public ViewHolder(View itemView) {
        super(itemView);

        tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
        tvSubTitle = (TextView) itemView.findViewById(R.id.tvSubTitle);
        llExpandArea = (LinearLayout) itemView.findViewById(R.id.llExpandArea);
    }
}

This should expand only one item at a time, using the system-default animation for the layout change. At least it works for me. Hope it helps.

Is there a way to include commas in CSV columns without breaking the formatting?

I faced the same problem and quoting the , did not help. Eventually, I replaced the , with +, finished the processing, saved the output into an outfile and replaced the + with ,. This may seem ugly but it worked for me.

how to create a cookie and add to http response from inside my service layer?

In Spring MVC you get the HtppServletResponce object by default .

   @RequestMapping("/myPath.htm")
    public ModelAndView add(HttpServletRequest request,
         HttpServletResponse response) throws Exception{
            //Do service call passing the response
    return new ModelAndView("CustomerAddView");
    }

//Service code
Cookie myCookie =
  new Cookie("name", "val");
  response.addCookie(myCookie);

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

Only the "drop armageddon" solution worked for me:

  • remove app from device
  • clean project
  • run new install on device

adb command for getting ip address assigned by operator

Try this command, it will help you to get ipaddress

adb shell ifconfig tiwlan0

tiwlan0 is the name of the wi-fi network interface on the device. This is generic command for getting ipaddress,

 adb shell netcfg

It will output like this

usb0     DOWN  0.0.0.0         0.0.0.0         0×00001002
sit0     DOWN  0.0.0.0         0.0.0.0         0×00000080
ip6tnl0  DOWN  0.0.0.0         0.0.0.0         0×00000080
gannet0  DOWN  0.0.0.0         0.0.0.0         0×00001082
rmnet0   UP    112.79.87.220   255.0.0.0       0x000000c1
rmnet1   DOWN  0.0.0.0         0.0.0.0         0×00000080
rmnet2   DOWN  0.0.0.0         0.0.0.0         0×00000080

android start activity from service

If you need to recal an Activity that is in bacgrounde, from your service, I suggest the following link. Intent.FLAG_ACTIVITY_NEW_TASK is not the solution.

https://stackoverflow.com/a/8759867/1127429

git is not installed or not in the PATH

while @vitocorleone is technically correct. If you have already installed, there is no need to reinstall. You just need to add it to your path. You will find yourself doing this for many of the tools for the mean stack so you should get used to doing it. You don't want to have to be in the folder that holds the executable to run it.

  • Control Panel --> System and Security --> System
  • click on Advanced System Settings on the left.
  • make sure you are on the advanced tab
  • click the Environment Variables button on the bottom
  • under system variables on the bottom find the Path variable
  • at the end of the line type (assuming this is where you installed it)

    ;C:\Program Files (x86)\git\cmd

  • click ok, ok, and ok to save

This essentially tells the OS.. if you don't find this executable in the folder I am typing in, look in Path to fide where it is.

Convert Month Number to Month Name Function in SQL

There is no system defined function in SQL server. But you can create your own user-defined function- a scalar function. You would find scalar functions in the Object Explorer for your database: Programmability->Functions->Scalar-valued Functions. Below, I use a table variable to bring it all together.

--Create the user-defined function
CREATE FUNCTION getmonth (@num int)
RETURNS varchar(9) --since 'September' is the longest string, length 9
AS
BEGIN

DECLARE @intMonth Table (num int PRIMARY KEY IDENTITY(1,1), month varchar(9))

INSERT INTO @intMonth VALUES ('January'), ('February'), ('March'), ('April'), ('May')
                           , ('June'), ('July'), ('August') ,('September'), ('October')
                           , ('November'), ('December')

RETURN (SELECT I.month
        FROM @intMonth I
        WHERE I.num = @num)
END
GO

--Use the function for various months
SELECT dbo.getmonth(4) AS [Month]
SELECT dbo.getmonth(5) AS [Month]
SELECT dbo.getmonth(6) AS [Month]

How disable / remove android activity label and label bar?

There is a code here that does it.

The trick is at this line:

 title.setVisibility(View.GONE);

What is the best way to compare floats for almost-equality in Python?

This maybe is a bit ugly hack, but it works pretty well when you don't need more than the default float precision (about 11 decimals).

The round_to function uses the format method from the built-in str class to round up the float to a string that represents the float with the number of decimals needed, and then applies the eval built-in function to the rounded float string to get back to the float numeric type.

The is_close function just applies a simple conditional to the rounded up float.

def round_to(float_num, prec):
    return eval("'{:." + str(int(prec)) + "f}'.format(" + str(float_num) + ")")

def is_close(float_a, float_b, prec):
    if round_to(float_a, prec) == round_to(float_b, prec):
        return True
    return False

>>>a = 10.0
10.0
>>>b = 10.0001
10.0001
>>>print is_close(a, b, prec=3)
True
>>>print is_close(a, b, prec=4)
False

Update:

As suggested by @stepehjfox, a cleaner way to build a rount_to function avoiding "eval" is using nested formatting:

def round_to(float_num, prec):
    return '{:.{precision}f}'.format(float_num, precision=prec)

Following the same idea, the code can be even simpler using the great new f-strings (Python 3.6+):

def round_to(float_num, prec):
    return f'{float_num:.{prec}f}'

So, we could even wrap it up all in one simple and clean 'is_close' function:

def is_close(a, b, prec):
    return f'{a:.{prec}f}' == f'{b:.{prec}f}'

Regular expression to match balanced parentheses

I didn't use regex since it is difficult to deal with nested code. So this snippet should be able to allow you to grab sections of code with balanced brackets:

def extract_code(data):
    """ returns an array of code snippets from a string (data)"""
    start_pos = None
    end_pos = None
    count_open = 0
    count_close = 0
    code_snippets = []
    for i,v in enumerate(data):
        if v =='{':
            count_open+=1
            if not start_pos:
                start_pos= i
        if v=='}':
            count_close +=1
            if count_open == count_close and not end_pos:
                end_pos = i+1
        if start_pos and end_pos:
            code_snippets.append((start_pos,end_pos))
            start_pos = None
            end_pos = None

    return code_snippets

I used this to extract code snippets from a text file.

Password hash function for Excel VBA

Here's a module for calculating SHA1 hashes that is usable for Excel formulas eg. '=SHA1HASH("test")'. To use it, make a new module called 'module_sha1' and copy and paste it all in. This is based on some VBA code from http://vb.wikia.com/wiki/SHA-1.bas, with changes to support passing it a string, and executable from formulas in Excel cells.

' Based on: http://vb.wikia.com/wiki/SHA-1.bas
Option Explicit

Private Type FourBytes
    A As Byte
    B As Byte
    C As Byte
    D As Byte
End Type
Private Type OneLong
    L As Long
End Type

Function HexDefaultSHA1(Message() As Byte) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 DefaultSHA1 Message, H1, H2, H3, H4, H5
 HexDefaultSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Function HexSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 xSHA1 Message, Key1, Key2, Key3, Key4, H1, H2, H3, H4, H5
 HexSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Sub DefaultSHA1(Message() As Byte, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 xSHA1 Message, &H5A827999, &H6ED9EBA1, &H8F1BBCDC, &HCA62C1D6, H1, H2, H3, H4, H5
End Sub

Sub xSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 'CA62C1D68F1BBCDC6ED9EBA15A827999 + "abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"
 '"abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"

 Dim U As Long, P As Long
 Dim FB As FourBytes, OL As OneLong
 Dim i As Integer
 Dim W(80) As Long
 Dim A As Long, B As Long, C As Long, D As Long, E As Long
 Dim T As Long

 H1 = &H67452301: H2 = &HEFCDAB89: H3 = &H98BADCFE: H4 = &H10325476: H5 = &HC3D2E1F0

 U = UBound(Message) + 1: OL.L = U32ShiftLeft3(U): A = U \ &H20000000: LSet FB = OL 'U32ShiftRight29(U)

 ReDim Preserve Message(0 To (U + 8 And -64) + 63)
 Message(U) = 128

 U = UBound(Message)
 Message(U - 4) = A
 Message(U - 3) = FB.D
 Message(U - 2) = FB.C
 Message(U - 1) = FB.B
 Message(U) = FB.A

 While P < U
     For i = 0 To 15
         FB.D = Message(P)
         FB.C = Message(P + 1)
         FB.B = Message(P + 2)
         FB.A = Message(P + 3)
         LSet OL = FB
         W(i) = OL.L
         P = P + 4
     Next i

     For i = 16 To 79
         W(i) = U32RotateLeft1(W(i - 3) Xor W(i - 8) Xor W(i - 14) Xor W(i - 16))
     Next i

     A = H1: B = H2: C = H3: D = H4: E = H5

     For i = 0 To 19
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key1), ((B And C) Or ((Not B) And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 20 To 39
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key2), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 40 To 59
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key3), ((B And C) Or (B And D) Or (C And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 60 To 79
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key4), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i

     H1 = U32Add(H1, A): H2 = U32Add(H2, B): H3 = U32Add(H3, C): H4 = U32Add(H4, D): H5 = U32Add(H5, E)
 Wend
End Sub

Function U32Add(ByVal A As Long, ByVal B As Long) As Long
 If (A Xor B) < 0 Then
     U32Add = A + B
 Else
     U32Add = (A Xor &H80000000) + B Xor &H80000000
 End If
End Function

Function U32ShiftLeft3(ByVal A As Long) As Long
 U32ShiftLeft3 = (A And &HFFFFFFF) * 8
 If A And &H10000000 Then U32ShiftLeft3 = U32ShiftLeft3 Or &H80000000
End Function

Function U32ShiftRight29(ByVal A As Long) As Long
 U32ShiftRight29 = (A And &HE0000000) \ &H20000000 And 7
End Function

Function U32RotateLeft1(ByVal A As Long) As Long
 U32RotateLeft1 = (A And &H3FFFFFFF) * 2
 If A And &H40000000 Then U32RotateLeft1 = U32RotateLeft1 Or &H80000000
 If A And &H80000000 Then U32RotateLeft1 = U32RotateLeft1 Or 1
End Function
Function U32RotateLeft5(ByVal A As Long) As Long
 U32RotateLeft5 = (A And &H3FFFFFF) * 32 Or (A And &HF8000000) \ &H8000000 And 31
 If A And &H4000000 Then U32RotateLeft5 = U32RotateLeft5 Or &H80000000
End Function
Function U32RotateLeft30(ByVal A As Long) As Long
 U32RotateLeft30 = (A And 1) * &H40000000 Or (A And &HFFFC) \ 4 And &H3FFFFFFF
 If A And 2 Then U32RotateLeft30 = U32RotateLeft30 Or &H80000000
End Function

Function DecToHex5(ByVal H1 As Long, ByVal H2 As Long, ByVal H3 As Long, ByVal H4 As Long, ByVal H5 As Long) As String
 Dim H As String, L As Long
 DecToHex5 = "00000000 00000000 00000000 00000000 00000000"
 H = Hex(H1): L = Len(H): Mid(DecToHex5, 9 - L, L) = H
 H = Hex(H2): L = Len(H): Mid(DecToHex5, 18 - L, L) = H
 H = Hex(H3): L = Len(H): Mid(DecToHex5, 27 - L, L) = H
 H = Hex(H4): L = Len(H): Mid(DecToHex5, 36 - L, L) = H
 H = Hex(H5): L = Len(H): Mid(DecToHex5, 45 - L, L) = H
End Function

' Convert the string into bytes so we can use the above functions
' From Chris Hulbert: http://splinter.com.au/blog

Public Function SHA1HASH(str)
  Dim i As Integer
  Dim arr() As Byte
  ReDim arr(0 To Len(str) - 1) As Byte
  For i = 0 To Len(str) - 1
   arr(i) = Asc(Mid(str, i + 1, 1))
  Next i
  SHA1HASH = Replace(LCase(HexDefaultSHA1(arr)), " ", "")
End Function

Sorting multiple keys with Unix sort

I just want to add some tips, when you using sort , be careful about your locale that effects the order of the key comparison. I usually explicitly use LC_ALL=C to make locale what I want.

Select the top N values by group

# start with the mtcars data frame (included with your installation of R)
mtcars

# pick your 'group by' variable
gbv <- 'cyl'
# IMPORTANT NOTE: you can only include one group by variable here
# ..if you need more, the `order` function below will need
# one per inputted parameter: order( x$cyl , x$am )

# choose whether you want to find the minimum or maximum
find.maximum <- FALSE

# create a simple data frame with only two columns
x <- mtcars

# order it based on 
x <- x[ order( x[ , gbv ] , decreasing = find.maximum ) , ]

# figure out the ranks of each miles-per-gallon, within cyl columns
if ( find.maximum ){
    # note the negative sign (which changes the order of mpg)
    # *and* the `rev` function, which flips the order of the `tapply` result
    x$ranks <- unlist( rev( tapply( -x$mpg , x[ , gbv ] , rank ) ) )
} else {
    x$ranks <- unlist( tapply( x$mpg , x[ , gbv ] , rank ) )
}
# now just subset it based on the rank column
result <- x[ x$ranks <= 3 , ]

# look at your results
result

# done!

# but note only *two* values where cyl == 4 were kept,
# because there was a tie for third smallest, and the `rank` function gave both '3.5'
x[ x$ranks == 3.5 , ]

# ..if you instead wanted to keep all ties, you could change the
# tie-breaking behavior of the `rank` function.
# using the `min` *includes* all ties.  using `max` would *exclude* all ties
if ( find.maximum ){
    # note the negative sign (which changes the order of mpg)
    # *and* the `rev` function, which flips the order of the `tapply` result
    x$ranks <- unlist( rev( tapply( -x$mpg , x[ , gbv ] , rank , ties.method = 'min' ) ) )
} else {
    x$ranks <- unlist( tapply( x$mpg , x[ , gbv ] , rank , ties.method = 'min' ) )
}
# and there are even more options..
# see ?rank for more methods

# now just subset it based on the rank column
result <- x[ x$ranks <= 3 , ]

# look at your results
result
# and notice *both* cyl == 4 and ranks == 3 were included in your results
# because of the tie-breaking behavior chosen.

nginx: connect() failed (111: Connection refused) while connecting to upstream

I had the same problem when I wrote two upstreams in NGINX conf

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
    server 127.0.0.1:9000;
}

...

fastcgi_pass php_upstream;

but in /etc/php/7.3/fpm/pool.d/www.conf I listened the socket only

listen = /var/run/php/my.site.sock

So I need just socket, no any 127.0.0.1:9000, and I just removed IP+port upstream

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
}

This could be rewritten without an upstream

fastcgi_pass unix:/var/run/php/my.site.sock;

Show "loading" animation on button click

            //do processing
            $(this).attr("label", $(this).text()).text("loading ....").animate({ disabled: true }, 1000, function () {
                //original event call
                $.when($(elm).delay(1000).one("click")).done(function () {//processing finalized
                    $(this).text($(this).attr("label")).animate({ disabled: false }, 1000, function () {
                    })
                });
            });

ngOnInit not being called when Injectable class is Instantiated

Lifecycle hooks, like OnInit() work with Directives and Components. They do not work with other types, like a service in your case. From docs:

A Component has a lifecycle managed by Angular itself. Angular creates it, renders it, creates and renders its children, checks it when its data-bound properties change and destroy it before removing it from the DOM.

Directive and component instances have a lifecycle as Angular creates, updates, and destroys them.

Javascript/Jquery to change class onclick?

Just using this will add "mynewclass" to the element with the id myElement and revert it on the next call.

<div id="showhide" class="meta-info" onclick="changeclass(this);">

function changeclass(element) {
    $(element).toggleClass('mynewclass');
}

Or for a slighly more jQuery way (you would run this after the DOM is loaded)

<div id="showhide" class="meta-info">

$('#showhide').click(function() {
    $(this).toggleClass('mynewclass');
});

See a working example of this here: http://jsfiddle.net/S76WN/

The character encoding of the HTML document was not declared

Well when you post, the browser only outputs $title - all your HTML tags and doctype go away. You need to include those in your insert.php file:

<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>insert page</title></head>
<body>
<?php 

   $title = $_POST["title"];
   $price = $_POST["price"];

  echo $title;


 ?>  
</body>
</html>

Creating JSON on the fly with JObject

Simple way of creating newtonsoft JObject from Properties.

This is a Sample User Properties

public class User
{
    public string Name;
    public string MobileNo;
    public string Address;
}

and i want this property in newtonsoft JObject is:

JObject obj = JObject.FromObject(new User()
{
    Name = "Manjunath",
    MobileNo = "9876543210",
    Address = "Mumbai, Maharashtra, India",
});

Output will be like this:

{"Name":"Manjunath","MobileNo":"9876543210","Address":"Mumbai, Maharashtra, India"}

How to get all checked checkboxes

A simple for loop which tests the checked property and appends the checked ones to a separate array. From there, you can process the array of checkboxesChecked further if needed.

// Pass the checkbox name to the function
function getCheckedBoxes(chkboxName) {
  var checkboxes = document.getElementsByName(chkboxName);
  var checkboxesChecked = [];
  // loop over them all
  for (var i=0; i<checkboxes.length; i++) {
     // And stick the checked ones onto an array...
     if (checkboxes[i].checked) {
        checkboxesChecked.push(checkboxes[i]);
     }
  }
  // Return the array if it is non-empty, or null
  return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}

// Call as
var checkedBoxes = getCheckedBoxes("mycheckboxes");

SQL Server - Create a copy of a database table and place it in the same database?

Copy Schema (Generate DDL) through SSMS UI

In SSMS expand your database in Object Explorer, go to Tables, right click on the table you're interested in and select Script Table As, Create To, New Query Editor Window. Do a find and replace (CTRL + H) to change the table name (i.e. put ABC in the Find What field and ABC_1 in the Replace With then click OK).

Copy Schema through T-SQL

The other answers showing how to do this by SQL also work well, but the difference with this method is you'll also get any indexes, constraints and triggers.

Copy Data

If you want to include data, after creating this table run the below script to copy all data from ABC (keeping the same ID values if you have an identity field):

set identity_insert ABC_1 on
insert into ABC_1 (column1, column2) select column1, column2 from ABC
set identity_insert ABC_1 off

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

It depends on what sender address you are talking about. The sender address visble in the recipients mailprogramm is extracted from the "From:" Header. which can probably easily be set from your program.

If you are talking about the SMTP envelope sender address, you can pass the -f argument to the sendmail binary. Depending on the server configuration you may not be allowed to do that with the apache user.

from the sendmail manpage :

   -f <address>
                 This  option  sets  the  address  of the envelope sender of a
                 locally-generated message (also known as  the  return  path).
                 The  option  can normally be used only by a trusted user, but
                 untrusted_set_sender can be set to allow untrusted  users  to
                 use it. [...]

How to replace NaNs by preceding values in pandas DataFrame?

You can use fillna to remove or replace NaN values.

NaN Remove

import pandas as pd

df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])

df.fillna(method='ffill')
     0    1    2
0  1.0  2.0  3.0
1  4.0  2.0  3.0
2  4.0  2.0  9.0

NaN Replace

df.fillna(0) # 0 means What Value you want to replace 
     0    1    2
0  1.0  2.0  3.0
1  4.0  0.0  0.0
2  0.0  0.0  9.0

Reference pandas.DataFrame.fillna

How to make a char string from a C macro's value?

#define TEST_FUN_NAME #FUNC_NAME

see here

What is the best way to implement a "timer"?

By using System.Windows.Forms.Timer class you can achieve what you need.

System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();


t.Interval = 15000; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
t.Start();

void timer_Tick(object sender, EventArgs e)
{
      //Call method
}

By using stop() method you can stop timer.

t.Stop();

enum to string in modern C++11 / C++14 / C++17 and future C++20

If your enum looks like

enum MyEnum
{
  AAA = -8,
  BBB = '8',
  CCC = AAA + BBB
};

You can move the content of the enum to a new file:

AAA = -8,
BBB = '8',
CCC = AAA + BBB

And then the values can be surrounded by a macro:

// default definition
#ifned ITEM(X,Y)
#define ITEM(X,Y)
#endif

// Items list
ITEM(AAA,-8)
ITEM(BBB,'8')
ITEM(CCC,AAA+BBB)

// clean up
#undef ITEM

Next step may be include the items in the enum again:

enum MyEnum
{
  #define ITEM(X,Y) X=Y,
  #include "enum_definition_file"
};

And finally you can generate utility functions about this enum:

std::string ToString(MyEnum value)
{
  switch( value )
  {
    #define ITEM(X,Y) case X: return #X;
    #include "enum_definition_file"
  }

  return "";
}

MyEnum FromString(std::string const& value)
{
  static std::map<std::string,MyEnum> converter
  {
    #define ITEM(X,Y) { #X, X },
    #include "enum_definition_file"
  };

  auto it = converter.find(value);
  if( it != converter.end() )
    return it->second;
  else
    throw std::runtime_error("Value is missing");
}

The solution can be applied to older C++ standards and it does not use modern C++ elements but it can be used to generate lot of code without too much effort and maintenance.

Getting the client's time zone (and offset) in JavaScript

This is very good work for me:

// Translation to offset in Unix Timestamp
let timeZoneOffset = ((new Date().getTimezoneOffset())/60)*3600;

Ignore parent padding

Easy fix, just do

margin:-10px

on the hr.

AngularJS: How can I pass variables between controllers?

--- I know this answer is not for this question, but I want people who reads this question and want to handle Services such as Factories to avoid trouble doing this ----

For this you will need to use a Service or a Factory.

The services are the BEST PRACTICE to share data between not nested controllers.

A very very good annotation on this topic about data sharing is how to declare objects. I was unlucky because I fell in a AngularJS trap before I read about it, and I was very frustrated. So let me help you avoid this trouble.

I read from the "ng-book: The complete book on AngularJS" that AngularJS ng-models that are created in controllers as bare-data are WRONG!

A $scope element should be created like this:

angular.module('myApp', [])
.controller('SomeCtrl', function($scope) {
  // best practice, always use a model
  $scope.someModel = {
    someValue: 'hello computer'
  });

And not like this:

angular.module('myApp', [])
.controller('SomeCtrl', function($scope) {
  // anti-pattern, bare value
  $scope.someBareValue = 'hello computer';
  };
});

This is because it is recomended(BEST PRACTICE) for the DOM(html document) to contain the calls as

<div ng-model="someModel.someValue"></div>  //NOTICE THE DOT.

This is very helpful for nested controllers if you want your child controller to be able to change an object from the parent controller....

But in your case you don't want nested scopes, but there is a similar aspect to get objects from services to the controllers.

Lets say you have your service 'Factory' and in the return space there is an objectA that contains objectB that contains objectC.

If from your controller you want to GET the objectC into your scope, is a mistake to say:

$scope.neededObjectInController = Factory.objectA.objectB.objectC;

That wont work... Instead use only one dot.

$scope.neededObjectInController = Factory.ObjectA;

Then, in the DOM you can call objectC from objectA. This is a best practice related to factories, and most important, it will help to avoid unexpected and non-catchable errors.

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:

^[a-zA-Z ._-]*$

If you use the case-insensitive modifier, you can shorten this to

^[a-z ._-]*$

Note that the space is significant (it is just a character like any other).

How to perform string interpolation in TypeScript?

Just use special `

var lyrics = 'Never gonna give you up';
var html = `<div>${lyrics}</div>`;

You can see more examples here.

How to check if an object is a list or tuple (but not string)?

I do this in my testcases.

def assertIsIterable(self, item):
    #add types here you don't want to mistake as iterables
    if isinstance(item, basestring): 
        raise AssertionError("type %s is not iterable" % type(item))

    #Fake an iteration.
    try:
        for x in item:
            break;
    except TypeError:
        raise AssertionError("type %s is not iterable" % type(item))

Untested on generators, I think you are left at the next 'yield' if passed in a generator, which may screw things up downstream. But then again, this is a 'unittest'

How do I count a JavaScript object's attributes?

There's no easy answer, because Object — which every object in JavaScript derives from — includes many attributes automatically, and the exact set of attributes you get depends on the particular interpreter and what code has executed before yours. So, you somehow have to separate the ones you defined from those you got "for free."

Here's one way:

var foo = {"key1": "value1", "key2": "value2", "key3": "value3"};
Object.prototype.foobie = 'bletch'; // add property to foo that won't be counted

var count = 0;
for (var k in foo) {
    if (foo.hasOwnProperty(k)) {
       ++count;
    }
}
alert("Found " + count + " properties specific to foo");

The second line shows how other code can add properties to all Object derivatives. If you remove the hasOwnProperty() check inside the loop, the property count will go up to at least 4. On a page with other JavaScript besides this code, it could be higher than 4, if that other code also modifies the Object prototype.

Adding +1 to a variable inside a function

You could also pass points to the function: Small example:

def test(points):
    addpoint = raw_input ("type ""add"" to add a point")
    if addpoint == "add":
        points = points + 1
    else:
        print "asd"
    return points;
if __name__ == '__main__':
    points = 0
    for i in range(10):
        points = test(points)
        print points

What is the equivalent of Java's final in C#?

http://en.csharp-online.net/CSharp_FAQ:_What_are_the_differences_between_CSharp_and_Java_constant_declarations

C# constants are declared using the const keyword for compile time constants or the readonly keyword for runtime constants. The semantics of constants is the same in both the C# and Java languages.

How to delete zero components in a vector in Matlab?

If you just wish to remove the zeros, leaving the non-zeros behind in a, then the very best solution is

a(a==0) = [];

This deletes the zero elements, using a logical indexing approach in MATLAB. When the index to a vector is a boolean vector of the same length as the vector, then MATLAB can use that boolean result to index it with. So this is equivalent to

a(find(a==0)) = [];

And, when you set some array elements to [] in MATLAB, the convention is to delete them.

If you want to put the zeros into a new result b, while leaving a unchanged, the best way is probably

b = a(a ~= 0);

Again, logical indexing is used here. You could have used the equivalent version (in terms of the result) of

b = a(find(a ~= 0));

but mlint will end up flagging the line as one where the purely logical index was more efficient, and thus more appropriate.

As always, beware EXACT tests for zero or for any number, if you would have accepted elements of a that were within some epsilonic tolerance of zero. Do those tests like this

b = a(abs(a) >= tol);

This retains only those elements of a that are at least as large as your tolerance.

Getting Raw XML From SOAPMessage in Java

Using Transformer Factory:-

public static String printSoapMessage(final SOAPMessage soapMessage) throws TransformerFactoryConfigurationError,
            TransformerConfigurationException, SOAPException, TransformerException
    {
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer();

        // Format it
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        final Source soapContent = soapMessage.getSOAPPart().getContent();

        final ByteArrayOutputStream streamOut = new ByteArrayOutputStream();
        final StreamResult result = new StreamResult(streamOut);
        transformer.transform(soapContent, result);

        return streamOut.toString();
    }

MySQL - SELECT all columns WHERE one column is DISTINCT

If what your asking is to only show rows that have 1 link for them then you can use the following:

SELECT * FROM posted WHERE link NOT IN 
(SELECT link FROM posted GROUP BY link HAVING COUNT(LINK) > 1)

Again this is assuming that you want to cut out anything that has a duplicate link.

How to set a fixed width column with CSS flexbox

In case anyone wants to have a responsive flexbox with percentages (%) it is much easier for media queries.

flex-basis: 25%;

This will be a lot smoother when testing.

// VARIABLES
$screen-xs:                                         480px;
$screen-sm:                                         768px;
$screen-md:                                         992px;
$screen-lg:                                         1200px;
$screen-xl:                                         1400px;
$screen-xxl:                                        1600px;

// QUERIES
@media screen (max-width: $screen-lg) {
    flex-basis: 25%;
}

@media screen (max-width: $screen-md) {
    flex-basis: 33.33%;
}

Accessing Objects in JSON Array (JavaScript)

You can loop the array with a for loop and the object properties with for-in loops.

for (var i=0; i<result.length; i++)
    for (var name in result[i]) {
        console.log("Item name: "+name);
        console.log("Source: "+result[i][name].sourceUuid);
        console.log("Target: "+result[i][name].targetUuid);
    }

Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier

You can only use - on the numeric entries, so you can use decreasing and negate the ones you want in increasing order:

DT[order(x,-v,decreasing=TRUE),]
      x y v
 [1,] c 1 7
 [2,] c 3 8
 [3,] c 6 9
 [4,] b 1 1
 [5,] b 3 2
 [6,] b 6 3
 [7,] a 1 4
 [8,] a 3 5
 [9,] a 6 6

Dynamically Add Variable Name Value Pairs to JSON Object

when using javascript objects, you can also just use "dot notation" to add an item, (which JSLint prefers)

var myArray = { name : "john" };
//will initiate a key-value array with one item "name" and the value "john"
myArray.lastName = "smith";
//will add a key named lastName with the value "smith"
//Object {name: "john", lastName: "smith"}

Here is a screenshot from testing in the Chrome console

screenshot

Escaping quotation marks in PHP

You can use the PHP function addslashes() to any string to make it compatible

Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap

I wrote about an alternative in this StackOverflow answer.

There I wrote step by step, explaining with code. The short way:

First: write an object

Second: create a converter to mapping the model extending the AbstractHttpMessageConverter

Third: tell to spring use this converter implementing a WebMvcConfigurer.class overriding the configureMessageConverters method

Fourth and final: using this implementation setting in the mapping inside your controller the consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE and @RequestBody in front of your object.

I'm using spring boot 2.

Pass data from Activity to Service using an Intent

If you are using kotlin you can try the following code,

In the sending activity,

  val intent = Intent(context, RecorderService::class.java);
  intent.putExtra("filename", filename);
  context.startService(intent)

In the service,

override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
    super.onStartCommand(intent, flags, startId)

    if (intent != null && intent.extras != null)
       val filename = intent.getStringExtra("filename")

}

How to bind an enum to a combobox control in WPF?

Nick's answer has really helped me, but I realised it could be tweaked slightly, to avoid an extra class, ValueDescription. I remembered that there exists a KeyValuePair class already in the framework, so this can be used instead.

The code changes only slightly :

public static IEnumerable<KeyValuePair<string, string>> GetAllValuesAndDescriptions<TEnum>() where TEnum : struct, IConvertible, IComparable, IFormattable
    {
        if (!typeof(TEnum).IsEnum)
        {
            throw new ArgumentException("TEnum must be an Enumeration type");
        }

        return from e in Enum.GetValues(typeof(TEnum)).Cast<Enum>()
               select new KeyValuePair<string, string>(e.ToString(),  e.Description());
    }


public IEnumerable<KeyValuePair<string, string>> PlayerClassList
{
   get
   {
       return EnumHelper.GetAllValuesAndDescriptions<PlayerClass>();
   }
}

and finally the XAML :

<ComboBox ItemSource="{Binding Path=PlayerClassList}"
          DisplayMemberPath="Value"
          SelectedValuePath="Key"
          SelectedValue="{Binding Path=SelectedClass}" />

I hope this is helpful to others.

CodeIgniter 404 Page Not Found, but why?

I had the same issue after migrating to a new environment and it was simply that the server didn't run mod_rewrite

a quick sudo a2enmod rewrite then sudo systemctl restart apache2

and problem solved...

Thanks @fanis who pointed that out in his comment on the question.

How to initialize all members of an array to the same value?

If you mean in parallel, I think the comma operator when used in conjunction with an expression can do that:

a[1]=1, a[2]=2, ..., a[indexSize]; 

or if you mean in a single construct, you could do that in a for loop:

for(int index = 0, value = 10; index < sizeof(array)/sizeof(array[0]); index++, value--)
  array[index] = index;

//Note the comma operator in an arguments list is not the parallel operator described above;

You can initialize an array decleration:

array[] = {1, 2, 3, 4, 5};

You can make a call to malloc/calloc/sbrk/alloca/etc to allocate a fixed region of storage to an object:

int *array = malloc(sizeof(int)*numberOfListElements/Indexes);

and access the members by:

*(array + index)

Etc.

Apply style ONLY on IE

Here is a COMPLETE Javascript-free, CSS-based solution that allows you to target Internet Explorer 1-11!

My Internet Explorer Only CSS Solution

This works by hiding IE1-7 from all your modern sheets using @import, giving IE1-7 a clean, white page layout, then applies three simple CSS media query "hacks" to isolate IE8-11 in the imported sheet. It even affects IE on Mac!

The advantage to this strategy is its 100% effective in targeting IE1-11, giving you complete control over how you customize CSS for those targeted browsers, while freeing you up as a designer to focus on newer CSS3 and cutting-edge styles and layouts in Edge and all other modern browsers going forward. I have been using a version of this since 2004 but recently updated it for 2021.

HOW IT WORKS

First create two CSS style sheet links. The first is a basic element style sheet that gives all browsers, old and new, a simple white, block-level layout. Linked CSS has wide support in older CSS1 browsers going back to 1995. A wide range of old browsers will see this first sheet and display your content and layouts in a clean, white block-level content page. I like to put "reset" element-only styles in here. The second sheet is an import sheet that will load all your advanced CSS styles using a single @import rule that hides styles to a wide range of browsers including IE1-7.

<link media="screen" rel="stylesheet" type="text/css" href="OldBrowsers.css" />
<link media="screen" rel="stylesheet" type="text/css" href="Import.css" />

Next, in your "Import.css" sheet add this @import rule exactly as formatted (Its hidden from IE1-7 and a wide range of older browsers listed below):

@import 'ModernBrowsers.css' all;

All CSS in this imported sheet will be hidden from IE1-7 and a wide range of older browsers. IE 1-7 doesn't understand "media type" value "all" so will fail to import this sheet. This specific version of import is also not recognized by many older browsers (pre-2001). Those browsers are so old now, you just need to deliver them a white web page with stacked blocks of content. Use "OldBrowsers" to do so.

Next, in "ModernBrowsers.css" you want to target IE8-11 using CSS media query "hacks" alongside all your normal selectors and classes. Simply apply the following media query, IE-only fixes to your modern, imported style sheet to target these specific IE browsers. Drop into these blocks any styles specific to them. You can attack your layout or other style issues in IE now in media query "batches" now rather than by multiple selector "hacks":

/* IE8 */
@media \0screen {
    body {
        background: red !important;
    }
}

/* IE9 */
@media all and (monochrome:0) {
    body {
        background: blue\9 !important;
    }
}

/* IE10-11 */
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
    body {
        background: green !important;
    }
}

Simple! You have now targeted styles for IE1-11 (all Internet Explorer browsers!)

With this solution you achieve the following:

  1. The @import excludes IE 1-7 from your modern styles, completely! Those agents, along with the list below, will never see your modern imported styles and get a clean white style sheet content page older browsers can still use as far as viewing your content (use "OldBrowsers.css" to style them). The following browsers are excluded from "ModernBrowsers.css" using the above @import rule:

    • Windows Internet Explorer 1-7.x
    • Macintosh Internet Explorer 1-5.x
    • Netscape 1-4.8
    • Opera 1-3.5
    • Konqueror 1-2.1
    • Windows Amaya 1-5.1
    • iCab 1-2
    • OmniWeb
  2. In your "ModernBrowsers" imported sheet, you can now safely target IE browsers version 8-11 using simple media query "hacks".

  3. This system uses a simple @import style sheet system that is fast and manageable using traditional, non-support for external style rules rather than CSS fixes sprinkled throughout multiple sheets. (BTW...Do not listen to anyone saying @import is slow, as it is not. My import sheet has ONE LINE and is maybe a kilobyte or less in size! @import has been used since the birth of the WWW and is no different than a simple CSS link. Compare this to the Megabytes of Javascript kids today are shoving into browsers using these new "modern" ECMAScript SPA API's just to display a tiny paragraph of news!)

  4. All old IE browsers and a wide range of other user agnets are excluded from modern styles now using this import strategy, which allows these agents to collapse back to plain, "block-level", white pages and stacked content layouts that are fully accessible by older browsers.

  5. Notice this solution has no IE conditional comments! (you should NEVER use those)

  6. With this solution, web designs are now 100% free to use custom, cutting edge CSS3 technologies without having to ever worry about older browsers and IE1-11 ever again!

I will be posting my formal version of this Universal CSS System on GitHub soon! So stay tuned...

This is part of the new "progressive" CSS, 100% Javacript-free, design concept in 2021 for addressing cross-browser style issues, where older agents are allowed to degrade gracefully to simpler layouts rather than struggling to fix problems in cryptic old, broken, box-model agents (IE6) that don't need custom layouts any longer today as the long tail of their slow demise continues online.

And its my hope we stop creating these gigantic, CPU-hog, Javascripted, polyfill nightmare solutions for addressing what used to be years ago solved by simple CSS solutions like this one.

How can I execute a PHP function in a form action?

I'm not sure I understand what you are trying to achieve as we don't have what username() is supposed to return but you might want to try something like that. I would also recommend you don't echo whole page and rather use something like that, it's much easier to read and maintain:

<?php
require_once ( 'username.php' );
if (isset($_POST)) {
  $textfield = $_POST['textfield']; // this will get you what was in the
                                    // textfield if the form was submitted
}
?>

<form name="form1" method="post" action="<?php echo($_SERVER['PHP_SELF']) ?">
  <p>Your username is: <?php echo(username()) ?></p>
  <p>
    <label>
      <input type="text" name="textfield" id="textfield">
    </label>
  </p>
  <p>
    <label>
      <input type="submit" name="button" id="button" value="Submit">
    </label>
  </p>
</form>

This will post the results in the same page. So first time you display the page, only the empty form is shown, if you press on submit, the textfield field will be in the $textfield variable and you can display it again as you want.

I don't know if the username() function was supposed to return you the URL of where you should send the results but that's what you'd want in the action attribute of your form. I've put the result down in a sample paragraph so you see how you can display the result. See the "Your username is..." part.


// Edit:

If you want to send the value without leaving the page, you want to use AJAX. Do a search on jQuery on StackOverflow or on Google.

You would probably want to have your function return the username instead of echo it though. But if you absolutely want to echo it from the function, just call it like that <?php username() ?> in your HTML form.

I think you will need to understand the flow of the client-server process of your pages before going further. Let's say that the sample code above is called form.php.

  1. Your form.php is called.
  2. The form.php generates the HTML and is sent to the client's browser.
  3. The client only sees the resulting HTML form.
  4. When the user presses the button, you have two choices: a) let the browser do its usual thing so send the values in the form fields to the page specified in action (in this case, the URL is defined by PHP_SELF which is the current page.php). Or b) use javascript to push this data to a page without refreshing the page, this is commonly called AJAX.
  5. A page, in your case, it could be changed to username.php, will then verify against the database if the username exists and then you want to regenerate HTML that contains the values you need, back to step 1.

Fixed position but relative to container

The magic is to take the screen width minus the container width and divide it by 2:

//1400px is according to container max-width (left can be also right)
.fixed {
  position: fixed;
  right: calc((100vw - 1400px)/2);
}

Note: css calc() function is almost, but not 100% supported. For most use-cases it is definitely supported enough. Click here for more details

Snippet (with a 300px container just to fit this website's widget):

_x000D_
_x000D_
.container {
  max-width: 300px;
  margin-left: auto;
  margin-right: auto;
}


.fixed {
  position: fixed;
  right: calc((100vw - 300px)/2);
}


@media screen and (max-width: 300px) {
  right: 0px;
}
_x000D_
<div style="height: 3000px">
    <div class="container">
        <button class="fixed">
            FIXED CONTENT
        </button>
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Laborum, eum? Animi quidem accusamus minima vel, dolorem suscipit quia accusantium minus harum modi commodi distinctio! Iste voluptatum earum quam voluptate culpa ad, ipsum dolorum recusandae quis atque eligendi necessitatibus magnam nisi dolores beatae qui? Perspiciatis natus cum nostrum in quod odio sapiente doloremque rerum quo dolore tenetur facere, quisquam atque accusamus fugiat eligendi, deleniti nisi minus recusandae distinctio dignissimos! Dicta quos ipsum qui pariatur at vel veritatis veniam quisquam minus modi et voluptas aliquam laborum, cumque in quo magnam sapiente. Expedita ut dolore laboriosam tempora reprehenderit vero eaque blanditiis, cumque voluptatibus, velit nemo, veniam tenetur quisquam numquam adipisci quae odio repellendus neque incidunt! Cum odio corporis soluta voluptate nesciunt, quasi nobis deleniti neque porro expedita fugiat placeat alias autem pariatur animi error, dicta veritatis atque perspiciatis inventore tempora dolor ad! Mollitia in dolorem ipsam eos porro magni perspiciatis possimus maiores, itaque facere ut. Eos culpa eum error quia incidunt repellendus quam possimus, asperiores earum ipsum molestias dicta sint fugit atque veniam dolorum illo? Officia harum sint incidunt totam, reiciendis illum eos maxime sequi neque repellat quis, expedita eum, corporis quaerat nemo qui soluta aspernatur animi. Sint ad rem numquam omnis sit.
    </div>
 </div>
_x000D_
_x000D_
_x000D_

Fastest way of finding differences between two files in unix?

This will work fast:

Case 1 - File2 = File1 + extra text appended.

grep -Fxvf File2.txt File1.txt >> File3.txt

File 1: 80 Lines File 2: 100 Lines File 3: 20 Lines

Export javascript data to CSV file without server interaction

We can easily create and export/download the excel file with any separator (in this answer I am using the comma separator) using javascript. I am not using any external package for creating the excel file.

_x000D_
_x000D_
    var Head = [[_x000D_
        'Heading 1',_x000D_
        'Heading 2', _x000D_
        'Heading 3', _x000D_
        'Heading 4'_x000D_
    ]];_x000D_
_x000D_
    var row = [_x000D_
       {key1:1,key2:2, key3:3, key4:4},_x000D_
       {key1:2,key2:5, key3:6, key4:7},_x000D_
       {key1:3,key2:2, key3:3, key4:4},_x000D_
       {key1:4,key2:2, key3:3, key4:4},_x000D_
       {key1:5,key2:2, key3:3, key4:4}_x000D_
    ];_x000D_
_x000D_
for (var item = 0; item < row.length; ++item) {_x000D_
       Head.push([_x000D_
          row[item].key1,_x000D_
          row[item].key2,_x000D_
          row[item].key3,_x000D_
          row[item].key4_x000D_
       ]);_x000D_
}_x000D_
_x000D_
var csvRows = [];_x000D_
for (var cell = 0; cell < Head.length; ++cell) {_x000D_
       csvRows.push(Head[cell].join(','));_x000D_
}_x000D_
            _x000D_
var csvString = csvRows.join("\n");_x000D_
let csvFile = new Blob([csvString], { type: "text/csv" });_x000D_
let downloadLink = document.createElement("a");_x000D_
downloadLink.download = 'MYCSVFILE.csv';_x000D_
downloadLink.href = window.URL.createObjectURL(csvFile);_x000D_
downloadLink.style.display = "none";_x000D_
document.body.appendChild(downloadLink);_x000D_
downloadLink.click();
_x000D_
_x000D_
_x000D_

error 1265. Data truncated for column when trying to load data from txt file

The reason is that mysql expecting end of the row symbol in the text file after last specified column, and this symbol is char(10) or '\n'. Depends on operation system where text file created or if you created your text file yourself, it can be other combination (Windows uses '\r\n' (chr(13)+chr(10)) as rows separator). Thus, if you use Windows generated text file, add following suffix to your LOAD command: “ LINES TERMINATED BY '\r\n' ”. Otherwise, check how rows are separated in your text file. On default mysql expecting char(10) as rows separator.

Open Google Chrome from VBA/Excel

I found an easier way to do it and it works perfectly even if you don't know the path where the chrome is located.

First of all, you have to paste this code in the top of the module.

Option Explicit
Private pWebAddress As String
Public Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
(ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, _
ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

After that you have to create this two modules:

Sub LoadExplorer()
    LoadFile "Chrome.exe" ' Here you are executing the chrome. exe
End Sub

Sub LoadFile(FileName As String)
    ShellExecute 0, "Open", FileName, "http://test.123", "", 1 ' You can change the URL.
End Sub

With this you will be able (if you want) to set a variable for the url or just leave it like hardcode.

Ps: It works perfectly for others browsers just changing "Chrome.exe" to opera, bing, etc.

How to run two jQuery animations simultaneously?

yes there is!

$(function () {
    $("#first").animate({
       width: '200px'
    }, { duration: 200, queue: false });

    $("#second").animate({
       width: '600px'
    }, { duration: 200, queue: false });
});

What exactly is the difference between Web API and REST API in MVC?

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

REST

RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.

SOAP

SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.

Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.

Reference: http://spf13.com/post/soap-vs-rest

And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/

Keyboard shortcut to change font size in Eclipse?

Here's a quicker way than multi-layer menus without resorting to plug-ins:

Use the Quick Access tool at the upper left corner.

Type in "font", then, from the list that drops down, click on the link for "Preferences->Colors and Fonts->General->Appearance".

One click replaces the 4 needed to get there through menus. I do it so often, my Quick Access tool pulls it up as a previous choice right at the top of the list so I can just type "font" with a tap on the enter key and Boom!, I'm there.

If you want a keyboard shortcut, Ctrl+3 sets the focus to the Quick Access tool. Better yet, this even automatically brings up a list with your previous choices. The last one you chose will be on top, in which case a simple Ctrl+3 followed by enter would bring you straight there! I use this all the time to make it bigger during long typing or reading sessions to ease eye strain, or to make it smaller if I need more text on the screen at one time to make it easier to find something.

It's not quite as nice as zooming with the scroll wheel or with a simple Ctrl+ or Ctrl-, but it's a lot better than navigating through the menus every time!

MultipartException: Current request is not a multipart request

In application.properties, please add this:

spring.servlet.multipart.max-file-size=128KB
spring.servlet.multipart.max-request-size=128KB
spring.http.multipart.enabled=false

and in your html form, you need an : enctype="multipart/form-data". For example:

<form method="POST" enctype="multipart/form-data" action="/">

Hope this help!

Laravel Check If Related Model Exists

I had to completely refactor my code when I updated my PHP version to 7.2+ because of bad usage of the count($x) function. This is a real pain and its also extremely scary as there are hundreds usages, in different scenarios and there is no one rules fits all..

Rules I followed to refactor everything, examples:

$x = Auth::user()->posts->find(6); (check if user has a post id=6 using ->find())

[FAILS] if(count($x)) { return 'Found'; } 
[GOOD] if($x) { return 'Found'; }

$x = Auth::user()->profile->departments; (check if profile has some departments, there can have many departments)

[FAILS] if(count($x)) { return 'Found'; }
[GOOD] if($x->count()) { return 'Found'; }

$x = Auth::user()->profile->get(); (check if user has a profile after using a ->get())

[FAILS] if(count($x)) { return 'Found'; }
[GOOD] if($x->count()) { return 'Found'; }

Hopes this can help, even 5 years after the question has been asked, this stackoverflow post has helped me a lot!

How to check if array is empty or does not exist?

You want to do the check for undefined first. If you do it the other way round, it will generate an error if the array is undefined.

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

Update

This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null values, other types of objects with a length property, etc. It is also not very idiomatic JavaScript.

The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length property.

if (!Array.isArray(array) || !array.length) {
  // array does not exist, is not an array, or is empty
  // ? do not attempt to process array
}

To break it down:

  1. Array.isArray(), unsurprisingly, checks whether its argument is an array. This weeds out values like null, undefined and anything else that is not an array.
    Note that this will also eliminate array-like objects, such as the arguments object and DOM NodeList objects. Depending on your situation, this might not be the behavior you're after.

  2. The array.length condition checks whether the variable's length property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0 or array.length !== 0 are not required here.

The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.

In those cases, I tend to go for the following, more idiomatic JavaScript:

if (!array || !array.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or, more frequently, its inverse:

if (array && array.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:

if (!array?.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or the opposite:

if (array?.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

Regex to split a CSV

Description

Instead of using a split, I think it would be easier to simply execute a match and process all the found matches.

This expression will:

  • divide your sample text on the comma delimits
  • will process empty values
  • will ignore double quoted commas, providing double quotes are not nested
  • trims the delimiting comma from the returned value
  • trims surrounding quotes from the returned value

Regex: (?:^|,)(?=[^"]|(")?)"?((?(1)[^"]*|[^,"]*))"?(?=,|$)

enter image description here

Example

Sample Text

123,2.99,AMO024,Title,"Description, more info",,123987564

ASP example using the non-java expression

Set regEx = New RegExp
regEx.Global = True
regEx.IgnoreCase = True
regEx.MultiLine = True
sourcestring = "your source string"
regEx.Pattern = "(?:^|,)(?=[^""]|("")?)""?((?(1)[^""]*|[^,""]*))""?(?=,|$)"
Set Matches = regEx.Execute(sourcestring)
  For z = 0 to Matches.Count-1
    results = results & "Matches(" & z & ") = " & chr(34) & Server.HTMLEncode(Matches(z)) & chr(34) & chr(13)
    For zz = 0 to Matches(z).SubMatches.Count-1
      results = results & "Matches(" & z & ").SubMatches(" & zz & ") = " & chr(34) & Server.HTMLEncode(Matches(z).SubMatches(zz)) & chr(34) & chr(13)
    next
    results=Left(results,Len(results)-1) & chr(13)
  next
Response.Write "<pre>" & results

Matches using the non-java expression

Group 0 gets the entire substring which includes the comma
Group 1 gets the quote if it's used
Group 2 gets the value not including the comma

[0][0] = 123
[0][1] = 
[0][2] = 123

[1][0] = ,2.99
[1][1] = 
[1][2] = 2.99

[2][0] = ,AMO024
[2][1] = 
[2][2] = AMO024

[3][0] = ,Title
[3][1] = 
[3][2] = Title

[4][0] = ,"Description, more info"
[4][1] = "
[4][2] = Description, more info

[5][0] = ,
[5][1] = 
[5][2] = 

[6][0] = ,123987564
[6][1] = 
[6][2] = 123987564

Disabling Chrome Autofill

For username password combos this is an easy issue to resolve. Chrome heuristics looks for the pattern:

<input type="text">

followed by:

<input type="password">

Simply break this process by invalidating this:

<input type="text">
<input type="text" onfocus="this.type='password'">

How do I prevent an Android device from going to sleep programmatically?

If you just want to prevent the sleep mode on a specific View, just call setKeepScreenOn(true) on that View or set the keepScreenOn property to true. This will prevent the screen from going off while the View is on the screen. No special permission required for this.

How to increase the timeout period of web service in asp.net?

1 - You can set a timeout in your application :

var client = new YourServiceReference.YourServiceClass();
client.Timeout = 60; // or -1 for infinite

It is in milliseconds.

2 - Also you can increase timeout value in httpruntime tag in web/app.config :

<configuration>
     <system.web>
          <httpRuntime executionTimeout="<<**seconds**>>" />
          ...
     </system.web>
</configuration>

For ASP.NET applications, the Timeout property value should always be less than the executionTimeout attribute of the httpRuntime element in Machine.config. The default value of executionTimeout is 90 seconds. This property determines the time ASP.NET continues to process the request before it returns a timed out error. The value of executionTimeout should be the proxy Timeout, plus processing time for the page, plus buffer time for queues. -- Source

Google drive limit number of download

It looks like that this limitation can be avoided if you use the following URL pattern:

https://googledrive.com/host/file-id

For your case the download URL will look like this - https://googledrive.com/host/0ByvXJAlpPqQPYWNqY0V3MGs0Ujg

Please keep in mind that this method works only if file is shared with "Public on the web" option.

Split string with string as delimiter

I've found two older scripts that use an indefinite or even a specific string to split. As an approach, these are always helpful.

https://www.administrator.de/contentid/226533#comment-1059704 https://www.administrator.de/contentid/267522#comment-1000886

@echo off
:noOption
if "%~1" neq "" goto :nohelp
echo Gibt eine Ausgabe bis zur angebenen Zeichenfolge&echo(
echo %~n0 ist mit Eingabeumleitung zu nutzen
echo %~n0 "Zeichenfolge" ^<Quelldatei [^>Zieldatei]&echo(
echo    Zeichenfolge    die zu suchende Zeichenfolge wird mit FIND bestimmt
echo            ohne AusgabeUmleitung Ausgabe im CMD Fenster
exit /b
:nohelp
setlocal disabledelayedexpansion
set "intemp=%temp%%time::=%"
set "string=%~1"
set "stringlength=0"
:Laenge string bestimmen
for /f eol^=^

^ delims^= %%i in (' cmd /u /von /c "echo(!string!"^|find /v "" ') do set /a Stringlength += 1

:Eingabe temporär speichern
>"%intemp%" find /n /v ""

:suchen der Zeichenfolge und Zeile bestimmen und speichen
set "NRout="
for /f "tokens=*delims=" %%a in (' find "%string%"^<"%intemp%" ') do if not defined NRout (set "LineStr=%%a"
  for /f "delims=[]" %%b in ("%%a") do set "NRout=%%b"
)
if not defined NRout >&2 echo Zeichenfolge nicht gefunden.& set /a xcode=1 &goto :end
if %NRout% gtr 1 call :Line
call :LineStr

:end
del "%intemp%"
exit /b %xcode%

:LineStr Suche nur jeden ersten Buchstaben des Strings in der Treffer-Zeile dann Ausgabe bis dahin
for /f eol^=^

^ delims^= %%a in ('cmd /u /von /c "echo(!String!"^|findstr .') do (
  for /f "delims=[]" %%i in (' cmd /u /von /c "echo(!LineStr!"^|find /n "%%a" ') do (
    setlocal enabledelayedexpansion
    for /f %%n in ('set /a %%i-1') do if !LineStr:^~%%n^,%stringlength%! equ !string! (
      set "Lineout=!LineStr:~0,%%n!!string!"
      echo(!Lineout:*]=!
      exit /b
    )
) )
exit /b 

:Line vorige Zeilen ausgeben
for /f "usebackq tokens=* delims=" %%i in ("%intemp%") do (
  for /f "tokens=1*delims=[]" %%n in ("%%i") do if %%n EQU %NRout%  exit /b
  set "Line=%%i"
  setlocal enabledelayedexpansion 
  echo(!Line:*]=!
  endlocal
)
exit /b

@echo off
:: CUTwithWildcards.cmd
:noOption
if "%~1" neq "" goto :nohelp
echo Gibt eine Ausgabe ohne die angebene Zeichenfolge.
echo Der Rest wird abgeschnitten.&echo(
echo %~n0 "Zeichenfolge" B n E [/i] &echo(
echo    Zeichenfolge    String zum Durchsuchen
echo    B   Zeichen Wonach am Anfang gesucht wird
echo    n   Auszulassende Zeichenanzahl
echo    E   Zeichen was das Ende der Zeichen Bestimmt
echo    /i  Case intensive
exit /b
:nohelp
setlocal disabledelayedexpansion
set  "Original=%~1"
set     "Begin=%~2"
set /a    Excl=%~3 ||echo Syntaxfehler.>&2 &&exit /b 1
set       "End=%~4"
if not defined end echo Syntaxfehler.>&2 &exit /b 1
set   "CaseInt=%~5"
:: end Setting Input Param
set       "out="
set      "more="
call :read Original
if errorlevel 1 echo Zeichenfolge nicht gefunden.>&2
exit /b
:read VarName B # E [/i]
for /f "delims=[]" %%a in (' cmd /u /von /c "echo  !%~1!"^|find /n %CaseInt% "%Begin%" ') do (
  if defined out exit /b 0
  for /f "delims=[]" %%b in (' cmd /u /von /c "echo !%1!"^|more +%Excl%^|find /n %CaseInt% "%End%"^|find "[%%a]" ') do (
    set "out=1"
    setlocal enabledelayedexpansion
    set "In=  !Original!"
    set "In=!In:~,%%a!"
    echo !In:^~2!
    endlocal
) )
if not defined out exit /b 1 
exit /b

::oneliner for CMDLine
set "Dq=""
for %i in ("*S??E*") do @set "out=1" &for /f "delims=[]" %a in ('cmd/u/c "echo  %i"^|find /n "S"') do @if defined out for /f "delims=[]" %b in ('cmd/u/c "echo %i"^|more +2^|find /n "E"^|find "[%a]"') do @if %a equ %b set "out=" & set in= "%i" &cmd /v/c echo ren "%i" !in:^~0^,%a!!Dq!)

Cropping images in the browser BEFORE the upload

#change-avatar-file is a file input #change-avatar-file is a img tag (the target of jcrop) The "key" is FR.onloadend Event https://developer.mozilla.org/en-US/docs/Web/API/FileReader

$('#change-avatar-file').change(function(){
        var currentImg;
        if ( this.files && this.files[0] ) {
            var FR= new FileReader();
            FR.onload = function(e) {
                $('#avatar-change-img').attr( "src", e.target.result );
                currentImg = e.target.result;
            };
            FR.readAsDataURL( this.files[0] );
            FR.onloadend = function(e){
                //console.log( $('#avatar-change-img').attr( "src"));
                var jcrop_api;

                $('#avatar-change-img').Jcrop({
                    bgFade:     true,
                    bgOpacity: .2,
                    setSelect: [ 60, 70, 540, 330 ]
                },function(){
                    jcrop_api = this;
                });
            }
        }
    });

Giving multiple URL patterns to Servlet Filter

In case you are using the annotation method for filter definition (as opposed to defining them in the web.xml), you can do so by just putting an array of mappings in the @WebFilter annotation:

/**
 * Filter implementation class LoginFilter
 */
@WebFilter(urlPatterns = { "/faces/Html/Employee","/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginFilter implements Filter {
    ...

And just as an FYI, this same thing works for servlets using the servlet annotation too:

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet({"/faces/Html/Employee", "/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginServlet extends HttpServlet {
    ...

Adding open/closed icon to Twitter Bootstrap collapsibles (accordions)

This has been answered by numerous ways but what I came up with was the simplest and easiest for me with Bootstrap 3 and font awesome. I just did

$('a.toggler').on('click', function () {$('i', this).toggleClass('fa-caret-up');});

This just toggles the CSS class of the icon I want to show. I add the class toggler to the item I want to apply this to. This can be added onto any item you want to toggle an icon.

How to convert a String to Bytearray

The best solution I've come up with at on the spot (though most likely crude) would be:

String.prototype.getBytes = function() {
    var bytes = [];
    for (var i = 0; i < this.length; i++) {
        var charCode = this.charCodeAt(i);
        var cLen = Math.ceil(Math.log(charCode)/Math.log(256));
        for (var j = 0; j < cLen; j++) {
            bytes.push((charCode << (j*8)) & 0xFF);
        }
    }
    return bytes;
}

Though I notice this question has been here for over a year.

Save Javascript objects in sessionStorage

You could also use the store library which performs it for you with crossbrowser ability.

example :

// Store current user
store.set('user', { name:'Marcus' })

// Get current user
store.get('user')

// Remove current user
store.remove('user')

// Clear all keys
store.clearAll()

// Loop over all stored values
store.each(function(value, key) {
    console.log(key, '==', value)
})

Getting Serial Port Information

EDIT: Sorry, I zipped past your question too quick. I realize now that you're looking for a list with the port name + port description. I've updated the code accordingly...

Using System.Management, you can query for all the ports, and all the information for each port (just like Device Manager...)

Sample code (make sure to add reference to System.Management):

using System;
using System.Management;
using System.Collections.Generic;
using System.Linq;
using System.IO.Ports;        

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var searcher = new ManagementObjectSearcher
                ("SELECT * FROM WIN32_SerialPort"))
            {
                string[] portnames = SerialPort.GetPortNames();
                var ports = searcher.Get().Cast<ManagementBaseObject>().ToList();
                var tList = (from n in portnames
                            join p in ports on n equals p["DeviceID"].ToString()
                            select n + " - " + p["Caption"]).ToList();

                tList.ForEach(Console.WriteLine);
            }

            // pause program execution to review results...
            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
    }
}

More info here: http://msdn.microsoft.com/en-us/library/aa394582%28VS.85%29.aspx

C++ program converts fahrenheit to celsius

Fahrenheit to celsius would be (Fahrenheit - 32) * 5 / 9

Can I use a case/switch statement with two variables?

var var1 = "something";
var var2 = "something_else";
switch(var1 + "|" + var2) {
    case "something|something_else":
        ...
        break;
    case "something|...":
        break;
    case "...|...":
        break;
}

If you have 5 possibilities for each one you will get 25 cases.

How to change maven java home

Just set JAVA_HOME env property.

Select current date by default in ASP.Net Calendar control

Two ways of doing it.

Late binding

<asp:Calendar ID="planning" runat="server" SelectedDate="<%# DateTime.Now %>"></asp:Calendar>

Code behind way (Page_Load solution)

protected void Page_Load(object sender, EventArgs e)
{
    BindCalendar();
}

private void BindCalendar()
{
    planning.SelectedDate = DateTime.Today;
}

Altough, I strongly recommend to do it from a BindMyStuff way. Single entry point easier to debug. But since you seems to know your game, you're all set.

What's the difference between ng-model and ng-bind

ng-bind has one-way data binding ($scope --> view). It has a shortcut {{ val }} which displays the scope value $scope.val inserted into html where val is a variable name.

ng-model is intended to be put inside of form elements and has two-way data binding ($scope --> view and view --> $scope) e.g. <input ng-model="val"/>.

JSONObject - How to get a value?

You can try the below function to get value from JSON string,

public static String GetJSONValue(String JSONString, String Field)
{
       return JSONString.substring(JSONString.indexOf(Field), JSONString.indexOf("\n", JSONString.indexOf(Field))).replace(Field+"\": \"", "").replace("\"", "").replace(",","");   
}

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Tensorflow 2.1 works with Cuda 10.1.

If you want a quick hack:

  • Just download cudart64_101.dll from here. Extract the zip file and copy the cudart64_101.dll to your CUDA bin directory

Else:

  • Install Cuda 10.1

Convert a row of a data frame to vector

If you don't want to change to numeric you can try this.

> as.vector(t(df)[,1])
[1] 1.0 2.0 2.6

Junit - run set up method once

JUnit 5 @BeforeAll can be non static provided the lifecycle of the test class is per class, i.e., annotate the test class with a @TestInstance(Lifecycle.PER_CLASS) and you are good to go

Removing a list of characters in string

How about this - a one liner.

reduce(lambda x,y : x.replace(y,"") ,[',', '!', '.', ';'],";Test , ,  !Stri!ng ..")

Launching a website via windows commandline

IE has a setting, located in Tools / Internet options / Advanced / Browsing, called Reuse windows for launching shortcuts, which is checked by default. For IE versions that support tabbed browsing, this option is relevant only when tab browsing is turned off (in fact, IE9 Beta explicitly mentions this). However, since IE6 does not have tabbed browsing, this option does affect opening URLs through the shell (as in your example).

What is the difference between GitHub and gist?

GitHub is the entire site. Gists are a particular service offered on that site, namely code snippets akin to pastebin. However, everything is driven by git revision control, so gists also have complete revision histories.

How to pass a parameter to routerLink that is somewhere inside the URL?

In your particular example you'd do the following routerLink:

[routerLink]="['user', user.id, 'details']"

To do so in a controller, you can inject Router and use:

router.navigate(['user', user.id, 'details']);

More info in the Angular docs Link Parameters Array section of Routing & Navigation

How to use multiple LEFT JOINs in SQL?

Yes, but the syntax is different than what you have

SELECT
    <fields>
FROM
    <table1>
    LEFT JOIN <table2>
        ON <criteria for join>
        AND <other criteria for join>
    LEFT JOIN <table3> 
        ON <criteria for join>
        AND <other criteria for join>

jQuery checkbox change and click event

Late answer, but you can also use on("change")

_x000D_
_x000D_
$('#check').on('change', function() {
     var checked = this.checked
    $('span').html(checked.toString())
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="check"> <span>Check me!</span>
_x000D_
_x000D_
_x000D_

Combining C++ and C - how does #ifdef __cplusplus work?

extern "C" doesn't really change the way that the compiler reads the code. If your code is in a .c file, it will be compiled as C, if it is in a .cpp file, it will be compiled as C++ (unless you do something strange to your configuration).

What extern "C" does is affect linkage. C++ functions, when compiled, have their names mangled -- this is what makes overloading possible. The function name gets modified based on the types and number of parameters, so that two functions with the same name will have different symbol names.

Code inside an extern "C" is still C++ code. There are limitations on what you can do in an extern "C" block, but they're all about linkage. You can't define any new symbols that can't be built with C linkage. That means no classes or templates, for example.

extern "C" blocks nest nicely. There's also extern "C++" if you find yourself hopelessly trapped inside of extern "C" regions, but it isn't such a good idea from a cleanliness perspective.

Now, specifically regarding your numbered questions:

Regarding #1: __cplusplus will stay defined inside of extern "C" blocks. This doesn't matter, though, since the blocks should nest neatly.

Regarding #2: __cplusplus will be defined for any compilation unit that is being run through the C++ compiler. Generally, that means .cpp files and any files being included by that .cpp file. The same .h (or .hh or .hpp or what-have-you) could be interpreted as C or C++ at different times, if different compilation units include them. If you want the prototypes in the .h file to refer to C symbol names, then they must have extern "C" when being interpreted as C++, and they should not have extern "C" when being interpreted as C -- hence the #ifdef __cplusplus checking.

To answer your question #3: functions without prototypes will have C++ linkage if they are in .cpp files and not inside of an extern "C" block. This is fine, though, because if it has no prototype, it can only be called by other functions in the same file, and then you don't generally care what the linkage looks like, because you aren't planning on having that function be called by anything outside the same compilation unit anyway.

For #4, you've got it exactly. If you are including a header for code that has C linkage (such as code that was compiled by a C compiler), then you must extern "C" the header -- that way you will be able to link with the library. (Otherwise, your linker would be looking for functions with names like _Z1hic when you were looking for void h(int, char)

5: This sort of mixing is a common reason to use extern "C", and I don't see anything wrong with doing it this way -- just make sure you understand what you are doing.

How can I change the thickness of my <hr> tag

I believe the best achievement for styling <hr> tag is as follow:

hr {
color:#ddd;
background-color:
#ddd; height:1px;
border:none;
max-width:100%;
}

And for the HTML code just add: <hr>.

How to test for $null array in PowerShell

if($foo -eq $null) { "yes" } else { "no" }

help about_comparison_operators 

displays help and includes this text:

All comparison operators except the containment operators (-contains, -notcontains) and type operators (-is, -isnot) return a Boolean value when the input to the operator (the value on the left side of the operator) is a single value (a scalar). When the input is a collection of values, the containment operators and the type operators return any matching values. If there are no matches in a collection, these operators do not return anything. The containment operators and type operators always return a Boolean value.

Check if a given time lies between two times regardless of date

Modified @Surendra Jnawali' code. It fails

if current time is 23:40:00 i.e greater than start time and less than equals to 23:59:59.

All credit goes to the real owner

This is how it should be :This works perfect

public static boolean isTimeBetweenTwoTime(String argStartTime,
            String argEndTime, String argCurrentTime) throws ParseException {
        String reg = "^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
        //
        if (argStartTime.matches(reg) && argEndTime.matches(reg)
                && argCurrentTime.matches(reg)) {
            boolean valid = false;
            // Start Time
            java.util.Date startTime = new SimpleDateFormat("HH:mm:ss")
                    .parse(argStartTime);
            Calendar startCalendar = Calendar.getInstance();
            startCalendar.setTime(startTime);

            // Current Time
            java.util.Date currentTime = new SimpleDateFormat("HH:mm:ss")
                    .parse(argCurrentTime);
            Calendar currentCalendar = Calendar.getInstance();
            currentCalendar.setTime(currentTime);

            // End Time
            java.util.Date endTime = new SimpleDateFormat("HH:mm:ss")
                    .parse(argEndTime);
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.setTime(endTime);

            //
            if (currentTime.compareTo(endTime) < 0) {

                currentCalendar.add(Calendar.DATE, 1);
                currentTime = currentCalendar.getTime();

            }

            if (startTime.compareTo(endTime) < 0) {

                startCalendar.add(Calendar.DATE, 1);
                startTime = startCalendar.getTime();

            }
            //
            if (currentTime.before(startTime)) {

                System.out.println(" Time is Lesser ");

                valid = false;
            } else {

                if (currentTime.after(endTime)) {
                    endCalendar.add(Calendar.DATE, 1);
                    endTime = endCalendar.getTime();

                }

                System.out.println("Comparing , Start Time /n " + startTime);
                System.out.println("Comparing , End Time /n " + endTime);
                System.out
                        .println("Comparing , Current Time /n " + currentTime);

                if (currentTime.before(endTime)) {
                    System.out.println("RESULT, Time lies b/w");
                    valid = true;
                } else {
                    valid = false;
                    System.out.println("RESULT, Time does not lies b/w");
                }

            }
            return valid;

        } else {
            throw new IllegalArgumentException(
                    "Not a valid time, expecting HH:MM:SS format");
        }

    }

RESULT

Comparing , Start Time /n    Thu Jan 01 23:00:00 IST 1970
Comparing , End Time /n      Fri Jan 02 02:00:00 IST 1970
Comparing , Current Time /n  Fri Jan 02 01:50:00 IST 1970
RESULT, Time lies b/w

How to check that an element is in a std::set?

In C++20 we'll finally get std::set::contains method.

#include <iostream>
#include <string>
#include <set>

int main()
{
    std::set<std::string> example = {"Do", "not", "panic", "!!!"};

    if(example.contains("panic")) {
        std::cout << "Found\n";
    } else {
        std::cout << "Not found\n";
    }
}

CSS: styled a checkbox to look like a button, is there a hover?

Do this for a cool border and font effect:

#ck-button:hover {             /*ADD :hover */
    margin:4px;
    background-color:#EFEFEF;
    border-radius:4px;
    border:1px solid red;      /*change border color*/ 
    overflow:auto;
    float:left;
    color:red;                 /*add font color*/
}

Example: http://jsfiddle.net/zAFND/6/

How to remove an element from a list by index

You probably want pop:

a = ['a', 'b', 'c', 'd']
a.pop(1)

# now a is ['a', 'c', 'd']

By default, pop without any arguments removes the last item:

a = ['a', 'b', 'c', 'd']
a.pop()

# now a is ['a', 'b', 'c']

How do I run a Python program?

You can just call

python /path/to/filename.py

How to search JSON data in MySQL?

If your are using MySQL Latest version following may help to reach your requirement.

select * from products where attribs_json->"$.feature.value[*]" in (1,3)

How to decrypt an encrypted Apple iTunes iPhone backup?

Haven't tried it, but Elcomsoft released a product they claim is capable of decrypting backups, for forensics purposes. Maybe not as cool as engineering a solution yourself, but it might be faster.

http://www.elcomsoft.com/eppb.html

Use String.split() with multiple delimiters

I'd use Apache Commons:

import org.apache.commons.lang3.StringUtils;

private void getId(String pdfName){
    String[] tokens = StringUtils.split(pdfName, "-.");
}

It'll split on any of the specified separators, as opposed to StringUtils.splitByWholeSeparator(str, separator) which uses the complete string as a separator

Query-string encoding of a Javascript Object

Here's a concise & recursive version with Object.entries. It handles arbitrarily nested arrays, but not nested objects. It also removes empty elements:

const format = (k,v) => v !== null ? `${k}=${encodeURIComponent(v)}` : ''

const to_qs = (obj) => {
    return [].concat(...Object.entries(obj)
                       .map(([k,v]) => Array.isArray(v) 
                          ? v.map(arr => to_qs({[k]:arr})) 
                          : format(k,v)))
           .filter(x => x)
           .join('&');
}

E.g.:

let json = { 
    a: [1, 2, 3],
    b: [],              // omit b
    c: 1,
    d: "test&encoding", // uriencode
    e: [[4,5],[6,7]],   // flatten this
    f: null,            // omit nulls
    g: 0
};

let qs = to_qs(json)

=> "a=1&a=2&a=3&c=1&d=test%26encoding&e=4&e=5&e=6&e=7&g=0"

sort dict by value python

From your comment to gnibbler answer, i'd say you want a list of pairs of key-value sorted by value:

sorted(data.items(), key=lambda x:x[1])

How to debug "ImagePullBackOff"?

I was facing the similar problem, but instead of one all of my pods were not ready and displaying Ready status 0/1 Something like enter image description here

I tried a lot of things but at last i found that the context was not correctly set. Please use following command and ensure you are in correct context

kubectl config get-contexts

Can you set a border opacity in CSS?

As an alternate solution that may work in some cases: change the border-style to dotted.

Having alternating groups of pixels between the foreground color and the background color isn't the same as a continuous line of partially transparent pixels. On the other hand, this requires significantly less CSS and it is much more compatible across every browser without any browser-specific directives.

How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags

Lea Verous solution is good but i wanted more control over the position of the bullets so this is my approach:

.entry ul {
    list-style: none;
    padding: 0;
    margin: 0;
    /* hide overflow in the case of floating elements around ... */
    overflow: hidden;
}
.entry li { 
    position: relative;
    padding-left: 24px;
}
.entry li:before {
    /* with absolute position you can move this around or make it bigger without getting unwanted scrollbars */
    position: absolute;
    content: "• ";
    color: #E94E24;
    font-size: 30px;
    left: 0;
    /* use fonts like "arial" or use "sans-serif" to make the dot perfect round */ 
    font-family: Arial, sans-serif;
}

What is difference between Axios and Fetch?

A job I do a lot it seems, it's to send forms via ajax, that usually includes an attachment and several input fields. In the more classic workflow (HTML/PHP/JQuery) I've used $.ajax() in the client and PHP on the server with total success.

I've used axios for dart/flutter but now I'm learning react for building my web sites, and JQuery doesn't make sense.

Problem is axios is giving me some headaches with PHP on the other side, when posting both normal input fields and uploading a file in the same form. I tried $_POST and file_get_contents("php://input") in PHP, sending from axios with FormData or using a json construct, but I can never get both the file upload and the input fields.

On the other hand with Fetch I've been successful with this code:

var formid = e.target.id;

// populate FormData
var fd    = buildFormData(formid);       

// post to remote
fetch('apiurl.php', {
  method: 'POST',
  body: fd,
  headers: 
  {
     'Authorization' : 'auth',
     "X-Requested-With" : "XMLHttpRequest"
  }
})    

On the PHP side I'm able to retrieve the uploads via $_FILES and processing the other fields data via $_POST:

  $posts = [];
  foreach ($_POST as $post) {
      $posts[] =  json_decode($post);
  }

multiple prints on the same line in Python

This simple example will print 1-10 on the same line.

for i in range(1,11):
    print (i, end=" ")

apache not accepting incoming connections from outside of localhost

CentOS 7 uses firewalld by default now. But all the answers focus on iptables. So I wanted to add an answer related to firewalld.

Since firewalld is a "wrapper" for iptables, using antonio-fornie's answer still seems to work but I was unable to "save" that new rule. So I wasn't able to connect to my apache server as soon as a restart of the firewall happened. Luckily it is actually much more straightforward to make an equivalent change with firewalld commands. First check if firewalld is running:

firewall-cmd --state

If it is running the response will simply be one line that says "running".

To allow http (port 80) connections temporarily on the public zone:

sudo firewall-cmd --zone=public --add-service=http

The above will not be "saved", next time the firewalld service is restarted it'll go back to default rules. You should use this temporary rule to test and make sure it solves your connection issue before moving on.

To permanently allow http connections on the public zone:

sudo firewall-cmd --zone=public --permanent --add-service=http

If you do the "permanent" command without doing the "temporary" command as well, you'll need to restart firewalld to get your new default rules (this might be different for non CentOS systems):

 sudo systemctl restart firewalld.service

If this hasn't solved your connection issues it may be because your interface isn't in the "public zone". The following link is a great resource for learning about firewalld. It goes over in detail how to check, assign, and configure zones: https://www.digitalocean.com/community/tutorials/how-to-set-up-a-firewall-using-firewalld-on-centos-7

Youtube - downloading a playlist - youtube-dl

I have tried everything above, but none could solve my problem. I fixed it by updating the old version of youtube-dl to download playlist. To update it

sudo youtube-dl -U

or

youtube-dl -U

after you have successfully updated using the above command

youtube-dl -cit https://www.youtube.com/playlist?list=PLttJ4RON7sleuL8wDpxbKHbSJ7BH4vvCk

WebSockets vs. Server-Sent events/EventSource

Here is a talk about the differences between web sockets and server sent events. Since Java EE 7 a WebSocket API is already part of the specification and it seems that server sent events will be released in the next version of the enterprise edition.

How do I use PHP namespaces with autoload?

I use this simple hack in one line:

spl_autoload_register(function($name){
        require_once 'lib/'.str_replace('\\','/',$name).'.php';
    });

jQuery count child elements

It is simply possible with childElementCount in pure javascript

_x000D_
_x000D_
var countItems = document.getElementsByTagName("ul")[0].childElementCount;_x000D_
console.log(countItems);
_x000D_
<div id="selected">_x000D_
  <ul>_x000D_
    <li>29</li>_x000D_
    <li>16</li>_x000D_
    <li>5</li>_x000D_
    <li>8</li>_x000D_
    <li>10</li>_x000D_
    <li>7</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Ship an application with a database

Android already provides a version-aware approach of database management. This approach has been leveraged in the BARACUS framework for Android applications.

It enables you to manage the database along the entire version lifecycle of an app, beeing able to update the sqlite database from any prior version to the current one.

Also, it allows you to run hot-backups and hot-recovery of the SQLite.

I am not 100% sure, but a hot-recovery for a specific device may enable you to ship a prepared database in your app. But I am not sure about the database binary format which might be specific to certain devices, vendors or device generations.

Since the stuff is Apache License 2, feel free to reuse any part of the code, which can be found on github

EDIT :

If you only want to ship data, you might consider instantiating and persisting POJOs at the applications first start. BARACUS got a built-in support to this (Built-in key value store for configuration infos, e.g. "APP_FIRST_RUN" plus a after-context-bootstrap hook in order to run post-launch operations on the context). This enables you to have tight coupled data shipped with your app; in most cases this fitted to my use cases.

Remove non-ASCII characters from CSV

Try tr instead of sed

tr -cd '[:print:]' < file.txt

Can I simultaneously declare and assign a variable in VBA?

You can sort-of do that with objects, as in the following.

Dim w As New Widget

But not with strings or variants.

Check if option is selected with jQuery, if not select a default

I found a good way to check, if option is selected and select a default when it isn't.

    if(!$('#some_select option[selected="selected"]').val()) {
        //here code if it HAS NOT selected value
        //for exaple adding the first value as "placeholder"
        $('#some_select option:first-child').before('<option disabled selected>Wybierz:</option>');
    }

If #some_select has't default selected option then .val() is undefined

Resize on div element

DIV does not fire a resize event, so you won't be able to do exactly what you've coded, but you could look into monitoring DOM properties.

If you are actually working with something like resizables, and that is the only way for a div to change in size, then your resize plugin will probably be implementing a callback of its own.

What are the special dollar sign shell variables?

  • $_ last argument of last command
  • $# number of arguments passed to current script
  • $* / $@ list of arguments passed to script as string / delimited list

off the top of my head. Google for bash special variables.

Get next / previous element using JavaScript?

that's so simple

var element = querySelector("div")
var nextelement = element.ParentElement.querySelector("div+div")

Here is the browser supports https://caniuse.com/queryselector

Regular expression for only characters a-z, A-Z

With POSIX Bracket Expressions (not supported by Javascript) it can be done this way:

/[:alpha:]+/

Any alpha character A to Z or a to z.

or

/^[[:alpha:]]+$/s

to match strictly with spaces.