Programs & Examples On #Ns2

Network Simulator version 2, more popularly known as ns-2, is an open source event driven network simulator. With ns-2 one can simulate a wide range of network environments in wired, wireless or even in mixed mode. Major networking standards, including Ethernet, WLAN, satellite networks, Bluetooth, and so on, are supported by ns-2.

Angular Material: mat-select not selecting default

As already mentioned in Angular 6 using ngModel in reactive forms is deprecated (and removed in Angular 7), so I modified the template and the component as following.

The template:

<mat-form-field>
    <mat-select [formControl]="filter" multiple 
                [compareWith]="compareFn">
        <mat-option *ngFor="let v of values" [value]="v">{{v.label}}</mat-option>
    </mat-select>
</mat-form-field>

The main parts of the component (onChanges and other details are omitted):

interface SelectItem {
    label: string;
    value: any;
}

export class FilterComponent implements OnInit {
    filter = new FormControl();

    @Input
    selected: SelectItem[] = [];

    @Input()
    values: SelectItem[] = [];

    constructor() { }

    ngOnInit() {
        this.filter.setValue(this.selected);
    }

    compareFn(v1: SelectItem, v2: SelectItem): boolean {
        return compareFn(v1, v2);
    }
}

function compareFn(v1: SelectItem, v2: SelectItem): boolean {
    return v1 && v2 ? v1.value === v2.value : v1 === v2;
}

Note this.filter.setValue(this.selected) in ngOnInit above.

It seems to work in Angular 6.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For more performance: A simple change is observing that after n = 3n+1, n will be even, so you can divide by 2 immediately. And n won't be 1, so you don't need to test for it. So you could save a few if statements and write:

while (n % 2 == 0) n /= 2;
if (n > 1) for (;;) {
    n = (3*n + 1) / 2;
    if (n % 2 == 0) {
        do n /= 2; while (n % 2 == 0);
        if (n == 1) break;
    }
}

Here's a big win: If you look at the lowest 8 bits of n, all the steps until you divided by 2 eight times are completely determined by those eight bits. For example, if the last eight bits are 0x01, that is in binary your number is ???? 0000 0001 then the next steps are:

3n+1 -> ???? 0000 0100
/ 2  -> ???? ?000 0010
/ 2  -> ???? ??00 0001
3n+1 -> ???? ??00 0100
/ 2  -> ???? ???0 0010
/ 2  -> ???? ???? 0001
3n+1 -> ???? ???? 0100
/ 2  -> ???? ???? ?010
/ 2  -> ???? ???? ??01
3n+1 -> ???? ???? ??00
/ 2  -> ???? ???? ???0
/ 2  -> ???? ???? ????

So all these steps can be predicted, and 256k + 1 is replaced with 81k + 1. Something similar will happen for all combinations. So you can make a loop with a big switch statement:

k = n / 256;
m = n % 256;

switch (m) {
    case 0: n = 1 * k + 0; break;
    case 1: n = 81 * k + 1; break; 
    case 2: n = 81 * k + 1; break; 
    ...
    case 155: n = 729 * k + 425; break;
    ...
}

Run the loop until n = 128, because at that point n could become 1 with fewer than eight divisions by 2, and doing eight or more steps at a time would make you miss the point where you reach 1 for the first time. Then continue the "normal" loop - or have a table prepared that tells you how many more steps are need to reach 1.

PS. I strongly suspect Peter Cordes' suggestion would make it even faster. There will be no conditional branches at all except one, and that one will be predicted correctly except when the loop actually ends. So the code would be something like

static const unsigned int multipliers [256] = { ... }
static const unsigned int adders [256] = { ... }

while (n > 128) {
    size_t lastBits = n % 256;
    n = (n >> 8) * multipliers [lastBits] + adders [lastBits];
}

In practice, you would measure whether processing the last 9, 10, 11, 12 bits of n at a time would be faster. For each bit, the number of entries in the table would double, and I excect a slowdown when the tables don't fit into L1 cache anymore.

PPS. If you need the number of operations: In each iteration we do exactly eight divisions by two, and a variable number of (3n + 1) operations, so an obvious method to count the operations would be another array. But we can actually calculate the number of steps (based on number of iterations of the loop).

We could redefine the problem slightly: Replace n with (3n + 1) / 2 if odd, and replace n with n / 2 if even. Then every iteration will do exactly 8 steps, but you could consider that cheating :-) So assume there were r operations n <- 3n+1 and s operations n <- n/2. The result will be quite exactly n' = n * 3^r / 2^s, because n <- 3n+1 means n <- 3n * (1 + 1/3n). Taking the logarithm we find r = (s + log2 (n' / n)) / log2 (3).

If we do the loop until n = 1,000,000 and have a precomputed table how many iterations are needed from any start point n = 1,000,000 then calculating r as above, rounded to the nearest integer, will give the right result unless s is truly large.

github: server certificate verification failed

To me a simple

sudo apt-get update

solved the issue. It was a clock issue and with this command it resets to the current date/time and everything worked

How do I correctly setup and teardown for my pytest class with tests?

According to Fixture finalization / executing teardown code, the current best practice for setup and teardown is to use yield instead of return:

import pytest

@pytest.fixture()
def resource():
    print("setup")
    yield "resource"
    print("teardown")

class TestResource:
    def test_that_depends_on_resource(self, resource):
        print("testing {}".format(resource))

Running it results in

$ py.test --capture=no pytest_yield.py
=== test session starts ===
platform darwin -- Python 2.7.10, pytest-3.0.2, py-1.4.31, pluggy-0.3.1
collected 1 items

pytest_yield.py setup
testing resource
.teardown


=== 1 passed in 0.01 seconds ===

Another way to write teardown code is by accepting a request-context object into your fixture function and calling its request.addfinalizer method with a function that performs the teardown one or multiple times:

import pytest

@pytest.fixture()
def resource(request):
    print("setup")

    def teardown():
        print("teardown")
    request.addfinalizer(teardown)
    
    return "resource"

class TestResource:
    def test_that_depends_on_resource(self, resource):
        print("testing {}".format(resource))

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

So I have faced the same problem when trying to start apache service and I would like to share my solutions with you. Here is some notes about services or programs that may use port 80:

  1. Skype: skype uses port 80/443 by default. You can change this from tools->options-> advanced->connections and disable checkbox "use port 80 and 443 for addtional incoming connections".
  2. IIS: IIS uses port 80 be default so you need to shut down it. You can use the following two commands net stop w3svc net stop iisadmin
  3. SQL Server Reporting Service: You need to stop this service because it may take port 80 if IIS is not running. Go to local services and stop it.

These options work great with me and I can start apache service without errors.

The other option is to change apache listen port from httpd.conf and set another port number.

Hope this solution helps anyone who face the same problem again.

How to get id from URL in codeigniter?

if you have to pass the value you should enter url like this

localhost/yoururl/index.php/products_controller/delete_controller/70

and in controller function you can read like this

function delete_controller( $product_id = NULL ) {
  echo $product_id;
}

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

I am now using Google Apps (for Email) and Heroku as web server. I am using Google Apps 301 Permanent Redirect feature to redirect the naked domain to WWW.your_domain.com

You can find the step-by-step instructions here https://stackoverflow.com/a/20115583/1440255

Creating a SOAP call using PHP with an XML body

There are a couple of ways to solve this. The least hackiest and almost what you want:

$client = new SoapClient(
    null,
    array(
        'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
        'uri' => 'http://example.com/wsdl',
        'trace' => 1,
        'use' => SOAP_LITERAL,
    )
);
$params = new \SoapVar("<Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer>", XSD_ANYXML);
$result = $client->Echo($params);

This gets you the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://example.com/wsdl">
    <SOAP-ENV:Body>
        <ns1:Echo>
            <Acquirer>
                <Id>MyId</Id>
                <UserId>MyUserId</UserId>
                <Password>MyPassword</Password>
            </Acquirer>
        </ns1:Echo>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

That is almost exactly what you want, except for the namespace on the method name. I don't know if this is a problem. If so, you can hack it even further. You could put the <Echo> tag in the XML string by hand and have the SoapClient not set the method by adding 'style' => SOAP_DOCUMENT, to the options array like this:

$client = new SoapClient(
    null,
    array(
        'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
        'uri' => 'http://example.com/wsdl',
        'trace' => 1,
        'use' => SOAP_LITERAL,
        'style' => SOAP_DOCUMENT,
    )
);
$params = new \SoapVar("<Echo><Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer></Echo>", XSD_ANYXML);
$result = $client->MethodNameIsIgnored($params);

This results in the following request XML:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Body>
        <Echo>
            <Acquirer>
                <Id>MyId</Id>
                <UserId>MyUserId</UserId>
                <Password>MyPassword</Password>
            </Acquirer>
        </Echo>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Finally, if you want to play around with SoapVar and SoapParam objects, you can find a good reference in this comment in the PHP manual: http://www.php.net/manual/en/soapvar.soapvar.php#104065. If you get that to work, please let me know, I failed miserably.

How to convert image into byte array and byte array to base64 String in android?

here is another solution...

System.IO.Stream st = new System.IO.StreamReader (picturePath).BaseStream;
byte[] buffer = new byte[4096];

System.IO.MemoryStream m = new System.IO.MemoryStream ();
while (st.Read (buffer,0,buffer.Length) > 0) {
    m.Write (buffer, 0, buffer.Length);
}  
imgView.Tag = m.ToArray ();
st.Close ();
m.Close ();

hope it helps!

Using dig to search for SPF records

I believe that I found the correct answer through this dig How To. I was able to look up the SPF records on a specific DNS, by using the following query:

dig @ns1.nameserver1.com domain.com txt

How to Display Multiple Google Maps per page with API V3

You could try nex approach css

 .map {
            height: 300px;
            width: 100%;
        }

HTML

@foreach(var map in maps)
{
  <div id="[email protected]" lat="@map.Latitude" lng="@map.Longitude" class="map">
  </div>
}

JavaScript

 <script>
    var maps = [];
    var markers = [];
    function initMap() {
        var $maps = $('.map');
        $.each($maps, function (i, value) {
            var uluru = { lat: parseFloat($(value).attr('lat')), lng: parseFloat($(value).attr('lng')) };

            var mapDivId = $(value).attr('id');

            maps[mapDivId] = new google.maps.Map(document.getElementById(mapDivId), {
                zoom: 17,
                center: uluru
            });

            markers[mapDivId] = new google.maps.Marker({
                position: uluru,
                map: maps[mapDivId]
            });
        })
    }
</script>

<script async defer
        src="https://maps.googleapis.com/maps/api/js?language=ru-Ru&key=YOUR_KEY&callback=initMap">
</script>

Windows Batch: How to add Host-Entries?

Create a new addHostEntry.bat file with the following content in it:

@echo off
TITLE Modifying your HOSTS file
COLOR F0
ECHO.

:LOOP
SET Choice=
SET /P Choice="Do you want to modify HOSTS file ? (Y/N)"

IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%

ECHO.
IF /I '%Choice%'=='Y' GOTO ACCEPTED
IF /I '%Choice%'=='N' GOTO REJECTED
ECHO Please type Y (for Yes) or N (for No) to proceed!
ECHO.
GOTO Loop


:REJECTED
ECHO Your HOSTS file was left unchanged>>%systemroot%\Temp\hostFileUpdate.log
ECHO Finished.
GOTO END


:ACCEPTED
SET NEWLINE=^& echo.
ECHO Carrying out requested modifications to your HOSTS file
FIND /C /I "mydomain.com" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1    mydomain.com>>%WINDIR%\system32\drivers\etc\hosts
ECHO Finished
GOTO END


:END
ECHO.
ping -n 11 127.0.0.1 > nul
EXIT

Hope this helps!

jQuery and TinyMCE: textarea value doesn't submit

I had this problem for a while and triggerSave() didn't work, nor did any of the other methods.

So I found a way that worked for me ( I'm adding this here because other people may have already tried triggerSave and etc... ):

tinyMCE.init({
   selector: '.tinymce', // This is my <textarea> class
   setup : function(ed) {
                  ed.on('change', function(e) {
                     // This will print out all your content in the tinyMce box
                     console.log('the content '+ed.getContent());
                     // Your text from the tinyMce box will now be passed to your  text area ... 
                     $(".tinymce").text(ed.getContent()); 
                  });
            }
   ... Your other tinyMce settings ...
});

When you're submitting your form or whatever all you have to do is grab the data from your selector ( In my case: .tinymce ) using $('.tinymce').text().

awk without printing newline

awk '{sum+=$3}; END {printf "%f",sum/NR}' ${file}_${f}_v1.xls >> to-plot-p.xls

print will insert a newline by default. You dont want that to happen, hence use printf instead.

Ball to Ball Collision - Detection and Handling

A good way of reducing the number of collision checks is to split the screen into different sections. You then only compare each ball to the balls in the same section.

Updating a dataframe column in spark

Commonly when updating a column, we want to map an old value to a new value. Here's a way to do that in pyspark without UDF's:

# update df[update_col], mapping old_value --> new_value
from pyspark.sql import functions as F
df = df.withColumn(update_col,
    F.when(df[update_col]==old_value,new_value).
    otherwise(df[update_col])).

Is Constructor Overriding Possible?

You can have many constructors as long as they take in different parameters. But the compiler putting a default constructor in is not called "constructor overriding".

How to unmerge a Git merge?

If you haven't committed the merge, then use:

git merge --abort

Disable LESS-CSS Overwriting calc()

Apart from using an escaped value as described in my other answer, it is also possible to fix this issue by enabling the Strict Math setting.

With strict math on, only maths that are inside unnecessary parentheses will be processed, so your code:

width: calc(100% - 200px);

Would work as expected with the strict math option enabled.

However, note that Strict Math is applied globally, not only inside calc(). That means, if you have:

font-size: 12px + 2px;

The math will no longer be processed by Less -- it will output font-size: 12px + 2px which is, obviously, invalid CSS. You'd have to wrap all maths that should be processed by Less in (previously unnecessary) parentheses:

font-size: (12px + 2px);

Strict Math is a nice option to consider when starting a new project, otherwise you'd possibly have to rewrite a good part of the code base. For the most common use cases, the escaped string approach described in the other answer is more suitable.

Math operations from string

A simple way but dangerous way to do this would be to use eval(). eval() executes the string passed to it as code. The dangerous thing about this is that if this string is gained from user input, they could maliciously execute code that could break the computer. I would get the input, check it with a regex, and then execute it if you determine if it's OK. If it's only going to be in the format "number operation number", then you could use a simple regex:

import re
s = raw_input('What is your math problem? ')
if re.findall('\d+? *?\+ *?\d+?', s):
  print eval(s)
else:
  print "Try entering a math problem"

Otherwise, you would have to come up with something a bit stricter than this. You could also do it conversely, using a regex to find if certain things are not in it, such as numbers and operations. Also you could check to see if the input contains certain commands.

Rollback transaction after @Test

I know, I am tooooo late to post an answer, but hoping that it might help someone. Plus, I just solved this issue I had with my tests. This is what I had in my test:

My test class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "path-to-context" })
@Transactional
public class MyIntegrationTest 

Context xml

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
   <property name="driverClassName" value="${jdbc.driverClassName}" />
   <property name="url" value="${jdbc.url}" />
   <property name="username" value="${jdbc.username}" />
   <property name="password" value="${jdbc.password}" />
</bean>

I still had the problem that, the database was not being cleaned up automatically.

Issue was resolved when I added following property to BasicDataSource

<property name="defaultAutoCommit" value="false" />

Hope it helps.

Reading Properties file in Java

None of the current answers show the InputStream being closed (this will leak a file descriptor), and/or don't deal with .getResourceAsStream() returning null when the resource is not found (this will lead to a NullPointerException with the confusing message, "inStream parameter is null"). You need something like the following:

String propertiesFilename = "server.properties";
Properties prop = new Properties();
try (var inputStream = getClass().getClassLoader().getResourceAsStream(propertiesFilename)) {
    if (inputStream == null) {
        throw new FileNotFoundException(propertiesFilename);
    }
    prop.load(inputStream);
} catch (IOException e) {
    throw new RuntimeException(
                "Could not read " + propertiesFilename + " resource file: " + e);
}

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

Simple do this:

df = df.loc[:, ~df.columns.str.contains('^Unnamed')]

How can I capitalize the first letter of each word in a string?

A quick function worked for Python 3

Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> capitalizeFirtChar = lambda s: s[:1].upper() + s[1:]
>>> print(capitalizeFirtChar('??????? ????? ????????. ???????? ?? ?????? ? ??????????????!'))
??????? ????? ????????. ???????? ?? ?????? ? ??????????????!
>>> print(capitalizeFirtChar('??? ???? ?????? ???????! ??? ???? ?????? ????? ???.'))
??? ???? ?????? ???????! ??? ???? ?????? ????? ???.
>>> print(capitalizeFirtChar('faith and Labour make Dreams come true.'))
Faith and Labour make Dreams come true.

Error in finding last used cell in Excel with VBA

Since the original question is about problems with finding the last cell, in this answer I will list the various ways you can get unexpected results; see my answer to "How can I find last row that contains data in the Excel sheet with a macro?" for my take on solving this.

I'll start by expanding on the answer by sancho.s and the comment by GlennFromIowa, adding even more detail:

[...] one has first to decide what is considered used. I see at least 6 meanings. Cell has:

  • 1) data, i.e., a formula, possibly resulting in a blank value;
  • 2) a value, i.e., a non-blank formula or constant;
  • 3) formatting;
  • 4) conditional formatting;
  • 5) a shape (including Comment) overlapping the cell;
  • 6) involvement in a Table (List Object).

Which combination do you want to test for? Some (such as Tables) may be more difficult to test for, and some may be rare (such as a shape outside of data range), but others may vary based on the situation (e.g., formulas with blank values).

Other things you might want to consider:

  • A) Can there be hidden rows (e.g. autofilter), blank cells or blank rows?
  • B) What kind of performance is acceptable?
  • C) Can the VBA macro affect the workbook or the application settings in any way?

With that in mind, let's see how the common ways of getting the "last cell" can produce unexpected results:

  • The .End(xlDown) code from the question will break most easily (e.g. with a single non-empty cell or when there are blank cells in between) for the reasons explained in the answer by Siddharth Rout here (search for "xlDown is equally unreliable.")
  • Any solution based on Counting (CountA or Cells*.Count) or .CurrentRegion will also break in presence of blank cells or rows
  • A solution involving .End(xlUp) to search backwards from the end of a column will, just as CTRL+UP, look for data (formulas producing a blank value are considered "data") in visible rows (so using it with autofilter enabled might produce incorrect results ??).

    You have to take care to avoid the standard pitfalls (for details I'll again refer to the answer by Siddharth Rout here, look for the "Find Last Row in a Column" section), such as hard-coding the last row (Range("A65536").End(xlUp)) instead of relying on sht.Rows.Count.

  • .SpecialCells(xlLastCell) is equivalent to CTRL+END, returning the bottom-most and right-most cell of the "used range", so all caveats that apply to relying on the "used range", apply to this method as well. In addition, the "used range" is only reset when saving the workbook and when accessing worksheet.UsedRange, so xlLastCell might produce stale results?? with unsaved modifications (e.g. after some rows were deleted). See the nearby answer by dotNET.
  • sht.UsedRange (described in detail in the answer by sancho.s here) considers both data and formatting (though not conditional formatting) and resets the "used range" of the worksheet, which may or may not be what you want.

    Note that a common mistake ?is to use .UsedRange.Rows.Count??, which returns the number of rows in the used range, not the last row number (they will be different if the first few rows are blank), for details see newguy's answer to How can I find last row that contains data in the Excel sheet with a macro?

  • .Find allows you to find the last row with any data (including formulas) or a non-blank value in any column. You can choose whether you're interested in formulas or values, but the catch is that it resets the defaults in the Excel's Find dialog ????, which can be highly confusing to your users. It also needs to be used carefully, see the answer by Siddharth Rout here (section "Find Last Row in a Sheet")
  • More explicit solutions that check individual Cells' in a loop are generally slower than re-using an Excel function (although can still be performant), but let you specify exactly what you want to find. See my solution based on UsedRange and VBA arrays to find the last cell with data in the given column -- it handles hidden rows, filters, blanks, does not modify the Find defaults and is quite performant.

Whatever solution you pick, be careful

  • to use Long instead of Integer to store the row numbers (to avoid getting Overflow with more than 65k rows) and
  • to always specify the worksheet you're working with (i.e. Dim ws As Worksheet ... ws.Range(...) instead of Range(...))
  • when using .Value (which is a Variant) avoid implicit casts like .Value <> "" as they will fail if the cell contains an error value.

Why is enum class preferred over plain enum?

From Bjarne Stroustrup's C++11 FAQ:

The enum classes ("new enums", "strong enums") address three problems with traditional C++ enumerations:

  • conventional enums implicitly convert to int, causing errors when someone does not want an enumeration to act as an integer.
  • conventional enums export their enumerators to the surrounding scope, causing name clashes.
  • the underlying type of an enum cannot be specified, causing confusion, compatibility problems, and makes forward declaration impossible.

The new enums are "enum class" because they combine aspects of traditional enumerations (names values) with aspects of classes (scoped members and absence of conversions).

So, as mentioned by other users, the "strong enums" would make the code safer.

The underlying type of a "classic" enum shall be an integer type large enough to fit all the values of the enum; this is usually an int. Also each enumerated type shall be compatible with char or a signed/unsigned integer type.

This is a wide description of what an enum underlying type must be, so each compiler will take decisions on his own about the underlying type of the classic enum and sometimes the result could be surprising.

For example, I've seen code like this a bunch of times:

enum E_MY_FAVOURITE_FRUITS
{
    E_APPLE      = 0x01,
    E_WATERMELON = 0x02,
    E_COCONUT    = 0x04,
    E_STRAWBERRY = 0x08,
    E_CHERRY     = 0x10,
    E_PINEAPPLE  = 0x20,
    E_BANANA     = 0x40,
    E_MANGO      = 0x80,
    E_MY_FAVOURITE_FRUITS_FORCE8 = 0xFF // 'Force' 8bits, how can you tell?
};

In the code above, some naive coder is thinking that the compiler will store the E_MY_FAVOURITE_FRUITS values into an unsigned 8bit type... but there's no warranty about it: the compiler may choose unsigned char or int or short, any of those types are large enough to fit all the values seen in the enum. Adding the field E_MY_FAVOURITE_FRUITS_FORCE8 is a burden and doesn't forces the compiler to make any kind of choice about the underlying type of the enum.

If there's some piece of code that rely on the type size and/or assumes that E_MY_FAVOURITE_FRUITS would be of some width (e.g: serialization routines) this code could behave in some weird ways depending on the compiler thoughts.

And to make matters worse, if some workmate adds carelessly a new value to our enum:

    E_DEVIL_FRUIT  = 0x100, // New fruit, with value greater than 8bits

The compiler doesn't complain about it! It just resizes the type to fit all the values of the enum (assuming that the compiler were using the smallest type possible, which is an assumption that we cannot do). This simple and careless addition to the enum could subtlety break related code.

Since C++11 is possible to specify the underlying type for enum and enum class (thanks rdb) so this issue is neatly addressed:

enum class E_MY_FAVOURITE_FRUITS : unsigned char
{
    E_APPLE        = 0x01,
    E_WATERMELON   = 0x02,
    E_COCONUT      = 0x04,
    E_STRAWBERRY   = 0x08,
    E_CHERRY       = 0x10,
    E_PINEAPPLE    = 0x20,
    E_BANANA       = 0x40,
    E_MANGO        = 0x80,
    E_DEVIL_FRUIT  = 0x100, // Warning!: constant value truncated
};

Specifying the underlying type if a field have an expression out of the range of this type the compiler will complain instead of changing the underlying type.

I think that this is a good safety improvement.

So Why is enum class preferred over plain enum?, if we can choose the underlying type for scoped(enum class) and unscoped (enum) enums what else makes enum class a better choice?:

  • They don't convert implicitly to int.
  • They don't pollute the surrounding namespace.
  • They can be forward-declared.

Python Key Error=0 - Can't find Dict error in code

The defaultdict solution is better. But for completeness you could also check and create empty list before the append. Add the + lines:

+ if not u in self.adj.keys():
+     self.adj[u] = []
  self.adj[u].append(edge)
.
.

Anaconda version with Python 3.5

To highlight a few points:

The docs recommend using an install environment: https://conda.io/docs/user-guide/install/download.html#choosing-a-version-of-anaconda-or-miniconda

The version archive is here: https://repo.continuum.io/archive/

The version history is here: https://docs.anaconda.com/anaconda/release-notes

"Anaconda3 then its python 3.x and if it is Anaconda2 then its 2.x" - +1 papbiceps

The version archive is sorted newest at the top, but Anaconda2 ABOVE Anaconda3.

Set a DateTime database field to "Now"

An alternative to GETDATE() is CURRENT_TIMESTAMP. Does the exact same thing.

How can I print a circular structure in a JSON-like format?

Note that there is also a JSON.decycle method implemented by Douglas Crockford. See his cycle.js. This allows you to stringify almost any standard structure:

var a = [];
a[0] = a;
a[1] = 123;
console.log(JSON.stringify(JSON.decycle(a)));
// result: '[{"$ref":"$"},123]'.

You can also recreate original object with retrocycle method. So you don't have to remove cycles from objects to stringify them.

However this will not work for DOM Nodes (which are typical cause of cycles in real life use-cases). For example this will throw:

var a = [document.body];
console.log(JSON.stringify(JSON.decycle(a)));

I've made a fork to solve that problem (see my cycle.js fork). This should work fine:

var a = [document.body];
console.log(JSON.stringify(JSON.decycle(a, true)));

Note that in my fork JSON.decycle(variable) works as in the original and will throw an exception when the variable contain DOM nodes/elements.

When you use JSON.decycle(variable, true) you accept the fact that the result will not be reversible (retrocycle will not re-create DOM nodes). DOM elements should be identifiable to some extent though. For example if a div element has an id then it will be replaced with a string "div#id-of-the-element".

"make_sock: could not bind to address [::]:443" when restarting apache (installing trac and mod_wsgi)

Let me add one more reason for the error. In httpd.conf I included explicitly

Include etc/apache24/extra/httpd-ssl.conf

while did not notice previous wildcard

Include etc/apache24/extra/*.conf

Grepping 443 will not find this.

How can I temporarily disable a foreign key constraint in MySQL?

I normally only disable foreign key constraints when I want to truncate a table, and since I keep coming back to this answer this is for future me:

SET FOREIGN_KEY_CHECKS=0;
TRUNCATE TABLE table;
SET FOREIGN_KEY_CHECKS=1;

getting the error: expected identifier or ‘(’ before ‘{’ token

{
int main(void);

should be

int main(void)
{

Then I let you fix the next compilation errors of your program...

Apache and Node.js on the Same Server

I recently ran into this kinda issue, where I need to communicate between client and server using websocket in a PHP based codeigniter project.

I resolved this issue by adding my port(node app running on) into Allow incoming TCP ports & Allow outgoing TCP ports lists.

You can find these configurations in Firewall Configurations in your server's WHM panel.

Python loop for inside lambda

Just in case, if someone is looking for a similar problem...

Most solutions given here are one line and are quite readable and simple. Just wanted to add one more that does not need the use of lambda(I am assuming that you are trying to use lambda just for the sake of making it a one line code). Instead, you can use a simple list comprehension.

[print(i) for i in x]

BTW, the return values will be a list on None s.

How do I change the select box arrow

You can skip the container or background image with pure css arrow:

select {

  /* make arrow and background */

  background:
    linear-gradient(45deg, transparent 50%, blue 50%),
    linear-gradient(135deg, blue 50%, transparent 50%),
    linear-gradient(to right, skyblue, skyblue);
  background-position:
    calc(100% - 21px) calc(1em + 2px),
    calc(100% - 16px) calc(1em + 2px),
    100% 0;
  background-size:
    5px 5px,
    5px 5px,
    2.5em 2.5em;
  background-repeat: no-repeat;

  /* styling and reset */

  border: thin solid blue;
  font: 300 1em/100% "Helvetica Neue", Arial, sans-serif;
  line-height: 1.5em;
  padding: 0.5em 3.5em 0.5em 1em;

  /* reset */

  border-radius: 0;
  margin: 0;      
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  -webkit-appearance:none;
  -moz-appearance:none;
}

Sample here

How do I display the value of a Django form field in a template?

If you've populated the form with an instance and not with POST data (as the suggested answer requires), you can access the data using {{ form.instance.my_field_name }}.

How to extract a string between two delimiters

  String s = "ABC[This is to extract]";

    System.out.println(s);
    int startIndex = s.indexOf('[');
    System.out.println("indexOf([) = " + startIndex);
    int endIndex = s.indexOf(']');
    System.out.println("indexOf(]) = " + endIndex);
    System.out.println(s.substring(startIndex + 1, endIndex));

Check if DataRow exists by column name in c#?

if (row.Columns.Contains("US_OTHERFRIEND"))

How do I make Git ignore file mode (chmod) changes?

If

git config --global core.filemode false

does not work for you, do it manually:

cd into yourLovelyProject folder

cd into .git folder:

cd .git

edit the config file:

nano config

change true to false

[core]
        repositoryformatversion = 0
        filemode = true

->

[core]
        repositoryformatversion = 0
        filemode = false

save, exit, go to upper folder:

cd ..

reinit the git

git init

you are done!

Making a flex item float right

You can't use float inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle.

So if you want to position child element to right of parent element you can use margin-left: auto but now child element will also push other div to the right as you can see here Fiddle.

What you can do now is change order of elements and set order: 2 on child element so it doesn't affect second div

_x000D_
_x000D_
.parent {_x000D_
  display: flex;_x000D_
}_x000D_
.child {_x000D_
  margin-left: auto;_x000D_
  order: 2;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="child">Ignore parent?</div>_x000D_
  <div>another child</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Transparent image - background color

If I understand you right, you can do this:

<img src="image.png" style="background-color:red;" />

In fact, you can even apply a whole background-image to the image, resulting in two "layers" without the need for multi-background support in the browser ;)

How to do a SOAP wsdl web services call from the command line

For Windows users looking for a PowerShell alternative, here it is (using POST). I've split it up onto multiple lines for readability.

$url = 'https://sandbox.mediamind.com/Eyeblaster.MediaMind.API/V2/AuthenticationService.svc'
$headers = @{
    'Content-Type' = 'text/xml';
    'SOAPAction' = 'http://api.eyeblaster.com/IAuthenticationService/ClientLogin'
}
$envelope = @'
    <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
        <Body>
            <yourEnvelopeContentsHere/>
        </Body>
    </Envelope>
'@     # <--- This line must not be indented

Invoke-WebRequest -Uri $url -Headers $headers -Method POST -Body $envelope

vertical-align with Bootstrap 3

There isn't any need for table and table-cells. It can be achieved easily using transform.

Example: http://codepen.io/arvind/pen/QNbwyM

Code:

_x000D_
_x000D_
.child {_x000D_
  height: 10em;_x000D_
  border: 1px solid green;_x000D_
  position: relative;_x000D_
}_x000D_
.child-content {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  -webkit-transform: translate(-50%, -50%);_x000D_
  transform: translate(-50%, -50%);_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="row parent">_x000D_
  <div class="col-xs-6 col-lg-6 child">_x000D_
    <div class="child-content">_x000D_
      <div style="height:4em;border:1px solid #000">Big</div>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="col-xs-6 col-lg-6 child">_x000D_
    <div class="child-content">_x000D_
      <div style="height:3em;border:1px solid #F00">Small</div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CSS table column autowidth

If you want to make sure that last row does not wrap and thus size the way you want it, have a look at

td {
 white-space: nowrap;
}

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

This method is deprecated now from now starting with Android Q.

Try This will really help.

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {// if build version is less than Q try the old traditional method
                    if (!wifiManager.isWifiEnabled()) {
                        wifiManager.setWifiEnabled(true);
                        btnOnOff.setText("Wifi ONN");
                    } else {
                        wifiManager.setWifiEnabled(false);
                        btnOnOff.setText("Wifi OFF");
                    }
                } else {// if it is Android Q and above go for the newer way    NOTE: You can also use this code for less than android Q also
                    Intent panelIntent = new Intent(Settings.Panel.ACTION_WIFI);
                    startActivityForResult(panelIntent, 1);
                }

How to handle invalid SSL certificates with Apache HttpClient?

For HttpClient, we can do this :

SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
        SSLContext.setDefault(ctx);

        String uri = new StringBuilder("url").toString();

        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        };

        HttpClient client = HttpClientBuilder.create().setSSLContext(ctx)
                .setSSLHostnameVerifier(hostnameVerifier).build()

Android - how to make a scrollable constraintlayout?

For me, none of the suggestions about removing bottom constraints nor setting scroll container to true seemed to work. What worked: expand the height of individual/nested views in my layout so they "spanned" beyond the parent by using the "Expand Vertically" option of the Constraint Layout Editor as shown below.

For any approach, it is important that the dotted preview lines extend vertically beyond the parent's top or bottom dimensions

Expand Vertically

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy and JoinColumn were not working).

I think you were trying to do a bi-directional relationships.

First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:

(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    private List<Post> posts;
}


public class Post {
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="user_id")
    private User user;
}

By doing so, the table for Post will have a column user_id which store the relationship. Hibernate is getting the relationship by the user in Post (Instead of posts in User. You will notice the difference if you have Post's user but missing User's posts).

You have mentioned mappedBy and JoinColumn is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.


Edit:

Just a bit extra information on the use of mappedBy as it is usually confusing at first. In mappedBy, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.

What is the .idea folder?

When you use the IntelliJ IDE, all the project-specific settings for the project are stored under the .idea folder.

Project settings are stored with each specific project as a set of xml files under the .idea folder. If you specify the default project settings, these settings will be automatically used for each newly created project.

Check this documentation for the IDE settings and here is their recommendation on Source Control and an example .gitignore file.

Note: If you are using git or some version control system, you might want to set this folder "ignore". Example - for git, add this directory to .gitignore. This way, the application is not IDE-specific.

Export a graph to .eps file with R

The easiest way I've found to create postscripts is the following, using the setEPS() command:

setEPS()
postscript("whatever.eps")
plot(rnorm(100), main="Hey Some Data")
dev.off()

How do I check if a SQL Server text column is empty?

You have to do both:

SELECT * FROM Table WHERE Text IS NULL or Text LIKE ''

How to determine whether code is running in DEBUG / RELEASE build?

For a solution in Swift please refer to this thread on SO.

Basically the solution in Swift would look like this:

#if DEBUG
    println("I'm running in DEBUG mode")
#else
    println("I'm running in a non-DEBUG mode")
#endif

Additionally you will need to set the DEBUG symbol in Swift Compiler - Custom Flags section for the Other Swift Flags key via a -D DEBUG entry. See the following screenshot for an example:

enter image description here

What's the best way to dedupe a table?

This can dedupe the duplicated values in c1:

select * from foo
minus
select f1.* from foo f1, foo f2
where f1.c1 = f2.c1 and f1.c2 > f2.c2

Sort objects in ArrayList by date?

Pass the ArrayList In argument.

    private static void order(ArrayList<Object> list) {

    Collections.sort(list, new Comparator() {

        public int compare(Object o2, Object o1) {

            String x1 =  o1.Date;
            String x2 =  o2.Date;

                return  x1.compareTo(x2);

        }
    });
}

Why does Eclipse Java Package Explorer show question mark on some classes?

It means the class is not yet added to the repository.

If your project was checked-out (most probably a CVS project) and you added a new class file, it will have the ? icon.

For other CVS Label Decorations, check http://help.eclipse.org/help33/index.jsp?topic=/org.eclipse.platform.doc.user/reference/ref-cvs-decorations.htm

How to declare a constant map in Golang?

And as suggested above by Siu Ching Pong -Asuka Kenji with the function which in my opinion makes more sense and leaves you with the convenience of the map type without the function wrapper around:

   // romanNumeralDict returns map[int]string dictionary, since the return
       // value is always the same it gives the pseudo-constant output, which
       // can be referred to in the same map-alike fashion.
       var romanNumeralDict = func() map[int]string { return map[int]string {
            1000: "M",
            900:  "CM",
            500:  "D",
            400:  "CD",
            100:  "C",
            90:   "XC",
            50:   "L",
            40:   "XL",
            10:   "X",
            9:    "IX",
            5:    "V",
            4:    "IV",
            1:    "I",
          }
        }

        func printRoman(key int) {
          fmt.Println(romanNumeralDict()[key])
        }

        func printKeyN(key, n int) {
          fmt.Println(strings.Repeat(romanNumeralDict()[key], n))
        }

        func main() {
          printRoman(1000)
          printRoman(50)
          printKeyN(10, 3)
        }

Try this at play.golang.org.

Avoid line break between html elements

If you need this for several words or elements, but can't apply it to a whole TD or similar, the Span tag can be used.

<span style="white-space: nowrap">Text to break together</span>
    or 
<span class=nobr>Text to break together</span>

If you use the class version, remember to set up the CSS as detailed in the accepted answer.

How to call a View Controller programmatically?

To create a view controller:

UIViewController * vc = [[UIViewController alloc] init];

To call a view controller (must be called from within another viewcontroller):

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

For one, use nil rather than null.


Loading a view controller from the storyboard:

NSString * storyboardName = @"MainStoryboard"; 
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"IDENTIFIER_OF_YOUR_VIEWCONTROLLER"];
[self presentViewController:vc animated:YES completion:nil];

Identifier of your view controller is either equal to the class name of your view controller, or a Storyboard ID that you can assign in the identity inspector of your storyboard.

Order discrete x scale by frequency/value

You can use reorder:

qplot(reorder(factor(cyl),factor(cyl),length),data=mtcars,geom="bar")

Edit:

To have the tallest bar at the left, you have to use a bit of a kludge:

qplot(reorder(factor(cyl),factor(cyl),function(x) length(x)*-1),
   data=mtcars,geom="bar")

I would expect this to also have negative heights, but it doesn't, so it works!

MongoDB: Combine data from multiple collections into one..how?

You've to do that in your application layer. If you're using an ORM, it could use annotations (or something similar) to pull references that exist in other collections. I only have worked with Morphia, and the @Reference annotation fetches the referenced entity when queried, so I am able to avoid doing it myself in the code.

Get the contents of a table row with a button click

Try this:

$(".use-address").click(function() {
   $(this).closest('tr').find('td').each(function() {
        var textval = $(this).text(); // this will be the text of each <td>
   });
});

This will find the closest tr (going up through the DOM) of the currently clicked button and then loop each td - you might want to create a string / array with the values.

Example here

Getting the full address using an array example here

reCAPTCHA ERROR: Invalid domain for site key

I had a similar problem due to the fact that I forgot to show the render parameter

<script src='https://www.google.com/recaptcha/api.js?render=SITE_KEY' async defer></script>

Serializing with Jackson (JSON) - getting "No serializer found"?

SpringBoot2.0 ,I resolve it by follow code:

@Bean public ObjectMapper objectMapper() {
 return new ObjectMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);}

Where is SQLite database stored on disk?

A SQLite database is a regular file. It is created in your script current directory.

Getting Gradle dependencies in IntelliJ IDEA using Gradle build

Tried everything in this thread and nothing worked for me in IntelliJ 2020.2. This answer did the trick, but I had to set the correct path to the JDK and choose it in Gradle settings after that (as showed in figures bellow):

  1. Setting the correct path for the Java SDK (under File->Project Structure):

enter image description here

  1. In Gradle Window, click in "Gradle Settings..."

enter image description here

  1. Select the correct SDK from (1) here:

enter image description here

After that, the option "Reload All Gradle Projects" downloaded all dependencies as expected.

Cheers.

Sending mass email using PHP

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

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

Android: textview hyperlink

Very simple way to do this---

In your Activity--

 TextView tv = (TextView) findViewById(R.id.site);
 tv.setText(Html.fromHtml("<a href=http://www.stackoverflow.com> STACK OVERFLOW "));
 tv.setMovementMethod(LinkMovementMethod.getInstance());

Then you will get just the Tag, not the whole link..

Hope it will help you...

How does one parse XML files?

If you're using .NET 2.0, try XmlReader and its subclasses XmlTextReader, and XmlValidatingReader. They provide a fast, lightweight (memory usage, etc.), forward-only way to parse an XML file.

If you need XPath capabilities, try the XPathNavigator. If you need the entire document in memory try XmlDocument.

Get URL query string parameters

$_SERVER['QUERY_STRING'] contains the data that you are looking for.


DOCUMENTATION

Archive the artifacts in Jenkins

Your understanding is correct, an artifact in the Jenkins sense is the result of a build - the intended output of the build process.

A common convention is to put the result of a build into a build, target or bin directory.

The Jenkins archiver can use globs (target/*.jar) to easily pick up the right file even if you have a unique name per build.

VBA using ubound on a multidimensional array

Looping D3 ways;

Sub SearchArray()
    Dim arr(3, 2) As Variant
    arr(0, 0) = "A"
    arr(0, 1) = "1"
    arr(0, 2) = "w"

    arr(1, 0) = "B"
    arr(1, 1) = "2"
    arr(1, 2) = "x"

    arr(2, 0) = "C"
    arr(2, 1) = "3"
    arr(2, 2) = "y"

    arr(3, 0) = "D"
    arr(3, 1) = "4"
    arr(3, 2) = "z"

    Debug.Print "Loop Dimension 1"
    For i = 0 To UBound(arr, 1)
        Debug.Print "arr(" & i & ", 0) is " & arr(i, 0)
    Next i
    Debug.Print ""

    Debug.Print "Loop Dimension 2"
    For j = 0 To UBound(arr, 2)
        Debug.Print "arr(0, " & j & ") is " & arr(0, j)
    Next j
    Debug.Print ""

    Debug.Print "Loop Dimension 1 and 2"
    For i = 0 To UBound(arr, 1)
        For j = 0 To UBound(arr, 2)
            Debug.Print "arr(" & i & ", " & j & ") is " & arr(i, j)
        Next j
    Next i
    Debug.Print ""

End Sub

Get the last inserted row ID (with SQL statement)

If your SQL Server table has a column of type INT IDENTITY (or BIGINT IDENTITY), then you can get the latest inserted value using:

INSERT INTO dbo.YourTable(columns....)
   VALUES(..........)

SELECT SCOPE_IDENTITY()

This works as long as you haven't inserted another row - it just returns the last IDENTITY value handed out in this scope here.

There are at least two more options - @@IDENTITY and IDENT_CURRENT - read more about how they works and in what way they're different (and might give you unexpected results) in this excellent blog post by Pinal Dave here.

The server response was: 5.7.0 Must issue a STARTTLS command first. i16sm1806350pag.18 - gsmtp

SEND Button logic:

string fromaddr = "[email protected]";
string toaddr = TextBox1.Text;//TO ADDRESS HERE
string password = "YOUR PASSWROD";

MailMessage msg = new MailMessage();
msg.Subject = "Username &password";
msg.From = new MailAddress(fromaddr);
msg.Body = "Message BODY";
msg.To.Add(new MailAddress(TextBox1.Text));
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
NetworkCredential nc = new NetworkCredential(fromaddr,password);
smtp.Credentials = nc;
smtp.Send(msg);

This code work 100%. If you have antivirus in your system or firewall that restrict sending mails from your system so disable your antivirus and firewall. After this run this code... In this above code TextBox1.Text control is used for TOaddress.

Padding zeros to the left in postgreSQL

You can use the rpad and lpad functions to pad numbers to the right or to the left, respectively. Note that this does not work directly on numbers, so you'll have to use ::char or ::text to cast them:

SELECT RPAD(numcol::text, 3, '0'), -- Zero-pads to the right up to the length of 3
       LPAD(numcol::text, 3, '0'), -- Zero-pads to the left up to the length of 3
FROM   my_table

How can I connect to a Tor hidden service using cURL in PHP?

You need to set option CURLOPT_PROXYTYPE to CURLPROXY_SOCKS5_HOSTNAME, which sadly wasn't defined in old PHP versions, circa pre-5.6; if you have earlier in but you can explicitly use its value, which is equal to 7:

curl_setopt($ch, CURLOPT_PROXYTYPE, 7);

Is Visual Studio Community a 30 day trial?

Remember, if you are inside of private red with some proxy, you must be logout and relogin with an external WIFI for example.

How do I format axis number format to thousands with a comma in matplotlib?

x = [10000.21, 22000.32, 10120.54]

Perhaps make a list (comprehension) for the labels, and then apply them "manually".

xlables = [f'{label:,}' for label in x]
plt.xticks(x, xlabels)

HTTP GET in VB.NET

In VB.NET:

Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString("http://api.hostip.info/?ip=68.180.206.184")

In C#:

System.Net.WebClient webClient = new System.Net.WebClient();
string result = webClient.DownloadString("http://api.hostip.info/?ip=68.180.206.184");

How to sort an array in Bash

There is a workaround for the usual problem of spaces and newlines:

Use a character that is not in the original array (like $'\1' or $'\4' or similar).

This function gets the job done:

# Sort an Array may have spaces or newlines with a workaround (wa=$'\4')
sortarray(){ local wa=$'\4' IFS=''
             if [[ $* =~ [$wa] ]]; then
                 echo "$0: error: array contains the workaround char" >&2
                 exit 1
             fi

             set -f; local IFS=$'\n' x nl=$'\n'
             set -- $(printf '%s\n' "${@//$nl/$wa}" | sort -n)
             for    x
             do     sorted+=("${x//$wa/$nl}")
             done
       }

This will sort the array:

$ array=( a b 'c d' $'e\nf' $'g\1h')
$ sortarray "${array[@]}"
$ printf '<%s>\n' "${sorted[@]}"
<a>
<b>
<c d>
<e
f>
<gh>

This will complain that the source array contains the workaround character:

$ array=( a b 'c d' $'e\nf' $'g\4h')
$ sortarray "${array[@]}"
./script: error: array contains the workaround char

description

  • We set two local variables wa (workaround char) and a null IFS
  • Then (with ifs null) we test that the whole array $*.
  • Does not contain any woraround char [[ $* =~ [$wa] ]].
  • If it does, raise a message and signal an error: exit 1
  • Avoid filename expansions: set -f
  • Set a new value of IFS (IFS=$'\n') a loop variable x and a newline var (nl=$'\n').
  • We print all values of the arguments received (the input array $@).
  • but we replace any new line by the workaround char "${@//$nl/$wa}".
  • send those values to be sorted sort -n.
  • and place back all the sorted values in the positional arguments set --.
  • Then we assign each argument one by one (to preserve newlines).
  • in a loop for x
  • to a new array: sorted+=(…)
  • inside quotes to preserve any existing newline.
  • restoring the workaround to a newline "${x//$wa/$nl}".
  • done

Permissions error when connecting to EC2 via SSH on Mac OSx

Tagging on to mecca831's answer:

ssh -v -i generated-key.pem [email protected]

[[email protected] ~]$ sudo passwd ec2-user newpassword newpassword

[[email protected] ~]$ sudo vi /etc/ssh/sshd_config Modify the file as follows:

    # To disable tunneled clear text passwords, change to no here!
    PasswordAuthentication yes
    #PermitEmptyPasswords no
    # EC2 uses keys for remote access
    #PasswordAuthentication no

Save

[[email protected] ~]$ sudo service sshd stop [[email protected] ~]$ sudo service sshd start

you should be able to exit and ssh in as follows:

ssh [email protected]

and be prompted for password no longer needing the key.

How to enter special characters like "&" in oracle database?

To Insert values which has got '&' in it. Use the folloiwng code.

Set define off;

Begin

INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 & Oracle_14');

End ;

And Press F5 from Oracle or Toad Editors.

How can I load webpage content into a div on page load?

With jQuery, it is possible, however not using ajax.

function LoadPage(){
  $.get('http://a_site.com/a_page.html', function(data) {
    $('#siteloader').html(data);
  });
}

And then place onload="LoadPage()" in the body tag.

Although if you follow this route, a php version might be better:

echo htmlspecialchars(file_get_contents("some URL"));

vuejs update parent data from child component

From the documentation:

In Vue.js, the parent-child component relationship can be summarized as props down, events up. The parent passes data down to the child via props, and the child sends messages to the parent via events. Let’s see how they work next.

enter image description here

How to pass props

Following is the code to pass props to a child element:

<div>
  <input v-model="parentMsg">
  <br>
  <child v-bind:my-message="parentMsg"></child>
</div>

How to emit event

HTML:

<div id="counter-event-example">
  <p>{{ total }}</p>
  <button-counter v-on:increment="incrementTotal"></button-counter>
  <button-counter v-on:increment="incrementTotal"></button-counter>
</div>

JS:

Vue.component('button-counter', {
  template: '<button v-on:click="increment">{{ counter }}</button>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    increment: function () {
      this.counter += 1
      this.$emit('increment')
    }
  },
})
new Vue({
  el: '#counter-event-example',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function () {
      this.total += 1
    }
  }
})

Should I use pt or px?

Here you've got a very detailed explanation of their differences

http://kyleschaeffer.com/development/css-font-size-em-vs-px-vs-pt-vs/

The jist of it (from source)

Pixels are fixed-size units that are used in screen media (i.e. to be read on the computer screen). Pixel stands for "picture element" and as you know, one pixel is one little "square" on your screen. Points are traditionally used in print media (anything that is to be printed on paper, etc.). One point is equal to 1/72 of an inch. Points are much like pixels, in that they are fixed-size units and cannot scale in size.

Multiple Updates in MySQL

UPDATE `your_table` SET 

`something` = IF(`id`="1","new_value1",`something`), `smth2` = IF(`id`="1", "nv1",`smth2`),
`something` = IF(`id`="2","new_value2",`something`), `smth2` = IF(`id`="2", "nv2",`smth2`),
`something` = IF(`id`="4","new_value3",`something`), `smth2` = IF(`id`="4", "nv3",`smth2`),
`something` = IF(`id`="6","new_value4",`something`), `smth2` = IF(`id`="6", "nv4",`smth2`),
`something` = IF(`id`="3","new_value5",`something`), `smth2` = IF(`id`="3", "nv5",`smth2`),
`something` = IF(`id`="5","new_value6",`something`), `smth2` = IF(`id`="5", "nv6",`smth2`) 

// You just building it in php like

$q = 'UPDATE `your_table` SET ';

foreach($data as $dat){

  $q .= '

       `something` = IF(`id`="'.$dat->id.'","'.$dat->value.'",`something`), 
       `smth2` = IF(`id`="'.$dat->id.'", "'.$dat->value2.'",`smth2`),';

}

$q = substr($q,0,-1);

So you can update hole table with one query

Reading file using relative path in python project

I was thundered when the following code worked.

import os

for file in os.listdir("../FutureBookList"):
    if file.endswith(".adoc"):
        filename, file_extension = os.path.splitext(file)
        print(filename)
        print(file_extension)
        continue
    else:
        continue

So, I checked the documentation and it says:

Changed in version 3.6: Accepts a path-like object.

path-like object:

An object representing a file system path. A path-like object is either a str or...

I did a little more digging and the following also works:

with open("../FutureBookList/file.txt") as file:
   data = file.read()

What is the best comment in source code you have ever encountered?

Beware of bugs in the above code; I have only proved it correct, not tried it.

That one is by Donald Knuth.

Find length of 2D array Python

You can also use np.size(a,1), 1 here is the axis and this will give you the number of columns

Sql Server equivalent of a COUNTIF aggregate function

I had to use COUNTIF() in my case as part of my SELECT columns AND to mimic a % of the number of times each item appeared in my results.

So I used this...

SELECT COL1, COL2, ... ETC
       (1 / SELECT a.vcount 
            FROM (SELECT vm2.visit_id, count(*) AS vcount 
                  FROM dbo.visitmanifests AS vm2 
                  WHERE vm2.inactive = 0 AND vm2.visit_id = vm.Visit_ID 
                  GROUP BY vm2.visit_id) AS a)) AS [No of Visits],
       COL xyz
FROM etc etc

Of course you will need to format the result according to your display requirements.

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

Be aware that one of PowerShell's security features is that users can NOT launch script with a double click. Use great care if you modify this setting. An alternative might be to package your script. Some editors like PrimalScript can do that. The users still need PowerShell installed but then they can double-click the exe. And it sounds like your team needs a little education.

How can I run a html file from terminal?

It is possible to view a html file from terminal using lynx or links. But none of those browswers support the onload javascript feature. By using lynx or links you will have to actively click the submit button.

How can I compile and run c# program without using visual studio?

Another option is an interesting open source project called ScriptCS. It uses some crafty techniques to allow you a development experience outside of Visual Studio while still being able to leverage NuGet to manage your dependencies. It's free, very easy to install using Chocolatey. You can check it out here http://scriptcs.net.

Another cool feature it has is the REPL from the command line. Which allows you to do stuff like this:

C:\> scriptcs
scriptcs (ctrl-c or blank to exit)

> var message = "Hello, world!";
> Console.WriteLine(message);
Hello, world!
> 

C:\>

You can create C# utility "scripts" which can be anything from small system tasks, to unit tests, to full on Web APIs. In the latest release I believe they're also allowing for hosting the runtime in your own apps.

Check out it development on the GitHub page too https://github.com/scriptcs/scriptcs

Vue.js get selected option on @change

You can save your @change="onChange()" an use watchers. Vue computes and watches, it´s designed for that. In case you only need the value and not other complex Event atributes.

Something like:

  ...
  watch: {
    leaveType () {
      this.whateverMethod(this.leaveType)
    }
  },
  methods: {
     onChange() {
         console.log('The new value is: ', this.leaveType)
     }
  }

changing default x range in histogram matplotlib

import matplotlib.pyplot as plt


...


plt.xlim(xmin=6.5, xmax = 12.5)

How to left align a fixed width string?

This version uses the str.format method.

Python 2.7 and newer

sys.stdout.write("{:<7}{:<51}{:<25}\n".format(code, name, industry))

Python 2.6 version

sys.stdout.write("{0:<7}{1:<51}{2:<25}\n".format(code, name, industry))

UPDATE

Previously there was a statement in the docs about the % operator being removed from the language in the future. This statement has been removed from the docs.

How to set default value for form field in Symfony2?

Default values are set by configuring corresponding entity. Before binding the entity to form set its color field to "#0000FF":

// controller action
$project = new Project();
$project->setColor('#0000FF');
$form = $this->createForm(new ProjectType(), $project);

Modelling an elevator using Object-Oriented Analysis and Design

First there is an elevator class. It has a direction (up, down, stand, maintenance), a current floor and a list of floor requests sorted in the direction. It receives request from this elevator.

Then there is a bank. It contains the elevators and receives the requests from the floors. These are scheduled to all active elevators (not in maintenance).

The scheduling will be like:

  • if available pick a standing elevator for this floor.
  • else pick an elevator moving to this floor.
  • else pick a standing elevator on an other floor.
  • else pick the elevator with the lowest load.

Each elevator has a set of states.

  • Maintenance: the elevator does not react to external signals (only to its own signals).
  • Stand: the elevator is fixed on a floor. If it receives a call. And the elevator is on that floor, the doors open. If it is on another floor, it moves in that direction.
  • Up: the elevator moves up. Each time it reaches a floor, it checks if it needs to stop. If so it stops and opens the doors. It waits for a certain amount of time and closes the door (unless someting is moving through them. Then it removes the floor from the request list and checks if there is another request. If so the elevator starts moving again. If not it enters the state stand.
  • Down: like up but in reverse direction.

There are additional signals:

  • alarm. The elevator stops. And if it is on a floor, the doors open, the request list is cleared, the requests moved back to the bank.
  • door open. Opens the doors if an elevator is on a floor and not moving.
  • door closes. Closed the door if they are open.

EDIT: Some elevators don't start at bottom/first_floor esp. in case of skyscrapers.

min_floor & max_floor are two additional attributes for Elevator.

Regex for not empty and not whitespace

I ended up using something similar to the accepted answer, with minor modifications

(^$)|(\s+$)

Explanation by the Expresso

Select from 2 alternatives (^$)
    [1] A numbered captured group ^$
        Beginning of line ^
        End of line $
    [2] A numbered captured group (\s+$)
        Whitespace, one or more repetitions \s+
        End of line $

SET NOCOUNT ON usage

SET NOCOUNT ON;

This line of code is used in SQL for not returning the number rows affected in the execution of the query. If we don't require the number of rows affected, we can use this as this would help in saving memory usage and increase the speeed of execution of the query.

Create ArrayList from array

Java 9

In Java 9, you can use List.of static factory method in order to create a List literal. Something like the following:

List<Element> elements = List.of(new Element(1), new Element(2), new Element(3));

This would return an immutable list containing three elements. If you want a mutable list, pass that list to the ArrayList constructor:

new ArrayList<>(List.of(// elements vararg))

JEP 269: Convenience Factory Methods for Collections

JEP 269 provides some convenience factory methods for Java Collections API. These immutable static factory methods are built into the List, Set, and Map interfaces in Java 9 and later.

How to check if smtp is working from commandline (Linux)

[root@piwik-dev tmp]# mail -v root@localhost
Subject: Test
Hello world
Cc:  <Ctrl+D>

root@localhost... Connecting to [127.0.0.1] via relay...
220 piwik-dev.example.com ESMTP Sendmail 8.13.8/8.13.8; Thu, 23 Aug 2012 10:49:40 -0400
>>> EHLO piwik-dev.example.com
250-piwik-dev.example.com Hello localhost.localdomain [127.0.0.1], pleased to meet you
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-8BITMIME
250-SIZE
250-DSN
250-ETRN
250-DELIVERBY
250 HELP
>>> MAIL From:<[email protected]> SIZE=46
250 2.1.0 <[email protected]>... Sender ok
>>> RCPT To:<[email protected]>
>>> DATA
250 2.1.5 <[email protected]>... Recipient ok
354 Enter mail, end with "." on a line by itself
>>> .
250 2.0.0 q7NEneju002633 Message accepted for delivery
root@localhost... Sent (q7NEneju002633 Message accepted for delivery)
Closing connection to [127.0.0.1]
>>> QUIT
221 2.0.0 piwik-dev.example.com closing connection

close fxml window by code, javafx

finally, I found a solution

 Window window =   ((Node)(event.getSource())).getScene().getWindow(); 
            if (window instanceof Stage){
                ((Stage) window).close();
            }

How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?

You can define foreign key by:

public class Parent
{
   public int Id { get; set; }
   public virtual ICollection<Child> Childs { get; set; }
}

public class Child
{
   public int Id { get; set; }
   // This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
   public int ParentId { get; set; } 
   public virtual Parent Parent { get; set; }
}

Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.

If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation

Data annotation:

// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }

Fluent API:

modelBuilder.Entity<Child>()
            .HasRequired(c => c.Parent)
            .WithMany(p => p.Childs)
            .HasForeignKey(c => c.ParentId);

Other types of constraints can be enforced by data annotations and model validation.

Edit:

You will get an exception if you don't set ParentId. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.

C# 'or' operator?

The single " | " operator will evaluate both sides of the expression.

    if (ActionsLogWriter.Close | ErrorDumpWriter.Close == true)
{
    // Do stuff here
}

The double operator " || " will only evaluate the left side if the expression returns true.

    if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{
    // Do stuff here
}

C# has many similarities to C++ but their still are differences between the two languages ;)

Iteration over std::vector: unsigned vs signed index variable

If your compiler supports it, you could use a range based for to access the vector elements:

vector<float> vertices{ 1.0, 2.0, 3.0 };

for(float vertex: vertices){
    std::cout << vertex << " ";
}

Prints: 1 2 3 . Note, you can't use this technique for changing the elements of the vector.

css divide width 100% to 3 column

A perfect 1/3 cannot exist in CSS with full cross browser support (anything below IE9). I personally would do: (It's not the perfect solution, but it's about as good as you'll get for all browsers)

#c1, #c2 {
    width: 33%;
}

#c3 {
    width: auto;
}

Conditionally displaying JSF components

Yes, use the rendered attribute.

<h:form rendered="#{some boolean condition}">

You usually tie it to the model rather than letting the model grab the component and manipulate it.

E.g.

<h:form rendered="#{bean.booleanValue}" />
<h:form rendered="#{bean.intValue gt 10}" />
<h:form rendered="#{bean.objectValue eq null}" />
<h:form rendered="#{bean.stringValue ne 'someValue'}" />
<h:form rendered="#{not empty bean.collectionValue}" />
<h:form rendered="#{not bean.booleanValue and bean.intValue ne 0}" />
<h:form rendered="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

Note the importance of keyword based EL operators such as gt, ge, le and lt instead of >, >=, <= and < as angle brackets < and > are reserved characters in XML. See also this related Q&A: Error parsing XHTML: The content of elements must consist of well-formed character data or markup.

As to your specific use case, let's assume that the link is passing a parameter like below:

<a href="page.xhtml?form=1">link</a>

You can then show the form as below:

<h:form rendered="#{param.form eq '1'}">

(the #{param} is an implicit EL object referring to a Map representing the request parameters)

See also:

How to exclude subdirectories in the destination while using /mir /xd switch in robocopy

When i tried the solution with /XD i found, that the path to exclude should be the source path - not the destination.

e.g. this Works

robocopy c:\test\a c:\test\b /MIR /XD c:\test\a\leavethisdiralone\

Getting value of selected item in list box as string

If you are using ListBox in your application and you want to return the selected value of ListBox and display it in a Label or any thing else then use this code, it will help you

 private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
         label1.Text  = listBox1.SelectedItem.ToString();
    }

Connection to SQL Server Works Sometimes

Ive had the same error just come up which aligned suspiciously with the latest round of Microsoft updates (09/02/2016). I found that SSMS connected without issue while my ASP.NET application returned the "timeout period elapsed while attempting to consume the pre-login handshake acknowledgement" error

The solution for me was to add a connection timeout of 30 seconds into the connection string eg:

ConnectionString="Data Source=xyz;Initial Catalog=xyz;Integrated Security=True;Connection Timeout=30;"

In my situation the only affected connection was one that was using integrated Security and I was impersonating a user before connecting, other connections to the same server using SQL Authentication worked fine!

2 test systems (separate clients and Sql servers) were affected at the same time leading me to suspect a microsoft update!

Find all controls in WPF Window by type

@Bryce, really nice answer.

VB.NET version:

Public Shared Iterator Function FindVisualChildren(Of T As DependencyObject)(depObj As DependencyObject) As IEnumerable(Of T)
    If depObj IsNot Nothing Then
        For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(depObj) - 1
            Dim child As DependencyObject = VisualTreeHelper.GetChild(depObj, i)
            If child IsNot Nothing AndAlso TypeOf child Is T Then
                Yield DirectCast(child, T)
            End If
            For Each childOfChild As T In FindVisualChildren(Of T)(child)
                Yield childOfChild
            Next
        Next
    End If
End Function

Usage (this disables all TextBoxes in a window):

        For Each tb As TextBox In FindVisualChildren(Of TextBox)(Me)
          tb.IsEnabled = False
        Next

SQL - ORDER BY 'datetime' DESC

Try:

SELECT post_datetime 
FROM post 
WHERE type = 'published' 
ORDER BY post_datetime DESC 
LIMIT 3

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

I found that following these instructions helped with finding what the problem was. For me, that was the killer, not knowing what was broken.

http://mythinkpond.wordpress.com/2011/07/01/tomcat-6-infamous-severe-error-listenerstart-message-how-to-debug-this-error/

Quoting from the link

In Tomcat 6 or above, the default logger is the”java.util.logging” logger and not Log4J. So if you are trying to add a “log4j.properties” file – this will NOT work. The Java utils logger looks for a file called “logging.properties” as stated here: http://tomcat.apache.org/tomcat-6.0-doc/logging.html

So to get to the debugging details create a “logging.properties” file under your”/WEB-INF/classes” folder of your WAR and you’re all set.

And now when you restart your Tomcat, you will see all of your debugging in it’s full glory!!!

Sample logging.properties file:

org.apache.catalina.core.ContainerBase.[Catalina].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].handlers = java.util.logging.ConsoleHandler

Replace non ASCII character from string

FailedDev's answer is good, but can be improved. If you want to preserve the ascii equivalents, you need to normalize first:

String subjectString = "öäü";
subjectString = Normalizer.normalize(subjectString, Normalizer.Form.NFD);
String resultString = subjectString.replaceAll("[^\\x00-\\x7F]", "");

=> will produce "oau"

That way, characters like "öäü" will be mapped to "oau", which at least preserves some information. Without normalization, the resulting String will be blank.

How to hide Android soft keyboard on EditText

   public class NonKeyboardEditText extends AppCompatEditText {

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

    @Override
    public boolean onCheckIsTextEditor() {
        return false;
    }
}

and add

NonKeyboardEditText.setTextIsSelectable(true);

Output grep results to text file, need cleaner output

Redirection of program output is performed by the shell.

grep ... > output.txt

grep has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1) man page for details, specifically the -C and --color options.

How to extract this specific substring in SQL Server?

Assuming they always exist and are not part of your data, this will work:

declare @string varchar(8000) = '23;chair,red [$3]'
select substring(@string, charindex(';', @string) + 1, charindex(' [', @string) - charindex(';', @string) - 1)

change directory in batch file using variable

The set statement doesn't treat spaces the way you expect; your variable is really named Pathname[space] and is equal to [space]C:\Program Files.

Remove the spaces from both sides of the = sign, and put the value in double quotes:

set Pathname="C:\Program Files"

Also, if your command prompt is not open to C:\, then using cd alone can't change drives.

Use

cd /d %Pathname%

or

pushd %Pathname%

instead.

How to format string to money

decimal value = 0.00M;
value = Convert.ToDecimal(12345.12345);
Console.WriteLine(value.ToString("C"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C1"));
//OutPut : $12345.1
Console.WriteLine(value.ToString("C2"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C3"));
//OutPut : $12345.123
Console.WriteLine(value.ToString("C4"));
//OutPut : $12345.1234
Console.WriteLine(value.ToString("C5"));
//OutPut : $12345.12345
Console.WriteLine(value.ToString("C6"));
//OutPut : $12345.123450

Console output:

Cannot open new Jupyter Notebook [Permission Denied]

  1. Open Anaconda prompt
  2. Go to C:\Users\your_name
  3. Write jupyter trust untitled.ipynb
  4. Then, write jupyter notebook

Get the current year in JavaScript

Such is how I have it embedded and outputted to my HTML web page:

<div class="container">
    <p class="text-center">Copyright &copy; 
        <script>
            var CurrentYear = new Date().getFullYear()
            document.write(CurrentYear)
        </script>
    </p>
</div>

Output to HTML page is as follows:

Copyright © 2018

How do I convert a PDF document to a preview image in PHP?

Think differently, You can use the following library to convert pdf to image using javascript

http://usefulangle.com/post/24/pdf-to-jpeg-png-with-pdfjs

Android Device Chooser -- device not showing up

In galaxy note 3 you need to enable the developer option. Access the "About Device" and click on the Build number multiple time until a message appear which telling you that the developer option has been enabled. Go back to general and there your go..the developer option has been enabled and select USB debugging option. This is for Galaxy note 3 N9005 Andriod 4.3.

Angular 4 - Observable catch error

catch needs to return an observable.

.catch(e => { console.log(e); return Observable.of(e); })

if you'd like to stop the pipeline after a caught error, then do this:

.catch(e => { console.log(e); return Observable.of(null); }).filter(e => !!e)

this catch transforms the error into a null val and then filter doesn't let falsey values through. This will however, stop the pipeline for ANY falsey value, so if you think those might come through and you want them to, you'll need to be more explicit / creative.

edit:

better way of stopping the pipeline is to do

.catch(e => Observable.empty())

Fastest way to remove first char in a String

You could profile it, if you really cared. Write a loop of many iterations and see what happens. Chances are, however, that this is not the bottleneck in your application, and TrimStart seems the most semantically correct. Strive to write code readably before optimizing.

Count all occurrences of a string in lots of files with grep

cat * | grep -c string

One of the rare useful applications of cat.

Close Android Application

not a one-line-code solution, but pretty easy:

sub-class Activity, then override and add finish() to onPause() method

this way, activity will be gone once it enters background, therefore the app won't keep a stack of activities, you can finish() the current activity and the app is gone!

adding css file with jquery

Your issue is that your selector is for an anchor element <a>. You are treating the <a> tag as if it represents the page which is not the case.

$('head') will work as long as this selector is being executed by the page that needs the css.

Why not simply add the css file to the page in question. Any particular reason to attempt this dynamically from another page? I am not even familiar with a way to inject css to remote pages like this ... seems like it would be a major security hole.

ADDENDUM to your reasoning:

Then you should simply pass a parameter to the page, read it using javascript, and then do whatever is needed based on the parameter.

How to restrict UITextField to take only numbers in Swift?

For allow some charactors

func CheckAddress(string:String) -> Bool  {
        let numberOnly = NSCharacterSet.init(charactersIn: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-@,&#/")
        let stringFromTextField = NSCharacterSet.init(charactersIn: string)
        return numberOnly.isSuperset(of: stringFromTextField as CharacterSet)
    }

print("\(CheckAddress(string: "123"))") //True
print("\(CheckAddress(string: "asdf-"))") //True
print("\(CheckAddress(string: "asd123$"))") //false

How do I center list items inside a UL element?

I overcame the problem with this solution.

HTML:

<div class="list-wrapper">
    <ul>
        <li>a</li>
        <li>b</li>
        <li>c</li>
        <li>d</li>
        <li>e</li>
    </ul>
</div>

CSS:

.list-wrapper {
   text-align: -webkit-center;
}
.list-wrapper ul {
    display:block;
}   

401 Unauthorized: Access is denied due to invalid credentials

If you're using IIS 7 do something like this:

  1. Select your site.
  2. Click on error pages.
  3. Edit feature settings.
  4. Select detailed errors.

How to get Url Hash (#) from server side

That's because the browser doesn't transmit that part to the server, sorry.

Closing Excel Application Process in C# after Data Access

workbook.Close(0);
excelApp.Quit();

Worked for me.

Simple C example of doing an HTTP POST and consuming the response

A message has a header part and a message body separated by a blank line. The blank line is ALWAYS needed even if there is no message body. The header starts with a command and has additional lines of key value pairs separated by a colon and a space. If there is a message body, it can be anything you want it to be.

Lines in the header and the blank line at the end of the header must end with a carraige return and linefeed pair (see HTTP header line break style) so that's why those lines have \r\n at the end.

A URL has the form of http://host:port/path?query_string

There are two main ways of submitting a request to a website:

  • GET: The query string is optional but, if specified, must be reasonably short. Because of this the header could just be the GET command and nothing else. A sample message could be:

    GET /path?query_string HTTP/1.0\r\n
    \r\n
    
  • POST: What would normally be in the query string is in the body of the message instead. Because of this the header needs to include the Content-Type: and Content-Length: attributes as well as the POST command. A sample message could be:

    POST /path HTTP/1.0\r\n
    Content-Type: text/plain\r\n
    Content-Length: 12\r\n
    \r\n
    query_string
    

So, to answer your question: if the URL you are interested in POSTing to is http://api.somesite.com/apikey=ARG1&command=ARG2 then there is no body or query string and, consequently, no reason to POST because there is nothing to put in the body of the message and so nothing to put in the Content-Type: and Content-Length:

I guess you could POST if you really wanted to. In that case your message would look like:

POST /apikey=ARG1&command=ARG2 HTTP/1.0\r\n
\r\n

So to send the message the C program needs to:

  • create a socket
  • lookup the IP address
  • open the socket
  • send the request
  • wait for the response
  • close the socket

The send and receive calls won't necessarily send/receive ALL the data you give them - they will return the number of bytes actually sent/received. It is up to you to call them in a loop and send/receive the remainder of the message.

What I did not do in this sample is any sort of real error checking - when something fails I just exit the program. Let me know if it works for you:

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#include <sys/socket.h> /* socket, connect */
#include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#include <netdb.h> /* struct hostent, gethostbyname */

void error(const char *msg) { perror(msg); exit(0); }

int main(int argc,char *argv[])
{
    /* first what are we going to send and where are we going to send it? */
    int portno =        80;
    char *host =        "api.somesite.com";
    char *message_fmt = "POST /apikey=%s&command=%s HTTP/1.0\r\n\r\n";

    struct hostent *server;
    struct sockaddr_in serv_addr;
    int sockfd, bytes, sent, received, total;
    char message[1024],response[4096];

    if (argc < 3) { puts("Parameters: <apikey> <command>"); exit(0); }

    /* fill in the parameters */
    sprintf(message,message_fmt,argv[1],argv[2]);
    printf("Request:\n%s\n",message);

    /* create the socket */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) error("ERROR opening socket");

    /* lookup the ip address */
    server = gethostbyname(host);
    if (server == NULL) error("ERROR, no such host");

    /* fill in the structure */
    memset(&serv_addr,0,sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(portno);
    memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);

    /* connect the socket */
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
        error("ERROR connecting");

    /* send the request */
    total = strlen(message);
    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);

    /* receive the response */
    memset(response,0,sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    do {
        bytes = read(sockfd,response+received,total-received);
        if (bytes < 0)
            error("ERROR reading response from socket");
        if (bytes == 0)
            break;
        received+=bytes;
    } while (received < total);

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);

    /* process response */
    printf("Response:\n%s\n",response);

    return 0;
}

Like the other answer pointed out, 4096 bytes is not a very big response. I picked that number at random assuming that the response to your request would be short. If it can be big you have two choices:

  • read the Content-Length: header from the response and then dynamically allocate enough memory to hold the whole response.
  • write the response to a file as the pieces arrive

Additional information to answer the question asked in the comments:

What if you want to POST data in the body of the message? Then you do need to include the Content-Type: and Content-Length: headers. The Content-Length: is the actual length of everything after the blank line that separates the header from the body.

Here is a sample that takes the following command line arguments:

  • host
  • port
  • command (GET or POST)
  • path (not including the query data)
  • query data (put into the query string for GET and into the body for POST)
  • list of headers (Content-Length: is automatic if using POST)

So, for the original question you would run:

a.out api.somesite.com 80 GET "/apikey=ARG1&command=ARG2"

And for the question asked in the comments you would run:

a.out api.somesite.com 80 POST / "name=ARG1&value=ARG2" "Content-Type: application/x-www-form-urlencoded"

Here is the code:

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit, atoi, malloc, free */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#include <sys/socket.h> /* socket, connect */
#include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#include <netdb.h> /* struct hostent, gethostbyname */

void error(const char *msg) { perror(msg); exit(0); }

int main(int argc,char *argv[])
{
    int i;

    /* first where are we going to send it? */
    int portno = atoi(argv[2])>0?atoi(argv[2]):80;
    char *host = strlen(argv[1])>0?argv[1]:"localhost";

    struct hostent *server;
    struct sockaddr_in serv_addr;
    int sockfd, bytes, sent, received, total, message_size;
    char *message, response[4096];

    if (argc < 5) { puts("Parameters: <host> <port> <method> <path> [<data> [<headers>]]"); exit(0); }

    /* How big is the message? */
    message_size=0;
    if(!strcmp(argv[3],"GET"))
    {
        message_size+=strlen("%s %s%s%s HTTP/1.0\r\n");        /* method         */
        message_size+=strlen(argv[3]);                         /* path           */
        message_size+=strlen(argv[4]);                         /* headers        */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* query string   */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        message_size+=strlen("\r\n");                          /* blank line     */
    }
    else
    {
        message_size+=strlen("%s %s HTTP/1.0\r\n");
        message_size+=strlen(argv[3]);                         /* method         */
        message_size+=strlen(argv[4]);                         /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        if(argc>5)
            message_size+=strlen("Content-Length: %d\r\n")+10; /* content length */
        message_size+=strlen("\r\n");                          /* blank line     */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* body           */
    }

    /* allocate space for the message */
    message=malloc(message_size);

    /* fill in the parameters */
    if(!strcmp(argv[3],"GET"))
    {
        if(argc>5)
            sprintf(message,"%s %s%s%s HTTP/1.0\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                strlen(argv[4])>0?argv[4]:"/",                 /* path           */
                strlen(argv[5])>0?"?":"",                      /* ?              */
                strlen(argv[5])>0?argv[5]:"");                 /* query string   */
        else
            sprintf(message,"%s %s HTTP/1.0\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                strlen(argv[4])>0?argv[4]:"/");                /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        strcat(message,"\r\n");                                /* blank line     */
    }
    else
    {
        sprintf(message,"%s %s HTTP/1.0\r\n",
            strlen(argv[3])>0?argv[3]:"POST",                  /* method         */
            strlen(argv[4])>0?argv[4]:"/");                    /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        if(argc>5)
            sprintf(message+strlen(message),"Content-Length: %d\r\n",strlen(argv[5]));
        strcat(message,"\r\n");                                /* blank line     */
        if(argc>5)
            strcat(message,argv[5]);                           /* body           */
    }

    /* What are we going to send? */
    printf("Request:\n%s\n",message);

    /* create the socket */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) error("ERROR opening socket");

    /* lookup the ip address */
    server = gethostbyname(host);
    if (server == NULL) error("ERROR, no such host");

    /* fill in the structure */
    memset(&serv_addr,0,sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(portno);
    memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);

    /* connect the socket */
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
        error("ERROR connecting");

    /* send the request */
    total = strlen(message);
    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);

    /* receive the response */
    memset(response,0,sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    do {
        bytes = read(sockfd,response+received,total-received);
        if (bytes < 0)
            error("ERROR reading response from socket");
        if (bytes == 0)
            break;
        received+=bytes;
    } while (received < total);

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);

    /* process response */
    printf("Response:\n%s\n",response);

    free(message);
    return 0;
}

How to set maximum fullscreen in vmware?

Go to view and press "Switch to scale mode" which will adjust the virtual screen when you adjust the application.

"Could not run curl-config: [Errno 2] No such file or directory" when installing pycurl

I encountered the same problem whilst trying to get Shinken 2.0.3 to fire up on Ubuntu. Eventually I did a full uninstall then reinstalled Shinken with pip -v. As it cleaned up, it mentioned:

Warning: missing python-pycurl lib, you MUST install it before launch the shinken daemons

Installed that with apt-get, and all the brokers fired up as expected :-)

How to split a string in Java

One way to do this is to run through the String in a for-each loop and use the required split character.

public class StringSplitTest {

    public static void main(String[] arg){
        String str = "004-034556";
        String split[] = str.split("-");
        System.out.println("The split parts of the String are");
        for(String s:split)
        System.out.println(s);
    }
}

Output:

The split parts of the String are:
004
034556

How to ignore a particular directory or file for tslint?

Currently using Visual Studio Code and the command to disable tslint is

/* tslint:disable */

Something to note. The disable above disables ALL tslint rules on that page. If you want to disable a specific rule you can specify one/multiple rules.

/* tslint:disable comment-format */
/* tslint:disable:rule1 rule2 rule3 etc.. */

Or enable a rule

/* tslint:enable comment-format */

More in depth on TSLint rule flags

How to sort the files according to the time stamp in unix?

File modification:

ls -t

Inode change:

ls -tc

File access:

ls -tu

"Newest" one at the bottom:

ls -tr

None of this is a creation time. Most Unix filesystems don't support creation timestamps.

Replace HTML Table with Divs

This ought to do the trick.

<style>
div.block{
  overflow:hidden;
}
div.block label{
  width:160px;
  display:block;
  float:left;
  text-align:left;
}
div.block .input{
  margin-left:4px;
  float:left;
}
</style>

<div class="block">
  <label>First field</label>
  <input class="input" type="text" id="txtFirstName"/>
</div>
<div class="block">
  <label>Second field</label>
  <input class="input" type="text" id="txtLastName"/>
</div>

I hope you get the concept.

TypeError: worker() takes 0 positional arguments but 1 was given

I get this error whenever I mistakenly create a Python class using def instead of class:

def Foo():
    def __init__(self, x):
        self.x = x
# python thinks we're calling a function Foo which takes 0 args   
a = Foo(x) 

TypeError: Foo() takes 0 positional arguments but 1 was given

Oops!

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

Format Date output in JSF

If you use OmniFaces you can also use it's EL functions like of:formatDate() to format Date objects. You would use it like this:

<h:outputText value="#{of:formatDate(someBean.dateField, 'dd.MM.yyyy HH:mm')}" />

This way you can not only use it for output but also to pass it on to other JSF components.

Fastest way to list all primes below N

I found a pure Python 2 prime generator here , in a comment by Willy Good, that is faster than rwh2_primes.

def primes235(limit):
yield 2; yield 3; yield 5
if limit < 7: return
modPrms = [7,11,13,17,19,23,29,31]
gaps = [4,2,4,2,4,6,2,6,4,2,4,2,4,6,2,6] # 2 loops for overflow
ndxs = [0,0,0,0,1,1,2,2,2,2,3,3,4,4,4,4,5,5,5,5,5,5,6,6,7,7,7,7,7,7]
lmtbf = (limit + 23) // 30 * 8 - 1 # integral number of wheels rounded up
lmtsqrt = (int(limit ** 0.5) - 7)
lmtsqrt = lmtsqrt // 30 * 8 + ndxs[lmtsqrt % 30] # round down on the wheel
buf = [True] * (lmtbf + 1)
for i in xrange(lmtsqrt + 1):
    if buf[i]:
        ci = i & 7; p = 30 * (i >> 3) + modPrms[ci]
        s = p * p - 7; p8 = p << 3
        for j in range(8):
            c = s // 30 * 8 + ndxs[s % 30]
            buf[c::p8] = [False] * ((lmtbf - c) // p8 + 1)
            s += p * gaps[ci]; ci += 1
for i in xrange(lmtbf - 6 + (ndxs[(limit - 7) % 30])): # adjust for extras
    if buf[i]: yield (30 * (i >> 3) + modPrms[i & 7])

My results:

$ time ./prime_rwh2.py 1e8
5761455 primes found < 1e8

real    0m3.201s
user    0m2.609s
sys     0m0.578s
$ time ./prime_wheel.py 1e8
5761455 primes found < 1e8

real    0m2.710s
user    0m2.469s
sys     0m0.219s

...on my recent midrange laptop (i5 8265U 1.6GHz) running Ubuntu on Win 10.

This is a mod 30 wheel sieve which skips multiples of 2, 3, and 5. It works great for me up to about 2.5e9, when my laptop starts running out of 8G RAM and swapping a lot.

I like mod 30 since it has only 8 remainders that aren't multiples of 2, 3, or 5. That enables using shifts and "&" for multiplication, division and mod, and should allow packing results for one mod 30 wheel into a byte. I have morphed Willy's code into a segmented mod 30 wheel sieve to eliminate the thrashing for big N and posted it here.

There is an even faster Javascript version which is segmented and uses a mod 210 wheel (no multiples of 2, 3, 5, or 7) by @GordonBGood with an in depth explanation that is useful to me.

How to retrieve form values from HTTPPOST, dictionary or?

Simply, you can use FormCollection like:

[HttpPost] 
public ActionResult SubmitAction(FormCollection collection)
{
     // Get Post Params Here
 string var1 = collection["var1"];
}

You can also use a class, that is mapped with Form values, and asp.net mvc engine automagically fills it:

//Defined in another file
class MyForm
{
  public string var1 { get; set; }
}

[HttpPost]
public ActionResult SubmitAction(MyForm form)
{      
  string var1 = form1.Var1;
}

How to increase space between dotted border dots

You could create a canvas (via javascript) and draw a dotted line within. Within the canvas you can control how long the dash and the space in between shall be.

What is the difference between i++ & ++i in a for loop?

Here's a sample class:

public class Increment
{
    public static void main(String [] args)
    {
        for (int i = 0; i < args.length; ++i)
        {
            System.out.println(args[i]);
        }
    }
}

If I disassemble this class using javap.exe I get this:

Compiled from "Increment.java"
public class Increment extends java.lang.Object{
public Increment();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   iconst_0
   1:   istore_1
   2:   iload_1
   3:   aload_0
   4:   arraylength
   5:   if_icmpge       23
   8:   getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   11:  aload_0
   12:  iload_1
   13:  aaload
   14:  invokevirtual   #3; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   17:  iinc    1, 1
   20:  goto    2
   23:  return

}

If I change the loop so it uses i++ and disassemble again I get this:

Compiled from "Increment.java"
public class Increment extends java.lang.Object{
public Increment();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   iconst_0
   1:   istore_1
   2:   iload_1
   3:   aload_0
   4:   arraylength
   5:   if_icmpge       23
   8:   getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   11:  aload_0
   12:  iload_1
   13:  aaload
   14:  invokevirtual   #3; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   17:  iinc    1, 1
   20:  goto    2
   23:  return

}

When I compare the two, TextPad tells me that the two are identical.

What this says is that from the point of view of the generated byte code there's no difference in a loop. In other contexts there is a difference between ++i and i++, but not for loops.

SQL Server command line backup statement

Combine Remove Old Backup files with above script then this can perform backup by a scheduler, keep last 10 backup files

echo off
:: set folder to save backup files ex. BACKUPPATH=c:\backup
set BACKUPPATH=<<back up folder here>>

:: set Sql Server location ex. set SERVERNAME=localhost\SQLEXPRESS
set SERVERNAME=<<sql host here>>

:: set Database name to backup
set DATABASENAME=<<db name here>>

:: filename format Name-Date (eg MyDatabase-2009-5-19_1700.bak)
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)

set DATESTAMP=%mydate%_%mytime%
set BACKUPFILENAME=%BACKUPPATH%\%DATABASENAME%-%DATESTAMP%.bak
echo.

sqlcmd -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = N'%BACKUPFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%DATABASENAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.

:: In this case, we are choosing to keep the most recent 10 files
:: Also, the files we are looking for have a 'bak' extension
for /f "skip=10 delims=" %%F in ('dir %BACKUPPATH%\*.bak /s/b/o-d/a-d') do del "%%F"

fatal: Not a valid object name: 'master'

When I git init a folder it doesn't create a master branch

This is true, and expected behaviour. Git will not create a master branch until you commit something.

When I do git --bare init it creates the files.

A non-bare git init will also create the same files, in a hidden .git directory in the root of your project.

When I type git branch master it says "fatal: Not a valid object name: 'master'"

That is again correct behaviour. Until you commit, there is no master branch.

You haven't asked a question, but I'll answer the question I assumed you mean to ask. Add one or more files to your directory, and git add them to prepare a commit. Then git commit to create your initial commit and master branch.

Can you use Microsoft Entity Framework with Oracle?

DevArt's OraDirect provider now supports entity framework. See http://devart.com/news/2008/directs475.html

Bootstrap 3: Using img-circle, how to get circle from non-square image?

You stated you want circular crops from recangles. This may not be able to be done with the 3 popular bootstrap classes (img-rounded; img-circle; img-polaroid)

You may want to write a custom CSS class using border-radius where you have more control. If you want it more circular just increase the radius.

_x000D_
_x000D_
.CattoBorderRadius_x000D_
{_x000D_
    border-radius: 25px;_x000D_
}
_x000D_
<img class="img-responsive CattoBorderRadius" src="http://placekitten.com/g/200/200" />
_x000D_
_x000D_
_x000D_

Fiddle URL: http://jsfiddle.net/ccatto/LyxEb/

I know this may not be the perfect radius but I think your answer will use a custom css class. Hope this helps.

Rails: update_attribute vs update_attributes

I think your question is if having an update_attribute in a before_save will lead to and endless loop (of update_attribute calls in before_save callbacks, originally triggered by an update_attribute call)

I'm pretty sure it does bypass the before_save callback since it doesn't actually save the record. You can also save a record without triggering validations by using

Model.save false

Convert Rows to columns using 'Pivot' in SQL Server

This is what you can do:

SELECT * 
FROM yourTable
PIVOT (MAX(xCount) 
       FOR Week in ([1],[2],[3],[4],[5],[6],[7])) AS pvt

DEMO

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

Select the project -> Right-Click -> clean and build and then run the project again simply solve the problem for me.

As, multiple process could bind the same port for example port 8086, In that case I have to kill all the processes involved with the port with PID. That might be cumbersome.

Error: stray '\240' in program

The /240 error is due to illegal spaces before every code of line.

eg.

Do

printf("Anything");

instead of

 printf("Anything");

This error is common when you copied and pasted the code in the IDE.

java: How can I do dynamic casting of a variable from one type to another?

Your problem is not the lack of "dynamic casting". Casting Integer to Double isn't possible at all. You seem to want to give Java an object of one type, a field of a possibly incompatible type, and have it somehow automatically figure out how to convert between the types.

This kind of thing is anathema to a strongly typed language like Java, and IMO for very good reasons.

What are you actually trying to do? All that use of reflection looks pretty fishy.

Count items in a folder with PowerShell

Only Files

Get-ChildItem D:\ -Recurse -File | Measure-Object | %{$_.Count}

Only Folders

Get-ChildItem D:\ -Recurse -Directory | Measure-Object | %{$_.Count}

Both

Get-ChildItem D:\ -Recurse | Measure-Object | %{$_.Count}

Uploading Laravel Project onto Web Server

I believe - your Laravel files/folders should not be placed in root directory.

e.g. If your domain is pointed to public_html directory then all content should placed in that directory. How ? let me tell you

  1. Copy all files and folders ( including public folder ) in public html
  2. Copy all content of public folder and paste it in document root ( i.e. public_html )
  3. Remove the public folder
  4. Open your bootstrap/paths.php and then changed 'public' => __DIR__.'/../public', into 'public' => __DIR__.'/..',

  5. and finally in index.php,

    Change

require __DIR__.'/../bootstrap/autoload.php';

$app = require_once __DIR__.'/../bootstrap/start.php';

into

require __DIR__.'/bootstrap/autoload.php';

$app = require_once __DIR__.'/bootstrap/start.php';

Your Laravel application should work now.

Reason: no suitable image found

faced same issue

  1. my developer certificate was expired so created new developer certificate and download
  2. clean and restart xcode this works for me

How to execute .sql script file using JDBC

I had the same problem trying to execute an SQL script that creates an SQL database. Googling here and there I found a Java class initially written by Clinton Begin which supports comments (see http://pastebin.com/P14HsYAG). I modified slightly the file to cater for triggers where one has to change the default DELIMITER to something different. I've used that version ScriptRunner (see http://pastebin.com/sb4bMbVv). Since an (open source and free) SQLScriptRunner class is an absolutely necessary utility, it would be good to have some more input from developers and hopefully we'll have soon a more stable version of it.

to call onChange event after pressing Enter key

React users, here's an answer for completeness.

React version 16.4.2

You either want to update for every keystroke, or get the value only at submit. Adding the key events to the component works, but there are alternatives as recommended in the official docs.

Controlled vs Uncontrolled components

Controlled

From the Docs - Forms and Controlled components:

In HTML, form elements such as input, textarea, and select typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState().

We can combine the two by making the React state be the “single source of truth”. Then the React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled component”.

If you use a controlled component you will have to keep the state updated for every change to the value. For this to happen, you bind an event handler to the component. In the docs' examples, usually the onChange event.

Example:

1) Bind event handler in constructor (value kept in state)

constructor(props) {
    super(props);
    this.state = {value: ''};

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

2) Create handler function

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

3) Create form submit function (value is taken from the state)

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

4) Render

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

If you use controlled components, your handleChange function will always be fired, in order to update and keep the proper state. The state will always have the updated value, and when the form is submitted, the value will be taken from the state. This might be a con if your form is very long, because you will have to create a function for every component, or write a simple one that handles every component's change of value.

Uncontrolled

From the Docs - Uncontrolled component

In most cases, we recommend using controlled components to implement forms. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.

To write an uncontrolled component, instead of writing an event handler for every state update, you can use a ref to get form values from the DOM.

The main difference here is that you don't use the onChange function, but rather the onSubmit of the form to get the values, and validate if neccessary.

Example:

1) Bind event handler and create ref to input in constructor (no value kept in state)

constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.input = React.createRef();
}

2) Create form submit function (value is taken from the DOM component)

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

3) Render

<form onSubmit={this.handleSubmit}>
    <label>
      Name:
      <input type="text" ref={this.input} />
    </label>
    <input type="submit" value="Submit" />
</form>

If you use uncontrolled components, there is no need to bind a handleChange function. When the form is submitted, the value will be taken from the DOM and the neccessary validations can happen at this point. No need to create any handler functions for any of the input components as well.

Your issue

Now, for your issue:

... I want it to be called when I push 'Enter when the whole number has been entered

If you want to achieve this, use an uncontrolled component. Don't create the onChange handlers if it is not necessary. The enter key will submit the form and the handleSubmit function will be fired.

Changes you need to do:

Remove the onChange call in your element

var inputProcent = React.CreateElement(bootstrap.Input, {type: "text",
    //    bsStyle: this.validationInputFactor(),
    placeholder: this.initialFactor,
    className: "input-block-level",
    // onChange: this.handleInput,
    block: true,
    addonBefore: '%',
    ref:'input',
    hasFeedback: true
});

Handle the form submit and validate your input. You need to get the value from your element in the form submit function and then validate. Make sure you create the reference to your element in the constructor.

  handleSubmit(event) {
      // Get value of input field
      let value = this.input.current.value;
      event.preventDefault();
      // Validate 'value' and submit using your own api or something
  }

Example use of an uncontrolled component:

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    // bind submit function
    this.handleSubmit = this.handleSubmit.bind(this);
    // create reference to input field
    this.input = React.createRef();
  }

  handleSubmit(event) {
    // Get value of input field
    let value = this.input.current.value;
    console.log('value in input field: ' + value );
    event.preventDefault();
    // Validate 'value' and submit using your own api or something
  }

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

ReactDOM.render(
  <NameForm />,
  document.getElementById('root')
);

Angular ReactiveForms: Producing an array of checkbox values?

If you are looking for checkbox values in JSON format

{ "name": "", "countries": [ { "US": true }, { "Germany": true }, { "France": true } ] }

Full example here.

I apologise for using Country Names as checkbox values instead of those in the question. Further explannation -

Create a FormGroup for the form

 createForm() {

    //Form Group for a Hero Form
    this.heroForm = this.fb.group({
      name: '',
      countries: this.fb.array([])
    });

    let countries=['US','Germany','France'];

    this.setCountries(countries);}
 }

Let each checkbox be a FormGroup built from an object whose only property is the checkbox's value.

 setCountries(countries:string[]) {

    //One Form Group for one country
    const countriesFGs = countries.map(country =>{
            let obj={};obj[country]=true;
            return this.fb.group(obj)
    });

    const countryFormArray = this.fb.array(countriesFGs);
    this.heroForm.setControl('countries', countryFormArray);
  }

The array of FormGroups for the checkboxes is used to set the control for the 'countries' in the parent Form.

  get countries(): FormArray {
      return this.heroForm.get('countries') as FormArray;
  };

In the template, use a pipe to get the name for the checkbox control

  <div formArrayName="countries" class="well well-lg">
      <div *ngFor="let country of countries.controls; let i=index" [formGroupName]="i" >
          <div *ngFor="let key of country.controls | mapToKeys" >
              <input type="checkbox" formControlName="{{key.key}}">{{key.key}}
          </div>
      </div>
  </div>

What does android:layout_weight mean?

layout_weight tells Android how to distribute your Views in a LinearLayout. Android then first calculates the total proportion required for all Views that have a weight specified and places each View according to what fraction of the screen it has specified it needs. In the following example, Android sees that the TextViews have a layout_weight of 0 (this is the default) and the EditTexts have a layout_weight of 2 each, while the Button has a weight of 1. So Android allocates 'just enough' space to display tvUsername and tvPassword and then divides the remainder of the screen width into 5 equal parts, two of which are allocated to etUsername, two to etPassword and the last part to bLogin:

<LinearLayout android:orientation="horizontal" ...>

    <TextView android:id="@+id/tvUsername" 
    android:text="Username" 
    android:layout_width="wrap_content" ... />

    <EditText android:id="@+id/etUsername"
    android:layout_width="0dp"
    android:layout_weight="2" ... />

    <TextView android:id="@+id/tvPassword"
    android:text="Password"
    android:layout_width="wrap_content" />

    <EditText android:id="@+id/etPassword"
    android:layout_width="0dp"
    android:layout_weight="2" ... />

    <Button android:id="@+id/bLogin"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:text="Login"... />

</LinearLayout>

It looks like:
landscape orientation and
portrait orientation

What is considered a good response time for a dynamic, personalized web application?

We strive for response times of 20 milliseconds, while some complex pages take up to 100 milliseconds. For the most complex pages, we break the page down into smaller pieces, and use the progressive display pattern to load each section. This way, some portions load quickly, even if the page takes 1 to 2 seconds to load, keeping the user engaged while the rest of the page is loading.

How to extract the decimal part from a floating point number in C?

Suppose A is your integer then (int)A, means casting the number to an integer and will be the integer part, the other is (A - (int)A)*10^n, here n is the number of decimals to keep.

How can I create keystore from an existing certificate (abc.crt) and abc.key files?

The easiest is probably to create a PKCS#12 file using OpenSSL:

openssl pkcs12 -export -in abc.crt -inkey abc.key -out abc.p12

You should be able to use the resulting file directly using the PKCS12 keystore type.

If you really need to, you can convert it to JKS using keytool -importkeystore (available in keytool from Java 6):

keytool -importkeystore -srckeystore abc.p12 \
        -srcstoretype PKCS12 \
        -destkeystore abc.jks \
        -deststoretype JKS

Pass element ID to Javascript function

Check this: http://jsfiddle.net/h7kRt/1/,

you should change in jsfiddle on top-left to No-wrap in <head>

Your code looks good and it will work inside a normal page. In jsfiddle your function was being defined inside a load handler and thus is in a different scope. By changing to No-wrap you have it in the global scope and can use it as you wanted.

Using StringWriter for XML Serialization

<TL;DR> The problem is rather simple, actually: you are not matching the declared encoding (in the XML declaration) with the datatype of the input parameter. If you manually added <?xml version="1.0" encoding="utf-8"?><test/> to the string, then declaring the SqlParameter to be of type SqlDbType.Xml or SqlDbType.NVarChar would give you the "unable to switch the encoding" error. Then, when inserting manually via T-SQL, since you switched the declared encoding to be utf-16, you were clearly inserting a VARCHAR string (not prefixed with an upper-case "N", hence an 8-bit encoding, such as UTF-8) and not an NVARCHAR string (prefixed with an upper-case "N", hence the 16-bit UTF-16 LE encoding).

The fix should have been as simple as:

  1. In the first case, when adding the declaration stating encoding="utf-8": simply don't add the XML declaration.
  2. In the second case, when adding the declaration stating encoding="utf-16": either
    1. simply don't add the XML declaration, OR
    2. simply add an "N" to the input parameter type: SqlDbType.NVarChar instead of SqlDbType.VarChar :-) (or possibly even switch to using SqlDbType.Xml)

(Detailed response is below)


All of the answers here are over-complicated and unnecessary (regardless of the 121 and 184 up-votes for Christian's and Jon's answers, respectively). They might provide working code, but none of them actually answer the question. The issue is that nobody truly understood the question, which ultimately is about how the XML datatype in SQL Server works. Nothing against those two clearly intelligent people, but this question has little to nothing to do with serializing to XML. Saving XML data into SQL Server is much easier than what is being implied here.

It doesn't really matter how the XML is produced as long as you follow the rules of how to create XML data in SQL Server. I have a more thorough explanation (including working example code to illustrate the points outlined below) in an answer on this question: How to solve “unable to switch the encoding” error when inserting XML into SQL Server, but the basics are:

  1. The XML declaration is optional
  2. The XML datatype stores strings always as UCS-2 / UTF-16 LE
  3. If your XML is UCS-2 / UTF-16 LE, then you:
    1. pass in the data as either NVARCHAR(MAX) or XML / SqlDbType.NVarChar (maxsize = -1) or SqlDbType.Xml, or if using a string literal then it must be prefixed with an upper-case "N".
    2. if specifying the XML declaration, it must be either "UCS-2" or "UTF-16" (no real difference here)
  4. If your XML is 8-bit encoded (e.g. "UTF-8" / "iso-8859-1" / "Windows-1252"), then you:
    1. need to specify the XML declaration IF the encoding is different than the code page specified by the default Collation of the database
    2. you must pass in the data as VARCHAR(MAX) / SqlDbType.VarChar (maxsize = -1), or if using a string literal then it must not be prefixed with an upper-case "N".
    3. Whatever 8-bit encoding is used, the "encoding" noted in the XML declaration must match the actual encoding of the bytes.
    4. The 8-bit encoding will be converted into UTF-16 LE by the XML datatype

With the points outlined above in mind, and given that strings in .NET are always UTF-16 LE / UCS-2 LE (there is no difference between those in terms of encoding), we can answer your questions:

Is there a reason why I shouldn't use StringWriter to serialize an Object when I need it as a string afterwards?

No, your StringWriter code appears to be just fine (at least I see no issues in my limited testing using the 2nd code block from the question).

Wouldn't setting the encoding to UTF-16 (in the xml tag) work then?

It isn't necessary to provide the XML declaration. When it is missing, the encoding is assumed to be UTF-16 LE if you pass the string into SQL Server as NVARCHAR (i.e. SqlDbType.NVarChar) or XML (i.e. SqlDbType.Xml). The encoding is assumed to be the default 8-bit Code Page if passing in as VARCHAR (i.e. SqlDbType.VarChar). If you have any non-standard-ASCII characters (i.e. values 128 and above) and are passing in as VARCHAR, then you will likely see "?" for BMP characters and "??" for Supplementary Characters as SQL Server will convert the UTF-16 string from .NET into an 8-bit string of the current Database's Code Page before converting it back into UTF-16 / UCS-2. But you shouldn't get any errors.

On the other hand, if you do specify the XML declaration, then you must pass into SQL Server using the matching 8-bit or 16-bit datatype. So if you have a declaration stating that the encoding is either UCS-2 or UTF-16, then you must pass in as SqlDbType.NVarChar or SqlDbType.Xml. Or, if you have a declaration stating that the encoding is one of the 8-bit options (i.e. UTF-8, Windows-1252, iso-8859-1, etc), then you must pass in as SqlDbType.VarChar. Failure to match the declared encoding with the proper 8 or 16 -bit SQL Server datatype will result in the "unable to switch the encoding" error that you were getting.

For example, using your StringWriter-based serialization code, I simply printed the resulting string of the XML and used it in SSMS. As you can see below, the XML declaration is included (because StringWriter does not have an option to OmitXmlDeclaration like XmlWriter does), which poses no problem so long as you pass the string in as the correct SQL Server datatype:

-- Upper-case "N" prefix == NVARCHAR, hence no error:
DECLARE @Xml XML = N'<?xml version="1.0" encoding="utf-16"?>
<string>Test ?</string>';
SELECT @Xml;
-- <string>Test ?</string>

As you can see, it even handles characters beyond standard ASCII, given that ? is BMP Code Point U+1234, and is Supplementary Character Code Point U+1F638. However, the following:

-- No upper-case "N" prefix on the string literal, hence VARCHAR:
DECLARE @Xml XML = '<?xml version="1.0" encoding="utf-16"?>
<string>Test ?</string>';

results in the following error:

Msg 9402, Level 16, State 1, Line XXXXX
XML parsing: line 1, character 39, unable to switch the encoding

Ergo, all of that explanation aside, the full solution to your original question is:

You were clearly passing the string in as SqlDbType.VarChar. Switch to SqlDbType.NVarChar and it will work without needing to go through the extra step of removing the XML declaration. This is preferred over keeping SqlDbType.VarChar and removing the XML declaration because this solution will prevent data loss when the XML includes non-standard-ASCII characters. For example:

-- No upper-case "N" prefix on the string literal == VARCHAR, and no XML declaration:
DECLARE @Xml2 XML = '<string>Test ?</string>';
SELECT @Xml2;
-- <string>Test ???</string>

As you can see, there is no error this time, but now there is data-loss 🙀.

What is the "Illegal Instruction: 4" error and why does "-mmacosx-version-min=10.x" fix it?

In my case, I got this while overloading

ostream & operator << (ostream &out, const MyClass &obj)

and forgot to return out. In other systems this just generates a warning, but on macos it also generated an error (although it seems to print correctly).

The error was resolved by adding the correct return value. In my case, adding the -mmacosx-version-min flag had no effect.

Efficiently convert rows to columns in sql server

There are several ways that you can transform data from multiple rows into columns.

Using PIVOT

In SQL Server you can use the PIVOT function to transform the data from rows to columns:

select Firstname, Amount, PostalCode, LastName, AccountNumber
from
(
  select value, columnname
  from yourtable
) d
pivot
(
  max(value)
  for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
) piv;

See Demo.

Pivot with unknown number of columnnames

If you have an unknown number of columnnames that you want to transpose, then you can use dynamic SQL:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName) 
                    from yourtable
                    group by ColumnName, id
                    order by id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = N'SELECT ' + @cols + N' from 
             (
                select value, ColumnName
                from yourtable
            ) x
            pivot 
            (
                max(value)
                for ColumnName in (' + @cols + N')
            ) p '

exec sp_executesql @query;

See Demo.

Using an aggregate function

If you do not want to use the PIVOT function, then you can use an aggregate function with a CASE expression:

select
  max(case when columnname = 'FirstName' then value end) Firstname,
  max(case when columnname = 'Amount' then value end) Amount,
  max(case when columnname = 'PostalCode' then value end) PostalCode,
  max(case when columnname = 'LastName' then value end) LastName,
  max(case when columnname = 'AccountNumber' then value end) AccountNumber
from yourtable

See Demo.

Using multiple joins

This could also be completed using multiple joins, but you will need some column to associate each of the rows which you do not have in your sample data. But the basic syntax would be:

select fn.value as FirstName,
  a.value as Amount,
  pc.value as PostalCode,
  ln.value as LastName,
  an.value as AccountNumber
from yourtable fn
left join yourtable a
  on fn.somecol = a.somecol
  and a.columnname = 'Amount'
left join yourtable pc
  on fn.somecol = pc.somecol
  and pc.columnname = 'PostalCode'
left join yourtable ln
  on fn.somecol = ln.somecol
  and ln.columnname = 'LastName'
left join yourtable an
  on fn.somecol = an.somecol
  and an.columnname = 'AccountNumber'
where fn.columnname = 'Firstname'

jQuery: Slide left and slide right

You can always just use jQuery to add a class, .addClass or .toggleClass. Then you can keep all your styles in your CSS and out of your scripts.

http://jsfiddle.net/B8L3x/1/

How do I get the scroll position of a document?

$(document).height() //returns window height

$(document).scrollTop() //returns scroll position from top of document

Reading a file line by line in Go

import (
     "bufio"
     "os"
)

var (
    reader = bufio.NewReader(os.Stdin)
)

func ReadFromStdin() string{
    result, _ := reader.ReadString('\n')
    witl := result[:len(result)-1]
    return witl
}

Here is an example with function ReadFromStdin() it's like fmt.Scan(&name) but its takes all strings with blank spaces like: "Hello My Name Is ..."

var name string = ReadFromStdin()

println(name)

Spring Boot JPA - configuring auto reconnect

whoami's answer is the correct one. Using the properties as suggested I was unable to get this to work (using Spring Boot 1.5.3.RELEASE)

I'm adding my answer since it's a complete configuration class so it might help someone using Spring Boot:

@Configuration
@Log4j
public class SwatDataBaseConfig {

    @Value("${swat.decrypt.location}")
    private String fileLocation;

    @Value("${swat.datasource.url}")
    private String dbURL;

    @Value("${swat.datasource.driver-class-name}")
    private String driverName;

    @Value("${swat.datasource.username}")
    private String userName;

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

    @Bean
    public DataSource primaryDataSource() {
        PoolProperties poolProperties = new PoolProperties();
        poolProperties.setUrl(dbURL);
        poolProperties.setUsername(userName);
        poolProperties.setPassword(password);
        poolProperties.setDriverClassName(driverName);
        poolProperties.setTestOnBorrow(true);
        poolProperties.setValidationQuery("SELECT 1");
        poolProperties.setValidationInterval(0);
        DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource(poolProperties);
        return ds;
    }
}

Import CSV file into SQL Server

Here's how I would solve it:

  1. Just Save your CSV File as a XLS Sheet in excel(By Doing so, you wouldn't have to worry about delimitiers. Excel's spreadsheet format will be read as a table and imported directly into a SQL Table)

  2. Import the File Using SSIS

  3. Write a Custom Script in the import manager to omit/modify the data you're looking for.(Or run a master script to scrutinize the data you're looking to remove)

Good Luck.

How to get current time with jQuery

The following

function gettzdate(){
    var fd = moment().format('YYYY-MM-DDTHH:MM:ss');
    return fd ; 
}

works for forcing the current date onto a <input type="datetime-local">

Save current directory in variable using Bash?

On a BASH shell, you can very simply run:

export PATH=$PATH:`pwd`/somethingelse

No need to save the current working directory into a variable...

Cannot load properties file from resources directory

Using ClassLoader.getSystemClassLoader()

Sample code :

Properties prop = new Properties();
InputStream input = null;
try {
    input = ClassLoader.getSystemClassLoader().getResourceAsStream("conf.properties");
    prop.load(input);

} catch (IOException io) {
    io.printStackTrace();
}

Where should I put the CSS and Javascript code in an HTML webpage?

  1. You should put the stylesheet links and javascript <script> in the <head>, as that is dictated by the formats. However, some put javascript <script>s at the bottom of the body, so that the page content will load without waiting for the <script>, but this is a tradeoff since script execution will be delayed until other resources have loaded.
  2. CSS takes precedence in the order by which they are linked (in reverse): first overridden by second, overridden by third, etc.

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

I wrote the following to print a list of results to standard out based on available charsets. Note that it also tells you what line fails from a 0 based line number in case you are troubleshooting what character is causing issues.

public static void testCharset(String fileName) {
    SortedMap<String, Charset> charsets = Charset.availableCharsets();
    for (String k : charsets.keySet()) {
        int line = 0;
        boolean success = true;
        try (BufferedReader b = Files.newBufferedReader(Paths.get(fileName),charsets.get(k))) {
            while (b.ready()) {
                b.readLine();
                line++;
            }
        } catch (IOException e) {
            success = false;
            System.out.println(k+" failed on line "+line);
        }
        if (success) 
            System.out.println("*************************  Successs "+k);
    }
}

css transform, jagged edges in chrome

Just thought that we'd throw in our solution too as we had the exact same problem on Chrome/Windows.

We tried the solution by @stevenWatkins above, but still had the "stepping".

Instead of

-webkit-backface-visibility: hidden;

We used:

-webkit-backface-visibility: initial;

For us this did the trick

How to redirect the output of a PowerShell to a file during its execution

Microsoft has announced on Powershell's Connections web site (2012-02-15 at 4:40 PM) that in version 3.0 they have extended the redirection as a solution to this problem.

In PowerShell 3.0, we've extended output redirection to include the following streams: 
 Pipeline (1) 
 Error    (2) 
 Warning  (3) 
 Verbose  (4) 
 Debug    (5)
 All      (*)

We still use the same operators
 >    Redirect to a file and replace contents
 >>   Redirect to a file and append to existing content
 >&1  Merge with pipeline output

See the "about_Redirection" help article for details and examples.

help about_Redirection

How to redirect output to a file and stdout

Another way that works for me is,

<command> |& tee  <outputFile>

as shown in gnu bash manual

Example:

ls |& tee files.txt

If ‘|&’ is used, command1’s standard error, in addition to its standard output, is connected to command2’s standard input through the pipe; it is shorthand for 2>&1 |. This implicit redirection of the standard error to the standard output is performed after any redirections specified by the command.

For more information, refer redirection

Insert a line at specific line number with sed or awk

sed -e '8iProject_Name=sowstest' -i start using GNU sed

Sample run:

[root@node23 ~]# for ((i=1; i<=10; i++)); do echo "Line #$i"; done > a_file
[root@node23 ~]# cat a_file
Line #1
Line #2
Line #3
Line #4
Line #5
Line #6
Line #7
Line #8
Line #9
Line #10
[root@node23 ~]# sed -e '3ixxx inserted line xxx' -i a_file 
[root@node23 ~]# cat -An a_file 
     1  Line #1$
     2  Line #2$
     3  xxx inserted line xxx$
     4  Line #3$
     5  Line #4$
     6  Line #5$
     7  Line #6$
     8  Line #7$
     9  Line #8$
    10  Line #9$
    11  Line #10$
[root@node23 ~]# 
[root@node23 ~]# sed -e '5ixxx (inserted) "line" xxx' -i a_file
[root@node23 ~]# cat -n a_file 
     1  Line #1
     2  Line #2
     3  xxx inserted line xxx
     4  Line #3
     5  xxx (inserted) "line" xxx
     6  Line #4
     7  Line #5
     8  Line #6
     9  Line #7
    10  Line #8
    11  Line #9
    12  Line #10
[root@node23 ~]# 

generate days from date range

The old school solution for doing this without a loop/cursor is to create a NUMBERS table, which has a single Integer column with values starting at 1.

CREATE TABLE  `example`.`numbers` (
  `id` int(10) unsigned NOT NULL auto_increment,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

You need to populate the table with enough records to cover your needs:

INSERT INTO NUMBERS (id) VALUES (NULL);

Once you have the NUMBERS table, you can use:

SELECT x.start_date + INTERVAL n.id-1 DAY
  FROM NUMBERS n
  JOIN (SELECT STR_TO_DATE('2010-01-20', '%Y-%m-%d') AS start_date 
          FROM DUAL) x
 WHERE x.start_date + INTERVAL n.id-1 DAY <= '2010-01-24'

The absolute low-tech solution would be:

SELECT STR_TO_DATE('2010-01-20', '%Y-%m-%d')
 FROM DUAL
UNION ALL
SELECT STR_TO_DATE('2010-01-21', '%Y-%m-%d')
 FROM DUAL
UNION ALL
SELECT STR_TO_DATE('2010-01-22', '%Y-%m-%d')
 FROM DUAL
UNION ALL
SELECT STR_TO_DATE('2010-01-23', '%Y-%m-%d')
 FROM DUAL
UNION ALL
SELECT STR_TO_DATE('2010-01-24', '%Y-%m-%d')
 FROM DUAL

What would you use it for?


To generate lists of dates or numbers in order to LEFT JOIN on to. You would to this in order to see where there are gaps in the data, because you are LEFT JOINing onto a list of sequencial data - null values will make it obvious where gaps exist.

How to use local docker images with Minikube?

minikube addons enable registry -p minikube

Registry addon on with docker uses 32769 please use that instead of default 5000
For more information see: https://minikube.sigs.k8s.io/docs/drivers/docker

docker tag ubuntu $(minikube ip -p minikube):32769/ubuntu
docker push $(minikube ip -p minikube):32769/ubuntu

OR

minikube addons enable registry
docker tag ubuntu $(minikube ip):32769/ubuntu
docker push $(minikube ip):32769/ubuntu

The above is good enough for development purpose. I am doing this on archlinux.

Editing the git commit message in GitHub

For Android Studio / intellij users:

  • Select Version Control
  • Select Log
  • Right click the commit for which you want to rename
  • Click Edit Commit Message
  • Write your commit message
  • Done

Excel formula to search if all cells in a range read "True", if not, then show "False"

=COUNTIFS(1:1,FALSE)=0

This will return TRUE or FALSE (Looks for FALSE, if count isn't 0 (all True) it will be false

Remove last item from array

I would consider .pop() to be the most 'correct' solution, however, sometimes it might not work since you need to use array without the last element right there...

In such a case you might want to use the following, it will return [1,2,3]

_x000D_
_x000D_
var arr = [1,2,3,4];_x000D_
console.log(arr.splice(0,arr.length-1));
_x000D_
_x000D_
_x000D_

while .pop() would return 4:

_x000D_
_x000D_
var arr = [1,2,3,4];_x000D_
console.log(arr.pop());
_x000D_
_x000D_
_x000D_

which might not be desirable...

Hope this saves you some time.

How can I check if a URL exists via PHP?

the simple way is curl (and FASTER too)

<?php
$mylinks="http://site.com/page.html";
$handlerr = curl_init($mylinks);
curl_setopt($handlerr,  CURLOPT_RETURNTRANSFER, TRUE);
$resp = curl_exec($handlerr);
$ht = curl_getinfo($handlerr, CURLINFO_HTTP_CODE);


if ($ht == '404')
     { echo 'OK';}
else { echo 'NO';}

?>

Volatile vs. Interlocked vs. lock

lock(...) works, but may block a thread, and could cause deadlock if other code is using the same locks in an incompatible way.

Interlocked.* is the correct way to do it ... much less overhead as modern CPUs support this as a primitive.

volatile on its own is not correct. A thread attempting to retrieve and then write back a modified value could still conflict with another thread doing the same.

OnItemClickListener using ArrayAdapter for ListView

you can use this way...

listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                final int position, long id) {

          String main = listView.getSelectedItem().toString();
        }
    });

How do you sort an array on multiple columns?

I found multisotr. This is simple, powerfull and small library for multiple sorting. I was need to sort an array of objects with dynamics sorting criteria:

_x000D_
_x000D_
const criteria = ['name', 'speciality']_x000D_
const data = [_x000D_
  { name: 'Mike', speciality: 'JS', age: 22 },_x000D_
  { name: 'Tom', speciality: 'Java', age: 30 },_x000D_
  { name: 'Mike', speciality: 'PHP', age: 40 },_x000D_
  { name: 'Abby', speciality: 'Design', age: 20 },_x000D_
]_x000D_
_x000D_
const sorted = multisort(data, criteria)_x000D_
_x000D_
console.log(sorted)
_x000D_
<script src="https://cdn.rawgit.com/peterkhayes/multisort/master/multisort.js"></script>
_x000D_
_x000D_
_x000D_

This library more mutch powerful, that was my case. Try it.

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country

I had a the same problem and I found the solution that I should put the code to retrieve the drop down list from database in the Edit Method. It worked for me. Solution for the similar problem

How do you do exponentiation in C?

The non-recursive version of the function is not too hard - here it is for integers:

long powi(long x, unsigned n)
{
    long p = x;
    long r = 1;

    while (n > 0)
    {
        if (n % 2 == 1)
            r *= p;
        p *= p;
        n /= 2;
    }

    return(r);
}

(Hacked out of code for raising a double value to an integer power - had to remove the code to deal with reciprocals, for example.)

How do I make a Windows batch script completely silent?

If you want that all normal output of your Batch script be silent (like in your example), the easiest way to do that is to run the Batch file with a redirection:

C:\Temp> test.bat >nul

This method does not require to modify a single line in the script and it still show error messages in the screen. To supress all the output, including error messages:

C:\Temp> test.bat >nul 2>&1

If your script have lines that produce output you want to appear in screen, perhaps will be simpler to add redirection to those lineas instead of all the lines you want to keep silent:

@ECHO OFF
SET scriptDirectory=%~dp0
COPY %scriptDirectory%test.bat %scriptDirectory%test2.bat
FOR /F %%f IN ('dir /B "%scriptDirectory%*.noext"') DO (
del "%scriptDirectory%%%f"
)
ECHO
REM Next line DO appear in the screen
ECHO Script completed >con

Antonio

Random row selection in Pandas dataframe

With pandas version 0.16.1 and up, there is now a DataFrame.sample method built-in:

import pandas

df = pandas.DataFrame(pandas.np.random.random(100))

# Randomly sample 70% of your dataframe
df_percent = df.sample(frac=0.7)

# Randomly sample 7 elements from your dataframe
df_elements = df.sample(n=7)

For either approach above, you can get the rest of the rows by doing:

df_rest = df.loc[~df.index.isin(df_percent.index)]

Array String Declaration

You are not initializing your String[]. You either need to initialize it using the exact array size, as suggested by @Tr?nSiLong, or use a List<String> and then convert to a String[] (in case you do not know the length):

String[] title = {
        "Abundance",
        "Anxiety",
        "Bruxism",
        "Discipline",
        "Drug Addiction"
    };
String urlbase = "http://www.somewhere.com/data/";
String imgSel = "/logo.png";
List<String> mStrings = new ArrayList<String>();

for(int i=0;i<title.length;i++) {
    mStrings.add(urlbase + title[i].toLowerCase() + imgSel);

    System.out.println(mStrings[i]);
}

String[] strings = new String[mStrings.size()];
strings = mStrings.toArray(strings);//now strings is the resulting array

JavaScript listener, "keypress" doesn't detect backspace?

Use one of keyup / keydown / beforeinput events instead.

based on this reference, keypress is deprecated and no longer recommended.

The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt, Shift, Ctrl, or Meta.

if you use "beforeinput" be careful about it's Browser compatibility. the difference between "beforeinput" and the other two is that "beforeinput" is fired when input value is about to changed, so with characters that can't change the input value, it is not fired (e.g shift, ctr ,alt).

I had the same problem and by using keyup it was solved.

How to use Ajax.ActionLink?

Sure, a very similar question was asked before. Set the controller for ajax requests:

public ActionResult Show()
{
    if (Request.IsAjaxRequest()) 
    {
        return PartialView("Your_partial_view", new Model());
    }
    else 
    {
        return View();
    }
}

Set the action link as wanted:

@Ajax.ActionLink("Show", 
                 "Show", 
                 null, 
                 new AjaxOptions { HttpMethod = "GET", 
                 InsertionMode = InsertionMode.Replace, 
                 UpdateTargetId = "dialog_window_id", 
                 OnComplete = "your_js_function();" })

Note that I'm using Razor view engine, and that your AjaxOptions may vary depending on what you want. Finally display it on a modal window. The jQuery UI dialog is suggested.

How do I add space between items in an ASP.NET RadioButtonList

Use css to add a right margin to those particular elements. Generally I would build the control, then run it to see what the resulting html structure is like, then make the css alter just those elements.

Preferably you do this by setting the class. Add the CssClass="myrblclass" attribute to your list declaration.

You can also add attributes to the items programmatically, which will come out the other side.

rblMyRadioButtonList.Items[x].Attributes.CssStyle.Add("margin-right:5px;")

This may be better for you since you can add that attribute for all but the last one.

How do I import other TypeScript files?

If you're using AMD modules, the other answers won't work in TypeScript 1.0 (the newest at the time of writing.)

You have different approaches available to you, depending upon how many things you wish to export from each .ts file.

Multiple exports

Foo.ts

export class Foo {}
export interface IFoo {}

Bar.ts

import fooModule = require("Foo");

var foo1 = new fooModule.Foo();
var foo2: fooModule.IFoo = {};

Single export

Foo.ts

class Foo
{}

export = Foo;

Bar.ts

import Foo = require("Foo");

var foo = new Foo();

how to convert from int to char*?

See this answer https://stackoverflow.com/a/23010605/2760919

For your case, just change the type in snprintf from long ("%ld") to int ("%n").

TypeError: '<=' not supported between instances of 'str' and 'int'

When you use the input function it automatically turns it into a string. You need to go:

vote = int(input('Enter the name of the player you wish to vote for'))

which turns the input into a int type value

Create a function with optional call variables

Not sure I understand the question correctly.

From what I gather, you want to be able to assign a value to Domain if it is null and also what to check if $args2 is supplied and according to the value, execute a certain code?

I changed the code to reassemble the assumptions made above.

Function DoStuff($computername, $arg2, $domain)
{
    if($domain -ne $null)
    {
        $domain = "Domain1"
    }

    if($arg2 -eq $null)
    {
    }
    else
    {
    }
}

DoStuff -computername "Test" -arg2 "" -domain "Domain2"
DoStuff -computername "Test" -arg2 "Test"  -domain ""
DoStuff -computername "Test" -domain "Domain2"
DoStuff -computername "Test" -arg2 "Domain2"

Did that help?

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

How to position the div popup dialog to the center of browser screen?

Its a classical problem, when you scroll the modal popup generated on the screen stays at it place and does not scroll along, so the user might be blocked as he might not see the popup on his viewable screen.

The following link also provides CSS only code for generating a modal box along with its absolute position.

http://settledcuriosity.wordpress.com/2014/10/03/centering-a-popup-box-absolutely-at-the-center-of-screen/

How do I automatically update a timestamp in PostgreSQL

Updating timestamp, only if the values changed

Based on E.J's link and add a if statement from this link (https://stackoverflow.com/a/3084254/1526023)

CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
   IF row(NEW.*) IS DISTINCT FROM row(OLD.*) THEN
      NEW.modified = now(); 
      RETURN NEW;
   ELSE
      RETURN OLD;
   END IF;
END;
$$ language 'plpgsql';

Magento Product Attribute Get Value

Mage::getResourceModel('catalog/product')->getAttributeRawValue($productId, 'attribute_code', $storeId);

JavaScript Array to Set

By definition "A Set is a collection of values, where each value may occur only once." So, if your array has repeated values then only one value among the repeated values will be added to your Set.

var arr = [1, 2, 3];
var set = new Set(arr);
console.log(set); // {1,2,3}


var arr = [1, 2, 1];
var set = new Set(arr);
console.log(set); // {1,2}

So, do not convert to set if you have repeated values in your array.

Spring Boot Multiple Datasource

I faced same issue few days back, I followed the link mentioned below and I could able to overcome the problem

http://www.baeldung.com/spring-data-jpa-multiple-databases