Programs & Examples On #Ssdl

How to make custom dialog with rounded corners in android

For API level >= 28 available attribute android:dialogCornerRadius . To support previous API versions need use

<style name="RoundedDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
        <item name="android:windowBackground">@drawable/dialog_bg</item>
    </style>

where dialog_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item >
        <shape >
            <solid android:color="@android:color/transparent" />
        </shape>
    </item>
    <item
        android:left="16dp"
        android:right="16dp">
        <shape>
            <solid
                android:color="@color/white"/>
            <corners
                android:radius="8dp" />

            <padding
                android:left="16dp"
                android:right="16dp" />
        </shape>
    </item>
</layer-list>

"The system cannot find the file specified"

I got same error after publish my project to my physical server. My web application works perfectly on my computer when I compile on VS2013. When I checked connection string on sql server manager, everything works perfect on server too. I also checked firewall (I switched it off). But still didn't work. I remotely try to connect database by SQL Manager with exactly same user/pass and instance name etc with protocol pipe/tcp and I saw that everything working normally. But when I try to open website I'm getting this error. Is there anyone know 4th option for fix this problem?.

NOTE: My App: ASP.NET 4.5 (by VS2013), Server: Windows 2008 R2 64bit, SQL: MS-SQL WEB 2012 SP1 Also other web applications works great at web browsers with their database on same server.


After one day suffering I found the solution of my issue:

First I checked all the logs and other details but i could find nothing. Suddenly I recognize that; when I try to use connection string which is connecting directly to published DB and run application on my computer by VS2013, I saw that it's connecting another database file. I checked local directories and I found it. ASP.NET Identity not using my connection string as I wrote in web.config file. And because of this VS2013 is creating or connecting a new database with the name "DefaultConnection.mdf" in App_Data folder. Then I found the solution, it was in IdentityModel.cs.

I changed code as this:

public class ApplicationUser : IdentityUser
{
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    //public ApplicationDbContext() : base("DefaultConnection") ---> this was original
    public ApplicationDbContext() : base("<myConnectionStringNameInWebConfigFile>") //--> changed
    {
    }
}

So, after all, I re-builded and published my project and everything works fine now :)

Entity Framework The underlying provider failed on Open

open SQL Server Configuration Manager then click on sql server services a list will be displayed from the list right click sql server and click on start

error: the details of the application error from being viewed remotely

Dear olga is clear what the message says. Turn off the custom errors to see the details about this error for fix it, and then you close them back. So add mode="off" as:

<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>

Relative answer: Deploying website: 500 - Internal server error

By the way: The error message declare that the web.config is not the one you type it here. Maybe you have forget to upload your web.config ? And remember to close the debug flag on the web.config that you use for online pages.

The 'packages' element is not declared

Change the node to and create a file, packages.xsd, in the same folder (and include it in the project) with the following contents:

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
      targetNamespace="urn:packages" xmlns="urn:packages">
  <xs:element name="packages">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="package" maxOccurs="unbounded">
          <xs:complexType>
            <xs:attribute name="id" type="xs:string" use="required" />
            <xs:attribute name="version" type="xs:string" use="required" />
            <xs:attribute name="targetFramework" type="xs:string" use="optional" />
            <xs:attribute name="allowedVersions" type="xs:string" use="optional" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Keyword not supported: "data source" initializing Entity Framework Context

The real reason you were getting this error is because of the &quot; values in your connection string.

If you replace those with single quotes then it will work fine.

https://docs.microsoft.com/archive/blogs/rickandy/explicit-connection-string-for-ef

(Posted so others can get the fix faster than I did.)

Entity Framework Timeouts

For Entity framework 6 I use this annotation and works fine.

  public partial class MyDbContext : DbContext
  {
      private const int TimeoutDuration = 300;

      public MyDbContext ()
          : base("name=Model1")
      {
          this.Database.CommandTimeout = TimeoutDuration;
      }
       // Some other codes
    }

The CommandTimeout parameter is a nullable integer that set timeout values as seconds, if you set null or don't set it will use default value of provider you use.

Connection Strings for Entity Framework

Instead of using config files you can use a configuration database with a scoped systemConfig table and add all your settings there.

CREATE TABLE [dbo].[SystemConfig]  
    (  
      [Id] [int] IDENTITY(1, 1)  
                 NOT NULL ,  
      [AppName] [varchar](128) NULL ,  
      [ScopeName] [varchar](128) NOT NULL ,  
      [Key] [varchar](256) NOT NULL ,  
      [Value] [varchar](MAX) NOT NULL ,  
      CONSTRAINT [PK_SystemConfig_ID] PRIMARY KEY NONCLUSTERED ( [Id] ASC )  
        WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,  
               IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,  
               ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]  
    )  
ON  [PRIMARY]  

GO  

SET ANSI_PADDING OFF  
GO  

ALTER TABLE [dbo].[SystemConfig] ADD  CONSTRAINT [DF_SystemConfig_ScopeName]  DEFAULT ('SystemConfig') FOR [ScopeName]  
GO 

With such configuration table you can create rows like such: enter image description here

Then from your your application dal(s) wrapping EF you can easily retrieve the scoped configuration.
If you are not using dal(s) and working in the wire directly with EF, you can make an Entity from the SystemConfig table and use the value depending on the application you are on.

entity framework Unable to load the specified metadata resource

Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.

The following res: (resource) references need to point to your model.

<add name="Entities" connectionString="metadata=
    res://*/Models.WraithNath.co.uk.csdl|
    res://*/Models.WraithNath.co.uk.ssdl|
    res://*/Models.WraithNath.co.uk.msl;

Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).

It also may help to specify the assembly rather than using "//*/".

Worst case, you can check everything (a bit slower but should always find the resource) by using

<add name="Entities" connectionString="metadata=
        res://*/;provider= <!-- ... -->

MSSQL Error 'The underlying provider failed on Open'

I was searching all over the web for this problem. I had the wrong name in the connection string, please check you connection string in web.config. I had name="AppTest" but it should have been name="App".

In my AppTestContext.cs file I had:

public AppTestContext() : this("App") { }

Wrong connection string:

<add connectionString="Data Source=127.0.0.1;Initial Catalog=AppTest;Integrated Security=SSPI;MultipleActiveResultSets=True" name="AppTest" providerName="System.Data.SqlClient" />

Right connection string:

<add connectionString="Data Source=127.0.0.1;Initial Catalog=AppTest;Integrated Security=SSPI;MultipleActiveResultSets=True" name="App" providerName="System.Data.SqlClient" />

The name 'ConfigurationManager' does not exist in the current context

Add the configuration manager file to connect to the database web.config

MetadataException when using Entity Framework Entity Connection

I had this problem when moving my .edmx database first model from one project to another.

I simply did the following:

  1. Deleted the connection strings in the app.config or web.config
  2. Deleted the 'Model.edmx'
  3. Re-added the model to the project.

Where does Oracle SQL Developer store connections?

for macOS

/Users/joseluisbz/.sqldeveloper/system18.1.0.095.1630/o.jdeveloper.db.connection/connections.xml

How to raise a ValueError?

Here's a revised version of your code which still works plus it illustrates how to raise a ValueError the way you want. By-the-way, I think find_last(), find_last_index(), or something simlar would be a more descriptive name for this function. Adding to the possible confusion is the fact that Python already has a container object method named __contains__() that does something a little different, membership-testing-wise.

def contains(char_string, char):
    largest_index = -1
    for i, ch in enumerate(char_string):
        if ch == char:
            largest_index = i
    if largest_index > -1:  # any found?
        return largest_index  # return index of last one
    else:
        raise ValueError('could not find {!r} in {!r}'.format(char, char_string))

print(contains('mississippi', 's'))  # -> 6
print(contains('bababa', 'k'))  # ->
Traceback (most recent call last):
  File "how-to-raise-a-valueerror.py", line 15, in <module>
    print(contains('bababa', 'k'))
  File "how-to-raise-a-valueerror.py", line 12, in contains
    raise ValueError('could not find {} in {}'.format(char, char_string))
ValueError: could not find 'k' in 'bababa'

Update — A substantially simpler way

Wow! Here's a much more concise version—essentially a one-liner—that is also likely faster because it reverses (via [::-1]) the string before doing a forward search through it for the first matching character and it does so using the fast built-in string index() method. With respect to your actual question, a nice little bonus convenience that comes with using index() is that it already raises a ValueError when the character substring isn't found, so nothing additional is required to make that happen.

Here it is along with a quick unit test:

def contains(char_string, char):
    #  Ending - 1 adjusts returned index to account for searching in reverse.
    return len(char_string) - char_string[::-1].index(char) - 1

print(contains('mississippi', 's'))  # -> 6
print(contains('bababa', 'k'))  # ->
Traceback (most recent call last):
  File "better-way-to-raise-a-valueerror.py", line 9, in <module>
    print(contains('bababa', 'k'))
  File "better-way-to-raise-a-valueerror", line 6, in contains
    return len(char_string) - char_string[::-1].index(char) - 1
ValueError: substring not found

How to find a value in an array of objects in JavaScript?

If you have an array such as

var people = [
  { "name": "bob", "dinner": "pizza" },
  { "name": "john", "dinner": "sushi" },
  { "name": "larry", "dinner": "hummus" }
];

You can use the filter method of an Array object:

people.filter(function (person) { return person.dinner == "sushi" });
  // => [{ "name": "john", "dinner": "sushi" }]

In newer JavaScript implementations you can use a function expression:

people.filter(p => p.dinner == "sushi")
  // => [{ "name": "john", "dinner": "sushi" }]

You can search for people who have "dinner": "sushi" using a map

people.map(function (person) {
  if (person.dinner == "sushi") {
    return person
  } else {
    return null
  }
}); // => [null, { "name": "john", "dinner": "sushi" }, null]

or a reduce

people.reduce(function (sushiPeople, person) {
  if (person.dinner == "sushi") {
    return sushiPeople.concat(person);
  } else {
    return sushiPeople
  }
}, []); // => [{ "name": "john", "dinner": "sushi" }]

I'm sure you are able to generalize this to arbitrary keys and values!

Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

Uncaught ReferenceError: google is not defined error will be gone when removed the async defer from the map API script tag.

How can I select rows by range?

For mysql you have limit, you can fire query as :

SELECT * FROM table limit 100` -- get 1st 100 records
SELECT * FROM table limit 100, 200` -- get 200 records beginning with row 101

For Oracle you can use rownum

See mysql select syntax and usage for limit here.

For SQLite, you have limit, offset. I haven't used SQLite but I checked it on SQLite Documentation. Check example for SQLite here.

Checking whether the pip is installed?

You need to run pip list in bash not in python.

pip list
DEPRECATION: Python 2.6 is no longer supported by the Python core team, please upgrade your Python. A future version of pip will drop support for Python 2.6
argparse (1.4.0)
Beaker (1.3.1)
cas (0.15)
cups (1.0)
cupshelpers (1.0)
decorator (3.0.1)
distribute (0.6.10)
---and other modules

Add carriage return to a string

I propose use StringBuilder

string s1 = "'99024','99050','99070','99143','99173','99191','99201','99202','99203','99204','99211','99212','99213','99214','99215','99217','99218','99219','99221','99222','99231','99232','99238','99239','99356','99357','99371','99374','99381','99382','99383','99384','99385','99386','99391','99392'";

var stringBuilder = new StringBuilder();           

foreach (var s in s1.Split(','))
{
    stringBuilder.Append(s).Append(",").AppendLine();
}
Console.WriteLine(stringBuilder);

What precisely does 'Run as administrator' do?

Okay, let's re-iterate...

The actual question (and an excellent one at that)

"What does 'run as admin' do that being a member of the administrators group does not?"

(Answer)1. It allows you to call on administrator rights while under a user session.

Note: The question is wrongly put; one is a command and the other is a group object to apply policies.

Open a command prompt and type runas /?.

This will list all the switches the runas command line can use.

As for the Administrators Group this is based on GPEDIT or SECPOL and whether or not a Domain administrator is present or not or a network is present or not.

Usually these things will apply restrictions on computers that the administrators group is not affected by.

The question should be

What does runas admin do that run as user does not?

OR

What does the Administrator group do that a customized user group can't?

You are mixing apples and oranges.

How to deserialize xml to object

The comments above are correct. You're missing the decorators. If you want a generic deserializer you can use this.

public static T DeserializeXMLFileToObject<T>(string XmlFilename)
{
    T returnObject = default(T);
    if (string.IsNullOrEmpty(XmlFilename)) return default(T);

    try
    {
        StreamReader xmlStream = new StreamReader(XmlFilename);
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        returnObject = (T)serializer.Deserialize(xmlStream);
    }
    catch (Exception ex)
    {
        ExceptionLogger.WriteExceptionToConsole(ex, DateTime.Now);
    }
    return returnObject;
}

Then you'd call it like this:

MyObjType MyObj = DeserializeXMLFileToObject<MyObjType>(FilePath);

JavaFX open new window

I use the following method in my JavaFX applications.

newWindowButton.setOnMouseClicked((event) -> {
    try {
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(getClass().getResource("NewWindow.fxml"));
        /* 
         * if "fx:controller" is not set in fxml
         * fxmlLoader.setController(NewWindowController);
         */
        Scene scene = new Scene(fxmlLoader.load(), 600, 400);
        Stage stage = new Stage();
        stage.setTitle("New Window");
        stage.setScene(scene);
        stage.show();
    } catch (IOException e) {
        Logger logger = Logger.getLogger(getClass().getName());
        logger.log(Level.SEVERE, "Failed to create new Window.", e);
    }
});

Django CSRF check failing with an Ajax POST request

The issue is because django is expecting the value from the cookie to be passed back as part of the form data. The code from the previous answer is getting javascript to hunt out the cookie value and put it into the form data. Thats a lovely way of doing it from a technical point of view, but it does look a bit verbose.

In the past, I have done it more simply by getting the javascript to put the token value into the post data.

If you use {% csrf_token %} in your template, you will get a hidden form field emitted that carries the value. But, if you use {{ csrf_token }} you will just get the bare value of the token, so you can use this in javascript like this....

csrf_token = "{{ csrf_token }}";

Then you can include that, with the required key name in the hash you then submit as the data to the ajax call.

How to remove all callbacks from a Handler?

If you don't have the Runnable references, on the first callback, get the obj of the message, and use removeCallbacksAndMessages() to remove all related callbacks.

How can I set the focus (and display the keyboard) on my EditText programmatically

showSoftInput was not working for me at all.

I figured I needed to set the input mode : android:windowSoftInputMode="stateVisible" (here in the Activity component in the manifest)

Hope this help!

shell script. how to extract string using regular expressions

One way would be with sed. For example:

echo $name | sed -e 's?http://www\.??'

Normally the sed regular expressions are delimited by `/', but you can use '?' since you're searching for '/'. Here's another bash trick. @DigitalTrauma's answer reminded me that I ought to suggest it. It's similar:

echo ${name#http://www.}

(DigitalTrauma also gets credit for reminding me that the "http://" needs to be handled.)

HTML table: keep the same width for columns

In your case, since you are only showing 3 columns:

Name    Value       Business
  or
Name    Business    Ecommerce Pro

why not set all 3 to have a width of 33.3%. since only 3 are ever shown at once, the browser should render them all a similar width.

How do I install Python packages on Windows?

Upgrade the pip via command prompt ( Python Directory )

D:\Python 3.7.2>python -m pip install --upgrade pip

Now you can install the required Module

D:\Python 3.7.2>python -m pip install <<yourModuleName>>

How to get the Android device's primary e-mail address

Use this method:

 public String getUserEmail() {
    AccountManager manager = AccountManager.get(App.getInstance());
    Account[] accounts = manager.getAccountsByType("com.google");
    List<String> possibleEmails = new LinkedList<>();
    for (Account account : accounts) {
        possibleEmails.add(account.name);
    }
    if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
        return possibleEmails.get(0);
    }
    return "";
}

Note that this requires the GET_ACCOUNTS permission:

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

Then:

editTextEmailAddress.setText(getUserEmail());

Handling identity columns in an "Insert Into TABLE Values()" statement?

set identity_insert customer on
insert into Customer(id,Name,city,Salary) values(8,'bcd','Amritsar',1234)

where 'customer' is table name

Egit rejected non-fast-forward

Open git view :

1- select your project and choose merge 2- Select remote tracking 3- click ok

Git will merge the remote branch with local repository

4- then push

Better way to set distance between flexbox items

You can use transparent borders.

I have contemplated this issue while trying to build a flex grid model which can fallback to a tables + table-cell model for older browsers. And Borders for column gutters seemed to me the best appropriate choice. i.e. Table-cells don't have margins.

e.g.

.column{
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-bottom: 10px solid transparent;
}

Also note that you need min-width: 50px; for flexbox. The flex model will not handle fixed sizes unless you do flex: none; on the particular child element you want as fixed and therefore excluded from being "flexi". http://jsfiddle.net/GLpUp/4/ But all columns together with flex:none; is no longer a flex model. Here is something closer to a flex model: http://jsfiddle.net/GLpUp/5/

So you can actually use margins normally if you don't need the table-cell fallback for older browsers. http://jsfiddle.net/GLpUp/3/

Setting background-clip: padding-box; will be necessary when using a background, as otherwise the background will flow into the transparent border area.

jQuery return ajax result into outside variable

You are missing a comma after

'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' }

Also, if you want return_first to hold the result of your anonymous function, you need to make a function call:

var return_first = function () {
    var tmp = null;
    $.ajax({
        'async': false,
        'type': "POST",
        'global': false,
        'dataType': 'html',
        'url': "ajax.php?first",
        'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' },
        'success': function (data) {
            tmp = data;
        }
    });
    return tmp;
}();

Note () at the end.

How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default

<%: Html.RadioButtonFor(m => m.Gender, "Male", new { @checked = true } )%>

or

@checked = checked

if you like

Declaring variables in Excel Cells

I also just found out how to do this with the Excel Name Manager (Formulas > Defined Names Section > Name Manager).

You can define a variable that doesn't have to "live" within a cell and then you can use it in formulas.

Excel Name Manager

How to redirect and append both stdout and stderr to a file with Bash?

This should work fine:

your_command 2>&1 | tee -a file.txt

It will store all logs in file.txt as well as dump them on terminal.

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

NSAttributedString add text alignment

I was searching for the same issue and was able to center align the text in a NSAttributedString this way:

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init] ;
[paragraphStyle setAlignment:NSTextAlignmentCenter];

NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithString:string];
[attribString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [string length])];

PHP memcached Fatal error: Class 'Memcache' not found

The right is php_memcache.dll. In my case i was using lib compiled with vc9 instead of vc6 compiler. In apatche error logs i got something like:

PHP Startup: sqlanywhere: Unable to initialize module Module compiled with build ID=API20090626, TS,VC9 PHP compiled with build ID=API20090626, TS,VC6 These options need to match

Check if you have same log and try downloading different dll that are compiled with different compiler.

Removing rounded corners from a <select> element in Chrome/Webkit

Just my solution with dropdown image (inline svg)

select.form-control {
    -webkit-appearance: none;
    -webkit-border-radius: 0px;
    background-image: url("data:image/svg+xml;utf8,<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='24' height='24' viewBox='0 0 24 24'><path fill='%23444' d='M7.406 7.828l4.594 4.594 4.594-4.594 1.406 1.406-6 6-6-6z'></path></svg>");
    background-position: 100% 50%;
    background-repeat: no-repeat;
}

I'm using bootstrap that's why I used select.form-control
You can use select{ or select.your-custom-class{ instead.

Convert ascii value to char

for (int i = 0; i < 5; i++){
    int asciiVal = rand()%26 + 97;
    char asciiChar = asciiVal;
    cout << asciiChar << " and ";
}

How to return multiple values in one column (T-SQL)?

You can either loop through the rows with a cursor and append to a field in a temp table, or you could use the COALESCE function to concatenate the fields.

How to recompile with -fPIC

Have a look at this page.

you can try globally adding the flag using: export CXXFLAGS="$CXXFLAGS -fPIC"

How to place div in top right hand corner of page

Try css:

.topcorner{
    position:absolute;
    top:10px;
    right: 10px;
 }

you can play with the top and right properties.

If you want to float the div even when you scroll down, just change position:absolute; to position:fixed;.

Hope it helps.

Limiting double to 3 decimal places

Good answers above- if you're looking for something reusable here is the code. Note that you might want to check the decimal places value, and this may overflow.

public static decimal TruncateToDecimalPlace(this decimal numberToTruncate, int decimalPlaces)
{
    decimal power = (decimal)(Math.Pow(10.0, (double)decimalPlaces));

    return Math.Truncate((power * numberToTruncate)) / power;
}

Get all directories within directory nodejs

If you need to use all async version. You can have something like this.

  1. Record the directory length, uses it as an indicator to tell if all async stat tasks are finished.

  2. If the async stat tasks are finished, all the file stat has been checked, so call the callback

This will only work as long as Node.js is single thread, because it assumes no two async tasks will increase the counter at the same time.

'use strict';

var fs = require("fs");
var path = require("path");
var basePath = "./";

function result_callback(results) {
    results.forEach((obj) => {
        console.log("isFile: " + obj.fileName);
        console.log("fileName: " + obj.isFile);
    });
};

fs.readdir(basePath, (err, files) => {
    var results = [];
    var total = files.length;
    var finished = 0;

    files.forEach((fileName) => {
        // console.log(fileName);
        var fullPath = path.join(basePath, fileName);

        fs.stat(fullPath, (err, stat) => {
            // this will work because Node.js is single thread
            // therefore, the counter will not increment at the same time by two callback
            finished++;

            if (stat.isFile()) {
                results.push({
                    fileName: fileName,
                    isFile: stat.isFile()
                });
            }

            if (finished == total) {
                result_callback(results);
            }
        });
    });
});

As you can see, this is a "depth first" approach, and this could result in callback hell, and it is not quite "functional" . People try to solve this problem with Promise, by wrapping the async task into an Promise object.

'use strict';

var fs = require("fs");
var path = require("path");
var basePath = "./";

function result_callback(results) {
    results.forEach((obj) => {
        console.log("isFile: " + obj.fileName);
        console.log("fileName: " + obj.isFile);
    });
};

fs.readdir(basePath, (err, files) => {
    var results = [];
    var total = files.length;
    var finished = 0;

    var promises = files.map((fileName) => {
        // console.log(fileName);
        var fullPath = path.join(basePath, fileName);

        return new Promise((resolve, reject) => {
            // try to replace fullPath wil "aaa", it will reject
            fs.stat(fullPath, (err, stat) => {
                if (err) {
                    reject(err);
                    return;
                }

                var obj = {
                    fileName: fileName,
                    isFile: stat.isFile()
                };

                resolve(obj);
            });
        });
    });

    Promise.all(promises).then((values) => {
        console.log("All the promise resolved");
        console.log(values);
        console.log("Filter out folder: ");
        values
            .filter((obj) => obj.isFile)
            .forEach((obj) => {
                console.log(obj.fileName);
            });
    }, (reason) => {
        console.log("Not all the promise resolved");
        console.log(reason);
    });
});

How to set time to a date object in java

Can you show code which you use for setting date object? Anyway< you can use this code for intialisation of date:

new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2011-01-01 00:00:00")

How to run a C# application at Windows startup?

You could try copying a shortcut to your application into the startup folder instead of adding things to the registry. You can get the path with Environment.SpecialFolder.Startup. This is available in all .net frameworks since 1.1.

Alternatively, maybe this site will be helpful to you, it lists a lot of the different ways you can get an application to auto-start.

The term 'Get-ADUser' is not recognized as the name of a cmdlet

Check here for how to add the activedirectory module if not there by default. This can be done on any machine and then it will allow you to access your active directory "domain control" server.

EDIT

To prevent problems with stale links (I have found MSDN blogs to disappear for no reason in the past), in essence for Windows 7 you need to download and install Remote Server Administration Tools (KB958830). After installing do the following steps:

  • Open Control Panel -> Programs and Features -> Turn On/Off Windows Features
  • Find "Remote Server Administration Tools" and expand it
  • Find "Role Administration Tools" and expand it
  • Find "AD DS And AD LDS Tools" and expand it
  • Check the box next to "Active Directory Module For Windows PowerShell".
  • Click OK and allow Windows to install the feature

Windows server editions should already be OK but if not you need to download and install the Active Directory Management Gateway Service. If any of these links should stop working, you should still be able search for the KB article or download names and find them.

Sending mass email using PHP

First off, using the mail() function that comes with PHP is not an optimal solution. It is easily marked as spammed, and you need to set up header to ensure that you are sending HTML emails correctly. As for whether the code snippet will work, it would, but I doubt you will get HTML code inside it correctly without specifying extra headers

I'll suggest you take a look at SwiftMailer, which has HTML support, support for different mime types and SMTP authentication (which is less likely to mark your mail as spam).

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

You need to use jackson-module-kotlin to deserialize to data classes. See here for details.

The error message above is what Jackson gives you if you try to deserialize some value into a data class when that module isn't enabled or, even if it is, when the ObjectMapper it uses doesn't have the KotlinModule registered. For example, take this code:

data class TestDataClass (val foo: String)

val jsonString = """{ "foo": "bar" }"""
val deserializedValue = ObjectMapper().readerFor(TestDataClass::class.java).readValue<TestDataClass>(jsonString)

This will fail with the following error:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `test.SerializationTests$TestDataClass` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)

If you change the code above and replace ObjectMapper with jacksonObjectMapper (which simply returns a normal ObjectMapper with the KotlinModule registered), it works. i.e.

val deserializedValue = jacksonObjectMapper().readerFor(TestDataClass::class.java).readValue<TestDataClass>(jsonString)

I'm not sure about the Android side of things, but it looks like you'll need to get the system to use the jacksonObjectMapper to do the deserialization.

How can I join on a stored procedure?

I hope your stored procedure is not doing a cursor loop!

If not, take the query from your stored procedure and integrate that query within the query you are posting here:

SELECT t.TenantName, t.CarPlateNumber, t.CarColor, t.Sex, t.SSNO, t.Phone, t.Memo,
        u.UnitNumber,
        p.PropertyName
        ,dt.TenantBalance
FROM tblTenant t
    LEFT JOIN tblRentalUnit u ON t.UnitID = u.ID
    LEFT JOIN tblProperty   p ON u.PropertyID = p.ID
    LEFT JOIN (SELECT ID, SUM(ISNULL(trans.Amount,0)) AS TenantBalance
                   FROM tblTransaction
                   GROUP BY tenant.ID
              ) dt ON t.ID=dt.ID
ORDER BY p.PropertyName, t.CarPlateNumber

If you are doing something more than a query in your stored procedure, create a temp table and execute the stored procedure into this temp table and then join to that in your query.

create procedure test_proc
as
  select 1 as x, 2 as y
  union select 3,4 
  union select 5,6 
  union select 7,8 
  union select 9,10
  return 0
go 

create table #testing
(
  value1   int
  ,value2  int
)

INSERT INTO #testing
exec test_proc


select
  *
  FROM #testing

TypeError: 'NoneType' object has no attribute '__getitem__'

The function move.CompleteMove(events) that you use within your class probably doesn't contain a return statement. So nothing is returned to self.values (==> None). Use return in move.CompleteMove(events) to return whatever you want to store in self.values and it should work. Hope this helps.

Android Studio - ADB Error - "...device unauthorized. Please check the confirmation dialog on your device."

I had the same problem when debugging over wlan. I could launch the application from Android Studio but couldn't get any messages in logcat.

I fixed it by connecting the device to my pc via USB cable, launched the application once and everything was working. Then I disconnected the USB cable and tried debugging again via wlan and everything was working again.

Spring - applicationContext.xml cannot be opened because it does not exist

In Spring all source files are inside src/main/java. Similarly, the resources are generally kept inside src/main/resources. So keep your spring configuration file inside resources folder.

Make sure you have the ClassPath entry for your files inside src/main/resources as well.

In .classpath check for the following 2 lines. If they are missing add them.

<classpathentry path="src/main/java" kind="src"/>
<classpathentry path="src/main/resources" kind="src" />

So, if you have everything in place the below code should work.

ApplicationContext ctx = new ClassPathXmlApplicationContext("Spring-Module.xml");

How to serialize Joda DateTime with Jackson JSON processor?

https://stackoverflow.com/a/10835114/1113510

Although you can put an annotation for each date field, is better to do a global configuration for your object mapper. If you use jackson you can configure your spring as follow:

<bean id="jacksonObjectMapper" class="com.company.CustomObjectMapper" />

<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
    factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" >
</bean>

For CustomObjectMapper:

public class CustomObjectMapper extends ObjectMapper {

    public CustomObjectMapper() {
        super();
        configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false);
        setDateFormat(new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'ZZZ (z)"));
    }
}

Of course, SimpleDateFormat can use any format you need.

How can I query for null values in entity framework?

I'm not able to comment divega's post, but among the different solutions presented here, divega's solution produces the best SQL. Both performance wise and length wise. I just checked with SQL Server Profiler and by looking at the execution plan (with "SET STATISTICS PROFILE ON").

Generate a range of dates using SQL

I don't have the answer to re-use the digits table but here is a code sample that will work at least in SQL server and is a bit faster.

print("code sample");

select  top 366 current_timestamp - row_number() over( order by l.A * r.A) as DateValue
from (
select  1 as A union
select  2 union
select  3 union
select  4 union
select  5 union
select  6 union
select  7 union
select  8 union
select  9 union
select  10 union
select  11 union
select  12 union
select  13 union
select  14 union
select  15 union
select  16 union
select  17 union
select  18 union
select  19 union
select  20 union
select  21 
) l
cross join (
select 1 as A union
select 2 union
select 3 union
select 4 union
select 5 union
select 6 union
select 7 union
select 8 union
select 9 union
select 10 union
select 11 union
select 12 union
select 13 union
select 14 union
select 15 union
select 16 union
select 17 union
select 18
) r
print("code sample");

Spark Dataframe distinguish columns with duplicated name

There is a simpler way than writing aliases for all of the columns you are joining on by doing:

df1.join(df2,['a'])

This works if the key that you are joining on is the same in both tables.

See https://kb.databricks.com/data/join-two-dataframes-duplicated-columns.html

remove url parameters with javascript or jquery

Hmm... Looking for better way... here it is

var onlyUrl = window.location.href.replace(window.location.search,'');

How to read/write a boolean when implementing the Parcelable interface?

you declare like this

 private boolean isSelectionRight;

write

 out.writeInt(isSelectionRight ? 1 : 0);

read

isSelectionRight  = in.readInt() != 0;

boolean type needs to be converted to something that Parcel supports and so we can convert it to int.

How to use addTarget method in swift 3

The poster's second comment from September 21st is spot on. For those who may be coming to this thread later with the same problem as the poster, here is a brief explanation. The other answers are good to keep in mind, but do not address the common issue encountered by this code.

In Swift, declarations made with the let keyword are constants. Of course if you were going to add items to an array, the array can't be declared as a constant, but a segmented control should be fine, right?! Not if you reference the completed segmented control in its declaration.

Referencing the object (in this case a UISegmentedControl, but this also happens with UIButton) in its declaration when you say .addTarget and let the target be self, things crash. Why? Because self is in the midst of being defined. But we do want to define behaviour as part of the object... Declare it lazily as a variable with var. The lazy fools the compiler into thinking that self is well defined - it silences your compiler from caring at the time of declaration. Lazily declared variables don't get set until they are first called. So in this situation, lazy lets you use the notion of self without issue while you set up the object, and then when your object gets a .touchUpInside or .valueChanged or whatever your 3rd argument is in your .addTarget(), THEN it calls on the notion of self, which at that point is fully established and totally prepared to be a valid target. So it lets you be lazy in declaring your variable. In cases like these, I think they could give us a keyword like necessary, but it is generally seen as a lazy, sloppy practice and you don't want to use it all over your code, though it may have its place in this sort of situation. What it

There is no lazy let in Swift (no lazy for constants).

Here is the Apple documentation on lazy.

Here is the Apple on variables and constants. There is a little more in their Language Reference under Declarations.

How to make the division of 2 ints produce a float instead of another int?

JLS Standard

JLS 7 15.17.2. Division Operator / says:

Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d · q| = |n|. Moreover, q is positive when |n| = |d| and n and d have the same sign, but q is negative when |n| = |d| and n and d have opposite signs.

This is why 1/2 does not give a float.

Converting just either one to float as in (float)1/2 suffices because 15.17. Multiplicative Operators says:

Binary numeric promotion is performed on the operands

and 5.6.2. Binary Numeric Promotion says:

  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float

TypeError: list indices must be integers or slices, not str

I had same error and the mistake was that I had added list and dictionary into the same list (object) and when I used to iterate over the list of dictionaries and use to hit a list (type) object then I used to get this error.

Its was a code error and made sure that I only added dictionary objects to that list and list typed object into the list, this solved my issue as well.

Correct way to create rounded corners in Twitter Bootstrap

In Bootstrap 4, the correct way to border your elements is to name them as follows in the class list of your elements:

For a slight rounding effect on all corners; class="rounded"
For a slight rounding on the left; class="rounded-left"
For a slight rounding on the top; class="rounded-top"
For a slight rounding on the right; class="rounded-right"
For a slight rounding on the bottom; class="rounded-bottom" 
For a circle rounding, i.e. your element is made circular; class="rounded-circle"
And to remove rounding effects; class="rounded-0"

To use Bootstrap 4 css files, you can simply use the CDN, and use the following link in the of your HTML file:

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

This will provided you with the basics of Bootstrap 4. However if you would like to use the majority of Bootstrap 4 components, including tooltips, popovers, and dropdowns, then you are best to use the following code instead:

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

Alternatively, you can install Bootstrap using NPM, or Bower, and link to the files there.

*Note that the bottom tag of the three is the same as the first tag in the first link path.

A full working example, could be :

<img src="path/to/my/image/image.jpg" width="150" height="150" class="rounded-circle mx-auto">

In the above example, the image is centered by using the Bootstrap auto margin on left and right.

include external .js file in node.js app

The correct answer is usually to use require, but in a few cases it's not possible.

The following code will do the trick, but use it with care:

var fs = require('fs');
var vm = require('vm');
var includeInThisContext = function(path) {
    var code = fs.readFileSync(path);
    vm.runInThisContext(code, path);
}.bind(this);
includeInThisContext(__dirname+"/models/car.js");

Retain precision with double in Java

Do not waste your efford using BigDecimal. In 99.99999% cases you don't need it. java double type is of cource approximate but in almost all cases, it is sufficiently precise. Mind that your have an error at 14th significant digit. This is really negligible!

To get nice output use:

System.out.printf("%.2f\n", total);

Error message "Forbidden You don't have permission to access / on this server"

WORKING Method (unless there is no other problem)

By default, Apache is not restricting access from IPv4 (common external IP address)

What are restricted are the commands given in 'httpd.conf'.

Replace all

<Directory />
    AllowOverride none
    Require all denied
</Directory>

with

<Directory />
    AllowOverride none
    # Require all denied
</Directory>

hence removing out all restriction given to Apache.

Replace Require local with Require all granted for the C:/wamp/www/ directory.

<Directory "c:/wamp/www/">
    Options Indexes FollowSymLinks
    AllowOverride all
    Require all granted
    # Require local
</Directory>

How to know function return type and argument types?

For example: how to describe concisely in a docstring that a function returns a list of tuples, with each tuple of the form (node_id, node_name, uptime_minutes) and that the elements are respectively a string, string and integer?

Um... There is no "concise" description of this. It's complex. You've designed it to be complex. And it requires complex documentation in the docstring.

Sorry, but complexity is -- well -- complex.

Django. Override save for model

What I did to achieve the goal was to make this..

# I added an extra_command argument that defaults to blank
def save(self, extra_command="", *args, **kwargs):

and below the save() method is this..

# override the save method to create an image thumbnail
if self.image and extra_command != "skip creating photo thumbnail":
    # your logic here

so when i edit some fields but not editing the image, I put this..

Model.save("skip creating photo thumbnail")

you can replace the "skip creating photo thumbnail" with "im just editing the description" or a more formal text.

Hope this one helps!

What is Join() in jQuery?

I use join to separate the word in array with "and, or , / , &"

EXAMPLE

HTML

<p>London Mexico Canada</p>
<div></div>

JS

 newText = $("p").text().split(" ").join(" or ");
 $('div').text(newText);

Results

London or Mexico or Canada

DataGridView - Focus a specific cell

I had a similar problem. I've hidden some columns and afterwards I tried to select the first row. This didn't really work:

datagridview1.Rows[0].Selected = true;

So I tried selecting cell[0,0], but it also didn't work, because this cell was not displayed. Now my final solution is working very well:

datagridview1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;    
datagridview1.CurrentCell = datagridview1.FirstDisplayedCell;

So this selects the complete first row.

How to insert selected columns from a CSV file to a MySQL database using LOAD DATA INFILE

if you have number of columns in your database table more than number of columns in your csv you can proceed like this:

LOAD DATA LOCAL INFILE 'pathOfFile.csv'
INTO TABLE youTable 
CHARACTER SET latin1 FIELDS TERMINATED BY ';' #you can use ',' if you have comma separated
OPTIONALLY ENCLOSED BY '"' 
ESCAPED BY '\\' 
LINES TERMINATED BY '\r\n'
(yourcolumn,yourcolumn2,yourcolumn3,yourcolumn4,...);

Convert java.util.Date to java.time.LocalDate

LocalDate ld = new java.sql.Date( new java.util.Date().getTime() ).toLocalDate();

onchange event for input type="number"

Use mouseup and keyup

$(":input").bind('keyup mouseup', function () {
    alert("changed");            
});

http://jsfiddle.net/XezmB/2/

What is the difference between git pull and git fetch + git rebase?

TLDR:

git pull is like running git fetch then git merge
git pull --rebase is like git fetch then git rebase

In reply to your first statement,

git pull is like a git fetch + git merge.

"In its default mode, git pull is shorthand for git fetch followed by git merge FETCH_HEAD" More precisely, git pull runs git fetch with the given parameters and then calls git merge to merge the retrieved branch heads into the current branch"

(Ref: https://git-scm.com/docs/git-pull)


For your second statement/question:

'But what is the difference between git pull VS git fetch + git rebase'

Again, from same source:
git pull --rebase

"With --rebase, it runs git rebase instead of git merge."


Now, if you wanted to ask

'the difference between merge and rebase'

that is answered here too:
https://git-scm.com/book/en/v2/Git-Branching-Rebasing
(the difference between altering the way version history is recorded)

Split List into Sublists with LINQ

completely lazy, no counting or copying:

public static class EnumerableExtensions
{

  public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> source, int len)
  {
     if (len == 0)
        throw new ArgumentNullException();

     var enumer = source.GetEnumerator();
     while (enumer.MoveNext())
     {
        yield return Take(enumer.Current, enumer, len);
     }
  }

  private static IEnumerable<T> Take<T>(T head, IEnumerator<T> tail, int len)
  {
     while (true)
     {
        yield return head;
        if (--len == 0)
           break;
        if (tail.MoveNext())
           head = tail.Current;
        else
           break;
     }
  }
}

Difference between staticmethod and classmethod

Static Methods:

  • Simple functions with no self argument.
  • Work on class attributes; not on instance attributes.
  • Can be called through both class and instance.
  • The built-in function staticmethod()is used to create them.

Benefits of Static Methods:

  • It localizes the function name in the classscope
  • It moves the function code closer to where it is used
  • More convenient to import versus module-level functions since each method does not have to be specially imported

    @staticmethod
    def some_static_method(*args, **kwds):
        pass
    

Class Methods:

  • Functions that have first argument as classname.
  • Can be called through both class and instance.
  • These are created with classmethod in-built function.

     @classmethod
     def some_class_method(cls, *args, **kwds):
         pass
    

Best way to return a value from a python script

If you want your script to return values, just do return [1,2,3] from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:

Return values (from a wrapping-function)

(again, this would have to be run by a separate Python script and be imported in order to even do any good):

import ...
def main():
    # calculate stuff
    return [1,2,3]

Exit codes as indicators

(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)

import sys
# calculate and stuff
sys.exit(100)

And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.

(os._exit(100) also works, and is a bit more forceful)

Stdout as your relay

If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.

import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)

Are you running your script in a controlled scheduling environment then exit codes are the best way to go.

Files as conveyors

There's also the option to simply write information to a file, and store the result there.

# calculate
with open('finish.txt', 'wb') as fh:
    fh.write(str(5)+'\n')

And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.

Sockets as conveyors

If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.

openssl s_client -cert: Proving a client certificate was sent to the server

In order to verify a client certificate is being sent to the server, you need to analyze the output from the combination of the -state and -debug flags.

First as a baseline, try running

$ openssl s_client -connect host:443 -state -debug

You'll get a ton of output, but the lines we are interested in look like this:

SSL_connect:SSLv3 read server done A
write to 0x211efb0 [0x21ced50] (12 bytes => 12 (0xC))
0000 - 16 03 01 00 07 0b 00 00-03                        .........
000c - <SPACES/NULS>
SSL_connect:SSLv3 write client certificate A

What's happening here:

  • The -state flag is responsible for displaying the end of the previous section:

    SSL_connect:SSLv3 read server done A  
    

    This is only important for helping you find your place in the output.

  • Then the -debug flag is showing the raw bytes being sent in the next step:

    write to 0x211efb0 [0x21ced50] (12 bytes => 12 (0xC))
    0000 - 16 03 01 00 07 0b 00 00-03                        .........
    000c - <SPACES/NULS>
    
  • Finally, the -state flag is once again reporting the result of the step that -debug just echoed:

    SSL_connect:SSLv3 write client certificate A
    

So in other words: s_client finished reading data sent from the server, and sent 12 bytes to the server as (what I assume is) a "no client certificate" message.


If you repeat the test, but this time include the -cert and -key flags like this:

$ openssl s_client -connect host:443 \
   -cert cert_and_key.pem \
   -key cert_and_key.pem  \
   -state -debug

your output between the "read server done" line and the "write client certificate" line will be much longer, representing the binary form of your client certificate:

SSL_connect:SSLv3 read server done A
write to 0x7bd970 [0x86d890] (1576 bytes => 1576 (0x628))
0000 - 16 03 01 06 23 0b 00 06-1f 00 06 1c 00 06 19 31   ....#..........1
(*SNIP*)
0620 - 95 ca 5e f4 2f 6c 43 11-                          ..^%/lC.
SSL_connect:SSLv3 write client certificate A

The 1576 bytes is an excellent indication on its own that the cert was transmitted, but on top of that, the right-hand column will show parts of the certificate that are human-readable: You should be able to recognize the CN and issuer strings of your cert in there.

Don't understand why UnboundLocalError occurs (closure)

Python has lexical scoping by default, which means that although an enclosed scope can access values in its enclosing scope, it cannot modify them (unless they're declared global with the global keyword).

A closure binds values in the enclosing environment to names in the local environment. The local environment can then use the bound value, and even reassign that name to something else, but it can't modify the binding in the enclosing environment.

In your case you are trying to treat counter as a local variable rather than a bound value. Note that this code, which binds the value of x assigned in the enclosing environment, works fine:

>>> x = 1

>>> def f():
>>>  return x

>>> f()
1

Add a UIView above all, even the navigation bar

Dalef great solution in swift:

self.navigationController?.view.addSubview(view)

Excel Looping through rows and copy cell values to another worksheet

Private Sub CommandButton1_Click() 

Dim Z As Long 
Dim Cellidx As Range 
Dim NextRow As Long 
Dim Rng As Range 
Dim SrcWks As Worksheet 
Dim DataWks As Worksheet 
Z = 1 
Set SrcWks = Worksheets("Sheet1") 
Set DataWks = Worksheets("Sheet2") 
Set Rng = EntryWks.Range("B6:ad6") 

NextRow = DataWks.UsedRange.Rows.Count 
NextRow = IIf(NextRow = 1, 1, NextRow + 1) 

For Each RA In Rng.Areas 
    For Each Cellidx In RA 
        Z = Z + 1 
        DataWks.Cells(NextRow, Z) = Cellidx 
    Next Cellidx 
Next RA 
End Sub

Alternatively

Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10") 

This is a CopynPaste - Method

Sub CopyDataToPlan()

Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean

On Error GoTo Err_Execute

'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value

Sheets("Plan").Select

'Start at column B
LColumn = 2
LFound = False

While LFound = False

  'Encountered blank cell in row 2, terminate search
  If Len(Cells(2, LColumn)) = 0 Then
     MsgBox "No matching date was found."
     Exit Sub

  'Found match in row 2
  ElseIf Cells(2, LColumn) = LDate Then

     'Select values to copy from "Rolling Plan" sheet
     Sheets("Rolling Plan").Select
     Range("B5:H6").Select
     Selection.Copy

     'Paste onto "Plan" sheet
     Sheets("Plan").Select
     Cells(3, LColumn).Select
     Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
     False, Transpose:=False

     LFound = True
     MsgBox "The data has been successfully copied."

     'Continue searching
      Else
         LColumn = LColumn + 1
      End If

   Wend

   Exit Sub

Err_Execute:
  MsgBox "An error occurred."

End Sub

And there might be some methods doing that in Excel.

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

I want to share my experience on this issue!

Suppose you have a class A and class B.

class A {
    protected $userB;

    public function __construct() {
        $this->userB = new B();
    }
}

class B {
    protected $userA;

    public function __construct() {
        $this->userA = new A();
    }
}

this will initiate a chain formation of objects which may be create this kind of issue!

How do I display the current value of an Android Preference in the Preference summary?

My solution is to create a custom EditTextPreference, used in XML like this: <com.example.EditTextPreference android:title="Example Title" />

EditTextPreference.java:-

package com.example;

import android.content.Context;
import android.util.AttributeSet;

public class EditTextPreference extends android.preference.EditTextPreference
{
    public EditTextPreference(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

    public EditTextPreference(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public EditTextPreference(Context context)
    {
        super(context, null);
    }

    @Override
    protected void onDialogClosed(boolean positiveResult)
    {
        super.onDialogClosed(positiveResult);

        setSummary(getSummary());
    }

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

"The Controls collection cannot be modified because the control contains code blocks"

The "<%#" databinding technique will not directly work inside <link> tags in the <head> tag:

<head runat="server">

  <link rel="stylesheet" type="text/css" 
        href="css/style.css?v=<%# My.Constants.CSS_VERSION %>" />

</head>

The above code will evaluate to

<head>

  <link rel="stylesheet" type="text/css" 
        href="css/style.css?v=&lt;%# My.Constants.CSS_VERSION %>" />

</head>

Instead, you should do the following (note the two double quotes inside):

<head runat="server">

  <link rel="stylesheet" type="text/css" 
        href="css/style.css?v=<%# "" + My.Constants.CSS_VERSION %>" />

</head>

And you will get the desired result:

<head>

  <link rel="stylesheet" type="text/css" href="css/style.css?v=1.5" />

</head>

JavaScript: Create and destroy class instance through class method

You can only manually delete properties of objects. Thus:

var container = {};

container.instance = new class();

delete container.instance;

However, this won't work on any other pointers. Therefore:

var container = {};

container.instance = new class();

var pointer = container.instance;

delete pointer; // false ( ie attempt to delete failed )

Furthermore:

delete container.instance; // true ( ie attempt to delete succeeded, but... )

pointer; // class { destroy: function(){} }

So in practice, deletion is only useful for removing object properties themselves, and is not a reliable method for removing the code they point to from memory.

A manually specified destroy method could unbind any event listeners. Something like:

function class(){
  this.properties = { /**/ }

  function handler(){ /**/ }

  something.addEventListener( 'event', handler, false );

  this.destroy = function(){
    something.removeEventListener( 'event', handler );
  }
}

Add line break within tooltips

This CSS is what finally worked for me in conjunction with a linefeed in my editor:

.tooltip-inner {
    white-space: pre-wrap;
}

Found here: How to make Twitter bootstrap tooltips have multiple lines?

How to get an object's methods?

function getMethods(obj)
{
    var res = [];
    for(var m in obj) {
        if(typeof obj[m] == "function") {
            res.push(m)
        }
    }
    return res;
}

GET parameters in the URL with CodeIgniter

Even easier:

curl -X POST -d "param=value&param2=value" http://example.com/form.cgi

that plugin's pretty cool though.

Store select query's output in one array in postgres

I had exactly the same problem. Just one more working modification of the solution given by Denis (the type must be specified):

SELECT ARRAY(
SELECT column_name::text
FROM information_schema.columns
WHERE table_name='aean'
)

foreach for JSON array , syntax

Try this:

$.each(result,function(index, value){
    console.log('My array has at position ' + index + ', this value: ' + value);
});

jQuery form validation on button click

You can also achieve other way using button tag

According new html5 attribute you also can add a form attribute like

<form id="formId">
    <input type="text" name="fname">
</form>

<button id="myButton" form='#formId'>My Awesome Button</button>

So the button will be attached to the form.

This should work with the validate() plugin of jQuery like :

var validator = $( "#formId" ).validate();
validator.element( "#myButton" );

It's working too with input tag

Source :

https://developer.mozilla.org/docs/Web/HTML/Element/Button

Using .otf fonts on web browsers

From the Google Font Directory examples:

@font-face {
  font-family: 'Tangerine';
  font-style: normal;
  font-weight: normal;
  src: local('Tangerine'), url('http://example.com/tangerine.ttf') format('truetype');
}
body {
  font-family: 'Tangerine', serif;
  font-size: 48px;
}

This works cross browser with .ttf, I believe it may work with .otf. (Wikipedia says .otf is mostly backwards compatible with .ttf) If not, you can convert the .otf to .ttf

Here are some good sites:

How to use Switch in SQL Server

The CASE is just a "switch" to return a value - not to execute a whole code block.

You need to change your code to something like this:

SELECT 
   @selectoneCount = CASE @Temp
                         WHEN 1 THEN @selectoneCount + 1
                         WHEN 2 THEN @selectoneCount + 1
                     END

If @temp is set to none of those values (1 or 2), then you'll get back a NULL

Creating a range of dates in Python

A monthly date range generator with datetime and dateutil. Simple and easy to understand:

import datetime as dt
from dateutil.relativedelta import relativedelta

def month_range(start_date, n_months):
        for m in range(n_months):
            yield start_date + relativedelta(months=+m)

grid controls for ASP.NET MVC?

If it's just for viewing data, I use simple foreach or even aspRepeater. For editing I build specialized views and actions. Didn't like webforms GridView inline edit capabilities anyway, this is kinda much clearer and better - one view for viewing and another for edit/new.

Font Awesome & Unicode

For those who are using Font Awesome version 4.7,

css_selector::before{
content:"\f006";
font-family:"fontawesome";
font-weight:900;
}

Which to use <div class="name"> or <div id="name">?

They do not do the same thing.id is used to target a specific element, classname can be used to target multiple elements.

Example:

<div id="mycolor1" class="mycolor2">     hello world </div>
<div class="mycolor2">     hello world2 </div>
<div class="mycolor2">     hello world3 </div>

Now, you can refer all the divs with classname mycolor2 at once using

.mycolor2{ color: red } //for example - in css

This would set all nodes with class mycolor2 to red.

However, if you want to set specifically mycolor1 to blue , you can target it specifically like this:

#mycolor1{ color: blue; }

How to run shell script on host from docker container?

My laziness led me to find the easiest solution that wasn't published as an answer here.

It is based on the great article by luc juggery.

All you need to do in order to gain a full shell to your linux host from within your docker container is:

docker run --privileged --pid=host -it alpine:3.8 \
nsenter -t 1 -m -u -n -i sh

Explanation:

--privileged : grants additional permissions to the container, it allows the container to gain access to the devices of the host (/dev)

--pid=host : allows the containers to use the processes tree of the Docker host (the VM in which the Docker daemon is running) nsenter utility: allows to run a process in existing namespaces (the building blocks that provide isolation to containers)

nsenter (-t 1 -m -u -n -i sh) allows to run the process sh in the same isolation context as the process with PID 1. The whole command will then provide an interactive sh shell in the VM

This setup has major security implications and should be used with cautions (if any).

How to use __DATE__ and __TIME__ predefined macros in as two integers, then stringify?

Short answer (asked version): (format 3.33.20150710.182906)

Please, simple use a makefile with:

MAJOR = 3
MINOR = 33
BUILD = $(shell date +"%Y%m%d.%H%M%S")
VERSION = "\"$(MAJOR).$(MINOR).$(BUILD)\""
CPPFLAGS = -DVERSION=$(VERSION)

program.x : source.c
       gcc $(CPPFLAGS) source.c -o program.x

and if you don't want a makefile, shorter yet, just compile with:

gcc source.c -o program.x -DVERSION=\"2.22.$(date +"%Y%m%d.%H%M%S")\"

Short answer (suggested version): (format 150710.182906)

Use a double for version number:

MakeFile:

VERSION = $(shell date +"%g%m%d.%H%M%S")
CPPFLAGS = -DVERSION=$(VERSION)
program.x : source.c
      gcc $(CPPFLAGS) source.c -o program.x

Or a simple bash command:

$ gcc source.c -o program.x -DVERSION=$(date +"%g%m%d.%H%M%S")

Tip: Still don't like makefile or is it just for a not-so-small test program? Add this line:

 export CPPFLAGS='-DVERSION='$(date +"%g%m%d.%H%M%S")

to your ~/.profile, and remember compile with gcc $CPPFLAGS ...


Long answer:

I know this question is older, but I have a small contribution to make. Best practice is always automatize what otherwise can became a source of error (or oblivion).

I was used to a function that created the version number for me. But I prefer this function to return a float. My version number can be printed by: printf("%13.6f\n", version()); which issues something like: 150710.150411 (being Year (2 digits) month day DOT hour minute seconds).

But, well, the question is yours. If you prefer "major.minor.date.time", it will have to be a string. (Trust me, double is better. If you insist in a major, you can still use double if you set the major and let the decimals to be date+time, like: major.datetime = 1.150710150411

Lets get to business. The example bellow will work if you compile as usual, forgetting to set it, or use -DVERSION to set the version directly from shell, but better of all, I recommend the third option: use a makefile.


Three forms of compiling and the results:

Using make:

beco> make program.x
gcc -Wall -Wextra -g -O0 -ansi -pedantic-errors -c -DVERSION="\"3.33.20150710.045829\"" program.c -o program.o
gcc  program.o -o program.x

Running:

__DATE__: 'Jul 10 2015'
__TIME__: '04:58:29'
VERSION: '3.33.20150710.045829'

Using -DVERSION:

beco> gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors -DVERSION=\"2.22.$(date +"%Y%m%d.%H%M%S")\"

Running:

__DATE__: 'Jul 10 2015'
__TIME__: '04:58:37'
VERSION: '2.22.20150710.045837'

Using the build-in function:

beco> gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors

Running:

__DATE__: 'Jul 10 2015'
__TIME__: '04:58:43'
VERSION(): '1.11.20150710.045843'

Source code

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4 
  5 #define FUNC_VERSION (0)
  6 #ifndef VERSION
  7   #define MAJOR 1
  8   #define MINOR 11
  9   #define VERSION version()
 10   #undef FUNC_VERSION
 11   #define FUNC_VERSION (1)
 12   char sversion[]="9999.9999.20150710.045535";
 13 #endif
 14 
 15 #if(FUNC_VERSION)
 16 char *version(void);
 17 #endif
 18 
 19 int main(void)
 20 {
 21 
 22   printf("__DATE__: '%s'\n", __DATE__);
 23   printf("__TIME__: '%s'\n", __TIME__);
 24 
 25   printf("VERSION%s: '%s'\n", (FUNC_VERSION?"()":""), VERSION);
 26   return 0;
 27 }
 28 
 29 /* String format: */
 30 /* __DATE__="Oct  8 2013" */
 31 /*  __TIME__="00:13:39" */
 32
 33 /* Version Function: returns the version string */
 34 #if(FUNC_VERSION)
 35 char *version(void)
 36 {
 37   const char data[]=__DATE__;
 38   const char tempo[]=__TIME__;
 39   const char nomes[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
 40   char omes[4];
 41   int ano, mes, dia, hora, min, seg;
 42 
 43   if(strcmp(sversion,"9999.9999.20150710.045535"))
 44     return sversion;
 45 
 46   if(strlen(data)!=11||strlen(tempo)!=8)
 47     return NULL;
 48 
 49   sscanf(data, "%s %d %d", omes, &dia, &ano);
 50   sscanf(tempo, "%d:%d:%d", &hora, &min, &seg);
 51   mes=(strstr(nomes, omes)-nomes)/3+1;
 52   sprintf(sversion,"%d.%d.%04d%02d%02d.%02d%02d%02d", MAJOR, MINOR, ano, mes, dia, hora, min, seg);
 53 
 54   return sversion;
 55 }
 56 #endif

Please note that the string is limited by MAJOR<=9999 and MINOR<=9999. Of course, I set this high value that will hopefully never overflow. But using double is still better (plus, it's completely automatic, no need to set MAJOR and MINOR by hand).

Now, the program above is a bit too much. Better is to remove the function completely, and guarantee that the macro VERSION is defined, either by -DVERSION directly into GCC command line (or an alias that automatically add it so you can't forget), or the recommended solution, to include this process into a makefile.

Here it is the makefile I use:


MakeFile source:

  1   MAJOR = 3
  2   MINOR = 33
  3   BUILD = $(shell date +"%Y%m%d.%H%M%S")
  4   VERSION = "\"$(MAJOR).$(MINOR).$(BUILD)\""
  5   CC = gcc
  6   CFLAGS = -Wall -Wextra -g -O0 -ansi -pedantic-errors
  7   CPPFLAGS = -DVERSION=$(VERSION)
  8   LDLIBS =
  9   
 10    %.x : %.c
 11          $(CC) $(CFLAGS) $(CPPFLAGS) $(LDLIBS) $^ -o $@

A better version with DOUBLE

Now that I presented you "your" preferred solution, here it is my solution:

Compile with (a) makefile or (b) gcc directly:

(a) MakeFile:

   VERSION = $(shell date +"%g%m%d.%H%M%S")
   CC = gcc
   CFLAGS = -Wall -Wextra -g -O0 -ansi -pedantic-errors 
   CPPFLAGS = -DVERSION=$(VERSION)
   LDLIBS =
   %.x : %.c
         $(CC) $(CFLAGS) $(CPPFLAGS) $(LDLIBS) $^ -o $@

(b) Or a simple bash command:

 $ gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors -DVERSION=$(date +"%g%m%d.%H%M%S")

Source code (double version):

#ifndef VERSION
  #define VERSION version()
#endif

double version(void);

int main(void)
{
  printf("VERSION%s: '%13.6f'\n", (FUNC_VERSION?"()":""), VERSION);
  return 0;
}

double version(void)
{
  const char data[]=__DATE__;
  const char tempo[]=__TIME__;
  const char nomes[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  char omes[4];
  int ano, mes, dia, hora, min, seg;
  char sversion[]="130910.001339";
  double fv;

  if(strlen(data)!=11||strlen(tempo)!=8)
    return -1.0;

  sscanf(data, "%s %d %d", omes, &dia, &ano);
  sscanf(tempo, "%d:%d:%d", &hora, &min, &seg);
  mes=(strstr(nomes, omes)-nomes)/3+1;
  sprintf(sversion,"%04d%02d%02d.%02d%02d%02d", ano, mes, dia, hora, min, seg);
  fv=atof(sversion);

  return fv;
}

Note: this double function is there only in case you forget to define macro VERSION. If you use a makefile or set an alias gcc gcc -DVERSION=$(date +"%g%m%d.%H%M%S"), you can safely delete this function completely.


Well, that's it. A very neat and easy way to setup your version control and never worry about it again!

git push to specific branch

I would like to add an updated answer - now I have been using git for a while, I find that I am often using the following commands to do any pushing (using the original question as the example):

  • git push origin amd_qlp_tester - push to the branch located in the remote called origin on remote-branch called amd_qlp_tester.
  • git push -u origin amd_qlp_tester - same as last one, but sets the upstream linking the local branch to the remote branch so that next time you can just use git push/pull if not already linked (only need to do it once).
  • git push - Once you have set the upstream you can just use this shorter version.

Note -u option is the short version of --set-upstream - they are the same.

Java POI : How to read Excel cell value and not the formula computing it?

If you want to extract a raw-ish value from a HSSF cell, you can use something like this code fragment:

CellBase base = (CellBase) cell;
CellType cellType = cell.getCellType();
base.setCellType(CellType.STRING);
String result = cell.getStringCellValue();
base.setCellType(cellType);

At least for strings that are completely composed of digits (and automatically converted to numbers by Excel), this returns the original string (e.g. "12345") instead of a fractional value (e.g. "12345.0"). Note that setCellType is available in interface Cell(as of v. 4.1) but deprecated and announced to be eliminated in v 5.x, whereas this method is still available in class CellBase. Obviously, it would be nicer either to have getRawValue in the Cell interface or at least to be able use getStringCellValue on non STRING cell types. Unfortunately, all replacements of setCellType mentioned in the description won't cover this use case (maybe a member of the POI dev team reads this answer).

Android JSONObject - How can I loop through a flat JSON object to get each key and value

Take a look at the JSONObject reference:

http://www.json.org/javadoc/org/json/JSONObject.html

Without actually using the object, it looks like using either getNames() or keys() which returns an Iterator is the way to go.

How to set session timeout dynamically in Java web applications?

I need to give my user a web interface to change the session timeout interval. So, different installations of the web application would be able to have different timeouts for their sessions, but their web.xml cannot be different.

your question is simple, you need session timeout interval should be configurable at run time and configuration should be done through web interface and there shouldn't be overhead of restarting the server.

I am extending Michaels answer to address your question.

Logic: You need to store configured value in either .properties file or to database. On server start read that stored value and copy to a variable use that variable until server is UP. As config is updated update variable also. Thats it.

Expaination

In MyHttpSessionListener class 1. create a static variable with name globalSessionTimeoutInterval.

  1. create a static block(executed for only for first time of class is being accessed) and read timeout value from config.properties file and set value to globalSessionTimeoutInterval variable.

  2. Now use that value to set maxInactiveInterval

  3. Now Web part i.e, Admin configuration page

    a. Copy configured value to static variable globalSessionTimeoutInterval.

    b. Write same value to config.properties file. (consider server is restarted then globalSessionTimeoutInterval will be loaded with value present in config.properties file)

  4. Alternative .properties file OR storing it into database. Choice is yours.

Logical code for achieving the same

public class MyHttpSessionListener implements HttpSessionListener 
{
  public static Integer globalSessionTimeoutInterval = null;

  static
  {
      globalSessionTimeoutInterval =  Read value from .properties file or database;
  }
  public void sessionCreated(HttpSessionEvent event)
  {
      event.getSession().setMaxInactiveInterval(globalSessionTimeoutInterval);
  }

  public void sessionDestroyed(HttpSessionEvent event) {}

}

And in your Configuration Controller or Configuration servlet

String valueReceived = request.getParameter(timeoutValue);
if(valueReceived  != null)
{
    MyHttpSessionListener.globalSessionTimeoutInterval = Integer.parseInt(timeoutValue);
          //Store valueReceived to config.properties file or database
}

How can I get client information such as OS and browser

Here's my code that works, as of today, with some of the latest browsers.

Naturally, it will break as User-Agent's evolve, but it's simple, and easy to fix.

    String userAgent = "Unknown";
    String osType = "Unknown";
    String osVersion = "Unknown";
    String browserType = "Unknown";
    String browserVersion = "Unknown";
    String deviceType = "Unknown";

    try {
        userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.165";
        //userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0";
        //userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36";
        //userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134";
        //userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 12_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Mobile/15E148 Safari/604.1";
        boolean exceptionTest = false;
        if(exceptionTest) throw new Exception("EXCEPTION TEST");

        if (userAgent.indexOf("Windows NT") >= 0) {
            osType = "Windows";
            osVersion = userAgent.substring(userAgent.indexOf("Windows NT ")+11, userAgent.indexOf(";"));

        } else if (userAgent.indexOf("Mac OS") >= 0) {
            osType = "Mac";
            osVersion = userAgent.substring(userAgent.indexOf("Mac OS ")+7, userAgent.indexOf(")"));

            if(userAgent.indexOf("iPhone") >= 0) {
                deviceType = "iPhone";
            } else if(userAgent.indexOf("iPad") >= 0) {
                deviceType = "iPad";
            }

        } else if (userAgent.indexOf("X11") >= 0) {
            osType = "Unix";
            osVersion = "Unknown";

        } else if (userAgent.indexOf("android") >= 0) {
            osType = "Android";
            osVersion = "Unknown";
        }
        logger.trace("end of os section");

        if (userAgent.contains("Edge/")) {
            browserType = "Edge";
            browserVersion = userAgent.substring(userAgent.indexOf("Edge")).split("/")[1];

        } else if (userAgent.contains("Safari/") && userAgent.contains("Version/")) {
            browserType = "Safari";
            browserVersion = userAgent.substring(userAgent.indexOf("Version/")+8).split(" ")[0];

        } else if (userAgent.contains("OPR/") || userAgent.contains("Opera/")) {
            browserType = "Opera";
            browserVersion = userAgent.substring(userAgent.indexOf("OPR")).split("/")[1];

        } else if (userAgent.contains("Chrome/")) {
            browserType = "Chrome"; 
            browserVersion = userAgent.substring(userAgent.indexOf("Chrome")).split("/")[1];
            browserVersion = browserVersion.split(" ")[0];

        } else if (userAgent.contains("Firefox/")) {
            browserType = "Firefox"; 
            browserVersion = userAgent.substring(userAgent.indexOf("Firefox")).split("/")[1];
        }            
        logger.trace("end of browser section");

    } catch (Exception ex) {
        logger.error("ERROR: " +ex);            
    }

    logger.debug(
              "\n userAgent: " + userAgent
            + "\n osType: " + osType
            + "\n osVersion: " + osVersion
            + "\n browserType: " + browserType
            + "\n browserVersion: " + browserVersion
            + "\n deviceType: " + deviceType
            );

Logger Output:

 userAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.165
 osType: Windows
 osVersion: 10.0
 browserType: Opera
 browserVersion: 60.0.3255.165
 deviceType: Unknown

View content of H2 or HSQLDB in-memory database

For H2, you can start a web server within your code during a debugging session if you have a database connection object. You could add this line to your code, or as a 'watch expression' (dynamically):

org.h2.tools.Server.startWebServer(conn);

The server tool will start a web browser locally that allows you to access the database.

Scrolling a flexbox with overflowing content

Add this:

align-items: flex-start;

to the rule for .content {}. That fixes it in your pen for me, at least (in both Firefox & Chrome).

By default, .content has align-items: stretch, which makes it size all of its auto-height children to match its own height, per http://dev.w3.org/csswg/css-flexbox/#algo-stretch. In contrast, the value flex-start lets the children compute their own heights, and align themselves at its starting edge (and overflow, and trigger a scrollbar).

Matching strings with wildcard

public class Wildcard
{
    private readonly string _pattern;

    public Wildcard(string pattern)
    {
        _pattern = pattern;
    }

    public static bool Match(string value, string pattern)
    {
        int start = -1;
        int end = -1;
        return Match(value, pattern, ref start, ref end);
    }

    public static bool Match(string value, string pattern, char[] toLowerTable)
    {
        int start = -1;
        int end = -1;
        return Match(value, pattern, ref start, ref end, toLowerTable);
    }

    public static bool Match(string value, string pattern, ref int start, ref int end)
    {
        return new Wildcard(pattern).IsMatch(value, ref start, ref end);
    }

    public static bool Match(string value, string pattern, ref int start, ref int end, char[] toLowerTable)
    {
        return new Wildcard(pattern).IsMatch(value, ref start, ref end, toLowerTable);
    }

    public bool IsMatch(string str)
    {
        int start = -1;
        int end = -1;
        return IsMatch(str, ref start, ref end);
    }

    public bool IsMatch(string str, char[] toLowerTable)
    {
        int start = -1;
        int end = -1;
        return IsMatch(str, ref start, ref end, toLowerTable);
    }

    public bool IsMatch(string str, ref int start, ref int end)
    {
        if (_pattern.Length == 0) return false;
        int pindex = 0;
        int sindex = 0;
        int pattern_len = _pattern.Length;
        int str_len = str.Length;
        start = -1;
        while (true)
        {
            bool star = false;
            if (_pattern[pindex] == '*')
            {
                star = true;
                do
                {
                    pindex++;
                }
                while (pindex < pattern_len && _pattern[pindex] == '*');
            }
            end = sindex;
            int i;
            while (true)
            {
                int si = 0;
                bool breakLoops = false;
                for (i = 0; pindex + i < pattern_len && _pattern[pindex + i] != '*'; i++)
                {
                    si = sindex + i;
                    if (si == str_len)
                    {
                        return false;
                    }
                    if (str[si] == _pattern[pindex + i])
                    {
                        continue;
                    }
                    if (si == str_len)
                    {
                        return false;
                    }
                    if (_pattern[pindex + i] == '?' && str[si] != '.')
                    {
                        continue;
                    }
                    breakLoops = true;
                    break;
                }
                if (breakLoops)
                {
                    if (!star)
                    {
                        return false;
                    }
                    sindex++;
                    if (si == str_len)
                    {
                        return false;
                    }
                }
                else
                {
                    if (start == -1)
                    {
                        start = sindex;
                    }
                    if (pindex + i < pattern_len && _pattern[pindex + i] == '*')
                    {
                        break;
                    }
                    if (sindex + i == str_len)
                    {
                        if (end <= start)
                        {
                            end = str_len;
                        }
                        return true;
                    }
                    if (i != 0 && _pattern[pindex + i - 1] == '*')
                    {
                        return true;
                    }
                    if (!star)
                    {
                        return false;
                    }
                    sindex++;
                }
            }
            sindex += i;
            pindex += i;
            if (start == -1)
            {
                start = sindex;
            }
        }
    }

    public bool IsMatch(string str, ref int start, ref int end, char[] toLowerTable)
    {
        if (_pattern.Length == 0) return false;

        int pindex = 0;
        int sindex = 0;
        int pattern_len = _pattern.Length;
        int str_len = str.Length;
        start = -1;
        while (true)
        {
            bool star = false;
            if (_pattern[pindex] == '*')
            {
                star = true;
                do
                {
                    pindex++;
                }
                while (pindex < pattern_len && _pattern[pindex] == '*');
            }
            end = sindex;
            int i;
            while (true)
            {
                int si = 0;
                bool breakLoops = false;

                for (i = 0; pindex + i < pattern_len && _pattern[pindex + i] != '*'; i++)
                {
                    si = sindex + i;
                    if (si == str_len)
                    {
                        return false;
                    }
                    char c = toLowerTable[str[si]];
                    if (c == _pattern[pindex + i])
                    {
                        continue;
                    }
                    if (si == str_len)
                    {
                        return false;
                    }
                    if (_pattern[pindex + i] == '?' && c != '.')
                    {
                        continue;
                    }
                    breakLoops = true;
                    break;
                }
                if (breakLoops)
                {
                    if (!star)
                    {
                        return false;
                    }
                    sindex++;
                    if (si == str_len)
                    {
                        return false;
                    }
                }
                else
                {
                    if (start == -1)
                    {
                        start = sindex;
                    }
                    if (pindex + i < pattern_len && _pattern[pindex + i] == '*')
                    {
                        break;
                    }
                    if (sindex + i == str_len)
                    {
                        if (end <= start)
                        {
                            end = str_len;
                        }
                        return true;
                    }
                    if (i != 0 && _pattern[pindex + i - 1] == '*')
                    {
                        return true;
                    }
                    if (!star)
                    {
                        return false;
                    }
                    sindex++;
                    continue;
                }
            }
            sindex += i;
            pindex += i;
            if (start == -1)
            {
                start = sindex;
            }
        }
    }
}

How to completely uninstall kubernetes

In my "Ubuntu 16.04", I use next steps to completely remove and clean Kubernetes (installed with "apt-get"):

kubeadm reset
sudo apt-get purge kubeadm kubectl kubelet kubernetes-cni kube*   
sudo apt-get autoremove  
sudo rm -rf ~/.kube

And restart the computer.

jquery: get value of custom attribute

You need some form of iteration here, as val (except when called with a function) only works on the first element:

$("input[placeholder]").val($("input[placeholder]").attr("placeholder"));

should be:

$("input[placeholder]").each( function () {
    $(this).val( $(this).attr("placeholder") );
});

or

$("input[placeholder]").val(function() {
    return $(this).attr("placeholder");
});

How to Specify "Vary: Accept-Encoding" header in .htaccess

I'm afraid Aularon didn't provide enough steps to complete the process. With a little trial and error, I was able to successfully enable Gzipping on my dedicated WHM server.

Below are the steps:

  • Run EasyApache within WHM, select Deflate within the Exhaustive Options list, and rebuild the server.

  • Once done, goto Services Configuration >> Apache Configuration >> Include Editor >> Post VirtualHost Include, select All Versions, and then paste the mod_headers.c and mod_headers.c code (listed above in Aularon's post) on top of on another within the input field.

  • Once saved, I was seeing a 75.36% data savings on average! You can run a before and after test by using this HTTP Compression tool to see your own results: http://www.whatsmyip.org/http_compression/

Hope this works for you all!

  • Matt

Why is my CSS style not being applied?

Clear the cache and cookies and restart the browser .As the style is not suppose to change frequently for a website browser kinda store it .

How to duplicate a whole line in Vim?

For someone who doesn't know vi, some answers from above might mislead him with phrases like "paste ... after/before current line".
It's actually "paste ... after/before cursor".

yy or Y to copy the line
or
dd to delete the line

then

p to paste the copied or deleted text after the cursor
or
P to paste the copied or deleted text before the cursor


For more key bindings, you can visit this site: vi Complete Key Binding List

static constructors in C++? I need to initialize private static objects

Here's my variant of EFraim's solution; the difference is that, thanks to implicit template instantiation, the static constructor is only called if instances of the class are created, and that no definition in the .cpp file is needed (thanks to template instantiation magic).

In the .h file, you have:

template <typename Aux> class _MyClass
{
    public:
        static vector<char> a;
        _MyClass() {
            (void) _initializer; //Reference the static member to ensure that it is instantiated and its initializer is called.
        }
    private:
        static struct _init
        {
            _init() { for(char i='a'; i<='z'; i++) a.push_back(i); }
        } _initializer;

};
typedef _MyClass<void> MyClass;

template <typename Aux> vector<char> _MyClass<Aux>::a;
template <typename Aux> typename _MyClass<Aux>::_init _MyClass<Aux>::_initializer;

In the .cpp file, you can have:

void foobar() {
    MyClass foo; // [1]

    for (vector<char>::iterator it = MyClass::a.begin(); it < MyClass::a.end(); ++it) {
        cout << *it;
    }
    cout << endl;
}

Note that MyClass::a is initialized only if line [1] is there, because that calls (and requires instantiation of) the constructor, which then requires instantiation of _initializer.

php Replacing multiple spaces with a single space

preg_replace("/[[:blank:]]+/"," ",$input)

Remove non-utf8 characters from string

So the rules are that the first UTF-8 octlet has the high bit set as a marker, and then 1 to 4 bits to indicate how many additional octlets; then each of the additional octlets must have the high two bits set to 10.

The pseudo-python would be:

newstring = ''
cont = 0
for each ch in string:
  if cont:
    if (ch >> 6) != 2: # high 2 bits are 10
      # do whatever, e.g. skip it, or skip whole point, or?
    else:
      # acceptable continuation of multi-octlet char
      newstring += ch
    cont -= 1
  else:
    if (ch >> 7): # high bit set?
      c = (ch << 1) # strip the high bit marker
      while (c & 1): # while the high bit indicates another octlet
        c <<= 1
        cont += 1
        if cont > 4:
           # more than 4 octels not allowed; cope with error
      if !cont:
        # illegal, do something sensible
      newstring += ch # or whatever
if cont:
  # last utf-8 was not terminated, cope

This same logic should be translatable to php. However, its not clear what kind of stripping is to be done once you get a malformed character.

How to upgrade Angular CLI to the latest version

ng6+ -> 7.0

Update RxJS (depends on RxJS 6.3)

npm install -g rxjs-tslint
rxjs-5-to-6-migrate -p src/tsconfig.app.json

Remove rxjs-compat

Then update the core packages and Cli:

ng update @angular/cli @angular/core

(Optional: update Node.js to version 10 which is supported in NG7)

ng6+ (Cli 6.0+): features simplified commands

First, update your Cli

npm install -g @angular/cli
npm install @angular/cli
ng update @angular/cli

Then, update your core packages

ng update @angular/core

If you use RxJS, run

ng update rxjs

It will update RxJS to version 6 and install the rxjs-compat package under the hood.

If you run into build errors, try a manual install of:

npm i rxjs-compat
npm i @angular-devkit/build-angular

Lastly, check your version

ng v

Note on production build:

ng6 no longer uses intl in polyfills.ts

//remove them to avoid errors
import 'intl';
import 'intl/locale-data/jsonp/en';

ng5+ (Cli 1.5+)

npm install @angular/{animations,common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router}@next [email protected] rxjs@'^5.5.2'
npm install [email protected] --save-exact

Note:

  1. The supported Typescript version for Cli 1.6 as of writing is up to 2.5.3.
  2. Using @next updates the package to beta, if available. Use @latest to get the latest non-beta version.

After updating both the global and local package, clear the cache to avoid errors:

npm cache verify (recommended)
npm cache clean (for older npm versions)

Here are the official references:

  1. Updating the Cli
  2. Updating the core packages core package.

Make JQuery UI Dialog automatically grow or shrink to fit its contents

If you need it to work in IE7, you can't use the undocumented, buggy, and unsupported {'width':'auto'} option. Instead, add the following to your .dialog():

'open': function(){ $(this).dialog('option', 'width', this.scrollWidth) }

Whether .scrollWidth includes the right-side padding depends on the browser (Firefox differs from Chrome), so you can either add a subjective "good enough" number of pixels to .scrollWidth, or replace it with your own width-calculation function.

You might want to include width: 0 among your .dialog() options, since this method will never decrease the width, only increase it.

Tested to work in IE7, IE8, IE9, IE10, IE11, Firefox 30, Chrome 35, and Opera 22.

error: package com.android.annotations does not exist

All you need to do is to replace 'import android.support.annotation.Nullable' in class imports to 'import androidx.annotation.Nullable;'

Thats a common practice..whenever any import giving issue...remove that import and simply press Alt+Enter on the related class..that will give you option to 'import class'..hint Enter and things will get resolved...

How different is Objective-C from C++?

Obj-C has much more dynamic capabilities in the language itself, whereas C++ is more focused on compile-time capabilities with some dynamic capabilities.

In, C++ parametric polymorphism is checked at compile-time, whereas in Obj-C, parametric polymorphism is achieved through dynamic dispatch and is not checked at compile-time.

Obj-C is very dynamic in nature. You can add methods to a class during run-time. Also, it has introspection at run-time to look at classes. In C++, the definition of class can't change, and all introspection must be done at compile-time. Although, the dynamic nature of Obj-C could be achieved in C++ using a map of functions(or something like that), it is still more verbose than in Obj-C.

In C++, there is a lot more checks that can be done at compile time. For example, using a variant type(like a union) the compiler can enforce that all cases are written or handled. So you don't forget about handling the edge cases of a problem. However, all these checks come at a price when compiling. Obj-C is much faster at compiling than C++.

Marker in leaflet, click event

The accepted answer is correct. However, I needed a little bit more clarity, so in case someone else does too:

Leaflet allows events to fire on virtually anything you do on its map, in this case a marker.

So you could create a marker as suggested by the question above:

L.marker([10.496093,-66.881935]).addTo(map).on('mouseover', onClick);

Then create the onClick function:

function onClick(e) {
    alert(this.getLatLng());
}

Now anytime you mouseover that marker it will fire an alert of the current lat/long.

However, you could use 'click', 'dblclick', etc. instead of 'mouseover' and instead of alerting lat/long you can use the body of onClick to do anything else you want:

L.marker([10.496093,-66.881935]).addTo(map).on('click', function(e) {
    console.log(e.latlng);
});

Here is the documentation: http://leafletjs.com/reference.html#events

How to make CREATE OR REPLACE VIEW work in SQL Server?

Altering a view could be accomplished by dropping the view and recreating it. Use the following to drop and recreate your view.

IF EXISTS
(SELECT NAME FROM SYS.VIEWS WHERE NAME = 'dbo.test_abc_def')
DROP VIEW dbo.test_abc_def) go

CREATE VIEW dbo.test_abc_def AS
SELECT 
    VCV.xxxx, 
    VCV.yyyy AS yyyy
    ,VCV.zzzz AS zzzz
FROM TABLE_A

how do you view macro code in access?

You can try the following VBA code to export Macro contents directly without converting them to VBA first. Unlike Tables, Forms, Reports, and Modules, the Macros are in a container called Scripts. But they are there and can be exported and imported using SaveAsText and LoadFromText

Option Compare Database

Option Explicit

Public Sub ExportDatabaseObjects()
On Error GoTo Err_ExportDatabaseObjects

    Dim db As Database
    Dim d As Document
    Dim c As Container
    Dim sExportLocation As String

    Set db = CurrentDb()

    sExportLocation = "C:\SomeFolder\"
    Set c = db.Containers("Scripts")
    For Each d In c.Documents
        Application.SaveAsText acMacro, d.Name, sExportLocation & "Macro_" & d.Name & ".txt"
    Next d

An alternative object to use is as follows:

  For Each obj In Access.Application.CurrentProject.AllMacros
    Access.Application.SaveAsText acMacro, obj.Name, strFilePath & "\Macro_" & obj.Name & ".txt"
  Next

How to implement a binary tree?

#!/usr/bin/python

class BinaryTree:
    def __init__(self, left, right, data):
        self.left = left
        self.right = right
        self.data = data


    def pre_order_traversal(root):
        print(root.data, end=' ')

        if root.left != None:
            pre_order_traversal(root.left)

        if root.right != None:
            pre_order_traversal(root.right)

    def in_order_traversal(root):
        if root.left != None:
            in_order_traversal(root.left)
        print(root.data, end=' ')
        if root.right != None:
            in_order_traversal(root.right)

    def post_order_traversal(root):
        if root.left != None:
            post_order_traversal(root.left)
        if root.right != None:
            post_order_traversal(root.right)
        print(root.data, end=' ')

"register" keyword in C?

During the seventies, at the very beginning of the C language, the register keyword has been introduced in order to allow the programmer to give hints to the compiler, telling it that the variable would be used very often, and that it should be wise to keep it’s value in one of the processor’s internal register.

Nowadays, optimizers are much more efficient than programmers to determine variables that are more likely to be kept into registers, and the optimizer does not always take the programmer’s hint into account.

So many people wrongly recommend not to use the register keyword.

Let’s see why!

The register keyword has an associated side effect: you can not reference (get the address of) a register type variable.

People advising others not to use registers takes wrongly this as an additional argument.

However, the simple fact of knowing that you can not take the address of a register variable, allows the compiler (and its optimizer) to know that the value of this variable can not be modified indirectly through a pointer.

When at a certain point of the instruction stream, a register variable has its value assigned in a processor’s register, and the register has not been used since to get the value of another variable, the compiler knows that it does not need to re-load the value of the variable in that register. This allows to avoid expensive useless memory access.

Do your own tests and you will get significant performance improvements in your most inner loops.

c_register_side_effect_performance_boost

Get current URL with jQuery?

java-script provides many methods to retrieve current URL which is displayed in browser's address bar.

Test URL :

http://
stackoverflow.com/questions/5515310/get-current-url-with-jquery/32942762
?
rq=1&page=2&tab=active&answertab=votes
#
32942762
resourceAddress.hash();
console.log('URL Object ', webAddress);
console.log('Parameters ', param_values);

Function:

var webAddress = {};
var param_values = {};
var protocol = '';
var resourceAddress = {

    fullAddress : function () {
        var addressBar = window.location.href;
        if ( addressBar != '' && addressBar != 'undefined') {
            webAddress[ 'href' ] = addressBar;
        }
    },
    protocol_identifier : function () { resourceAddress.fullAddress();

        protocol = window.location.protocol.replace(':', '');
        if ( protocol != '' && protocol != 'undefined') {
            webAddress[ 'protocol' ] = protocol;
        }
    },
    domain : function () {      resourceAddress.protocol_identifier();

        var domain = window.location.hostname;
        if ( domain != '' && domain != 'undefined' && typeOfVar(domain) === 'string') {
            webAddress[ 'domain' ] = domain;
            var port = window.location.port;
            if ( (port == '' || port == 'undefined') && typeOfVar(port) === 'string') {
                if(protocol == 'http') port = '80';
                if(protocol == 'https') port = '443';           
            }
            webAddress[ 'port' ] = port;
        }
    },
    pathname : function () {        resourceAddress.domain();

        var resourcePath = window.location.pathname;
        if ( resourcePath != '' && resourcePath != 'undefined') {
            webAddress[ 'resourcePath' ] = resourcePath;
        }
    },
    params : function () {      resourceAddress.pathname();

        var v_args = location.search.substring(1).split("&");

        if ( v_args != '' && v_args != 'undefined')
        for (var i = 0; i < v_args.length; i++) {
            var pair = v_args[i].split("=");

            if ( typeOfVar( pair ) === 'array' ) {
                param_values[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
            }
        }
        webAddress[ 'params' ] = param_values;
    },
    hash : function () {        resourceAddress.params();

        var fragment = window.location.hash.substring(1);
        if ( fragment != '' && fragment != 'undefined')
            webAddress[ 'hash' ] = fragment;        
    }
};
function typeOfVar (obj) {
      return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
  • protocol « Web-browsers use Internet Protocol by following some rules for communication between WebHosted Applications and Web Client(Browser). (http = 80, https (SSL) = 443, ftp = 21, etc.)

EX: With default port numbers

<protocol>//<hostname>:<port>/<pathname><search><hash>
https://en.wikipedia.org:443/wiki/Pretty_Good_Privacy
http://stackoverflow.com:80/
  • (//) « Host is the name given to an end-point(machine on which resource lives) on the Internet. www.stackoverflow.com - DNS IP Address of an Application (OR) localhost:8080 - localhost

Domain names are which you register by the rules and procedures of the Domain Name System(DNS) tree. DNS servers of someone who manages your domain with IP-Address for addressing purposes. In DNS server hierarchy the Root name of an stackoverlfow.com is com.

gTLDs      - com « stackoverflow (OR) in « co « google

Local system you have to maintain domain's which are not PUBLIC in Host Files. localhost.yash.com « localhsot - subdomain(web-server), yash.com - maindomain(Proxy-Server). myLocalApplication.com 172.89.23.777

  • (/) « The path gives info about the specific resource within the host that the Web client wants to access
  • (?) « An optional query is to pass a sequence of attribute–value pairs separated by a delimiter(&).
  • (#) « An optional fragment is often an id attribute of a specific element, and web browsers will scroll this element into view.

If parameter has an Epoch ?date=1467708674 then use.

var epochDate = 1467708674; var date = new Date( epochDate );

URL enter image description here


Authentication url with username:password, If usernaem/password contains @ symbol
like:

Username = `my_email@gmail`
Password = `Yash@777`

then You need to URL encode the @ as %40. Refer...

http://my_email%40gmail.com:Yash%[email protected]_site.com

encodeURI() (vs) encodeURIComponent() example

var testURL = "http:my_email@gmail:Yash777@//stackoverflow.com?tab=active&page=1#32942762";

var Uri = "/:@?&=,#", UriComponent = "$;+", Unescaped = "(-_.!~*')"; // Fixed
var encodeURI_Str = encodeURI(Uri) +' '+ encodeURI( UriComponent ) +' '+ encodeURI(Unescaped);
var encodeURIComponent_Str =  encodeURIComponent( Uri ) +' '+ encodeURIComponent( UriComponent ) +' '+ encodeURIComponent( Unescaped );
console.log(encodeURI_Str, '\n', encodeURIComponent_Str);
/*
 /:@?&=,# +$; (-_.!~*') 
 %2F%3A%40%3F%26%3D%2C%23 %2B%24%3B (-_.!~*')
*/

How to print a query string with parameter values when using Hibernate

Log4Jdbc plugin would be best for your requirement. It shows following-

1. Complete SQL query being hit to the db
2. Parameter values being passed to the query
3. Execution time taken by each query

Refer below link to configure Log4Jdbc-

https://code.google.com/p/log4jdbc/

Zip lists in Python

zip takes a bunch of lists likes

a: a1 a2 a3 a4 a5 a6 a7...
b: b1 b2 b3 b4 b5 b6 b7...
c: c1 c2 c3 c4 c5 c6 c7...

and "zips" them into one list whose entries are 3-tuples (ai, bi, ci). Imagine drawing a zipper horizontally from left to right.

MySQL - Get row number on select

You can use MySQL variables to do it. Something like this should work (though, it consists of two queries).

SELECT 0 INTO @x;

SELECT itemID, 
       COUNT(*) AS ordercount, 
       (@x:=@x+1) AS rownumber 
FROM orders 
GROUP BY itemID 
ORDER BY ordercount DESC; 

No Android SDK found - Android Studio

From the File menu, choose Project Structure (if you're running 0.4.4 there's a bug and the menu item doesn't have a title, but it still works), and choose the Android SDK item. You should see something like this where you can set up your JDK and SDK.

Project Structure dialog, Android SDK tab

After setting it, quit Android Studio and relaunch it for good measure.

How to center Font Awesome icons horizontally?

If your icons are in an icon stack you can use the following code:

.icon-stack{ margin: auto; display: block; } 

What is the purpose of "pip install --user ..."?

--user installs in site.USER_SITE.

For my case, it was /Users/.../Library/Python/2.7/bin. So I have added that to my PATH (in ~/.bash_profile file):

export PATH=$PATH:/Users/.../Library/Python/2.7/bin

How to Define Callbacks in Android?

No need to define a new interface when you can use an existing one: android.os.Handler.Callback. Pass an object of type Callback, and invoke callback's handleMessage(Message msg).

How can I check for NaN values?

How to remove NaN (float) item(s) from a list of mixed data types

If you have mixed types in an iterable, here is a solution that does not use numpy:

from math import isnan

Z = ['a','b', float('NaN'), 'd', float('1.1024')]

[x for x in Z if not (
                      type(x) == float # let's drop all float values…
                      and isnan(x) # … but only if they are nan
                      )]
['a', 'b', 'd', 1.1024]

Short-circuit evaluation means that isnan will not be called on values that are not of type 'float', as False and (…) quickly evaluates to False without having to evaluate the right-hand side.

Cannot install node modules that require compilation on Windows 7 x64/VS2012

Thanks to @felixrieseberg, you just need to install windows-build-tools npm package and you are good to go.

npm install --global --production windows-build-tools

You won't need to install Visual Studio.

You won't need to install Microsoft Build Tools.

From the repo:

After installation, npm will automatically execute this module, which downloads and installs Visual C++ Build Tools 2015, provided free of charge by Microsoft. These tools are required to compile popular native modules. It will also install Python 2.7, configuring your machine and npm appropriately.

Windows Vista / 7 requires .NET Framework 4.5.1 (Currently not installed automatically by this package)

Both installations are conflict-free, meaning that they do not mess with existing installations of Visual Studio, C++ Build Tools, or Python.

Filtering collections in C#

If you're using C# 3.0 you can use linq, way better and way more elegant:

List<int> myList = GetListOfIntsFromSomewhere();

// This will filter out the list of ints that are > than 7, Where returns an
// IEnumerable<T> so a call to ToList is required to convert back to a List<T>.
List<int> filteredList = myList.Where( x => x > 7).ToList();

If you can't find the .Where, that means you need to import using System.Linq; at the top of your file.

Cast IList to List

List<ProjectResources> list = new List<ProjectResources>();        
IList<ProjectResources> obj = `Your Data Will Be Here`;
list = obj.ToList<ProjectResources>();

This Would Convert IList Object to List Object.

How to check for Is not Null And Is not Empty string in SQL server?

If you only want to match "" as an empty string

WHERE DATALENGTH(COLUMN) > 0 

If you want to count any string consisting entirely of spaces as empty

WHERE COLUMN <> '' 

Both of these will not return NULL values when used in a WHERE clause. As NULL will evaluate as UNKNOWN for these rather than TRUE.

CREATE TABLE T 
  ( 
     C VARCHAR(10) 
  ); 

INSERT INTO T 
VALUES      ('A'), 
            (''),
            ('    '), 
            (NULL); 

SELECT * 
FROM   T 
WHERE  C <> ''

Returns just the single row A. I.e. The rows with NULL or an empty string or a string consisting entirely of spaces are all excluded by this query.

SQL Fiddle

test if event handler is bound to an element in jQuery

For jQuery 1.9+

var eventListeners = $._data($('.classname')[0], "events");

I needed the [0] array literal.

Create a new cmd.exe window from within another cmd.exe prompt

start cmd.exe 

opens a separate window

start file.cmd 

opens the batch file and executes it in another command prompt

Creating and Update Laravel Eloquent

2020 Update

As in Laravel >= 5.3, if someone is still curious how to do so in easy way. Its possible by using : updateOrCreate().

For example for asked question you can use something like:

$matchThese = ['shopId'=>$theID,'metadataKey'=>2001];
ShopMeta::updateOrCreate($matchThese,['shopOwner'=>'New One']);

Above code will check the table represented by ShopMeta, which will be most likely shop_metas unless not defined otherwise in model itself

and it will try to find entry with

column shopId = $theID

and

column metadateKey = 2001

and if it finds then it will update column shopOwner of found row to New One.

If it finds more than one matching rows then it will update the very first row that means which has lowest primary id.

If not found at all then it will insert a new row with :

shopId = $theID,metadateKey = 2001 and shopOwner = New One

Notice Check your model for $fillable and make sue that you have every column name defined there which you want to insert or update and rest columns have either default value or its id column auto incremented one.

Otherwise it will throw error when executing above example:

Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1364 Field '...' doesn't have a default value (SQL: insert into `...` (`...`,.., `updated_at`, `created_at`) values (...,.., xxxx-xx-xx xx:xx:xx, xxxx-xx-xx xx:xx:xx))'

As there would be some field which will need value while inserting new row and it will not be possible as either its not defined in $fillable or it doesnt have default value.

For more reference please see Laravel Documentation at : https://laravel.com/docs/5.3/eloquent

One example from there is:

// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99]
);

which pretty much clears everything.

Query Builder Update

Someone has asked if it is possible using Query Builder in Laravel. Here is reference for Query Builder from Laravel docs.

Query Builder works exactly the same as Eloquent so anything which is true for Eloquent is true for Query Builder as well. So for this specific case, just use the same function with your query builder like so:

$matchThese = array('shopId'=>$theID,'metadataKey'=>2001);
DB::table('shop_metas')::updateOrCreate($matchThese,['shopOwner'=>'New One']);

Of course, don't forget to add DB facade:

use Illuminate\Support\Facades\DB;

OR

use DB;

I hope it helps

Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists

The resolution for this problem is copying the three xcode/project files in the directory and then creating new directory (Whereever else) and then paste the three files/directories.

Prevent textbox autofill with previously entered values

For firefox

Either:

<asp:TextBox id="Textbox1" runat="server" autocomplete="off"></asp:TextBox>

Or from the CodeBehind:

Textbox1.Attributes.Add("autocomplete", "off");

How to get Wikipedia content using Wikipedia's API?

$keyword = "Batman"; //Term you want to search

$url = 'http://en.wikipedia.org/w/api.php?action=parse&page='.$keyword.'&format=json&prop=text&section=0';
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_USERAGENT, 'Infeeds Sniper');
$c = curl_exec($ch);
$json = json_decode($c);
if($json !='' && isset($json->{'parse'})){
   $title = $json->{'parse'}->{'title'};
   $content = $json->{'parse'}->{'text'}->{'*'};
   $pattern = '#<p>(.*)</p>#Us';
   if(preg_match($pattern, $content, $matches)){
      if($matches[1]!=''){
         $con = preg_replace_callback("/\[[^)]+\]/", function($m){return '';}, $matches[1]);
         echo '<h2>'.$title.'</h2>'.strip_tags($con).'</p><src>Source: <a href="https://en.wikipedia.org/wiki/'.$keyword.'" target="_blank">Wikipedia</a></src>';
      }
   }
}

Wiki Summary Scrapper w/ PHP

Wiki scrapper gist to get summary from either Wikipedia or DB Pedia API with PHP. Hope it helps.

How to fully clean bin and obj folders within Visual Studio?

This is how I do with a batch file to delete all BIN and OBJ folders recursively.

  • Create an empty file and name it DeleteBinObjFolders.bat
  • Copy-paste code the below code into the DeleteBinObjFolders.bat
  • Move the DeleteBinObjFolders.bat file in the same folder with your solution (*.sln) file.
@echo off
@echo Deleting all BIN and OBJ folders...
for /d /r . %%d in (bin,obj) do @if exist "%%d" rd /s/q "%%d"
@echo BIN and OBJ folders successfully deleted :) Close the window.
pause > nul

Display Images Inline via CSS

The code you have posted here and code on your site both are different. There is a break <br> after second image, so the third image into new line, remove this <br> and it will display correctly.

Pip install Matplotlib error with virtualenv

To generate graph in png format you need to Install following dependent packages

sudo apt-get install libpng-dev
sudo apt-get install libfreetype6-dev

Ubuntu https://apps.ubuntu.com/cat/applications/libpng12-0/ or using following command

sudo apt-get install libpng12-0

How to supply value to an annotation from a Constant java

I am thinking this may not be possible in Java because annotation and its parameters are resolved at compile time.

With Seam 2 http://seamframework.org/ you were able to resolve annotation parameters at runtime, with expression language inside double quotes.

In Seam 3 http://seamframework.org/Seam3/Solder, this feature is the module Seam Solder

Setting values of input fields with Angular 6

You should use the following:

       <td><input id="priceInput-{{orderLine.id}}" type="number" [(ngModel)]="orderLine.price"></td>

You will need to add the FormsModule to your app.module in the inputs section as follows:

import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  ..

The use of the brackets around the ngModel are as follows:

  • The [] show that it is taking an input from your TS file. This input should be a public member variable. A one way binding from TS to HTML.

  • The () show that it is taking output from your HTML file to a variable in the TS file. A one way binding from HTML to TS.

  • The [()] are both (e.g. a two way binding)

See here for more information: https://angular.io/guide/template-syntax

I would also suggest replacing id="priceInput-{{orderLine.id}}" with something like this [id]="getElementId(orderLine)" where getElementId(orderLine) returns the element Id in the TS file and can be used anywere you need to reference the element (to avoid simple bugs like calling it priceInput1 in one place and priceInput-1 in another. (if you still need to access the input by it's Id somewhere else)

How to get Bitmap from an Uri?

private fun setImage(view: ImageView, uri: Uri) {
        val stream = contentResolver.openInputStream(uri)
        val bitmap = BitmapFactory.decodeStream(stream)
        view.setImageBitmap(bitmap)
}

Python: most idiomatic way to convert None to empty string?

If you actually want your function to behave like the str() built-in, but return an empty string when the argument is None, do this:

def xstr(s):
    if s is None:
        return ''
    return str(s)

How to map an array of objects in React

you must put object in your JSX, It`s easy way to do this just see my simple code here:

const link = [
  {
   name: "Cold Drink",
   link: "/coldDrink"
  },
  {
   name: "Hot Drink",
   link: "/HotDrink"
  },

{ name: "chease Cake", link: "/CheaseCake" } ]; and you must map this array in your code with simple object see this code :

const links = (this.props.link);
{links.map((item, i) => (
 <li key={i}>
   <Link to={item.link}>{item.name}</Link>
 </li>
 ))}

I hope this answer will be helpful for you ...:)

Show hidden div on ng-click within ng-repeat

Use ng-show and toggle the value of a show scope variable in the ng-click handler.

Here is a working example: http://jsfiddle.net/pvtpenguin/wD7gR/1/

<ul class="procedures">
    <li ng-repeat="procedure in procedures">
        <h4><a href="#" ng-click="show = !show">{{procedure.definition}}</a></h4>
         <div class="procedure-details" ng-show="show">
            <p>Number of patient discharges: {{procedure.discharges}}</p>
            <p>Average amount covered by Medicare: {{procedure.covered}}</p>
            <p>Average total payments: {{procedure.payments}}</p>
         </div>
    </li>
</ul>

How to merge two arrays in JavaScript and de-duplicate items

ES2019

You can use it like union(array1, array2, array3, ...)

/**
 * Merges two or more arrays keeping unique items. This method does
 * not change the existing arrays, but instead returns a new array.
 */
function union<T>(...arrays: T[]) {
  return [...new Set([...arrays].flat())];
}

It is ES2019 because of the flat() function, but you can use core-js to get it as a polyfill. The T here is TypeScript generic type, that you can remove if you are not using TypeScript. If you are using TypeScript, make sure to add "lib": ["es2019.array"] to compiler options in tsconfig.json.

or...

just use lodash _.union

Sending Email in Android using JavaMail API without using the default/built-in app

SMTP

Using SMTP is one way to go, and the others have already pointed out ways how to do it. Just note that while doing this, you completely circumvent the built in mail app, and you will have to provide the address of the SMTP server, the user name and password for that server, either statically in your code, or query it from the user.

HTTP

Another way would involve a simple server side script, like php, that takes some URL parameters and uses them to send a mail. This way, you only need to make an HTTP request from the device (easily possible with the built in libraries) and don't need to store the SMTP login data on the device. This is one more indirection compared to direct SMTP usage, but because it's so very easy to make HTTP request and send mails from PHP, it might even be simpler than the direct way.

Mail Application

If the mail shall be send from the users default mail account that he already registered with the phone, you'd have to take some other approach. If you have enough time and experience, you might want to check the source code of the Android Email application to see if it offers some entry point to send a mail without user interaction (I don't know, but maybe there is one).

Maybe you even find a way to query the users account details (so you can use them for SMTP), though I highly doubt that this is possible, because it would be a huge security risk and Android is built rather securely.

Intellij Idea: Importing Gradle project - getting JAVA_HOME not defined yet

You need to setup a SDK for Java projects, like @rizzletang said, but you don't need to create a new project, you can do it from the Welcome screen.

On the bottom right, select Configure > Project Defaults > Project Structure: enter image description here

Picking the Project tab on the left will show that you have no SDK selected:

enter image description here

Just click the New... button on the right hand side of the dropdown and point it to your JDK. After that, you can go back to the import screen and it should just show up.

Difference between exit() and sys.exit() in Python

If I use exit() in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing. See here

But sys.exit() is better in this case. It closes the program and doesn't create any dialogue box.

Avoid dropdown menu close on click inside

You can also use form tag. Example:

<div class="dropdown-menu">
    <form>
        Anything inside this wont close the dropdown!
        <button class="btn btn-primary" type="button" value="Click me!"/>
    </form>
    <div class="dropdown-divider"></div>
    <a class="dropdown-item" href="#">Clik this and the dropdown will be closed</a>
    <a class="dropdown-item" href="#">This too</a>
</div>

Source: https://getbootstrap.com/docs/5.0/components/dropdowns/#forms

Opening PDF String in new window with javascript

I realize this is a pretty old question, but I had the same thing come up today and came up with the following solution:

doSomethingToRequestData().then(function(downloadedFile) {
  // create a download anchor tag
  var downloadLink      = document.createElement('a');
  downloadLink.target   = '_blank';
  downloadLink.download = 'name_to_give_saved_file.pdf';

  // convert downloaded data to a Blob
  var blob = new Blob([downloadedFile.data], { type: 'application/pdf' });

  // create an object URL from the Blob
  var URL = window.URL || window.webkitURL;
  var downloadUrl = URL.createObjectURL(blob);

  // set object URL as the anchor's href
  downloadLink.href = downloadUrl;

  // append the anchor to document body
  document.body.appendChild(downloadLink);

  // fire a click event on the anchor
  downloadLink.click();

  // cleanup: remove element and revoke object URL
  document.body.removeChild(downloadLink);
  URL.revokeObjectURL(downloadUrl);
});

Placeholder in UITextView

In .h class

@interface RateCommentViewController : UIViewController<UITextViewDelegate>{IBoutlet UITextview *commentTxtView;}

In .m class

- (void)viewDidLoad{      
    commentTxtView.text = @"Comment";
    commentTxtView.textColor = [UIColor lightGrayColor];
    commentTxtView.delegate = self;
}

- (BOOL) textViewShouldBeginEditing:(UITextView *)textView
{
    commentTxtView.text = @"";
    commentTxtView.textColor = [UIColor blackColor];
    return YES;
}

-(void) textViewDidChange:(UITextView *)textView
{
    if(commentTxtView.text.length == 0){
        commentTxtView.textColor = [UIColor lightGrayColor];
        commentTxtView.text = @"Comment";
        [commentTxtView resignFirstResponder];
    }
}

How to get all enum values in Java?

YourEnumClass[] yourEnums = YourEnumClass.class.getEnumConstants();

Or

YourEnumClass[] yourEnums = YourEnumClass.values();

pypi UserWarning: Unknown distribution option: 'install_requires'

This was the first result on my google search, but had no answer. I found that upgrading setuptools resolved the issue for me (and pip for good measure)

pip install --upgrade pip
pip install --upgrade setuptools

Hope this helps the next person to find this link!

Retrieve last 100 lines logs

Look, the sed script that prints the 100 last lines you can find in the documentation for sed (https://www.gnu.org/software/sed/manual/sed.html#tail):

$ cat sed.cmd
1! {; H; g; }
1,100 !s/[^\n]*\n//
$p

$ sed -nf sed.cmd logfilename

For me it is way more difficult than your script so

tail -n 100 logfilename

is much much simpler. And it is quite efficient, it will not read all file if it is not necessary. See my answer with strace report for tail ./huge-file: https://unix.stackexchange.com/questions/102905/does-tail-read-the-whole-file/102910#102910

Map a network drive to be used by a service

The reason why you are able to access the drive in when you normally run the executable from command prompt is that when u are executing it as normal exe you are running that application in the User account from which you have logged on . And that user has the privileges to access the network. But , when you install the executable as a service , by default if you see in the task manage it runs under 'SYSTEM' account . And you might be knowing that the 'SYSTEM' doesn't have rights to access network resources.

There can be two solutions to this problem.

  1. To map the drive as persistent as already pointed above.

  2. There is one more approach that can be followed. If you open the service manager by typing in the 'services.msc'you can go to your service and in the properties of your service there is a logOn tab where you can specify the account as any other account than 'System' you can either start service from your own logged on user account or through 'Network Service'. When you do this .. the service can access any network component and drive even if they are not persistent also. To achieve this programmatically you can look into 'CreateService' function at http://msdn.microsoft.com/en-us/library/ms682450(v=vs.85).aspx and can set the parameter 'lpServiceStartName ' to 'NT AUTHORITY\NetworkService'. This will start your service under 'Network Service' account and then you are done.

  3. You can also try by making the service as interactive by specifying SERVICE_INTERACTIVE_PROCESS in the servicetype parameter flag of your CreateService() function but this will be limited only till XP as Vista and 7 donot support this feature.

Hope the solutions help you.. Let me know if this worked for you .

ADB device list is empty

This helped me at the end:

Quick guide:

  • Download Google USB Driver

  • Connect your device with Android Debugging enabled to your PC

  • Open Device Manager of Windows from System Properties.

  • Your device should appear under Other devices listed as something like Android ADB Interface or 'Android Phone' or similar. Right-click that and click on Update Driver Software...

  • Select Browse my computer for driver software

  • Select Let me pick from a list of device drivers on my computer

  • Double-click Show all devices

  • Press the Have disk button

  • Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf

  • Select Android ADB Interface from the list of device types.

  • Press the Yes button

  • Press the Install button

  • Press the Close button

Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.

How do I remove a single breakpoint with GDB?

Use:

clear fileName:lineNum   // Removes all breakpoints at the specified line.
delete breakpoint number // Delete one breakpoint whose number is 'number'

check if a std::vector contains a certain object?

If searching for an element is important, I'd recommend std::set instead of std::vector. Using this:

std::find(vec.begin(), vec.end(), x) runs in O(n) time, but std::set has its own find() member (ie. myset.find(x)) which runs in O(log n) time - that's much more efficient with large numbers of elements

std::set also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()....

The difference between "require(x)" and "import x"

This simple diagram that helps me to understand the difference between require and import.

enter image description here

Apart from that,

You can't selectively load only the pieces you need with require but with imports, you can selectively load only the pieces you need. That can save memory.

Loading is synchronous(step by step) for require on the other hand import can be asynchronous(without waiting for previous import) so it can perform a little better than require.

How to run ssh-add on windows?

Original answer using git's start-ssh-agent

Make sure you have Git installed and have git's cmd folder in your PATH. For example, on my computer the path to git's cmd folder is C:\Program Files\Git\cmd

Make sure your id_rsa file is in the folder c:\users\yourusername\.ssh

Restart your command prompt if you haven't already, and then run start-ssh-agent. It will find your id_rsa and prompt you for the passphrase

Update 2019 - A better solution if you're using Windows 10: OpenSSH is available as part of Windows 10 which makes using SSH from cmd/powershell much easier in my opinion. It also doesn't rely on having git installed, unlike my previous solution.

  1. Open Manage optional features from the start menu and make sure you have Open SSH Client in the list. If not, you should be able to add it.

  2. Open Services from the start Menu

  3. Scroll down to OpenSSH Authentication Agent > right click > properties

  4. Change the Startup type from Disabled to any of the other 3 options. I have mine set to Automatic (Delayed Start)

  5. Open cmd and type where ssh to confirm that the top listed path is in System32. Mine is installed at C:\Windows\System32\OpenSSH\ssh.exe. If it's not in the list you may need to close and reopen cmd.

Once you've followed these steps, ssh-agent, ssh-add and all other ssh commands should now work from cmd. To start the agent you can simply type ssh-agent.

  1. Optional step/troubleshooting: If you use git, you should set the GIT_SSH environment variable to the output of where ssh which you ran before (e.g C:\Windows\System32\OpenSSH\ssh.exe). This is to stop inconsistencies between the version of ssh you're using (and your keys are added/generated with) and the version that git uses internally. This should prevent issues that are similar to this

Some nice things about this solution:

  • You won't need to start the ssh-agent every time you restart your computer
  • Identities that you've added (using ssh-add) will get automatically added after restarts. (It works for me, but you might possibly need a config file in your c:\Users\User\.ssh folder)
  • You don't need git!
  • You can register any rsa private key to the agent. The other solution will only pick up a key named id_rsa

Hope this helps

How can I pad an integer with zeros on the left?

Check my code that will work for integer and String.

Assume our first number is 2. And we want to add zeros to that so the the length of final string will be 4. For that you can use following code

    int number=2;
    int requiredLengthAfterPadding=4;
    String resultString=Integer.toString(number);
    int inputStringLengh=resultString.length();
    int diff=requiredLengthAfterPadding-inputStringLengh;
    if(inputStringLengh<requiredLengthAfterPadding)
    {
        resultString=new String(new char[diff]).replace("\0", "0")+number;
    }        
    System.out.println(resultString);

How to kill an application with all its activities?

Using onBackPressed() method:

@Override
public void onBackPressed() {    
    android.os.Process.killProcess(android.os.Process.myPid());
}

or use the finish() method, I have something like

//Password Error, I call function
    Quit();             


    protected void Quit() {
        super.finish();
    }

With super.finish() you close the super class's activity.

SELECT max(x) is returning null; how can I make it return 0?

Oracle would be

SELECT NVL(MAX(X), 0) AS MaxX
FROM tbl
WHERE XID = 1;

How do I resolve "Run-time error '429': ActiveX component can't create object"?

You say it works once you install the VB6 IDE so the problem is likely to be that the components you are trying to use depend on the VB6 runtime being installed.

The VB6 runtime isn't installed on Windows by default.

Installing the IDE is one way to get the runtime. For non-developer machines, a "redistributable" installer package from Microsoft should be used instead.

Here is one VB6 runtime installer from Microsoft. I'm not sure if it will be the right version for your components:

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=7b9ba261-7a9c-43e7-9117-f673077ffb3c

What's the best way to validate an XML file against an XSD file?

Using Woodstox, configure the StAX parser to validate against your schema and parse the XML.

If exceptions are caught the XML is not valid, otherwise it is valid:

// create the XSD schema from your schema file
XMLValidationSchemaFactory schemaFactory = XMLValidationSchemaFactory.newInstance(XMLValidationSchema.SCHEMA_ID_W3C_SCHEMA);
XMLValidationSchema validationSchema = schemaFactory.createSchema(schemaInputStream);

// create the XML reader for your XML file
WstxInputFactory inputFactory = new WstxInputFactory();
XMLStreamReader2 xmlReader = (XMLStreamReader2) inputFactory.createXMLStreamReader(xmlInputStream);

try {
    // configure the reader to validate against the schema
    xmlReader.validateAgainst(validationSchema);

    // parse the XML
    while (xmlReader.hasNext()) {
        xmlReader.next();
    }

    // no exceptions, the XML is valid

} catch (XMLStreamException e) {

    // exceptions, the XML is not valid

} finally {
    xmlReader.close();
}

Note: If you need to validate multiple files, you should try to reuse your XMLInputFactory and XMLValidationSchema in order to maximize the performance.

Angular 2: How to call a function after get a response from subscribe http.post

You can code as a lambda expression as the third parameter(on complete) to the subscribe method. Here I re-set the departmentModel variable to the default values.

saveData(data:DepartmentModel){
  return this.ds.sendDepartmentOnSubmit(data).
  subscribe(response=>this.status=response,
   ()=>{},
   ()=>this.departmentModel={DepartmentId:0});
}

How to change an Android app's name?

The change in Manifest file did not change the App name,

<application android:icon="@drawable/ic__logo" android:theme="@style/AppTheme" android:largeHeap="true" android:label="@string/app_name">

but changing the Label attribute in the MainLauncher did the trick for me .

[Activity(Label = "@string/app_name", MainLauncher = true, Theme = "@style/MainActivityNoActionBarTheme", ScreenOrientation = ScreenOrientation.Portrait)]

AngularJS : Initialize service with asynchronous data

Have you had a look at $routeProvider.when('/path',{ resolve:{...}? It can make the promise approach a bit cleaner:

Expose a promise in your service:

app.service('MyService', function($http) {
    var myData = null;

    var promise = $http.get('data.json').success(function (data) {
      myData = data;
    });

    return {
      promise:promise,
      setData: function (data) {
          myData = data;
      },
      doStuff: function () {
          return myData;//.getSomeData();
      }
    };
});

Add resolve to your route config:

app.config(function($routeProvider){
  $routeProvider
    .when('/',{controller:'MainCtrl',
    template:'<div>From MyService:<pre>{{data | json}}</pre></div>',
    resolve:{
      'MyServiceData':function(MyService){
        // MyServiceData will also be injectable in your controller, if you don't want this you could create a new promise with the $q service
        return MyService.promise;
      }
    }})
  }):

Your controller won't get instantiated before all dependencies are resolved:

app.controller('MainCtrl', function($scope,MyService) {
  console.log('Promise is now resolved: '+MyService.doStuff().data)
  $scope.data = MyService.doStuff();
});

I've made an example at plnkr: http://plnkr.co/edit/GKg21XH0RwCMEQGUdZKH?p=preview

Spring Data: "delete by" is supported?

If you will use pre defined delete methods as directly provided by spring JPA then below two queries will be execute by the framework.

  • First collect data(like id and other column) using by execute select query with delete query where clause.

  • then after getting resultSet of first query, second delete queries will be execute for all id(one by one)

    Note : This is not optimized way for your application because many queries will be execute for single MYSQL delete query.

This is another optimized way for delete query code because only one delete query will execute by using below customized methods.



@NamedNativeQueries({

@NamedNativeQuery(name = "Abc.deleteByCreatedTimeBetween",
            query = "DELETE FROM abc WHERE create_time BETWEEN ?1 AND ?2")
    ,

    @NamedNativeQuery(name = "Abc.getByMaxId",
            query = "SELECT max(id) from abc")
})

@Entity
public class Abc implements Serializable {

}

@Repository
public interface AbcRepository extends CrudRepository {

    int getByMaxId();

    @Transactional
    @Modifying
    void deleteByCreatedTimeBetween(String startDate, String endDate);
}

load csv into 2D matrix with numpy for plotting

You can read a CSV file with headers into a NumPy structured array with np.genfromtxt. For example:

import numpy as np

csv_fname = 'file.csv'
with open(csv_fname, 'w') as fp:
    fp.write("""\
"A","B","C","D","E","F","timestamp"
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291111964948E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291113113366E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291120650486E12
""")

# Read the CSV file into a Numpy record array
r = np.genfromtxt(csv_fname, delimiter=',', names=True, case_sensitive=True)
print(repr(r))

which looks like this:

array([(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111196e+12),
       (611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111311e+12),
       (611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29112065e+12)],
      dtype=[('A', '<f8'), ('B', '<f8'), ('C', '<f8'), ('D', '<f8'), ('E', '<f8'), ('F', '<f8'), ('timestamp', '<f8')])

You can access a named column like this r['E']:

array([1715.37476, 1715.37476, 1715.37476])

Note: this answer previously used np.recfromcsv to read the data into a NumPy record array. While there was nothing wrong with that method, structured arrays are generally better than record arrays for speed and compatibility.

Multiple submit buttons in the same form calling different Servlets

In addition to the previous response, the best option to submit a form with different buttons without language problems is actually using a button tag.

<form>
    ...
    <button type="submit" name="submit" value="servlet1">Go to 1st Servlet</button>
    <button type="submit" name="submit" value="servlet2">Go to 2nd Servlet</button>
</form>

How to get the Display Name Attribute of an Enum member via MVC Razor code?

One liner - Fluent syntax

public static class Extensions
{
    /// <summary>
    ///     A generic extension method that aids in reflecting 
    ///     and retrieving any attribute that is applied to an `Enum`.
    /// </summary>
    public static TAttribute GetAttribute<TAttribute>(this Enum enumValue) 
            where TAttribute : Attribute
    {
        return enumValue.GetType()
                        .GetMember(enumValue.ToString())
                        .First()
                        .GetCustomAttribute<TAttribute>();
    }
}

Example

public enum Season 
{
   [Display(Name = "It's autumn")]
   Autumn,

   [Display(Name = "It's winter")]
   Winter,

   [Display(Name = "It's spring")]
   Spring,

   [Display(Name = "It's summer")]
   Summer
}

public class Foo 
{
    public Season Season = Season.Summer;

    public void DisplayName()
    {
        var seasonDisplayName = Season.GetAttribute<DisplayAttribute>();
        Console.WriteLine("Which season is it?");
        Console.WriteLine (seasonDisplayName.Name);
    } 
}

Output

Which season is it?
It's summer

Performing a query on a result from another query?

Usually you can plug a Query's result (which is basically a table) as the FROM clause source of another query, so something like this will be written:

SELECT COUNT(*), SUM(SUBQUERY.AGE) from
(
  SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age
  FROM availables
  INNER JOIN rooms
  ON availables.room_id=rooms.id
  WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
  GROUP BY availables.bookdate
) AS SUBQUERY

ng-repeat: access key and value for each object in array of objects

Here is another way, without the need for nesting the repeaters.

From the Angularjs docs:

It is possible to get ngRepeat to iterate over the properties of an object using the following syntax:

<div ng-repeat="(key, value) in steps"> {{key}} : {{value}} </div>

how to access iFrame parent page using jquery?

in parent window put :

<script>
function ifDoneChildFrame(val)
{
   $('#parentPrice').html(val);
}
</script>

and in iframe src file put :

<script>window.parent.ifDoneChildFrame('Your value here');</script>

Pull new updates from original GitHub repository into forked GitHub repository

This video shows how to update a fork directly from GitHub

Steps:

  1. Open your fork on GitHub.
  2. Click on Pull Requests.
  3. Click on New Pull Request. By default, GitHub will compare the original with your fork, and there shouldn’t be anything to compare if you didn’t make any changes.
  4. Click on switching the base. Now GitHub will compare your fork with the original, and you should see all the latest changes.
  5. Click on Create a pull request for this comparison and assign a predictable name to your pull request (e.g., Update from original).
  6. Click on Create pull request.
  7. Scroll down and click Merge pull request and finally Confirm merge. If your fork didn’t have any changes, you will be able to merge it automatically.

How to create a new file in unix?

The command is lowercase: touch filename.

Keep in mind that touch will only create a new file if it does not exist! Here's some docs for good measure: http://unixhelp.ed.ac.uk/CGI/man-cgi?touch

If you always want an empty file, one way to do so would be to use:

echo "" > filename

Where is my m2 folder on Mac OS X Mavericks

Go to finder:

Press on keyboard CMD+shift+G . it will show u a popup like this

Enter path ~/.m2

press enter.

What is the difference between atomic / volatile / synchronized?

Synchronized Vs Atomic Vs Volatile:

  • Volatile and Atomic is apply only on variable , While Synchronized apply on method.
  • Volatile ensure about visibility not atomicity/consistency of object , While other both ensure about visibility and atomicity.
  • Volatile variable store in RAM and it’s faster in access but we can’t achive Thread safety or synchronization whitout synchronized keyword.
  • Synchronized implemented as synchronized block or synchronized method while both not. We can thread safe multiple line of code with help of synchronized keyword while with both we can’t achieve the same.
  • Synchronized can lock the same class object or different class object while both can’t.

Please correct me if anything i missed.

How can I check whether Google Maps is fully loaded?

This was bothering me for a while with GMaps v3.

I found a way to do it like this:

google.maps.event.addListenerOnce(map, 'idle', function(){
    // do something only the first time the map is loaded
});

The "idle" event is triggered when the map goes to idle state - everything loaded (or failed to load). I found it to be more reliable then tilesloaded/bounds_changed and using addListenerOnce method the code in the closure is executed the first time "idle" is fired and then the event is detached.

See also the events section in the Google Maps Reference.

How to set proper codeigniter base url?

Dynamic Base Url (codeigniter)

Just overwrite the line in config/config.php with the following:

$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/';

Is returning out of a switch statement considered a better practice than using break?

A break will allow you continue processing in the function. Just returning out of the switch is fine if that's all you want to do in the function.

What's the difference between deadlock and livelock?

Imagine you've thread A and thread B. They are both synchronised on the same object and inside this block there's a global variable they are both updating;

static boolean commonVar = false;
Object lock = new Object;

...

void threadAMethod(){
    ...
    while(commonVar == false){
         synchornized(lock){
              ...
              commonVar = true
         }
    }
}

void threadBMethod(){
    ...
    while(commonVar == true){
         synchornized(lock){
              ...
              commonVar = false
         }
    }
}

So, when thread A enters in the while loop and holds the lock, it does what it has to do and set the commonVar to true. Then thread B comes in, enters in the while loop and since commonVar is true now, it is be able to hold the lock. It does so, executes the synchronised block, and sets commonVar back to false. Now, thread A again gets it's new CPU window, it was about to quit the while loop but thread B has just set it back to false, so the cycle repeats over again. Threads do something (so they're not blocked in the traditional sense) but for pretty much nothing.

It maybe also nice to mention that livelock does not necessarily have to appear here. I'm assuming that the scheduler favours the other thread once the synchronised block finish executing. Most of the time, I think it's a hard-to-hit expectation and depends on many things happening under the hood.

Using json_encode on objects in PHP (regardless of scope)

$products=R::findAll('products');
$string = rtrim(implode(',', $products), ',');
echo $string;

TypeError: sequence item 0: expected string, int found

Replace

values = ",".join(value_list)

with

values = ','.join([str(i) for i in value_list])

OR

values = ','.join(str(value_list)[1:-1])

How would one write object-oriented code in C?

I think that the first thing to say is that (IMHO at least) C's implementation of function pointers is REALLY hard to use. I would jump through a WHOLE lot of hoops to avoid function pointers...

that said, I think that what other people have said is pretty good. you have structures, you have modules, instead of foo->method(a,b,c), you end up with method(foo,a,b,c) If you have more than one type with a "method" method, then you can prefix it with the type, so FOO_method(foo,a,b,c), as others have said... with good use of .h files you can get private and public, etc.

Now, there are a few things that this technique WON'T give you. It won't give you private data fields. that, I think, you have to do with willpower and good coding hygiene... Also, there isn't an easy way to do inheritance with this.

Those are the easy parts at least...the rest, I think is a 90/10 kind of situation. 10% of the benefit will require 90% of the work...

Typescript Date Type?

Typescript recognizes the Date interface out of the box - just like you would with a number, string, or custom type. So Just use:

myDate : Date;

Permission denied on accessing host directory in Docker

In my situation the problem was different. I don't know why, but even if directory on host had chmod 777 run on it, inside docker it was visible as 755.

Running inside container sudo chmod 777 my_volume_dir fixed it.

Java: Literal percent sign in printf statement

The percent sign is escaped using a percent sign:

System.out.printf("%s\t%s\t%1.2f%%\t%1.2f%%\n",ID,pattern,support,confidence);

The complete syntax can be accessed in java docs. This particular information is in the section Conversions of the first link.

The reason the compiler is generating an error is that only a limited amount of characters may follow a backslash. % is not a valid character.

Why this "Implicit declaration of function 'X'"?

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
{
    // ...

get keys of json-object in JavaScript

The working code

_x000D_
_x000D_
var jsonData = [{person:"me", age :"30"},{person:"you",age:"25"}];_x000D_
_x000D_
for(var obj in jsonData){_x000D_
    if(jsonData.hasOwnProperty(obj)){_x000D_
    for(var prop in jsonData[obj]){_x000D_
        if(jsonData[obj].hasOwnProperty(prop)){_x000D_
           alert(prop + ':' + jsonData[obj][prop]);_x000D_
        }_x000D_
    }_x000D_
}_x000D_
}
_x000D_
_x000D_
_x000D_

Why is synchronized block better than synchronized method?

In your case both are equivalent!

Synchronizing a static method is equivalent to a synchronized block on corresponding Class object.

In fact when you declare a synchronized static method lock is obtained on the monitor corresponding to the Class object.

public static synchronized int getCount() {
    // ...
}

is same as

public int getCount() {
    synchronized (ClassName.class) {
        // ...
    }
}

What is the difference between visibility:hidden and display:none?

visibility:hidden will keep the element in the page and occupies that space but does not show to the user.

display:none will not be available in the page and does not occupy any space.

Convert NSDate to String in iOS Swift

Your updated code.update it.

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date as Date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
print(yourDate!)

How can I call a WordPress shortcode within a template?

Make sure to enable the use of shortcodes in text widgets.

// To enable the use, add this in your *functions.php* file:
add_filter( 'widget_text', 'do_shortcode' );

// and then you can use it in any PHP file:  
<?php echo do_shortcode('[YOUR-SHORTCODE-NAME/TAG]'); ?>

Check the documentation for more.

How to return Json object from MVC controller to view

$.ajax({
    dataType: "json",
    type: "POST",
    url: "/Home/AutocompleteID",
    data: data,
    success: function (data) {
        $('#search').html('');
        $('#search').append(data[0].Scheme_Code);
        $('#search').append(data[0].Scheme_Name);
    }
});

From Arraylist to Array

ArrayList<String> a = new ArrayList<String>();
a.add( "test" );
@SuppressWarnings( "unused")
Object[] array = a.toArray();

It depends on what you want to achieve if you need to manipulate the array later it would cost more effort than keeping the string in the ArrayList. You have also random access with an ArrayList by list.get( index );