Programs & Examples On #Sql server 6.5

Use this tag for questions specific to the 6.5 version of Microsoft's SQL Server.

How to add 20 minutes to a current date?

you have a lot of answers in the post

var d1 = new Date (),
d2 = new Date ( d1 );
d2.setMinutes ( d1.getMinutes() + 20 );
alert ( d2 );

React - uncaught TypeError: Cannot read property 'setState' of undefined

Arrow function could have make your life more easier to avoid binding this keyword. Like so:

 delta = () => {
       this.setState({
           count : this.state.count++
      });
   }

IIS: Display all sites and bindings in PowerShell

Try this

function DisplayLocalSites
{

try{

Set-ExecutionPolicy unrestricted

$list = @()
foreach ($webapp in get-childitem IIS:\Sites\)
{
    $name = "IIS:\Sites\" + $webapp.name
    $item = @{}

$item.WebAppName = $webapp.name

foreach($Bind in $webapp.Bindings.collection)
{
    $item.SiteUrl = $Bind.Protocol +'://'+         $Bind.BindingInformation.Split(":")[-1]
}


$obj = New-Object PSObject -Property $item
$list += $obj
}

$list | Format-Table -a -Property "WebAppName","SiteUrl"

$list | Out-File -filepath C:\websites.txt

Set-ExecutionPolicy restricted

}
catch
{
$ExceptionMessage = "Error in Line: " + $_.Exception.Line + ". " +     $_.Exception.GetType().FullName + ": " + $_.Exception.Message + " Stacktrace: "    + $_.Exception.StackTrace
$ExceptionMessage
}
}

ARG or ENV, which one to use in this case?

From Dockerfile reference:

  • The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

  • The ENV instruction sets the environment variable <key> to the value <value>.
    The environment variables set using ENV will persist when a container is run from the resulting image.

So if you need build-time customization, ARG is your best choice.
If you need run-time customization (to run the same image with different settings), ENV is well-suited.

If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable

Given the number of combinations involved, using ENV to set those features at runtime is best here.

But you can combine both by:

  • building an image with a specific ARG
  • using that ARG as an ENV

That is, with a Dockerfile including:

ARG var
ENV var=${var}

You can then either build an image with a specific var value at build-time (docker build --build-arg var=xxx), or run a container with a specific runtime value (docker run -e var=yyy)

UICollectionView - Horizontal scroll, horizontal layout?

You can write a custom UICollectionView layout to achieve this, here is demo image of my implementation:

demo image

Here's code repository: KSTCollectionViewPageHorizontalLayout

@iPhoneDev (this maybe help you too)

How to get value by key from JObject?

This should help -

var json = "{'@STARTDATE': '2016-02-17 00:00:00.000',  '@ENDDATE': '2016-02-18 23:59:00.000' }";
var fdate = JObject.Parse(json)["@STARTDATE"];

Python function overloading

Overloading methods is tricky in Python. However, there could be usage of passing the dict, list or primitive variables.

I have tried something for my use cases, and this could help here to understand people to overload the methods.

Let's take your example:

A class overload method with call the methods from different class.

def add_bullet(sprite=None, start=None, headto=None, spead=None, acceleration=None):

Pass the arguments from the remote class:

add_bullet(sprite = 'test', start=Yes,headto={'lat':10.6666,'long':10.6666},accelaration=10.6}

Or

add_bullet(sprite = 'test', start=Yes, headto={'lat':10.6666,'long':10.6666},speed=['10','20,'30']}

So, handling is being achieved for list, Dictionary or primitive variables from method overloading.

Try it out for your code.

How to pass multiple checkboxes using jQuery ajax post

Just came across this trying to find a solution for the same problem. Implementing Paul's solution I've made a few tweaks to make this function properly.

var data = { 'venue[]' : []};

$("input:checked").each(function() {
   data['venue[]'].push($(this).val());
});

In short the addition of input:checked as opposed to :checked limits the fields input into the array to just the checkboxes on the form. Paul is indeed correct with this needing to be enclosed as $(this)

Identifying and removing null characters in UNIX

A large number of unwanted NUL characters, say one every other byte, indicates that the file is encoded in UTF-16 and that you should use iconv to convert it to UTF-8.

How to download a branch with git?

git checkout -b branch/name

git pull origin branch/name

HRESULT: 0x800A03EC on Worksheet.range

We were receiving the same. The exception was

Stacktrace: at Microsoft.Office.Interop.Excel._Workbook.SaveAs(Object Filename, Object FileFormat, Object Password, Object WriteResPassword, Object ReadOnlyRecommended, Object CreateBackup, XlSaveAsAccessMode AccessMode, Object ConflictResolution, Object AddToMru, Object TextCodepage, Object Text VisualLayout, Object Local)`

with an inner exception of

Exception from HRESULT: 0x800A03EC 2012-11-01 10:37:59`

We were able to resolve the problem with information from this post, which I quote here for convenience...

  1. Login to the server as a administrator.
  2. Go to "Start" -> "Run" and enter "taskmgr"
  3. Go to the process tab in task manager and check "Show Processes from all users"
  4. If there are any "Excel.exe" entries on the list, right click on the entry and select "End Process"
  5. Close task manager.
  6. Go to "Start" -> "Run" and enter "services.msc"
  7. Stop the service automating Excel if it is running.
  8. Go to "Start" -> "Run" and enter "dcomcnfg"
  9. This will bring up the component services window, expand out "Console Root" -> "Computers" -> "DCOM Config"
  10. Find "Microsoft Excel Application" in the list of components.
  11. Right click on the entry and select "Properties"
  12. Go to the "Identity" tab on the properties dialog.
  13. Select "The interactive user."
  14. Click the "OK" button.
  15. Switch to the services console
  16. Start the service automating Excel
  17. Test you application again.

Scala check if element is present in a list

this should work also with different predicate

myFunction(strings.find( _ == mystring ).isDefined)

What is the difference between private and protected members of C++ classes?

It all depends on what you want to do, and what you want the derived classes to be able to see.

class A
{
private:
    int _privInt = 0;
    int privFunc(){return 0;}
    virtual int privVirtFunc(){return 0;}
protected:
    int _protInt = 0;
    int protFunc(){return 0;}
public:
    int _publInt = 0;
    int publFunc()
    {
         return privVirtFunc();
    }
};

class B : public A
{
private:
    virtual int privVirtFunc(){return 1;}
public:
    void func()
    {
        _privInt = 1; // wont work
        _protInt = 1; // will work
        _publInt = 1; // will work
        privFunc(); // wont work
        privVirtFunc(); // wont work
        protFunc(); // will work
        publFunc(); // will return 1 since it's overridden in this class
    }
}

How can I test a change made to Jenkinsfile locally?

TL;DR

Long Version
Jenkins Pipeline testing becomes more and more of a pain. Unlike the classic declarative job configuration approach where the user was limited to what the UI exposed the new Jenkins Pipeline is a full fledged programming language for the build process where you mix the declarative part with your own code. As good developers we want to have some unit tests for this kind of code as well.

There are three steps you should follow when developing Jenkins Pipelines. The step 1. should cover 80% of the uses cases.

  1. Do as much as possible in build scripts (eg. Maven, Gradle, Gulp etc.). Then in your pipeline scripts just calls the build tasks in the right order. The build pipeline just orchestrates and executes the build tasks but does not have any major logic that needs a special testing.
  2. If the previous rule can't be fully applied then move over to Pipeline Shared libraries where you can develop and test custom logic on its own and integrate them into the pipeline.
  3. If all of the above fails you, you can try one of those libraries that came up recently (March-2017). Jenkins Pipeline Unit testing framework or pipelineUnit (examples). Since 2018 there is also Jenkinsfile Runner, a package to execution Jenkins pipelines from a command line tool.

Examples

The pipelineUnit GitHub repo contains some Spock examples on how to use Jenkins Pipeline Unit testing framework

DATEDIFF function in Oracle

You can simply subtract two dates. You have to cast it first, using to_date:

select to_date('2000-01-01', 'yyyy-MM-dd')
       - to_date('2000-01-02', 'yyyy-MM-dd')
       datediff
from   dual
;

The result is in days, to the difference of these two dates is -1 (you could swap the two dates if you like). If you like to have it in hours, just multiply the result with 24.

How do you fix a MySQL "Incorrect key file" error when you can't repair the table?

Apply proper charset and collation to database, table and columns/fields.

I creates database and table structure using sql queries from one server to another. it creates database structure as follows:

  1. database with charset of "utf8", collation of "utf8_general_ci"
  2. tables with charset of "utf8" and collation of "utf8_bin".
  3. table columns / fields have charset "utf8" and collation of "utf8_bin".

I change collation of table and column to utf8_general_ci, and it resolves the error.

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

If you're using bindings you can do

val headerView = binding.navView.getHeaderView(0)
val headerBinding = NavDrawerHeaderBinding.bind(headerView)
headerBinding.textView.text = "Your text here"

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

    def wordCount(mystring):  
        tempcount = 0  
        count = 1  

        try:  
            for character in mystring:  
                if character == " ":  
                    tempcount +=1  
                    if tempcount ==1:  
                        count +=1  

                    else:  
                        tempcount +=1
                 else:
                     tempcount=0

             return count  

         except Exception:  
             error = "Not a string"  
             return error  

    mystring = "I   am having   a    very nice 23!@$      day."           

    print(wordCount(mystring))  

output is 8

Simulation of CONNECT BY PRIOR of Oracle in SQL Server

@Alex Martelli's answer is great! But it work only for one element at time (WHERE name = 'Joan') If you take out the WHERE clause, the query will return all the root rows together...

I changed a little bit for my situation, so it can show the entire tree for a table.

table definition:

CREATE TABLE [dbo].[mar_categories] ( 
    [category]  int IDENTITY(1,1) NOT NULL,
    [name]      varchar(50) NOT NULL,
    [level]     int NOT NULL,
    [action]    int NOT NULL,
    [parent]    int NULL,
    CONSTRAINT [XPK_mar_categories] PRIMARY KEY([category])
)

(level is literally the level of a category 0: root, 1: first level after root, ...)

and the query:

WITH n(category, name, level, parent, concatenador) AS 
(
    SELECT category, name, level, parent, '('+CONVERT(VARCHAR (MAX), category)+' - '+CONVERT(VARCHAR (MAX), level)+')' as concatenador
    FROM mar_categories
    WHERE parent is null
        UNION ALL
    SELECT m.category, m.name, m.level, m.parent, n.concatenador+' * ('+CONVERT (VARCHAR (MAX), case when ISNULL(m.parent, 0) = 0 then 0 else m.category END)+' - '+CONVERT(VARCHAR (MAX), m.level)+')' as concatenador
    FROM mar_categories as m, n
    WHERE n.category = m.parent
)
SELECT distinct * FROM n ORDER BY concatenador asc

(You don't need to concatenate the level field, I did just to make more readable)

the answer for this query should be something like:

sql return

I hope it helps someone!

now, I'm wondering how to do this on MySQL... ^^

Resize image proportionally with MaxHeight and MaxWidth constraints

Like this?

public static void Test()
{
    using (var image = Image.FromFile(@"c:\logo.png"))
    using (var newImage = ScaleImage(image, 300, 400))
    {
        newImage.Save(@"c:\test.png", ImageFormat.Png);
    }
}

public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
    var ratioX = (double)maxWidth / image.Width;
    var ratioY = (double)maxHeight / image.Height;
    var ratio = Math.Min(ratioX, ratioY);

    var newWidth = (int)(image.Width * ratio);
    var newHeight = (int)(image.Height * ratio);

    var newImage = new Bitmap(newWidth, newHeight);

    using (var graphics = Graphics.FromImage(newImage))
        graphics.DrawImage(image, 0, 0, newWidth, newHeight);

    return newImage;
}

How to change the color of an svg element?

2020 answer

CSS Filter works on all current browsers

To change any SVGs color

  1. Add the SVG image using an <img> tag.
<img src="dotted-arrow.svg" class="filter-green"/>
  1. To filter to a specific color, use the following Codepen(Click Here to open codepen) to convert a hex color code to a CSS filter:

For example, output for #00EE00 is

filter: invert(42%) sepia(93%) saturate(1352%) hue-rotate(87deg) brightness(119%) contrast(119%);
  1. Add the CSS filter into this class.
    .filter-green{
        filter: invert(48%) sepia(79%) saturate(2476%) hue-rotate(86deg) brightness(118%) contrast(119%);
    }

Excel VBA App stops spontaneously with message "Code execution has been halted"

I found hitting ctrl+break while the macro wasn't running fixed the problem.

How can I switch my signed in user in Visual Studio 2013?

You don't need to reset all your user data to switch users. Try clicking on your name in the upper right corner then click on "Account settings". There you will get an option to sign out of the IDE. Once signed out you can sign back in as another Microsoft account.

Why rgb and not cmy?

There's a difference between additive colors (http://en.wikipedia.org/wiki/Additive_color) and subtractive colors (http://en.wikipedia.org/wiki/Subtractive_color).

With additive colors, the more you add, the brighter the colors become. This is because they are emitting light. This is why the day light is (more or less) white, since the Sun is emitting in almost all the visible wavelength spectrum.

On the other hand, with subtractive colors the more colors you mix, the darker the resulting color. This is because they are reflecting light. This is also why the black colors get hotter quickly, because it absorbs (almost) all light energy and reflects (almost) none.

Specifically to your question, it depends what medium you are working on. Traditionally, additive colors (RGB) are used because the canon for computer graphics was the computer monitor, and since it's emitting light, it makes sense to use the same structure for the graphic card (the colors are shown without conversions). However, if you are used to graphic arts and press, subtractive color model is used (CMYK). In programs such as Photoshop, you can choose to work in CMYK space although it doesn't matter what color model you use: the primary colors of one group are the secondary colors of the second one and viceversa.

P.D.: my father worked at graphic arts, this is why i know this... :-P

What's the point of the X-Requested-With header?

Some frameworks are using this header to detect xhr requests e.g. grails spring security is using this header to identify xhr request and give either a json response or html response as response.

Most Ajax libraries (Prototype, JQuery, and Dojo as of v2.1) include an X-Requested-With header that indicates that the request was made by XMLHttpRequest instead of being triggered by clicking a regular hyperlink or form submit button.

Source: http://grails-plugins.github.io/grails-spring-security-core/guide/helperClasses.html

How to select the first element with a specific attribute using XPath

if namespace is provided on the given xml, its better to use this.

(/*[local-name() ='bookstore']/*[local-name()='book'][@location='US'])[1]

Scanner only reads first word instead of line

Javadoc to the rescue :

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace

nextLine is probably the method you should use.

Implement division with bit-wise operator

With the usual caveats about C's behaviour with shifts, this ought to work for unsigned quantities regardless of the native size of an int...

static unsigned int udiv(unsigned int a, unsigned int b) {
  unsigned int c = 1, result = 0;

  if (b == 0) return (unsigned int)-1 /*infinity*/;

  while (((int)b > 0) && (b < a)) { b = b<<1; c = c<<1; }

  do {
    if (a >= b) { a -= b; result += c; }
    b = b>>1; c = c>>1;
  } while (c);

  return result;
}

C# equivalent to Java's charAt()?

You can index into a string in C# like an array, and you get the character at that index.

Example:

In Java, you would say

str.charAt(8);

In C#, you would say

str[8];

System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second

This is not the correct usage of the System.Threading.Timer. When you instantiate the Timer, you should almost always do the following:

_timer = new Timer( Callback, null, TIME_INTERVAL_IN_MILLISECONDS, Timeout.Infinite );

This will instruct the timer to tick only once when the interval has elapsed. Then in your Callback function you Change the timer once the work has completed, not before. Example:

private void Callback( Object state )
{
    // Long running operation
   _timer.Change( TIME_INTERVAL_IN_MILLISECONDS, Timeout.Infinite );
}

Thus there is no need for locking mechanisms because there is no concurrency. The timer will fire the next callback after the next interval has elapsed + the time of the long running operation.

If you need to run your timer at exactly N milliseconds, then I suggest you measure the time of the long running operation using Stopwatch and then call the Change method appropriately:

private void Callback( Object state )
{
   Stopwatch watch = new Stopwatch();

   watch.Start();
   // Long running operation

   _timer.Change( Math.Max( 0, TIME_INTERVAL_IN_MILLISECONDS - watch.ElapsedMilliseconds ), Timeout.Infinite );
}

I strongly encourage anyone doing .NET and is using the CLR who hasn't read Jeffrey Richter's book - CLR via C#, to read is as soon as possible. Timers and thread pools are explained in great details there.

elasticsearch bool query combine must with OR

  • OR is spelled should
  • AND is spelled must
  • NOR is spelled should_not

Example:

You want to see all the items that are (round AND (red OR blue)):

{
    "query": {
        "bool": {
            "must": [
                {
                    "term": {"shape": "round"}
                },
                {
                    "bool": {
                        "should": [
                            {"term": {"color": "red"}},
                            {"term": {"color": "blue"}}
                        ]
                    }
                }
            ]
        }
    }
}

You can also do more complex versions of OR, for example if you want to match at least 3 out of 5, you can specify 5 options under "should" and set a "minimum_should" of 3.

Thanks to Glen Thompson and Sebastialonso for finding where my nesting wasn't quite right before.

Thanks also to Fatmajk for pointing out that "term" becomes "match" in ElasticSearch 6.

Write to file, but overwrite it if it exists

Just noting that if you wish to redirect both stderr and stdout to a file while you have noclobber set (i.e. set -o noclobber), you can use the code:

cmd >| file.txt 2>&1

More information about this can be seen at https://stackoverflow.com/a/876242.

Also this answer's @TuBui's question on the answer @BrDaHa provided above at Aug 9 '18 at 9:34.

Very Simple Image Slider/Slideshow with left and right button. No autoplay

Why try to reinvent the wheel? There are more lightweight jQuery slideshow solutions out there then you could poke a stick at, and someone has already done the hard work for you and thought about issues that you might run into (cross-browser compatability etc).

jQuery Cycle is one of my favourite light weight libraries.

What you want to achieve could be done in just

    jQuery("#slideshow").cycle({
    timeout:0, // no autoplay
    fx: 'fade', //fade effect, although there are heaps
    next: '#next',
    prev: '#prev'
    });

JSFIDDLE TO SEE HOW EASY IT IS

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

How to count the number of letters in a string without the spaces?

OK, if that's what you want, here's what I would do to fix your existing code:

from collections import Counter

def count_letters(words):
    counter = Counter()
    for word in words.split():
        counter.update(word)
    return sum(counter.itervalues())

words = "The grey old fox is an idiot"
print count_letters(words)  # 22

If you don't want to count certain non-whitespace characters, then you'll need to remove them -- inside the for loop if not sooner.

Public free web services for testing soap client

There is a bunch on here:

http://www.webservicex.net/WS/wscatlist.aspx

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

Oracle date format picture ends before converting entire input string

Perhaps you should check NLS_DATE_FORMAT and use the date string conforming the format. Or you can use to_date function within the INSERT statement, like the following:

insert into visit
values(123456, 
       to_date('19-JUN-13', 'dd-mon-yy'),
       to_date('13-AUG-13 12:56 A.M.', 'dd-mon-yyyy hh:mi A.M.'));

Additionally, Oracle DATE stores date and time information together.

Differences between Ant and Maven

I'd say it depends upon the size of your project... Personnally, I would use Maven for simple projects that need straightforward compiling, packaging and deployment. As soon as you need to do some more complicated things (many dependencies, creating mapping files...), I would switch to Ant...

How to disable registration new users in Laravel

In Laravel 5.5 is very simple, if you are using CRUD route system.

Go to app/http/controllers/RegisterController there is namespace: Illuminate\Foundation\Auth\RegistersUser

You need to go to the RegistersUser: Illuminate\Foundation\Auth\RegistersUser

There is the method call showRegistrationForm change this: return view('auth.login'); for this: return redirect()->route('auth.login'); and remove from you blade page route call register. It may look like that:

 <li role="presentation">
     <a class="nav-link" href="{{ route('register') }}">Register</a>
 </li> 

What is attr_accessor in Ruby?

Attributes and accessor methods

Attributes are class components that can be accessed from outside the object. They are known as properties in many other programming languages. Their values are accessible by using the "dot notation", as in object_name.attribute_name. Unlike Python and a few other languages, Ruby does not allow instance variables to be accessed directly from outside the object.

class Car
  def initialize
    @wheels = 4  # This is an instance variable
  end
end

c = Car.new
c.wheels     # Output: NoMethodError: undefined method `wheels' for #<Car:0x00000000d43500>

In the above example, c is an instance (object) of the Car class. We tried unsuccessfully to read the value of the wheels instance variable from outside the object. What happened is that Ruby attempted to call a method named wheels within the c object, but no such method was defined. In short, object_name.attribute_name tries to call a method named attribute_name within the object. To access the value of the wheels variable from the outside, we need to implement an instance method by that name, which will return the value of that variable when called. That's called an accessor method. In the general programming context, the usual way to access an instance variable from outside the object is to implement accessor methods, also known as getter and setter methods. A getter allows the value of a variable defined within a class to be read from the outside and a setter allows it to be written from the outside.

In the following example, we have added getter and setter methods to the Car class to access the wheels variable from outside the object. This is not the "Ruby way" of defining getters and setters; it serves only to illustrate what getter and setter methods do.

class Car
  def wheels  # getter method
    @wheels
  end

  def wheels=(val)  # setter method
    @wheels = val
  end
end

f = Car.new
f.wheels = 4  # The setter method was invoked
f.wheels  # The getter method was invoked
# Output: => 4

The above example works and similar code is commonly used to create getter and setter methods in other languages. However, Ruby provides a simpler way to do this: three built-in methods called attr_reader, attr_writer and attr_acessor. The attr_reader method makes an instance variable readable from the outside, attr_writer makes it writeable, and attr_acessor makes it readable and writeable.

The above example can be rewritten like this.

class Car
  attr_accessor :wheels
end

f = Car.new
f.wheels = 4
f.wheels  # Output: => 4

In the above example, the wheels attribute will be readable and writable from outside the object. If instead of attr_accessor, we used attr_reader, it would be read-only. If we used attr_writer, it would be write-only. Those three methods are not getters and setters in themselves but, when called, they create getter and setter methods for us. They are methods that dynamically (programmatically) generate other methods; that's called metaprogramming.

The first (longer) example, which does not employ Ruby's built-in methods, should only be used when additional code is required in the getter and setter methods. For instance, a setter method may need to validate data or do some calculation before assigning a value to an instance variable.

It is possible to access (read and write) instance variables from outside the object, by using the instance_variable_get and instance_variable_set built-in methods. However, this is rarely justifiable and usually a bad idea, as bypassing encapsulation tends to wreak all sorts of havoc.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

There is a single quote in $submitsubject or $submit_message

Why is this a problem?

The single quote char terminates the string in MySQL and everything past that is treated as a sql command. You REALLY don't want to write your sql like that. At best, your application will break intermittently (as you're observing) and at worst, you have just introduced a huge security vulnerability.

Imagine if someone submitted '); DROP TABLE private_messages; in submit message.

Your SQL Command would be:

INSERT INTO private_messages (to_id, from_id, time_sent, subject, message) 
        VALUES('sender_id', 'id', now(),'subjet','');

DROP TABLE private_messages;

Instead you need to properly sanitize your values.

AT A MINIMUM you must run each value through mysql_real_escape_string() but you should really be using prepared statements.

If you were using mysql_real_escape_string() your code would look like this:

if($_POST['submit_message']){

if($_POST['form_subject']==""){
    $submit_subject="(no subject)";
}else{
    $submit_subject=mysql_real_escape_string($_POST['form_subject']); 
}
$submit_message=mysql_real_escape_string($_POST['form_message']);
$sender_id = mysql_real_escape_string($_POST['sender_id']);

Here is a great article on prepared statements and PDO.

How to get my project path?

var requiredPath = Path.GetDirectoryName(Path.GetDirectoryName(
System.IO.Path.GetDirectoryName( 
      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase )));

What does the red exclamation point icon in Eclipse mean?

Make sure you don't have any undefined classpath variables (like M2_REPO).

Is there a vr (vertical rule) in html?

An <hr> inside a display:flex will make it display vertically.

JSFiddle: https://jsfiddle.net/w6y5t1kL/

Example:

<div style="display:flex;">
  <div>
    Content
    <ul>
      <li>Continued content...</li>
    </ul>
  </div>
  <hr>
  <div>
    Content
    <ul>
      <li>Continued content...</li>
    </ul>
  </div>
</div>

What data type to use for hashed password field and what length?

Hashes are a sequence of bits (128 bits, 160 bits, 256 bits, etc., depending on the algorithm). Your column should be binary-typed, not text/character-typed, if MySQL allows it (SQL Server datatype is binary(n) or varbinary(n)). You should also salt the hashes. Salts may be text or binary, and you will need a corresponding column.

Interfaces vs. abstract classes

The real question is: whether to use interfaces or base classes. This has been covered before.

In C#, an abstract class (one marked with the keyword "abstract") is simply a class from which you cannot instantiate objects. This serves a different purpose than simply making the distinction between base classes and interfaces.

What is meant with "const" at end of function declaration?

Bar is guaranteed not to change the object it is being invoked on. See the section about const correctness in the C++ FAQ, for example.

Batch file to map a drive when the folder name contains spaces

I just created some directories, shared them and mapped using:

net use y: "\\mycomputername\folder with spaces"

So this solution gets "works on my machine" certificate. What error code do you get?

Smooth GPS data

This might come a little late...

I wrote this KalmanLocationManager for Android, which wraps the two most common location providers, Network and GPS, kalman-filters the data, and delivers updates to a LocationListener (like the two 'real' providers).

I use it mostly to "interpolate" between readings - to receive updates (position predictions) every 100 millis for instance (instead of the maximum gps rate of one second), which gives me a better frame rate when animating my position.

Actually, it uses three kalman filters, on for each dimension: latitude, longitude and altitude. They're independent, anyway.

This makes the matrix math much easier: instead of using one 6x6 state transition matrix, I use 3 different 2x2 matrices. Actually in the code, I don't use matrices at all. Solved all equations and all values are primitives (double).

The source code is working, and there's a demo activity. Sorry for the lack of javadoc in some places, I'll catch up.

Flexbox not working in Internet Explorer 11

According to Flexbugs:

In IE 10-11, min-height declarations on flex containers work to size the containers themselves, but their flex item children do not seem to know the size of their parents. They act as if no height has been set at all.

Here are a couple of workarounds:

1. Always fill the viewport + scrollable <aside> and <section>:

_x000D_
_x000D_
html {
  height: 100%;
}

body {
  display: flex;
  flex-direction: column;
  height: 100%;
  margin: 0;
}

header,
footer {
  background: #7092bf;
}

main {
  flex: 1;
  display: flex;
}

aside, section {
  overflow: auto;
}

aside {
  flex: 0 0 150px;
  background: #3e48cc;
}

section {
  flex: 1;
  background: #9ad9ea;
}
_x000D_
<header>
  <p>header</p>
</header>

<main>
  <aside>
    <p>aside</p>
  </aside>
  <section>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
  </section>
</main>

<footer>
  <p>footer</p>
</footer>
_x000D_
_x000D_
_x000D_

2. Fill the viewport initially + normal page scroll with more content:

_x000D_
_x000D_
html {
  height: 100%;
}

body {
  display: flex;
  flex-direction: column;
  height: 100%;
  margin: 0;
}

header,
footer {
  background: #7092bf;
}

main {
  flex: 1 0 auto;
  display: flex;
}

aside {
  flex: 0 0 150px;
  background: #3e48cc;
}

section {
  flex: 1;
  background: #9ad9ea;
}
_x000D_
<header>
  <p>header</p>
</header>

<main>
  <aside>
    <p>aside</p>
  </aside>
  <section>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
  </section>
</main>

<footer>
  <p>footer</p>
</footer>
_x000D_
_x000D_
_x000D_

PHP Accessing Parent Class Variable

Just echo it since it's inherited

echo $this->bb;

Write string to output stream

You may use Apache Commons IO:

try (OutputStream outputStream = ...) {
    IOUtils.write("data", outputStream, "UTF-8");
}

The connection to adb is down, and a severe error has occurred

The problem might be with your firewall or antivirus.

  1. Disable all network connection
  2. Disable firewall
  3. Disable Antivirus

Make sure they all disabled.

Run your script in Eclipse. If it works, then 2 and 3 might be the culprit. For me, it was comodo firewall. I created a filter for Adb.exe

Why am I getting "IndentationError: expected an indented block"?

There are in fact multiples things you need to know about indentation in Python:

Python really cares about indention.

In a lot of other languages the indention is not necessary but improves readability. In Python indentation replaces the keyword begin / end or { } and is therefore necessary.

This is verified before the execution of the code, therefore even if the code with the indentation error is never reached, it won't work.

There are different indention errors and you reading them helps a lot:

1. "IndentationError: expected an indented block"

They are two main reasons why you could have such an error:

- You have a ":" without an indented block behind.

Here are two examples:

Example 1, no indented block:

Input:

if 3 != 4:
    print("usual")
else:

Output:

  File "<stdin>", line 4

    ^
IndentationError: expected an indented block

The output states that you need to have an indented block on line 4, after the else: statement

Example 2, unindented block:

Input:

if 3 != 4:
print("usual")

Output

  File "<stdin>", line 2
    print("usual")
        ^
IndentationError: expected an indented block

The output states that you need to have an indented block line 2, after the if 3 != 4: statement

- You are using Python2.x and have a mix of tabs and spaces:

Input

def foo():
    if 1:
        print 1

Please note that before if, there is a tab, and before print there is 8 spaces.

Output:

  File "<stdin>", line 3
    print 1
      ^
IndentationError: expected an indented block

It's quite hard to understand what is happening here, it seems that there is an indent block... But as I said, I've used tabs and spaces, and you should never do that.

  • You can get some info here.
  • Remove all tabs and replaces them by four spaces.
  • And configure your editor to do that automatically.

2. "IndentationError: unexpected indent"

It is important to indent blocks, but only blocks that should be indent. So basically this error says:

- You have an indented block without a ":" before it.

Example:

Input:

a = 3
  a += 3

Output:

  File "<stdin>", line 2
    a += 3
    ^
IndentationError: unexpected indent

The output states that he wasn't expecting an indent block line 2, then you should remove it.

3. "TabError: inconsistent use of tabs and spaces in indentation" (python3.x only)

  • You can get some info here.
  • But basically it's, you are using tabs and spaces in your code.
  • You don't want that.
  • Remove all tabs and replaces them by four spaces.
  • And configure your editor to do that automatically.


Eventually, to come back on your problem:

Just look at the line number of the error, and fix it using the previous information.

Adding a JAR to an Eclipse Java library

You might also consider using a build tool like Maven to manage your dependencies. It is very easy to setup and helps manage those dependencies automatically in eclipse. Definitely worth the effort if you have a large project with a lot of external dependencies.

how to check if object already exists in a list

Are you sure you need a list in this case? If you are populating the list with many items, performance will suffer with myList.Contains or myList.Any; the run-time will be quadratic. You might want to consider using a better data structure. For example,

 public class MyClass
    {
        public string Property1 { get; set; }
        public string Property2 { get; set; }

    }

    public class MyClassComparer : EqualityComparer<MyClass>
    {
        public override bool Equals(MyClass x, MyClass y)
        {
            if(x == null || y == null)
               return x == y;

            return x.Property1 == y.Property1 && x.Property2 == y.Property2;
        }

        public override int GetHashCode(MyClass obj)
        {
            return obj == null ? 0 : (obj.Property1.GetHashCode() ^ obj.Property2.GetHashCode());
        }
    }

You could use a HashSet in the following manner:

  var set = new HashSet<MyClass>(new MyClassComparer());
  foreach(var myClass in ...)
     set.Add(myClass);

Of course, if this definition of equality for MyClass is 'universal', you needn't write an IEqualityComparer implementation; you could just override GetHashCode and Equals in the class itself.

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

It doesn't appear that iframes display and scroll properly. You can use an object tag to replace an iframe and the contents will be scrollable with 2 fingers. Here's a simple example:

<html>
    <head>
        <meta name="viewport" content="minimum-scale=1.0; maximum-scale=1.0; user-scalable=false; initial-scale=1.0;"/>
    </head>
    <body>
        <div>HEADER - use 2 fingers to scroll contents:</div>
        <div id="scrollee" style="height:75%;" >
            <object id="object" height="90%" width="100%" type="text/html" data="http://en.wikipedia.org/"></object>
        </div>
        <div>FOOTER</div>
    </body>
</html>

How to increase size of DOSBox window?

For using DOSBox with SDL, you will need to set or change the following:

[sdl]
windowresolution=1280x960
output=opengl

Here is three options to put those settings:

  1. Edit user's default configuration, for example, using vi:

    $ dosbox -printconf
    /home/USERNAME/.dosbox/dosbox-0.74.conf
    $ vi "$(dosbox -printconf)"
    $ dosbox
    
  2. For temporary resize, create a new configuration with the three lines above, say newsize.conf:

    $ dosbox -conf newsize.conf
    

    You can use -conf to load multiple configuration and/or with -userconf for default configuration, for example:

    $ dosbox -userconf -conf newsize.conf 
    [snip]
    ---
    CONFIG:Loading primary settings from config file /home/USERNAME/.dosbox/dosbox-0.74.conf
    CONFIG:Loading additional settings from config file newsize.conf
    [snip]
    
  3. Create a dosbox.conf under current directory, DOSBox loads it as default.

DOSBox should start up and resize to 1280x960 in this case.

Note that you probably would not get any size you desired, for instance, I set 1280x720 and I got 1152x720.

Debug message "Resource interpreted as other but transferred with MIME type application/javascript"

This bug seem to have resurfaced (Noticed it November 2010)

I think the WebKit bug reports involved are this one and this. Essentially it boils down to incorrect cache handling when doing an If-Modified-Since which get a 304 response.

What does "The following object is masked from 'package:xxx'" mean?

The message means that both the packages have functions with the same names. In this particular case, the testthat and assertive packages contain five functions with the same name.

When two functions have the same name, which one gets called?

R will look through the search path to find functions, and will use the first one that it finds.

search()
 ##  [1] ".GlobalEnv"        "package:assertive" "package:testthat" 
 ##  [4] "tools:rstudio"     "package:stats"     "package:graphics" 
 ##  [7] "package:grDevices" "package:utils"     "package:datasets" 
 ## [10] "package:methods"   "Autoloads"         "package:base"

In this case, since assertive was loaded after testthat, it appears earlier in the search path, so the functions in that package will be used.

is_true
## function (x, .xname = get_name_in_parent(x)) 
## {
##     x <- coerce_to(x, "logical", .xname)
##     call_and_name(function(x) {
##         ok <- x & !is.na(x)
##         set_cause(ok, ifelse(is.na(x), "missing", "false"))
##     }, x)
## }
<bytecode: 0x0000000004fc9f10>
<environment: namespace:assertive.base>

The functions in testthat are not accessible in the usual way; that is, they have been masked.

What if I want to use one of the masked functions?

You can explicitly provide a package name when you call a function, using the double colon operator, ::. For example:

testthat::is_true
## function () 
## {
##     function(x) expect_true(x)
## }
## <environment: namespace:testthat>

How do I suppress the message?

If you know about the function name clash, and don't want to see it again, you can suppress the message by passing warn.conflicts = FALSE to library.

library(testthat)
library(assertive, warn.conflicts = FALSE)
# No output this time

Alternatively, suppress the message with suppressPackageStartupMessages:

library(testthat)
suppressPackageStartupMessages(library(assertive))
# Also no output

Impact of R's Startup Procedures on Function Masking

If you have altered some of R's startup configuration options (see ?Startup) you may experience different function masking behavior than you might expect. The precise order that things happen as laid out in ?Startup should solve most mysteries.

For example, the documentation there says:

Note that when the site and user profile files are sourced only the base package is loaded, so objects in other packages need to be referred to by e.g. utils::dump.frames or after explicitly loading the package concerned.

Which implies that when 3rd party packages are loaded via files like .Rprofile you may see functions from those packages masked by those in default packages like stats, rather than the reverse, if you loaded the 3rd party package after R's startup procedure is complete.

How do I list all the masked functions?

First, get a character vector of all the environments on the search path. For convenience, we'll name each element of this vector with its own value.

library(dplyr)
envs <- search() %>% setNames(., .)

For each environment, get the exported functions (and other variables).

fns <- lapply(envs, ls)

Turn this into a data frame, for easy use with dplyr.

fns_by_env <- data_frame(
  env = rep.int(names(fns), lengths(fns)),
  fn  = unlist(fns)
)

Find cases where the object appears more than once.

fns_by_env %>% 
  group_by(fn) %>% 
  tally() %>% 
  filter(n > 1) %>% 
  inner_join(fns_by_env)

To test this, try loading some packages with known conflicts (e.g., Hmisc, AnnotationDbi).

How do I prevent name conflict bugs?

The conflicted package throws an error with a helpful error message, whenever you try to use a variable with an ambiguous name.

library(conflicted)
library(Hmisc)
units
## Error: units found in 2 packages. You must indicate which one you want with ::
##  * Hmisc::units
##  * base::units

How to find the Number of CPU Cores via .NET/C#?

There are several different pieces of information relating to processors that you could get:

  1. Number of physical processors
  2. Number of cores
  3. Number of logical processors.

These can all be different; in the case of a machine with 2 dual-core hyper-threading-enabled processors, there are 2 physical processors, 4 cores, and 8 logical processors.

The number of logical processors is available through the Environment class, but the other information is only available through WMI (and you may have to install some hotfixes or service packs to get it on some systems):

Make sure to add a reference in your project to System.Management.dll In .NET Core, this is available (for Windows only) as a NuGet package.

Physical Processors:

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
    Console.WriteLine("Number Of Physical Processors: {0} ", item["NumberOfProcessors"]);
}

Cores:

int coreCount = 0;
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
{
    coreCount += int.Parse(item["NumberOfCores"].ToString());
}
Console.WriteLine("Number Of Cores: {0}", coreCount);

Logical Processors:

Console.WriteLine("Number Of Logical Processors: {0}", Environment.ProcessorCount);

OR

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
    Console.WriteLine("Number Of Logical Processors: {0}", item["NumberOfLogicalProcessors"]);
}

Processors excluded from Windows:

You can also use Windows API calls in setupapi.dll to discover processors that have been excluded from Windows (e.g. through boot settings) and aren't detectable using the above means. The code below gives the total number of logical processors (I haven't been able to figure out how to differentiate physical from logical processors) that exist, including those that have been excluded from Windows:

static void Main(string[] args)
{
    int deviceCount = 0;
    IntPtr deviceList = IntPtr.Zero;
    // GUID for processor classid
    Guid processorGuid = new Guid("{50127dc3-0f36-415e-a6cc-4cb3be910b65}");

    try
    {
        // get a list of all processor devices
        deviceList = SetupDiGetClassDevs(ref processorGuid, "ACPI", IntPtr.Zero, (int)DIGCF.PRESENT);
        // attempt to process each item in the list
        for (int deviceNumber = 0; ; deviceNumber++)
        {
            SP_DEVINFO_DATA deviceInfo = new SP_DEVINFO_DATA();
            deviceInfo.cbSize = Marshal.SizeOf(deviceInfo);

            // attempt to read the device info from the list, if this fails, we're at the end of the list
            if (!SetupDiEnumDeviceInfo(deviceList, deviceNumber, ref deviceInfo))
            {
                deviceCount = deviceNumber;
                break;
            }
        }
    }
    finally
    {
        if (deviceList != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceList); }
    }
    Console.WriteLine("Number of cores: {0}", deviceCount);
}

[DllImport("setupapi.dll", SetLastError = true)]
private static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid,
    [MarshalAs(UnmanagedType.LPStr)]String enumerator,
    IntPtr hwndParent,
    Int32 Flags);

[DllImport("setupapi.dll", SetLastError = true)]
private static extern Int32 SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);

[DllImport("setupapi.dll", SetLastError = true)]
private static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet,
    Int32 MemberIndex,
    ref SP_DEVINFO_DATA DeviceInterfaceData);

[StructLayout(LayoutKind.Sequential)]
private struct SP_DEVINFO_DATA
{
    public int cbSize;
    public Guid ClassGuid;
    public uint DevInst;
    public IntPtr Reserved;
}

private enum DIGCF
{
    DEFAULT = 0x1,
    PRESENT = 0x2,
    ALLCLASSES = 0x4,
    PROFILE = 0x8,
    DEVICEINTERFACE = 0x10,
}

Laravel: How do I parse this json data in view blade?

The catch all for me is taking an object, encoding it, and then passing the string into a javascript script tag. To do this you have to do some replacements.

First replace every \ with a double slash \\ and then every quote" with a \".

$payload = json_encode($payload);
$payload = preg_replace("_\\\_", "\\\\\\", $payload);
$payload = preg_replace("/\"/", "\\\"", $payload);
return View::make('pages.javascript')
  ->with('payload', $payload)

Then in the blade template

@if(isset($payload))
<script>
  window.__payload = JSON.parse("{!!$payload!!}");
</script>
@endif

This basically allows you to take an object on the php side, and then have an object on the javascript side.

HTML: How to limit file upload to be only images?

This is what I have been using successfully:

...
<div class="custom-file">
    <input type="file" class="custom-file-input image-gallery" id="image-gallery" name="image-gallery[]" multiple accept="image/*">
   <label class="custom-file-label" for="image-gallery">Upload Image(s)</label>
</div>
...

It is always a good idea to check for the actual file type on the server-side as well.

Circular (or cyclic) imports in Python

There was a really good discussion on this over at comp.lang.python last year. It answers your question pretty thoroughly.

Imports are pretty straightforward really. Just remember the following:

'import' and 'from xxx import yyy' are executable statements. They execute when the running program reaches that line.

If a module is not in sys.modules, then an import creates the new module entry in sys.modules and then executes the code in the module. It does not return control to the calling module until the execution has completed.

If a module does exist in sys.modules then an import simply returns that module whether or not it has completed executing. That is the reason why cyclic imports may return modules which appear to be partly empty.

Finally, the executing script runs in a module named __main__, importing the script under its own name will create a new module unrelated to __main__.

Take that lot together and you shouldn't get any surprises when importing modules.

How to create a string with format?

let str = "\(INT_VALUE), \(FLOAT_VALUE), \(DOUBLE_VALUE), \(STRING_VALUE)"

Update: I wrote this answer before Swift had String(format:) added to it's API. Use the method given by the top answer.

How do I pass JavaScript variables to PHP?

Your code has a few things wrong with it.

  • You define a JavaScript function, func_load3(), but do not call it.
  • Your function is defined in the wrong place. When it is defined in your page, the HTML objects it refers to have not yet been loaded. Most JavaScript code checks whether the document is fully loaded before executing, or you can just move your code past the elements it refers to in the page.
  • Your form has no means to submit it. It needs a submit button.
  • You do not check whether your form has been submitted.

It is possible to set a JavaScript variable in a hidden variable in a form, then submit it, and read the value back in PHP. Here is a simple example that shows this:

<?php
if (isset($_POST['hidden1'])) {
   echo "You submitted {$_POST['hidden1']}";
   die;
}

echo <<<HTML
   <form name="myform" action="{$_SERVER['PHP_SELF']}" method="post" id="myform">
      <input type="submit" name="submit" value="Test this mess!" />
      <input type="hidden" name="hidden1" id="hidden1" />
   </form>

   <script type="text/javascript">
      document.getElementById("hidden1").value = "This is an example";
   </script>
HTML;
?>

VirtualBox error "Failed to open a session for the virtual machine"

Something that I tried and work for me is simply you create a new virtual machine and you use the existing virtual hard disk file and everything is like you left it.

Error: the entity type requires a primary key

Yet another reason may be that your entity class has several properties named somhow /.*id/i - so ending with ID case insensitive AND elementary type AND there is no [Key] attribute.

EF will namely try to figure out the PK by itself by looking for elementary typed properties ending in ID.

See my case:

public class MyTest, IMustHaveTenant
{
  public long Id { get; set; }
  public int TenantId { get; set; }
  [MaxLength(32)]
  public virtual string Signum{ get; set; }
  public virtual string ID { get; set; }
  public virtual string ID_Other { get; set; }
}

don't ask - lecacy code. The Id was even inherited, so I could not use [Key] (just simplifying the code here)

But here EF is totally confused.

What helped was using modelbuilder this in DBContext class.

            modelBuilder.Entity<MyTest>(f =>
            {
                f.HasKey(e => e.Id);
                f.HasIndex(e => new { e.TenantId });
                f.HasIndex(e => new { e.TenantId, e.ID_Other });
            });

the index on PK is implicit.

Convert double to string C++?

You can't do it directly. There are a number of ways to do it:

  1. Use a std::stringstream:

    std::ostringstream s;
    s << "(" << c1 << ", " << c2 << ")";
    storedCorrect[count] = s.str()
    
  2. Use boost::lexical_cast:

    storedCorrect[count] = "(" + boost::lexical_cast<std::string>(c1) + ", " + boost::lexical_cast<std::string>(c2) + ")";
    
  3. Use std::snprintf:

    char buffer[256];  // make sure this is big enough!!!
    snprintf(buffer, sizeof(buffer), "(%g, %g)", c1, c2);
    storedCorrect[count] = buffer;
    

There are a number of other ways, using various double-to-string conversion functions, but these are the main ways you'll see it done.

Is there a way to @Autowire a bean that requires constructor arguments?

You can also configure your component like this :

package mypackage;
import org.springframework.context.annotation.Configuration;
   @Configuration
   public class MyConstructorClassConfig {


   @Bean
   public MyConstructorClass myConstructorClass(){
      return new myConstructorClass("foobar");
   }
  }
}

With the Bean annotation, you are telling Spring to register the returned bean in the BeanFactory.

So you can autowire it as you wish.

Xcode "Build and Archive" from command line

I have given a brief description of steps to follow, and parameters to pass while generating an ipa using terrminal below:

  1. Go to the folder which contains the MyApp.xcodeproject file in terminal

  2. By using the command given below you will get all the Targets of the application

    /usr/bin/xcodebuild -list 
    
  3. After the above command is executed, you will get a list of targets of which you should select a specific target you need to generate .ipa

    /usr/bin/xcodebuild -target $TARGET -sdk iphoneos -configuration Release
    
  4. The above command builds the project and creates a .app file.The path to locate the .app file is ./build/Release-iphoneos/MyApp.app

  5. After Build gets succeeded then execute the following command to generate .ipa of the application using Developer Name and Provisioning Profile using the syntax below:

    /usr/bin/xcrun -sdk iphoneos PackageApplication -v “${TARGET}.app” -o “${OUTDIR}/${TARGET}.ipa” –sign “${IDENTITY}” –embed “${PROVISONING_PROFILE}”
    

Explanation of each Parameter in the above syntax:

${TARGET}.app                == Target path (ex :/Users/XXXXXX/desktop/Application/build/Release-iphoneos/MyApp.app)
${OUTDIR}                    == Select the output directory(Where you want to save .ipa file)
${IDENTITY}                   == iPhone Developer: XXXXXXX (XXXXXXXXXX)(which can be obtained from Keychain access)
${PROVISONING_PROFILE}   == Path to the provisioning profile(/Users/XXXXXX/Library/MobileDevice/Provisioning Profiles/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX.mobileprovision”)
  1. ipa will be generated at selected output directory "${OUTDIR}"

How to draw a circle with given X and Y coordinates as the middle spot of the circle?

The only thing that worked for me:

g.drawOval((getWidth()-200)/2,(getHeight()-200)/2, 200, 200);    

Can you force Visual Studio to always run as an Administrator in Windows 8?

In Windows 8 & 10, you have to right-click devenv.exe and select "Troubleshoot compatibility".

  1. Select "Troubleshoot program"
  2. Check "The program requires additional permissions"
  3. Click "Next"
  4. Click "Test the program..."
  5. Wait for the program to launch
  6. Click "Next"
  7. Select "Yes, save these settings for this program"
  8. Click "Close"

If, when you open Visual Studio it asks to save changes to devenv.sln, see this answer to disable it:

Disable Visual Studio devenv solution save dialog


If you change your mind and wish to undo the "Run As Administrator" Compatibility setting, see the answer here: How to Fix Unrecognized Guid format in Visual Studio 2015

Oracle Error ORA-06512

The variable pCv is of type VARCHAR2 so when you concat the insert you aren't putting it inside single quotes:

 EXECUTE IMMEDIATE  'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('''||pCv||''', '||pSup||', '||pIdM||')';

Additionally the error ORA-06512 raise when you are trying to insert a value too large in a column. Check the definiton of the table M_pNum_GR and the parameters that you are sending. Just for clarify if you try to insert the value 100 on a NUMERIC(2) field the error will raise.

400 BAD request HTTP error code meaning?

In neither case is the "syntax malformed". It's the semantics that are wrong. Hence, IMHO a 400 is inappropriate. Instead, it would be appropriate to return a 200 along with some kind of error object such as { "error": { "message": "Unknown request keyword" } } or whatever.

Consider the client processing path(s). An error in syntax (e.g. invalid JSON) is an error in the logic of the program, in other words a bug of some sort, and should be handled accordingly, in a way similar to a 403, say; in other words, something bad has gone wrong.

An error in a parameter value, on the other hand, is an error of semantics, perhaps due to say poorly validated user input. It is not an HTTP error (although I suppose it could be a 422). The processing path would be different.

For instance, in jQuery, I would prefer not to have to write a single error handler that deals with both things like 500 and some app-specific semantic error. Other frameworks, Ember for one, also treat HTTP errors like 400s and 500s identically as big fat failures, requiring the programmer to detect what's going on and branch depending on whether it's a "real" error or not.

iOS Detection of Screenshot?

I found the answer!! Taking a screenshot interrupts any touches that are on the screen. This is why snapchat requires holding to see the picture. Reference: http://tumblr.jeremyjohnstone.com/post/38503925370/how-to-detect-screenshots-on-ios-like-snapchat

How I can check if an object is null in ruby on rails 2?

You can check if an object is nil (null) by calling present? or blank? .

@object.present?

this will return false if the project is an empty string or nil .

or you can use

@object.blank?

this is the same as present? with a bang and you can use it if you don't like 'unless'. this will return true for an empty string or nil .

Does C have a string type?

C does not support a first class string type.

C++ has std::string

Is there a way to get colored text in GitHubflavored Markdown?

You cannot include style directives in GFM.

The most complete documentation/example is "Markdown Cheatsheet", and it illustrates that this element <style> is missing.

If you manage to include your text in one of the GFM elements, then you can play with a github.css stylesheet in order to colors that way, meaning to color using inline CSS style directives, referring to said css stylesheet.

App not setup: This app is still in development mode

make sure your app is live on developer.facebook.com

This green circle is indicating the app is live enter image description here

If it is not then follow this two steps for make your app live

Step 1 Go to your application -> setting => and add Contact Email and apply save Changes

Setp 2 Then goto App Review option and make sure this toggle is Yes i added a screen shot

enter image description here

Angular ng-class if else

You can use the ternary operator notation:

<div id="homePage" ng-class="page.isSelected(1)? 'center' : 'left'">

Initialize a byte array to a certain value, other than the default null?

Just to expand on my answer a neater way of doing this multiple times would probably be:

PopulateByteArray(UserCode, 0x20);

which calls:

public static void PopulateByteArray(byte[] byteArray, byte value)
{
    for (int i = 0; i < byteArray.Length; i++)
    {
        byteArray[i] = value;
    }
}

This has the advantage of a nice efficient for loop (mention to gwiazdorrr's answer) as well as a nice neat looking call if it is being used a lot. And a lot mroe at a glance readable than the enumeration one I personally think. :)

How can I redirect a php page to another php page?

<?php  
header('Location: http://www.google.com'); //Send browser to http://www.google.com
?>  

How to search and replace text in a file?

fileinput already supports inplace editing. It redirects stdout to the file in this case:

#!/usr/bin/env python3
import fileinput

with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(text_to_search, replacement_text), end='')

How do I extract a substring from a string until the second space is encountered?

There are shorter ways of doing it like others have said, but you can also check each character until you encounter a second space yourself, then return the corresponding substring.

static string Extract(string str)
{
    bool end = false;
    int length = 0 ;
    foreach (char c in str)
    {
        if (c == ' ' && end == false)
        {
            end = true;
        }
        else if (c == ' ' && end == true)
        {
            break;
        }

        length++;
    }

    return str.Substring(0, length);
}

Python: How to check a string for substrings from a list?

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

Regular Expression to match string starting with a specific word

/stop([a-zA-Z])+/

Will match any stop word (stop, stopped, stopping, etc)

However, if you just want to match "stop" at the start of a string

/^stop/

will do :D

Using set_facts and with_items together in Ansible

Looks like this behavior is how Ansible currently works, although there is a lot of interest in fixing it to work as desired. There's currently a pull request with the desired functionality so hopefully this will get incorporated into Ansible eventually.

ffmpeg usage to encode a video to H264 codec format

I believe that by now the above answers are outdated (or at least unclear) so here's my little go at it. I tried compiling ffmpeg with the option --enable-encoders=libx264 and it will give no error but it won't enable anything (I can't seem to find where I found that suggestion).

Anyways step-by-step, first you must compile libx264 yourself because repository version is outdated:

  wget ftp://ftp.videolan.org/pub/x264/snapshots/last_x264.tar.bz2
  tar --bzip2 -xvf last_x264.tar.bz2
  cd x264-snapshot-XXXXXXXX-XXXX/
  ./configure
  make
  sudo make install

And then get and compile ffmpeg with libx264 enabled. I'm using the latest release which is "Happiness":

wget http://ffmpeg.org/releases/ffmpeg-0.11.2.tar.bz2
tar --bzip2 -xvf ffmpeg-0.11.2.tar.bz2
cd ffmpeg-0.11.2/
./configure --enable-libx264 --enable-gpl
make
sudo install

Now finally you have the libx264 codec to encode, to check it you may run

ffmpeg -codecs | grep h264

and you'll see the options you have were the first D means decoding and the first E means encoding

How to embed a PDF?

<iframe src="http://docs.google.com/gview?url=http://domain.com/pdf.pdf&embedded=true" 
style="width:600px; height:500px;" frameborder="0"></iframe>

Google docs allows you to embed PDFs, Microsoft Office Docs, and other applications by just linking to their services with an iframe. Its user-friendly, versatile, and attractive.

HTML/CSS font color vs span style

<span style="color:#ffffff; font-size:18px; line-height:35px; font-family: Calibri;">Our Activities </span>

This works for me well:) As it has been already mentioned above "The font tag has been deprecated, at least in XHTML. It always safe to use span tag. font may not give you desire results, at least in my case it didn't.

How to use activity indicator view on iPhone?

- (IBAction)toggleSpinner:(id)sender
{
    if (self.spinner.isAnimating)
    {
        [self.spinner stopAnimating];
        ((UIButton *)sender).titleLabel.text = @"Start spinning";
        [self.controlState setValue:[NSNumber numberWithBool:NO] forKey:@"SpinnerAnimatingState"];
    }
    else
    {
        [self.spinner startAnimating];
        ((UIButton *)sender).titleLabel.text = @"Stop spinning";
        [self.controlState setValue:[NSNumber numberWithBool:YES] forKey:@"SpinnerAnimatingState"];
    }
}

How to use not contains() in xpath?

I need to select every production with a category that doesn't contain "Business"

Although I upvoted @Arran's answer as correct, I would also add this... Strictly interpreted, the OP's specification would be implemented as

//production[category[not(contains(., 'Business'))]]

rather than

//production[not(contains(category, 'Business'))]

The latter selects every production whose first category child doesn't contain "Business". The two XPath expressions will behave differently when a production has no category children, or more than one.

It doesn't make any difference in practice as long as every <production> has exactly one <category> child, as in your short example XML. Whether you can always count on that being true or not, depends on various factors, such as whether you have a schema that enforces that constraint. Personally, I would go for the more robust option, since it doesn't "cost" much... assuming your requirement as stated in the question is really correct (as opposed to e.g. 'select every production that doesn't have a category that contains "Business"').

IOS - How to segue programmatically using swift

Another option is to use modal segue

STEP 1: Go to the storyboard, and give the View Controller a Storyboard ID. You can find where to change the storyboard ID in the Identity Inspector on the right. Lets call the storyboard ID ModalViewController

STEP 2: Open up the 'sender' view controller (let's call it ViewController) and add this code to it

public class ViewController {
  override func viewDidLoad() {
    showModalView()
  }

  func showModalView() {
    if let mvc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ModalViewController") as? ModalViewController {
      self.present(mvc, animated: true, completion: nil)
    }
  }
}

Note that the View Controller we want to open is also called ModalViewController

STEP 3: To close ModalViewController, add this to it

public class ModalViewController {
   @IBAction func closeThisViewController(_ sender: Any?) {
      self.presentingViewController?.dismiss(animated: true, completion: nil)
   }
}

Basic authentication with fetch?

A simple example for copy-pasting into Chrome console:

fetch('https://example.com/path', {method:'GET', 
headers: {'Authorization': 'Basic ' + btoa('login:password')}})
.then(response => response.json())
.then(json => console.log(json));

How to get all checked checkboxes

Get all the checked checkbox value in an array - one liner

_x000D_
_x000D_
const data = [...document.querySelectorAll('.inp:checked')].map(e => e.value);_x000D_
console.log(data);
_x000D_
<div class="row">_x000D_
    <input class="custom-control-input inp"type="checkbox" id="inlineCheckbox1" Checked value="option1"> _x000D_
    <label class="custom-control-label" for="inlineCheckbox1">Option1</label>_x000D_
    <input class="custom-control-input inp"  type="checkbox" id="inlineCheckbox1" value="option2"> _x000D_
    <label class="custom-control-label" for="inlineCheckbox1">Option2</label>_x000D_
    <input class="custom-control-input inp" Checked  type="checkbox" id="inlineCheckbox1" value="option3"> _x000D_
    <label class="custom-control-label" for="inlineCheckbox1">Option3</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

iPhone get SSID without private library

Here's the cleaned up ARC version, based on @elsurudo's code:

- (id)fetchSSIDInfo {
     NSArray *ifs = (__bridge_transfer NSArray *)CNCopySupportedInterfaces();
     NSLog(@"Supported interfaces: %@", ifs);
     NSDictionary *info;
     for (NSString *ifnam in ifs) {
         info = (__bridge_transfer NSDictionary *)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
         NSLog(@"%@ => %@", ifnam, info);
         if (info && [info count]) { break; }
     }
     return info;
}

How to write a:hover in inline CSS?

As pointed out, you cannot set arbitrary inline styles for hover, but you can change the style of the hover cursor in CSS using the following in the appropriate tag:

style="cursor: pointer;"

How to run JUnit test cases from the command line

Personally I would use the Maven surefire JUnit runner to do that.

How to select last two characters of a string

Try this, note that you don't need to specify the end index in substring.

var characters = member.substr(member.length -2);

What does it mean "No Launcher activity found!"

Do you have an activity set up the be the launched activity when the application starts?

This is done in your Manifest.xml file, something like:

    <activity android:name=".Main" android:label="@string/app_name"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications?

You can easily install it by writing

Install-Package AjaxControlToolkit in package manager console.

for more information you can check this link

How can I clear the terminal in Visual Studio Code?

I am using Visual Studio Code 1.52.1 on windows 10 machine.'cls' or 'Clear' doesn't clear the terminal.

just write

exit

It will close the terminal and press

ctrl+shift+`

to open new terminal.

Trim a string based on the string length

StringUtils.abbreviate from Apache Commons Lang library could be your friend:

StringUtils.abbreviate("abcdefg", 6) = "abc..."
StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
StringUtils.abbreviate("abcdefg", 4) = "a..."

Commons Lang3 even allow to set a custom String as replacement marker. With this you can for example set a single character ellipsis.

StringUtils.abbreviate("abcdefg", "\u2026", 6) = "abcde…"

How to make HTTP Post request with JSON body in Swift

Try this,

// prepare json data
let json: [String: Any] = ["title": "ABC",
                           "dict": ["1":"First", "2":"Second"]]

let jsonData = try? JSONSerialization.data(withJSONObject: json)

// create post request
let url = URL(string: "http://httpbin.org/post")!
var request = URLRequest(url: url)
request.httpMethod = "POST"

// insert json data to the request
request.httpBody = jsonData

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print(error?.localizedDescription ?? "No data")
        return
    }
    let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
    if let responseJSON = responseJSON as? [String: Any] {
        print(responseJSON)
    }
}

task.resume()

or try a convenient way Alamofire

How to filter a data frame

You are missing a comma in your statement.

Try this:

data[data[, "Var1"]>10, ]

Or:

data[data$Var1>10, ]

Or:

subset(data, Var1>10)

As an example, try it on the built-in dataset, mtcars

data(mtcars)

mtcars[mtcars[, "mpg"]>25, ]

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2


mtcars[mtcars$mpg>25, ]

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

subset(mtcars, mpg>25)

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

How to pretty print XML from the command line?

xmllint --format yourxmlfile.xml

xmllint is a command line XML tool and is included in libxml2 (http://xmlsoft.org/).

================================================

Note: If you don't have libxml2 installed you can install it by doing the following:

CentOS

cd /tmp
wget ftp://xmlsoft.org/libxml2/libxml2-2.8.0.tar.gz
tar xzf libxml2-2.8.0.tar.gz
cd libxml2-2.8.0/
./configure
make
sudo make install
cd

Ubuntu

sudo apt-get install libxml2-utils

Cygwin

apt-cyg install libxml2

MacOS

To install this on MacOS with Homebrew just do: brew install libxml2

Git

Also available on Git if you want the code: git clone git://git.gnome.org/libxml2

Split text with '\r\n'

This worked for me.

using System.IO;

//  

    string readStr = File.ReadAllText(file.FullName);          
    string[] read = readStr.Split(new char[] {'\r','\n'},StringSplitOptions.RemoveEmptyEntries);

Howto: Clean a mysql InnoDB storage engine?

The InnoDB engine does not store deleted data. As you insert and delete rows, unused space is left allocated within the InnoDB storage files. Over time, the overall space will not decrease, but over time the 'deleted and freed' space will be automatically reused by the DB server.

You can further tune and manage the space used by the engine through an manual re-org of the tables. To do this, dump the data in the affected tables using mysqldump, drop the tables, restart the mysql service, and then recreate the tables from the dump files.

How to specify jackson to only use fields - preferably globally

You can configure individual ObjectMappers like this:

ObjectMapper mapper  = new ObjectMapper();
mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
                .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));

If you want it set globally, I usually access a configured mapper through a wrapper class.

How to check if input is numeric in C++

When cin gets input it can't use, it sets failbit:

int n;
cin >> n;
if(!cin) // or if(cin.fail())
{
    // user didn't input a number
    cin.clear(); // reset failbit
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //skip bad input
    // next, request user reinput
}

When cin's failbit is set, use cin.clear() to reset the state of the stream, then cin.ignore() to expunge the remaining input, and then request that the user re-input. The stream will misbehave so long as the failure state is set and the stream contains bad input.

C pass int array pointer as parameter into a function

main()
{
    int *arr[5];
    int i=31, j=5, k=19, l=71, m;

    arr[0]=&i;
    arr[1]=&j;
    arr[2]=&k;
    arr[3]=&l;
    arr[4]=&m;

    for(m=0; m<=4; m++)
    {
        printf("%d",*(arr[m]));
    }
    return 0;
}

How can I join multiple SQL tables using the IDs?

You have not joined TableD, merely selected the TableD FIELD (dID) from one of the tables.

Get class labels from Keras functional model

It is possible to save a "list" of labels in keras model directly. This way the user who uses the model for predictions and does not have any other sources of information can perform the lookup himself. Here is a dummy example of how one can perform an "injection" of labels

# assume we get labels as list
labels = ["cat","dog","horse","tomato"]
# here we start building our model with input image 299x299 and one output layer
xx = Input(shape=(299,299,3))
flat = Flatten()(xx)
output = Dense(shape=(4))(flat)
# here we perform injection of labels
tf_labels = tf.constant([labels],dtype="string")
tf_labels = tf.tile(labels,[tf.shape(xx)[0],1])
output_labels = Lambda(lambda x: tf_labels,name="label_injection")(xx)
#and finaly creating a model
model=tf.keras.Model(xx,[output,output_labels])

When used for prediction, this model returns tensor of scores and tensot of string labels. Model like this can be saved to h5. In this case the file contains the labels. This model can also be exported to saved_model and used for serving in the cloud.

What is the difference between SQL and MySQL?

SQL is the actual language that as defined by the ISO and ANSI. Here is a link to the Wikipedia article. MySQL is a specific implementation of this standard. I believe Oracle bought the company that originally developed MySQL. Other companies also have their own implementations of the SQL standard.

send/post xml file using curl command line

With Jenkins 1.494, I was able to send a file to a job parameter on Ubuntu Linux 12.10 using curl with --form parameters:

curl --form name=myfileparam --form file=@/local/path/to/your/file.xml \
  -Fjson='{"parameter": {"name": "myfileparam", "file": "file"}}' \
  -Fsubmit=Build \
  http://user:password@jenkinsserver/job/jobname/build

On the Jenkins server, I configured a job that accepts a single parameter: a file upload parameter named myfileparam.

The first line of that curl call constructs a web form with a parameter named myfileparam (same as in the job); its value will be the contents of a file on the local file system named /local/path/to/your/file.txt. The @ symbol prefix tells curl to send a local file instead of the given filename.

The second line defines a JSON request that matches the form parameters on line one: a file parameter named myfileparam.

The third line activates the form's Build button. The forth line is the job URL with the "/build" suffix.

If this call is successful, curl returns 0. If it is unsuccessful, the error or exception from the service is printed to the console. This answer takes a lot from an old blog post relating to Hudson, which I deconstructed and re-worked for my own needs.

AngularJS: Basic example to use authentication in Single Page Application

I like the approach and implemented it on server-side without doing any authentication related thing on front-end

My 'technique' on my latest app is.. the client doesn't care about Auth. Every single thing in the app requires a login first, so the server just always serves a login page unless an existing user is detected in the session. If session.user is found, the server just sends index.html. Bam :-o

Look for the comment by "Andrew Joslin".

https://groups.google.com/forum/?fromgroups=#!searchin/angular/authentication/angular/POXLTi_JUgg/VwStpoWCPUQJ

SELECT query with CASE condition and SUM()

Use an "Or"

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where (CPaymentType='Check' Or CPaymentType='Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

or an "IN"

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where CPaymentType IN ('Check', 'Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

When to use LinkedList over ArrayList in Java?

If your code has add(0) and remove(0), use a LinkedList and it's prettier addFirst() and removeFirst() methods. Otherwise, use ArrayList.

And of course, Guava's ImmutableList is your best friend.

Error in plot.new() : figure margins too large, Scatter plot

Just run graphics.off() before plotting your data. This instruction solved my error. So, it's harmless to try it before taking a more complex solution.

How to show DatePickerDialog on Button click?

enter image description here

I. In your build.gradle add latest appcompat library, at the time 24.2.1

dependencies {  
    compile 'com.android.support:appcompat-v7:X.X.X' 
    // where X.X.X version
}

II. Make your activity extend android.support.v7.app.AppCompatActivity and implement the DatePickerDialog.OnDateSetListener interface.

public class MainActivity extends AppCompatActivity  
    implements DatePickerDialog.OnDateSetListener {

III. Create your DatePickerDialog setting a context, the implementation of the listener and the start year, month and day of the date picker.

DatePickerDialog datePickerDialog = new DatePickerDialog(  
    context, MainActivity.this, startYear, starthMonth, startDay);

IV. Show your dialog on the click event listener of your button

((Button) findViewById(R.id.myButton))
    .setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        datePickerDialog.show();
    }
});

Android Studio: Default project directory

This may be what you want. Settings -> Appearance & Behavior -> System Settings > Project Opening > Default Directory

  1. Open 'Preferences'
  2. Select System Settings -> Project Opening
  3. Set 'Default Directory' where you want.

It worked for me. I tried Android Studio 3.5.

Difference between git stash pop and git stash apply

Assuming there will be no errors thrown, and you want to work on the top stash item in the list of available stashes:

git stash pop = git stash apply + git stash drop

How to decode encrypted wordpress admin password?

You can't easily decrypt the password from the hash string that you see. You should rather replace the hash string with a new one from a password that you do know.

There's a good howto here:

https://jakebillo.com/wordpress-phpass-generator-resetting-or-creating-a-new-admin-user/

Basically:

  1. generate a new hash from a known password using e.g. http://scriptserver.mainframe8.com/wordpress_password_hasher.php, as described in the above link, or any other product that uses the phpass library,
  2. use your DB interface (e.g. phpMyAdmin) to update the user_pass field with the new hash string.

If you have more users in this WordPress installation, you can also copy the hash string from one user whose password you know, to the other user (admin).

How to delete an item in a list if it exists?

Here's another one-liner approach to throw out there:

next((some_list.pop(i) for i, l in enumerate(some_list) if l == thing), None)

It doesn't create a list copy, doesn't make multiple passes through the list, doesn't require additional exception handling, and returns the matched object or None if there isn't a match. Only issue is that it makes for a long statement.

In general, when looking for a one-liner solution that doesn't throw exceptions, next() is the way to go, since it's one of the few Python functions that supports a default argument.

Calling a class method raises a TypeError in Python

From your example, it seems to me you want to use a static method.

class mystuff:
  @staticmethod
  def average(a,b,c): #get the average of three numbers
    result=a+b+c
    result=result/3
    return result

print mystuff.average(9,18,27)

Please note that an heavy usage of static methods in python is usually a symptom of some bad smell - if you really need functions, then declare them directly on module level.

How to preSelect an html dropdown list with php?

<select>
<option value="1" <?php if ($myVar==1) echo 'selected="selected"';?>>Yes</options>
<option value="2" <?php if ($myVar==2) echo 'selected="selected"';?>>No</options>
<option value="3" <?php if ($myVar==3) echo 'selected="selected"';?>>Fine</options>
</select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">

This is a very simple and straightforward way, if I understand your question correctly.

How to get correct timestamp in C#

var timestamp = DateTime.Now.ToFileTime();

//output: 132260149842749745

This is an alternative way to individuate distinct transactions. It's not unix time, but windows filetime.

From the docs:

A Windows file time is a 64-bit value that represents the number of 100- 
nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 
A.D. (C.E.) Coordinated Universal Time (UTC).

How to get a thread and heap dump of a Java process on Windows that's not running in a console

You could run jconsole (included with Java 6's SDK) then connect to your Java application. It will show you every Thread running and its stack trace.

Calculating days between two dates with Java

The best way, and it converts to a String as bonus ;)

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try {
        //Dates to compare
        String CurrentDate=  "09/24/2015";
        String FinalDate=  "09/26/2015";

        Date date1;
        Date date2;

        SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");

        //Setting dates
        date1 = dates.parse(CurrentDate);
        date2 = dates.parse(FinalDate);

        //Comparing dates
        long difference = Math.abs(date1.getTime() - date2.getTime());
        long differenceDates = difference / (24 * 60 * 60 * 1000);

        //Convert long to String
        String dayDifference = Long.toString(differenceDates);

        Log.e("HERE","HERE: " + dayDifference);
    }
    catch (Exception exception) {
        Log.e("DIDN'T WORK", "exception " + exception);
    }
}

Display HTML snippets in HTML

This is how I did it:

$str = file_get_contents("my-code-file.php");
echo "<textarea disabled='true' style='border: none;background-color:white;'>";
echo $str;
echo "</textarea>";

How to include another XHTML in XHTML using JSF 2.0 Facelets?

Included page:

<!-- opening and closing tags of included page -->
<ui:composition ...>
</ui:composition>

Including page:

<!--the inclusion line in the including page with the content-->
<ui:include src="yourFile.xhtml"/>
  • You start your included xhtml file with ui:composition as shown above.
  • You include that file with ui:include in the including xhtml file as also shown above.

a page can have only one server-side form tag

It sounds like you have a form tag in a Master Page and in the Page that is throwing the error.

You can have only one.

Checking version of angular-cli that's installed?

Go to your folder path in cmd where your angular is installed and type ng --version it will show your angular version. Thanks.

Getting "conflicting types for function" in C, why?

You have to declare the function before you use it. If the function name appears before its declaration, C compiler will follow certain rules and makes the declaration itself. If it is wrong, you will get that error.

You have two options: (1) define it before you use it, or (2) use forward declaration without implementation. For example:

char *do_something(char *dest, const char *src);

Note the semicolon at the end.

In Java, remove empty elements from a list of Strings

If you are using Java 8 then try this using lambda expression and org.apache.commons.lang.StringUtils, that will also clear null and blank values from array input

public static String[] cleanArray(String[] array) {
    return Arrays.stream(array).filter(x -> !StringUtils.isBlank(x)).toArray(String[]::new);
}

ref - https://stackoverflow.com/a/41935895/9696526

Simulate user input in bash script

You should find the 'expect' command will do what you need it to do. Its widely available. See here for an example : http://www.thegeekstuff.com/2010/10/expect-examples/

(very rough example)

#!/usr/bin/expect
set pass "mysecret"

spawn /usr/bin/passwd

expect "password: "
send "$pass"
expect "password: "
send "$pass"

python requests file upload

If upload_file is meant to be the file, use:

files = {'upload_file': open('file.txt','rb')}
values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'}

r = requests.post(url, files=files, data=values)

and requests will send a multi-part form POST body with the upload_file field set to the contents of the file.txt file.

The filename will be included in the mime header for the specific field:

>>> import requests
>>> open('file.txt', 'wb')  # create an empty demo file
<_io.BufferedWriter name='file.txt'>
>>> files = {'upload_file': open('file.txt', 'rb')}
>>> print(requests.Request('POST', 'http://example.com', files=files).prepare().body.decode('ascii'))
--c226ce13d09842658ffbd31e0563c6bd
Content-Disposition: form-data; name="upload_file"; filename="file.txt"


--c226ce13d09842658ffbd31e0563c6bd--

Note the filename="file.txt" parameter.

You can use a tuple for the files mapping value, with between 2 and 4 elements, if you need more control. The first element is the filename, followed by the contents, and an optional content-type header value and an optional mapping of additional headers:

files = {'upload_file': ('foobar.txt', open('file.txt','rb'), 'text/x-spam')}

This sets an alternative filename and content type, leaving out the optional headers.

If you are meaning the whole POST body to be taken from a file (with no other fields specified), then don't use the files parameter, just post the file directly as data. You then may want to set a Content-Type header too, as none will be set otherwise. See Python requests - POST data from a file.

How to list files in an android directory?

In order to access the files, the permissions must be given in the manifest file.

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

Try this:

String path = Environment.getExternalStorageDirectory().toString()+"/Pictures";
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
    Log.d("Files", "FileName:" + files[i].getName());
}

In C#, should I use string.Empty or String.Empty or "" to intitialize a string?

string is synonym for System.String type, They are identical.

Values are also identical: string.Empty == String.Empty == ""

I would not use character constant "" in code, rather string.Empty or String.Empty - easier to see what programmer meant.

Between string and String I like lower case string more just because I used to work with Delphi for lot of years and Delphi style is lowercase string.

So, if I was your boss, you would be writing string.Empty

Pagination on a list using ng-repeat

I know this thread is old now but I am answering it to keep things a bit updated.

With Angular 1.4 and above you can directly use limitTo filter which apart from accepting the limit parameter also accepts a begin parameter.

Usage: {{ limitTo_expression | limitTo : limit : begin}}

So now you may not need to use any third party library to achieve something like pagination. I have created a fiddle to illustrate the same.

How to fix java.net.SocketException: Broken pipe?

I noticed I was using the incorrect HTTP request url while making it, later which i changed that it resolved my problem. my upload url was : http://192.168.0.31:5000/uploader while i was using http://192.168.0.31:5000. that was a get call. and got a java.net.SocketException: Broken pipe? exception.

That was my reason. might lead you to check one more point when this issue

  public void postRequest()  {


        Security.insertProviderAt(Conscrypt.newProvider(), 1);

        System.out.println("mediafilename-->>" + mediaFileName);
        String[] dirarray = mediaFileName.split("/");
        String file_name = dirarray[6];
        //Thread.sleep(10000);

        RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file",file_name, RequestBody.create(MediaType.parse("video/mp4"), new File(mediaFileName))).build();
        OkHttpClient okHttpClient = new OkHttpClient();
//        ExecutorService executor = newFixedThreadPool(20);
//        Request request = new Request.Builder().post(requestBody).url("https://192.168.0.31:5000/uploader").build();
        Request request = new Request.Builder().url("http://192.168.0.31:5000/uploader").post(requestBody).build();
//        Request request = new Request.Builder().url("http://192.168.0.31:5000").build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

//

                call.cancel();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),"Something went wrong:" + " ", Toast.LENGTH_SHORT).show();

                    }
                });
                e.printStackTrace();

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {


                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        try {
                            System.out.println(response.body().string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });


                System.out.println("Response ; " + response.body().toString());
//                Toast.makeText(getApplicationContext(), response.body().toString(),Toast.LENGTH_LONG).show();
                System.out.println(response);

            }
        });

Required attribute HTML5

Safari 7.0.5 still does not support notification for validation of input fields.

To overcome it is possible to write fallback script like this: http://codepen.io/ashblue/pen/KyvmA

To see what HTML5 / CSS3 features are supported by browsers check: http://caniuse.com/form-validation

function hasHtml5Validation () {
  //Check if validation supported && not safari
  return (typeof document.createElement('input').checkValidity === 'function') && 
    !(navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0);
}

$('form').submit(function(){
    if(!hasHtml5Validation())
    {
        var isValid = true;
        var $inputs = $(this).find('[required]');
        $inputs.each(function(){
            var $input = $(this);
            $input.removeClass('invalid');
            if(!$.trim($input.val()).length)
            {
                isValid = false;
                $input.addClass('invalid');                 
            }
        });
        if(!isValid)
        {
            return false;
        }
    }
});

SASS / LESS:

input, select, textarea {
    @include appearance(none);
    border-radius: 0px;

    &.invalid {
        border-color: red !important;
    }
}

Plotting multiple curves same graph and same scale

points or lines comes handy if

  • y2 is generated later, or
  • the new data does not have the same x but still should go into the same coordinate system.

As your ys share the same x, you can also use matplot:

matplot (x, cbind (y1, y2), pch = 19)

matplot (x, cbind (y1, y2), pch = 19)

(without the pch matplopt will plot the column numbers of the y matrix instead of dots).

Sorting options elements alphabetically using jQuery

Accepted answer is not the best in all cases because sometimes you want to perserve classes of options and different arguments (for example data-foo).

My solution is:

var sel = $('#select_id');
var selected = sel.val(); // cache selected value, before reordering
var opts_list = sel.find('option');
opts_list.sort(function(a, b) { return $(a).text() > $(b).text() ? 1 : -1; });
sel.html('').append(opts_list);
sel.val(selected); // set cached selected value

//For ie11 or those who get a blank options, replace html('') empty()

How to sign an android apk file

APK Signing Process

To manually sign an Android APK file run these three commands:

  1. Generate Keystore file

    keytool -genkey -v -keystore YOUR_KEYSTORE_NAME.keystore -alias ALIAS_NAME -keyalg RSA -keysize 2048 -validity 10000
    
  2. Sign Your APK file using jarsigner

    jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore KEYSTORE_FILE_PATH UNSIGNED_APK_PATH ALIAS_NAME
    
  3. Align Signed APK using zipalign tool

    zipalign -v 4 JARSIGNED_APK_FILE_PATH ZIPALIGNED_SIGNED_APK_FILE_PATH
    

STEP 1


Generate Keystore file

keytool -genkey -v -keystore YOUR_KEYSTORE_NAME.keystore -alias ALIAS_NAME -keyalg RSA -keysize 2048 -validity 10000

Example:

keytool -genkey -v -keystore id.keystore -alias MySignedApp -keyalg RSA -keysize 2048 -validity 10000

keystore password : yourApp@123 key password : yourApp@123

CMD O/P

D:\ru\SignedBuilds\MySignedApp>keytool -genkey -v -keystore id.keystore
 -alias MySignedApp -keyalg RSA -keysize 2048 -validity 10000
Enter keystore password:
Re-enter new password:
What is your first and last name?
  [Unknown]:  MySignedApp Sample
What is the name of your organizational unit?
  [Unknown]:  Information Technology
What is the name of your organization?
  [Unknown]:  MySignedApp Demo
What is the name of your City or Locality?
  [Unknown]:  Mumbai
What is the name of your State or Province?
  [Unknown]:  Maharashtra
What is the two-letter country code for this unit?
  [Unknown]:  IN
Is CN=MySignedApp Demo, OU=Information Technology, O=MySignedApp Demo, L=Mumbai, ST=Maharashtra, C=IN corr
ect?
  [no]:  y

Generating 2,048 bit RSA key pair and self-signed certificate (SHA256withRSA) with a validity of 10,
000 days
        for: CN=MySignedApp Demo, OU=Information Technology, O=MySignedApp Demo, L=Mumbai, ST=Maharashtra,
 C=IN
Enter key password for <MySignedApp>
        (RETURN if same as keystore password):
Re-enter new password:
[Storing id.keystore]

D:\ru\SignedBuilds\MySignedApp>

STEP 2


Sign your app with your private keystore using jarsigner

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore KEYSTORE_FILE_PATH UNSIGNED_APK_PATH ALIAS_NAME

Example

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore D:\ru\SignedBuilds\MySignedApp\id.keystore D:\ru\SignedBuilds\MySignedApp\MySignedAppS1-release-unsigned.apk id

CMD O/P

D:\ru\SignedBuilds\MySignedApp>jarsigner -verbose -sigalg SHA1withRSA -
digestalg SHA1 -keystore D:\ru\SignedBuilds\MySignedApp\id.keystore D:\ru\SignedBuilds\MySignedApp\MySignedAppS1-release-unsigned.apk id ---
ect
Enter Passphrase for keystore:
   adding: META-INF/MANIFEST.MF
   adding: META-INF/---.SF
   adding: META-INF/---.RSA
  signing: AndroidManifest.xml
  ..... 
    signing: classes.dex
  signing: lib/commons-codec-1.6.jar
  signing: lib/armeabi/libkonyjsvm.so
jar signed.

Warning:
No -tsa or -tsacert is provided and this jar is not timestamped. Without a timestamp, users may not
be able to validate this jar after the signer certificate's expiration date (2044-02-07) or after an
y future revocation date.

D:\ru\SignedBuilds\MySignedApp>

Verify that your APK is signed

jarsigner -verify -verbose -certs JARSIGNED_APK_FILE_PATH

Example

jarsigner -verify -verbose -certs MySignedAppS1-release-unsigned.apk

CMD O/P

D:\ru\SignedBuilds\MySignedApp>jarsigner -verify -verbose -certs MySignedAppS1-release-unsigned.apk
 s = signature was verified
  m = entry is listed in manifest
  k = at least one certificate was found in keystore
  i = at least one certificate was found in identity scope

jar verified.

Warning:
This jar contains entries whose certificate chain is not validated.
This jar contains signatures that does not include a timestamp. Without a timestamp, users may not b
e able to validate this jar after the signer certificate's expiration date (2044-02-09) or after any
 future revocation date.

D:\ru\SignedBuilds\MySignedApp>

STEP 3


Align the final APK package using zipalign

zipalign -v 4 JARSIGNED_APK_FILE_PATH ZIPALIGNED_SIGNED_APK_FILE_PATH_WITH_NAME_ofSignedAPK

Example

zipalign -v 4 D:\ru\SignedBuilds\MySignedApp\MySignedAppS1-release-unsigned.apk D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk

CMD O/P

D:\Android\android-sdk\build-tools\19.1.0>zipalign -v 4 D:\ru\ru_doc\Signed_apk\MySignedApp\28.09.16
_prod_playstore\MySignedAppS1-release-unsigned.apk D:\ru\ru_doc\Signed_apk\MySignedApp\28.09.16_prod
_playstore\MySignedApp.apk
Verifying alignment of D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk (
4)...

  4528613 classes.dex (OK - compressed)
 5656594 lib/commons-codec-1.6.jar (OK - compressed)
 5841869 lib/armeabi/libkonyjsvm.so (OK - compressed)
Verification succesful

D:\Android\android-sdk\build-tools\19.1.0>

Verify that your APK is Aligned successfully

zipalign -c -v 4 YOUR_APK_PATH

Example

zipalign -c -v 4 D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk

CMD O/P

D:\Android\android-sdk\build-tools\19.1.0>zipalign -c -v 4 D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk
Verifying alignment of D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk (
4)...

 4453984 res/drawable/zoomout.png (OK)
 4454772 res/layout/tabview.xml (OK - compressed)
 4455243 res/layout/wheel_item.xml (OK - compressed)
 4455608 resources.arsc (OK)
 4470161 classes.dex (OK - compressed)
 5597923 lib/commons-codec-1.6.jar (OK - compressed)
 5783198 lib/armeabi/libkonyjsvm.so (OK - compressed)
Verification succesful

D:\Android\android-sdk\build-tools\19.1.0>

Note:

The verify command is just to check whether APK is built and signed correctly!

References

I hope this will help one and all :)

state machines tutorials

State machines can be very complex for a complex problem. They are also subject to unexpected bugs. They can turn into a nightmare if someone runs into a bug or needs to change the logic in the future. They are also difficult to follow and debug without the state diagram. Structured programming is much better (for example you would probably not use a state machine at mainline level). You can use structured programming even in interrupt context (which is where state machines are usually used). See this article "Macros to simulate multi-tasking/blocking code at interrupt level" found at codeproject.com.

Parcelable encountered IOException writing serializable object getactivity()

the Grade class must also implement Serializable

public class Grade implements Serializable {
.....your content....
}

How can I remove a key and its value from an associative array?

Consider this array:

$arr = array("key1" => "value1", "key2" => "value2", "key3" => "value3", "key4" => "value4");
  • To remove an element using the array key:

    // To unset an element from array using Key:
    unset($arr["key2"]);
    var_dump($arr);
    // output: array(3) { ["key1"]=> string(6) "value1" ["key3"]=> string(6) "value3" ["key4"]=> string(6) "value4" }
    
  • To remove element by value:

    // remove an element by value:
    $arr = array_diff($arr, ["value1"]);
    var_dump($arr);
    // output: array(2) { ["key3"]=> string(6) "value3" ["key4"]=> string(6) "value4" } 
    

read more about array_diff: http://php.net/manual/en/function.array-diff.php

  • To remove an element by using index:

    array_splice($arr, 1, 1);
    var_dump($arr);
    // array(1) { ["key3"]=> string(6) "value3" } 
    

read more about array_splice: http://php.net/manual/en/function.array-splice.php

How can I check if a value is a json object?

The chosen solution doesn't actually work for me because I get a

     "Unexpected Token <" 

error in Chrome. This is because the error is thrown as soon as the parse comes across and unknown character. However, there is a way around this if you are returning only string values through ajax (which can be fairly useful if you are using PHP or ASPX to process ajax requests and might or might not return JSON depending on conditions)

The solution is quite simple, you can do the following to check if it was a valid JSON return

       var IS_JSON = true;
       try
       {
               var json = $.parseJSON(msg);
       }
       catch(err)
       {
               IS_JSON = false;
       }                

As I have said before, this is the solution for if you are either returning string type stuff from your AJAX request or if you are returning mixed type.

ProgressDialog spinning circle

I was using View.INVISIBLE and View.VISIBLE and the ProgressBar would slowly flash instead of constantly being visible, switched to View.GONE and View.VISIBLE and it works perfectly

What is the best method to merge two PHP objects?

a solution To preserve,both methods and properties from merged onjects is to create a combinator class that can

  • take any number of objects on __construct
  • access any method using __call
  • accsess any property using __get

class combinator{
function __construct(){       
    $this->melt =  array_reverse(func_get_args());
      // array_reverse is to replicate natural overide
}
public function __call($method,$args){
    forEach($this->melt as $o){
        if(method_exists($o, $method)){
            return call_user_func_array([$o,$method], $args);
            //return $o->$method($args);
            }
        }
    }
public function __get($prop){
        foreach($this->melt as $o){
          if(isset($o->$prop))return $o->$prop;
        }
        return 'undefined';
    } 
}

simple use

class c1{
    public $pc1='pc1';
    function mc1($a,$b){echo __METHOD__." ".($a+$b);}
}
class c2{
    public $pc2='pc2';
    function mc2(){echo __CLASS__." ".__METHOD__;}
}

$comb=new combinator(new c1, new c2);

$comb->mc1(1,2);
$comb->non_existing_method();  //  silent
echo $comb->pc2;

How to use su command over adb shell?

On my Linux I see an error with

adb shell "su -c '[your command goes here]'"

su: invalid uid/gid '-c'

The solution is on Linux

adb shell su 0 '[your command goes here]'

Replace all non-alphanumeric characters in a string

Regex to the rescue!

import re

s = re.sub('[^0-9a-zA-Z]+', '*', s)

Example:

>>> re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')
'h*ell*o*w*orld'

How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#?

I was able to figure it out. In case someone wants to know below the code that worked for me:

ASCIIEncoding ascii = new ASCIIEncoding();
byte[] byteArray = Encoding.UTF8.GetBytes(sOriginal);
byte[] asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray);
string finalString = ascii.GetString(asciiArray);

Let me know if there is a simpler way o doing it.

How to use Python to login to a webpage and retrieve cookies for later usage?

import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()

resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.

add string to String array

As many of the answer suggesting better solution is to use ArrayList. ArrayList size is not fixed and it is easily manageable.

It is resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.

Note that this implementation is not synchronized.

ArrayList<String> scripts = new ArrayList<String>();
scripts.add("test1");
scripts.add("test2");
scripts.add("test3");

Lazy Loading vs Eager Loading

Lazy loading - is good when handling with pagination like on page load list of users appear which contains 10 users and as the user scrolls down the page an api call brings next 10 users.Its good when you don't want to load enitire data at once as it would take more time and would give bad user experience.

Eager loading - is good as other people suggested when there are not much relations and fetch entire data at once in single call to database

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

This happened to me when I was debugging my C# WinForms application in Visual Studio. My application makes calls to Win32 stuff via DllImport, e.g.

[DllImport("Secur32.dll", SetLastError = false)]
private static extern uint LsaEnumerateLogonSessions(out UInt64 LogonSessionCount, out IntPtr LogonSessionList);

Running Visual Studio "as Administrator" solved the problem for me.

Proper way to wait for one function to finish before continuing?

Use async/await :

async function firstFunction(){
  for(i=0;i<x;i++){
    // do something
  }
  return;
};

then use await in your other function to wait for it to return:

async function secondFunction(){
  await firstFunction();
  // now wait for firstFunction to finish...
  // do something else
};

Regular Expression For Duplicate Words

The widely-used PCRE library can handle such situations (you won't achieve the the same with POSIX-compliant regex engines, though):

(\b\w+\b)\W+\1

How do you develop Java Servlets using Eclipse?

I use Eclipse Java EE edition

Create a "Dynamic Web Project"

Install a local server in the server view, for the version of Tomcat I'm using. Then debug, and run on that server for testing.

When I deploy I export the project to a war file.

javac option to compile all java files under a given directory recursively

I would also suggest using some kind of build tool (Ant or Maven, Ant is already suggested and is easier to start with) or an IDE that handles the compilation (Eclipse uses incremental compilation with reconciling strategy, and you don't even have to care to press any "Compile" buttons).

Using Javac

If you need to try something out for a larger project and don't have any proper build tools nearby, you can always use a small trick that javac offers: the classnames to compile can be specified in a file. You simply have to pass the name of the file to javac with the @ prefix.

If you can create a list of all the *.java files in your project, it's easy:

# Linux / MacOS
$ find -name "*.java" > sources.txt
$ javac @sources.txt

:: Windows
> dir /s /B *.java > sources.txt
> javac @sources.txt
  • The advantage is that is is a quick and easy solution.
  • The drawback is that you have to regenerate the sources.txt file each time you create a new source or rename an existing one file which is an easy to forget (thus error-prone) and tiresome task.

Using a build tool

On the long run it is better to use a tool that was designed to build software.

Using Ant

If you create a simple build.xml file that describes how to build the software:

<project default="compile">
    <target name="compile">
        <mkdir dir="bin"/>
        <javac srcdir="src" destdir="bin"/>
    </target>
</project>

you can compile the whole software by running the following command:

$ ant
  • The advantage is that you are using a standard build tool that is easy to extend.
  • The drawback is that you have to download, set up and learn an additional tool. Note that most of the IDEs (like NetBeans and Eclipse) offer great support for writing build files so you don't have to download anything in this case.

Using Maven

Maven is not that trivial to set up and work with, but learning it pays well. Here's a great tutorial to start a project within 5 minutes.

  • It's main advantage (for me) is that it handles dependencies too, so you won't need to download any more Jar files and manage them by hand and I found it more useful for building, packaging and testing larger projects.
  • The drawback is that it has a steep learning curve, and if Maven plugins like to suppress errors :-) Another thing is that quite a lot of tools also operate with Maven repositories (like Sbt for Scala, Ivy for Ant, Graddle for Groovy).

Using an IDE

Now that what could boost your development productivity. There are a few open source alternatives (like Eclipse and NetBeans, I prefer the former) and even commercial ones (like IntelliJ) which are quite popular and powerful.

They can manage the project building in the background so you don't have to deal with all the command line stuff. However, it always comes handy if you know what actually happens in the background so you can hunt down occasional errors like a ClassNotFoundException.

One additional note

For larger projects, it is always advised to use an IDE and a build tool. The former boosts your productivity, while the latter makes it possible to use different IDEs with the project (e.g., Maven can generate Eclipse project descriptors with a simple mvn eclipse:eclipse command). Moreover, having a project that can be tested/built with a single line command is easy to introduce to new colleagues and into a continuous integration server for example. Piece of cake :-)

How to order by with union in SQL?

Just write

Select id,name,age
From Student
Where age < 15
Union
Select id,name,age
From Student
Where Name like "%a%"
Order by name

the order by is applied to the complete resultset

Using port number in Windows host file

-You can use any free address in the network 127.0.0.0/8 , in my case needed this for python flask and this is what I have done : add this line in the hosts file (you can find it is windows under : C:\Windows\System32\drivers\etc ) :

127.0.0.5 flask.dev
  • Make sure the port is the default port "80" in my case this is what in the python flask: app.run("127.0.0.5","80")

  • now run your code and browse flask.dev

How to find NSDocumentDirectory in Swift?

Usually I prefer to use this extension:

Swift 3.x and Swift 4.0:

extension FileManager {
    class func documentsDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as [String]
        return paths[0]
    }
    
    class func cachesDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) as [String]
        return paths[0]
    }
}

Swift 2.x:

extension NSFileManager {
    class func documentsDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as [String]
        return paths[0]
    }
    
    class func cachesDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true) as [String]
        return paths[0]
    }
}

Material Design not styling alert dialogs

Material Design styling alert dialogs: Custom Font, Button, Color & shape,..

 MaterialAlertDialogBuilder(requireContext(),
                R.style.MyAlertDialogTheme
            )
                .setIcon(R.drawable.ic_dialogs_24px)
                .setTitle("Feedback")
                //.setView(R.layout.edit_text)
                .setMessage("Do you have any additional comments?")
                .setPositiveButton("Send") { dialog, _ ->

                    val input =
                        (dialog as AlertDialog).findViewById<TextView>(
                            android.R.id.text1
                        )
                    Toast.makeText(context, input!!.text, Toast.LENGTH_LONG).show()

                }
                .setNegativeButton("Cancel") { _, _ ->
                    Toast.makeText(requireContext(), "Clicked cancel", Toast.LENGTH_SHORT).show()
                }
                .show()

Style:

  <style name="MyAlertDialogTheme" parent="Theme.MaterialComponents.DayNight.Dialog.Alert">
  
        <item name="android:textAppearanceSmall">@style/MyTextAppearance</item>
        <item name="android:textAppearanceMedium">@style/MyTextAppearance</item>
        <item name="android:textAppearanceLarge">@style/MyTextAppearance</item>

        <item name="buttonBarPositiveButtonStyle">@style/Alert.Button.Positive</item>
        <item name="buttonBarNegativeButtonStyle">@style/Alert.Button.Neutral</item>
        <item name="buttonBarNeutralButtonStyle">@style/Alert.Button.Neutral</item>

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

        <item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.MyApp.Dialog.Rounded
        </item>

    </style>




    <style name="MyTextAppearance" parent="TextAppearance.AppCompat">
        <item name="android:fontFamily">@font/rosarivo</item>
    </style>


        <style name="Alert.Button.Positive" parent="Widget.MaterialComponents.Button.TextButton">
   <!--     <item name="backgroundTint">@color/colorPrimaryDark</item>-->
        <item name="backgroundTint">@android:color/transparent</item>
        <item name="rippleColor">@color/colorAccent</item>
        <item name="android:textColor">@color/colorPrimary</item>
       <!-- <item name="android:textColor">@android:color/white</item>-->
        <item name="android:textSize">14sp</item>
        <item name="android:textAllCaps">false</item>
    </style>


    <style name="Alert.Button.Neutral" parent="Widget.MaterialComponents.Button.TextButton">
        <item name="backgroundTint">@android:color/transparent</item>
        <item name="rippleColor">@color/colorAccent</item>
        <item name="android:textColor">@color/colorPrimary</item>
        <!--<item name="android:textColor">@android:color/darker_gray</item>-->
        <item name="android:textSize">14sp</item>
        <item name="android:textAllCaps">false</item>
    </style>


  <style name="ShapeAppearanceOverlay.MyApp.Dialog.Rounded" parent="">
        <item name="cornerFamily">rounded</item>
        <item name="cornerSize">8dp</item>
    </style>

Output: enter image description here

Search a text file and print related lines in Python?

Note the potential for an out-of-range index with "i+3". You could do something like:

with open("file.txt", "r") as f:
    searchlines = f.readlines()
j=len(searchlines)-1
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        k=min(i+3,j)
        for l in searchlines[i:k]: print l,
        print

Edit: maybe not necessary. I just tested some examples. x[y] will give errors if y is out of range, but x[y:z] doesn't seem to give errors for out of range values of y and z.

How to select lines between two marker patterns which may occur multiple times with awk/sed

I tried to use awk to print lines between two patterns while pattern2 also match pattern1. And the pattern1 line should also be printed.

e.g. source

package AAA
aaa
bbb
ccc
package BBB
ddd
eee
package CCC
fff
ggg
hhh
iii
package DDD
jjj

should has an ouput of

package BBB
ddd
eee

Where pattern1 is package BBB, pattern2 is package \w*. Note that CCC isn't a known value so can't be literally matched.

In this case, neither @scai 's awk '/abc/{a=1}/mno/{print;a=0}a' file nor @fedorqui 's awk '/abc/{a=1} a; /mno/{a=0}' file works for me.

Finally, I managed to solve it by awk '/package BBB/{flag=1;print;next}/package \w*/{flag=0}flag' file, haha

A little more effort result in awk '/package BBB/{flag=1;print;next}flag;/package \w*/{flag=0}' file, to print pattern2 line also, that is,

package BBB
ddd
eee
package CCC

How do I force my .NET application to run as administrator?

The detailed steps are as follow.

  1. Add application manifest file to solution
  2. Change application setting to "app.manifest"
  3. Update tag of "requestedExecutionLevel" to requireAdministrator.

Adding file in Solution

Select Application Manifest File

Select Manifest option

Update Manifest file

Note that using this code you need to turn off the security settings of ClickOnce, for do this, go inside Properties -> Security -> ClickOnce Security

Override console.log(); for production

console.log = function(){};

Override it like any other thing.

Recommended SQL database design for tags or tagging

I've always kept the tags in a separate table and then had a mapping table. Of course I've never done anything on a really large scale either.

Having a "tags" table and a map table makes it pretty trivial to generate tag clouds & such since you can easily put together SQL to get a list of tags with counts of how often each tag is used.

Resetting MySQL Root Password with XAMPP on Localhost

Steps:

  1. Open your phpMyadmin dashboard
  2. go to user accounts
  3. on the user section Get the root user and click [ Edit privileges ]
  4. in the top section you will find change password button [ click on it ]
  5. make a good pass and fill 2 pass field .
  6. now hit the Go button.

7 . now open your xampp dir ( c:/xampp ) --> 8 . to phpMyadmin dir [C:\xampp\phpMyAdmin]

  1. open [ config.inc.php ] file with any text editor

10 .find [ $cfg['Servers'][$i]['auth_type'] = 'config'; ]line and replace 'config' to ‘cookie’

  1. go to [ $cfg['Servers'][$i]['AllowNoPassword'] = true; ] this line change ‘true’ to ‘false’.

last : save the file .

here is a video link in case you want to see it in Action [ click Here ]

MySQL JDBC Driver 5.1.33 - Time Zone Issue

Setting the time zone by location for a spring boot application inside the application.properties file to

spring.datasource.url=jdbc:mysql://localhost:3306/db?serverTimezone=Europe/Berlin

resolved the problem for the CET / CEST time zone. The pom.xml uses the maven artifact

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.22</version>
    </dependency>

ASP.NET Temporary files cleanup

Yes, it's safe to delete these, although it may force a dynamic recompilation of any .NET applications you run on the server.

For background, see the Understanding ASP.NET dynamic compilation article on MSDN.

How to display PDF file in HTML?

In html page for pc is easy to implement

<embed src="study/sample.pdf" type="application/pdf"   height="300px" width="100%">

but pdf show in mobile by this code is not possible you must need a plugin

if you have not responsive your site. Then above code pdf not show in mobile but you can put download option after the code

<embed src="study/sample.pdf" type="application/pdf"   height="300px" width="100%" class="responsive">
<a href="study/sample.pdf">download</a>

Image.open() cannot identify image file - Python?

For anyone who make it in bigger scale, you might have also check how many file descriptors you have. It will throw this error if you ran out at bad moment.

How to convert Blob to File in JavaScript

This function converts a Blob into a File and it works great for me.

Vanilla JavaScript

function blobToFile(theBlob, fileName){
    //A Blob() is almost a File() - it's just missing the two properties below which we will add
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
}

TypeScript (with proper typings)

public blobToFile = (theBlob: Blob, fileName:string): File => {
    var b: any = theBlob;
    //A Blob() is almost a File() - it's just missing the two properties below which we will add
    b.lastModifiedDate = new Date();
    b.name = fileName;

    //Cast to a File() type
    return <File>theBlob;
}

Usage

var myBlob = new Blob();

//do stuff here to give the blob some data...

var myFile = blobToFile(myBlob, "my-image.png");

What are the benefits of learning Vim?

I've been using vi and vim also for some 20 years, and I'm still learning new things.

David Rayner's Best of Vim Tips site is an excellent list, though it's probably more useful once you have some familiarity with vim.

I also want to mention the ViEmu site which has some great info on vi/vim tips and especially the article Why, oh WHY, do those nutheads use vi? (archived version)

jQuery: how do I animate a div rotation?

I needed to rotate an object but have a call back function. Inspired by John Kern's answer I created this.

function animateRotate (object,fromDeg,toDeg,duration,callback){
        var dummy = $('<span style="margin-left:'+fromDeg+'px;">')
        $(dummy).animate({
            "margin-left":toDeg+"px"
        },
        {
            duration:duration,
            step: function(now,fx){
                $(object).css('transform','rotate(' + now + 'deg)');
                if(now == toDeg){
                    if(typeof callback == "function"){
                        callback();
                    }
                }
            }
        }
    )};

Doing this you can simply call the rotate on the object like so... (in my case I'm doing it on a disclosure triangle icon that has already been rotated by default to 270 degress and I'm rotating it another 90 degrees to 360 degrees at 1000 milliseconds. The final argument is the callback after the animation has finished.

animateRotate($(".disclosure_icon"),270,360,1000,function(){
                alert('finished rotate');
            });

How do I replace whitespaces with underscore?

Replacing spaces is fine, but I might suggest going a little further to handle other URL-hostile characters like question marks, apostrophes, exclamation points, etc.

Also note that the general consensus among SEO experts is that dashes are preferred to underscores in URLs.

import re

def urlify(s):

    # Remove all non-word characters (everything except numbers and letters)
    s = re.sub(r"[^\w\s]", '', s)

    # Replace all runs of whitespace with a single dash
    s = re.sub(r"\s+", '-', s)

    return s

# Prints: I-cant-get-no-satisfaction"
print(urlify("I can't get no satisfaction!"))

Difference between ApiController and Controller in ASP.NET MVC

Which would you rather write and maintain?

ASP.NET MVC

public class TweetsController : Controller {
  // GET: /Tweets/
  [HttpGet]
  public ActionResult Index() {
    return Json(Twitter.GetTweets(), JsonRequestBehavior.AllowGet);
  }
}

ASP.NET Web API

public class TweetsController : ApiController {
  // GET: /Api/Tweets/
  public List<Tweet> Get() {
    return Twitter.GetTweets();
  }
}

Using $_POST to get select option value from HTML

Like this:

<?php
  $option = $_POST['taskOption'];
?>

The index of the $_POST array is always based on the value of the name attribute of any HTML input.

C# create simple xml file

You could use XDocument:

new XDocument(
    new XElement("root", 
        new XElement("someNode", "someValue")    
    )
)
.Save("foo.xml");

If the file you want to create is very big and cannot fit into memory you might use XmlWriter.

How can I convert JSON to a HashMap using Gson?

JSONObject typically uses HashMap internally to store the data. So, you can use it as Map in your code.

Example,

JSONObject obj = JSONObject.fromObject(strRepresentation);
Iterator i = obj.entrySet().iterator();
while (i.hasNext()) {
   Map.Entry e = (Map.Entry)i.next();
   System.out.println("Key: " + e.getKey());
   System.out.println("Value: " + e.getValue());
}

How do I instantiate a JAXBElement<String> object?

When you imported the WSDL, you should have an ObjectFactory class which should have bunch of methods for creating various input parameters.

ObjectFactory factory = new ObjectFactory();
JAXBElement<String> createMessageDescription = factory.createMessageDescription("description");
message.setDescription(createMessageDescription);

Could not find module "@angular-devkit/build-angular"

Simple solution

Hit below commend only to fix this error

npm install --save-dev @angular-devkit/build-angular

Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

This happens where a column is explicitly set to a different collation or the default collation is different in the table queried.

if you have many tables you want to change collation on run this query:

select concat('ALTER TABLE ', t.table_name , ' CONVERT TO CHARACTER 
SET utf8 COLLATE utf8_unicode_ci;') from (SELECT table_name FROM 
information_schema.tables where table_schema='SCHRMA') t;

this will output the queries needed to convert all the tables to use the correct collation per column

Batch script to install MSI

Here is the batch file which should work for you:

@echo off
Title HOST: Installing updates on %computername%
echo %computername%
set Server=\\SERVERNAME or PATH\msifolder

:select
cls
echo Select one of the following MSI install folders for installation task.
echo.
dir "%Server%" /AD /ON /B
echo.
set /P "MSI=Please enter the MSI folder to install: "
set "Package=%Server%\%MSI%\%MSI%.msi"

if not exist "%Package%" (
   echo.
   echo The entered folder/MSI file does not exist ^(typing mistake^).
   echo.
   setlocal EnableDelayedExpansion
   set /P "Retry=Try again [Y/N]: "
   if /I "!Retry!"=="Y" endlocal & goto select
   endlocal
   goto :EOF
)

echo.
echo Selected installation: %MSI%
echo.
echo.

:verify
echo Is This Correct?
echo.
echo.
echo    0: ABORT INSTALL
echo    1: YES
echo    2: NO, RE-SELECT
echo.
set /p "choice=Select YES, NO or ABORT? [0,1,2]: "
if [%choice%]==[0] goto :EOF
if [%choice%]==[1] goto yes
goto select

:yes
echo.
echo Running %MSI% installation ...
start "Install MSI" /wait "%SystemRoot%\system32\msiexec.exe" /i /quiet "%Package%"

The characters listed on last page output on entering in a command prompt window either help cmd or cmd /? have special meanings in batch files. Here are used parentheses and square brackets also in strings where those characters should be interpreted literally. Therefore it is necessary to either enclose the string in double quotes or escape those characters with character ^ as it can be seen in code above, otherwise command line interpreter exits batch execution because of a syntax error.

And it is not possible to call a file with extension MSI. A *.msi file is not an executable. On double clicking on a MSI file, Windows looks in registry which application is associated with this file extension for opening action. And the application to use is msiexec with the command line option /i to install the application inside MSI package.

Run msiexec.exe /? to get in a GUI window the available options or look at Msiexec (command-line options).

I have added already /quiet additionally to required option /i for a silent installation.

In batch code above command start is used with option /wait to start Windows application msiexec.exe and hold execution of batch file until installation finished (or aborted).

Why does an onclick property set with setAttribute fail to work in IE?

Actually, as far as I know, dynamically created inline event-handlers DO work perfectly within Internet Explorer 8 when created with the x.setAttribute() command; you just have to position them properly within your JavaScript code. I stumbled across the solution to your problem (and mine) here.

When I moved all of my statements containing x.appendChild() to their correct positions (i.e., immediately following the last setAttribute command within their groups), I found that EVERY single setAttribute worked in IE8 as it was supposed to, including all form input attributes (including "name" and "type" attributes, as well as my "onclick" event-handlers).

I found this quite remarkable, since all I got in IE before I did this was garbage rendered across the screen, and one error after another. In addition, I found that every setAttribute still worked within the other browsers as well, so if you just remember this simple coding-practice, you'll be good to go in most cases.

However, this solution won't work if you have to change any attributes on the fly, since they cannot be changed in IE once their HTML element has been appended to the DOM; in this case, I would imagine that one would have to delete the element from the DOM, and then recreate it and its attributes (in the correct order, of course!) for them to work properly, and not throw any errors.

Difference between mkdir() and mkdirs() in java for java.io.File

mkdirs() also creates parent directories in the path this File represents.

javadocs for mkdirs():

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

javadocs for mkdir():

Creates the directory named by this abstract pathname.

Example:

File  f = new File("non_existing_dir/someDir");
System.out.println(f.mkdir());
System.out.println(f.mkdirs());

will yield false for the first [and no dir will be created], and true for the second, and you will have created non_existing_dir/someDir

how to use jQuery ajax calls with node.js

Thanks to yojimbo for his answer. To add to his sample, I wanted to use the jquery method $.getJSON which puts a random callback in the query string so I also wanted to parse that out in the Node.js. I also wanted to pass an object back and use the stringify function.

This is my Client Side code.

$.getJSON("http://localhost:8124/dummy?action=dostuff&callback=?",
function(data){
  alert(data);
},
function(jqXHR, textStatus, errorThrown) {
    alert('error ' + textStatus + " " + errorThrown);
});

This is my Server side Node.js

var http = require('http');
var querystring = require('querystring');
var url = require('url');

http.createServer(function (req, res) {
    //grab the callback from the query string   
    var pquery = querystring.parse(url.parse(req.url).query);   
    var callback = (pquery.callback ? pquery.callback : '');

    //we probably want to send an object back in response to the request
    var returnObject = {message: "Hello World!"};
    var returnObjectString = JSON.stringify(returnObject);

    //push back the response including the callback shenanigans
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(callback + '(\'' + returnObjectString + '\')');
}).listen(8124);

Openssl is not recognized as an internal or external command

This is worked for me successfully.

"C:\Program Files\Java\jdk1.6.0_26\bin\keytool.exe" -exportcert -alias sociallisting -keystore "D:\keystore\SocialListing" | "C:\cygwin\bin\openssl.exe" sha1 -binary | "C:\cygwin\bin\openssl.exe" base64

Be careful with below path :

  • "C:\Program Files\Java\jdk1.6.0_26\bin\keytool.exe"
  • "D:\keystore\SocialListing" or it can be like this "C:\Users\Shaon.android\debug.keystore"
  • "C:\cygwin\bin\openssl.exe" or can be like this C:\Users\openssl\bin\openssl.exe

If command successfully work then you will see this command :

Enter keystore password : typeyourpassword

Encryptedhashkey**

How to convert from []byte to int in Go Programming

(reposting this answer)

You can use encoding/binary's ByteOrder to do this for 16, 32, 64 bit types

Play

package main

import "fmt"
import "encoding/binary"

func main() {
    var mySlice = []byte{244, 244, 244, 244, 244, 244, 244, 244}
    data := binary.BigEndian.Uint64(mySlice)
    fmt.Println(data)
}

Split string, convert ToList<int>() in one line

My problem was similar but with the inconvenience that sometimes the string contains letters (sometimes empty).

string sNumbers = "1,2,hh,3,4,x,5";

Trying to follow Pcode Xonos Extension Method:

public static List<int> SplitToIntList(this string list, char separator = ',')
{
      int result = 0;
      return (from s in list.Split(',')
              let isint = int.TryParse(s, out result)
              let val = result
              where isint
              select val).ToList(); 
}

Selecting between two dates within a DateTime field - SQL Server

SELECT * 
FROM tbl 
WHERE myDate BETWEEN #date one# AND #date two#;

MySQL vs MySQLi when using PHP

MySQLi stands for MySQL improved. It's an object-oriented interface to the MySQL bindings which makes things easier to use. It also offers support for prepared statements (which are very useful). If you're on PHP 5 use MySQLi.

How to extend / inherit components?

Let us understand some key limitations & features on Angular’s component inheritance system.

The component only inherits the class logic:

  • All meta-data in the @Component decorator is not inherited.
  • Component @Input properties and @Output properties are inherited.
  • Component lifecycle is not inherited.

These features are very important to have in mind so let us examine each one independently.

The Component only inherits the class logic

When you inherit a Component, all logic inside is equally inherited. It is worth noting that only public members are inherited as private members are only accessible in the class that implements them.

All meta-data in the @Component decorator is not inherited

The fact that no meta-data is inherited might seem counter-intuitive at first but, if you think about this it actually makes perfect sense. If you inherit from a Component say (componentA), you would not want the selector of ComponentA, which you are inheriting from to replace the selector of ComponentB which is the class that is inheriting. The same can be said for the template/templateUrl as well as the style/styleUrls.

Component @Input and @Output properties are inherited

This is another feature that I really love about component Inheritance in Angular. In a simple sentence, whenever you have a custom @Input and @Output property, these properties get inherited.

Component lifecycle is not inherited

This part is the one that is not so obvious especially to people who have not extensively worked with OOP principles. For example, say you have ComponentA which implements one of Angular’s many lifecycle hooks like OnInit. If you create ComponentB and inherit ComponentA, the OnInit lifecycle from ComponentA won't fire until you explicitly call it even if you do have this OnInit lifecycle for ComponentB.

Calling Super/Base Component Methods

In order to have the ngOnInit() method from ComponentA fire, we need to use the super keyword and then call the method we need which in this case is ngOnInit. The super keyword refers to the instance of the component that is being inherited from which in this case will be ComponentA.

ASP.NET MVC: Html.EditorFor and multi-line text boxes

Another way

@Html.TextAreaFor(model => model.Comments[0].Comment)

And in your css do this

textarea
{
    font-family: inherit;
    width: 650px;
    height: 65px;
}

That DataType dealie allows carriage returns in the data, not everybody likes those.