Programs & Examples On #Subscript operator

Map to String in Java

Use Object#toString().

String string = map.toString();

That's after all also what System.out.println(object) does under the hoods. The format for maps is described in AbstractMap#toString().

Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

For integers you can use implicit conversion from int to varchar:

SELECT RIGHT(1000 + field, 3)

Built in Python hash() function

The response is absolutely no surprise: in fact

In [1]: -5768830964305142685L & 0xffffffff
Out[1]: 1934711907L

so if you want to get reliable responses on ASCII strings, just get the lower 32 bits as uint. The hash function for strings is 32-bit-safe and almost portable.

On the other side, you can't rely at all on getting the hash() of any object over which you haven't explicitly defined the __hash__ method to be invariant.

Over ASCII strings it works just because the hash is calculated on the single characters forming the string, like the following:

class string:
    def __hash__(self):
        if not self:
            return 0 # empty
        value = ord(self[0]) << 7
        for char in self:
            value = c_mul(1000003, value) ^ ord(char)
        value = value ^ len(self)
        if value == -1:
            value = -2
        return value

where the c_mul function is the "cyclic" multiplication (without overflow) as in C.

UUID max character length

Section 3 of RFC4122 provides the formal definition of UUID string representations. It's 36 characters (32 hex digits + 4 dashes).

Sounds like you need to figure out where the invalid 60-char IDs are coming from and decide 1) if you want to accept them, and 2) what the max length of those IDs might be based on whatever API is used to generate them.

How can I easily switch between PHP versions on Mac OSX?

If you install PHP with homebrew, you can switch between versions very easily. Say you want php56 to point to Version 5.6.17, you just do:

brew switch php56 5.6.17

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

For an IIS MVC 5 / Angular CLI ( Yes, I am well aware your problem is with Angular JS ) project with API I did the following:

web.config under <system.webServer> node

    <staticContent>
      <remove fileExtension=".woff2" />
      <mimeMap fileExtension=".woff2" mimeType="font/woff2" />
    </staticContent>
    <httpProtocol>
      <customHeaders>
        <clear />
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type, atv2" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
      </customHeaders>
    </httpProtocol>

global.asax.cs

protected void Application_BeginRequest() {
  if (Request.Headers.AllKeys.Contains("Origin", StringComparer.OrdinalIgnoreCase) && Request.HttpMethod == "OPTIONS") {
    Response.Flush();
    Response.End();
  }
}

That should fix your issues for both MVC and WebAPI without having to do all the other run around. I then created an HttpInterceptor in the Angular CLI project that automatically added in the the relevant header information. Hope this helps someone out in a similar situation.

How to get JSON objects value if its name contains dots?

Just to make use of updated solution try using lodash utility https://lodash.com/docs#get

How to disable phone number linking in Mobile Safari?

A trick I use that works on more than just Mobile Safari is to use HTML escape codes and a little mark-up in the phone number. This makes it more difficult for the browser to "identify" a phone number, i.e.

Phone: 1-8&#48;&#48;<span>-</span>62&#48;<span>-</span>38&#48;3

disable all form elements inside div

For jquery 1.6+, use .prop() instead of .attr(),

$("#parent-selector :input").prop("disabled", true);

or

$("#parent-selector :input").attr("disabled", "disabled");

Skip a submodule during a Maven build

Maven version 3.2.1 added this feature, you can use the -pl switch (shortcut for --projects list) with ! or - (source) to exclude certain submodules.

mvn -pl '!submodule-to-exclude' install
mvn -pl -submodule-to-exclude install

Be careful in bash the character ! is a special character, so you either have to single quote it (like I did) or escape it with the backslash character.

The syntax to exclude multiple module is the same as the inclusion

mvn -pl '!submodule1,!submodule2' install
mvn -pl -submodule1,-submodule2 install

EDIT Windows does not seem to like the single quotes, but it is necessary in bash ; in Windows, use double quotes (thanks @awilkinson)

mvn -pl "!submodule1,!submodule2" install

Get first letter of a string from column

.str.get

This is the simplest to specify string methods

# Setup
df = pd.DataFrame({'A': ['xyz', 'abc', 'foobar'], 'B': [123, 456, 789]})
df

        A    B
0     xyz  123
1     abc  456
2  foobar  789

df.dtypes

A    object
B     int64
dtype: object

For string (read:object) type columns, use

df['C'] = df['A'].str[0]
# Similar to,
df['C'] = df['A'].str.get(0)

.str handles NaNs by returning NaN as the output.

For non-numeric columns, an .astype conversion is required beforehand, as shown in @Ed Chum's answer.

# Note that this won't work well if the data has NaNs. 
# It'll return lowercase "n"
df['D'] = df['B'].astype(str).str[0]

df
        A    B  C  D
0     xyz  123  x  1
1     abc  456  a  4
2  foobar  789  f  7

List Comprehension and Indexing

There is enough evidence to suggest a simple list comprehension will work well here and probably be faster.

# For string columns
df['C'] = [x[0] for x in df['A']]

# For numeric columns
df['D'] = [str(x)[0] for x in df['B']]

df
        A    B  C  D
0     xyz  123  x  1
1     abc  456  a  4
2  foobar  789  f  7

If your data has NaNs, then you will need to handle this appropriately with an if/else in the list comprehension,

df2 = pd.DataFrame({'A': ['xyz', np.nan, 'foobar'], 'B': [123, 456, np.nan]})
df2

        A      B
0     xyz  123.0
1     NaN  456.0
2  foobar    NaN

# For string columns
df2['C'] = [x[0] if isinstance(x, str) else np.nan for x in df2['A']]

# For numeric columns
df2['D'] = [str(x)[0] if pd.notna(x) else np.nan for x in df2['B']]

        A      B    C    D
0     xyz  123.0    x    1
1     NaN  456.0  NaN    4
2  foobar    NaN    f  NaN

Let's do some timeit tests on some larger data.

df_ = df.copy()
df = pd.concat([df_] * 5000, ignore_index=True) 

%timeit df.assign(C=df['A'].str[0])
%timeit df.assign(D=df['B'].astype(str).str[0])

%timeit df.assign(C=[x[0] for x in df['A']])
%timeit df.assign(D=[str(x)[0] for x in df['B']])

12 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
27.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

3.77 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.84 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

List comprehensions are 4x faster.

How to replicate vector in c?

You can use "Gena" library. It closely resembles stl::vector in pure C89.

From the README, it features:

  • Access vector elements just like plain C arrays: vec[k][j];
  • Have multi-dimentional arrays;
  • Copy vectors;
  • Instantiate necessary vector types once in a separate module, instead of doing this every time you needed a vector;
  • You can choose how to pass values into a vector and how to return them from it: by value or by pointer.

You can check it out here:

https://github.com/cher-nov/Gena

How to call multiple JavaScript functions in onclick event?

I would use the element.addEventListener method to link it to a function. From that function you can call multiple functions.

The advantage I see in binding an event to a single function and then calling multiple functions is that you can perform some error checking, have some if else statements so that some functions only get called if certain criteria are met.

Video file formats supported in iPhone

The short answer is the iPhone supports H.264 video, High profile and AAC audio, in container formats .mov, .mp4, or MPEG Segment .ts. MPEG Segment files are used for HTTP Live Streaming.

  • For maximum compatibility with Android and desktop browsers, use H.264 + AAC in an .mp4 container.
  • For extended length videos longer than 10 minutes you must use HTTP Live Streaming, which is H.264 + AAC in a series of small .ts container files (see App Store Review Guidelines rule 2.5.7).

Video

On the iPhone, H.264 is the only game in town. [1]

There are several different feature tiers or "profiles" available in H.264. All modern iPhones (3GS and above) support the High profile. These profiles are basically three different levels of algorithm "tricks" used to compress the video. More tricks give better compression, but require more CPU or dedicated hardware to decode. This is a table that lists the differences between the different profiles.

[1] Interestingly, Apple's own Facetime uses the newer H.265 (HEVC) video codec. However right now (August 2017) there is no Apple-provided library that gives access to a HEVC codec to developers. This is expected to change at some point.

In talking about what video format the iPhone supports, a distinction should be made between what the hardware can support, and what the (much lower) limits are for playback when streaming over a network.

The only data given about hardware video support by Apple about the current generation of iPhones (SE, 6S, 6S Plus, 7, 7 Plus) is that they support

4K [3840x2160] video recording at 30 fps

1080p [1920x1080] HD video recording at 30 fps or 60 fps.

Obviously the phone can play back what it can record, so we can guess that 3840x2160 at 30 fps and 1920x1080 at 60 fps represent design limits of the phone. In addition, the screen size on the 6S Plus and 7 Plus is 1920x1080. So if you're interested in playback on the phone, it doesn't make sense to send over more pixels then the screen can draw.

However, streaming video is a different matter. Since networks are slow and video is huge, it's typical to use lower resolutions, bitrates, and frame rates than the device's theoretical maximum.

The most detailed document giving recommendations for streaming is TN2224 Best Practices for Creating and Deploying HTTP Live Streaming Media for Apple Devices. Figure 3 in that document gives a table of recommended streaming parameters:

Table of Apple recommended video encoding settings This table is from May 2016.

As you can see, Apple recommends the relatively low resolution of 768x432 as the highest recommended resolution for streaming over a cellular network. Of course this is just a recommendation and YMMV.

Audio

The question is about video, but that video generally has one or more audio tracks with it. The iPhone supports a few audio formats, but the most modern and by far most widely used is AAC. The iPhone 7 / 7 Plus, 6S Plus / 6S, SE all support AAC bitrates of 8 to 320 Kbps.

Container

The audio and video tracks go inside a container. The purpose of the container is to combine (interleave) the different tracks together, to store metadata, and to support seeking. The iPhone supports

  1. QuickTime .mov,
  2. MP4, and
  3. MPEG-TS.

The .mov and .mp4 file formats are closely related (.mp4 is in fact based on .mov), however .mp4 is an ISO standard that has much wider support.

As noted above, you have to use MPEG-TS for videos longer than 10 minutes.

argparse module How to add option without any argument?

To create an option that needs no value, set the action [docs] of it to 'store_const', 'store_true' or 'store_false'.

Example:

parser.add_argument('-s', '--simulate', action='store_true')

Angular 2 router.navigate

If the first segment doesn't start with / it is a relative route. router.navigate needs a relativeTo parameter for relative navigation

Either you make the route absolute:

this.router.navigate(['/foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams)

or you pass relativeTo

this.router.navigate(['../foo-content', 'bar-contents', 'baz-content', 'page'], {queryParams: this.params.queryParams, relativeTo: this.currentActivatedRoute})

See also

Eclipse internal error while initializing Java tooling

Sometimes the issue is with the version of the Java installed. I was facing a similar issue when trying to start Spring Tool Suite on my Ubuntu 16.04. I had java 9 installed on my machine. I changed it to java 8. And it started working.

z-index not working with position absolute

z-index only applies to elements that have been given an explicit position. Add position:relative to #popupContent and you should be good to go.

How to compare LocalDate instances Java 8

Using equals() LocalDate does override equals:

int compareTo0(LocalDate otherDate) {
    int cmp = (year - otherDate.year);
    if (cmp == 0) {
        cmp = (month - otherDate.month);
        if (cmp == 0) {
            cmp = (day - otherDate.day);
        }
    }
    return cmp;
}

If you are not happy with the result of equals(), you are good using the predefined methods of LocalDate.

Notice that all of those method are using the compareTo0() method and just check the cmp value. if you are still getting weird result (which you shouldn't), please attach an example of input and output

Boxplot show the value of mean

You can use the output value from stat_summary()

ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) 
+ geom_boxplot() 
+ stat_summary(fun.y=mean, colour="darkred", geom="point", hape=18, size=3,show_guide = FALSE)
+ stat_summary(fun.y=mean, colour="red", geom="text", show_guide = FALSE, 
               vjust=-0.7, aes( label=round(..y.., digits=1)))

How to change the text on the action bar

getActionBar().setTitle("edit your text"); 

How can I assign an ID to a view programmatically?

You can just use the View.setId(integer) for this. In the XML, even though you're setting a String id, this gets converted into an integer. Due to this, you can use any (positive) Integer for the Views you add programmatically.

According to View documentation

The identifier does not have to be unique in this view's hierarchy. The identifier should be a positive number.

So you can use any positive integer you like, but in this case there can be some views with equivalent id's. If you want to search for some view in hierarchy calling to setTag with some key objects may be handy.

Credits to this answer.

What is the difference between Sprint and Iteration in Scrum and length of each Sprint?

Sprint == Iteration.

The lengths can vary, but it's a bad planning precedent to let them vary too much.

Keep them consistent in duration and you will get better at planning and delivering. Everything will be measured by how many 10-day sprints it takes to finish a series of use cases.

Keep them consistent in length and you can plan your deliveries, end-user testing, etc., with more accuracy.

The point is to release on time at a consistent pace. A regular schedule makes management slightly simpler and more predictable.

How to center icon and text in a android button with width set to "fill parent"

What happens if you try android:gravity="center_horizontal"?

Why am I getting "Unable to find manifest signing certificate in the certificate store" in my Excel Addin?

The issue of erroneous leftover entries in the .csproj file still occurs with VS2015update3 and can also occur if you try to change the signing certificate for a different one (even if that is one generated using the 'new' option in the certificate selection dropdown). The advice in the accepted answer (mark as not signed, save, unload project, edit .csproj, remove the properties relating to the old certificates/thumbprints/keys & reload project, set certificate) is reliable.

What is the difference between __dirname and ./ in node.js?

./ refers to the current working directory, except in the require() function. When using require(), it translates ./ to the directory of the current file called. __dirname is always the directory of the current file.

For example, with the following file structure

/home/user/dir/files/config.json

{
  "hello": "world"
}

/home/user/dir/files/somefile.txt

text file

/home/user/dir/dir.js

var fs = require('fs');

console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));

If I cd into /home/user/dir and run node dir.js I will get

{ hello: 'world' }
text file

But when I run the same script from /home/user/ I get

{ hello: 'world' }

Error: ENOENT, no such file or directory './files/somefile.txt'
    at Object.openSync (fs.js:228:18)
    at Object.readFileSync (fs.js:119:15)
    at Object.<anonymous> (/home/user/dir/dir.js:4:16)
    at Module._compile (module.js:432:26)
    at Object..js (module.js:450:10)
    at Module.load (module.js:351:31)
    at Function._load (module.js:310:12)
    at Array.0 (module.js:470:10)
    at EventEmitter._tickCallback (node.js:192:40)

Using ./ worked with require but not for fs.readFileSync. That's because for fs.readFileSync, ./ translates into the cwd (in this case /home/user/). And /home/user/files/somefile.txt does not exist.

ASP.NET Temporary files cleanup

Just an update on more current OS's (Vista, Win7, etc.) - the temp file path has changed may be different based on several variables. The items below are not definitive, however, they are a few I have encountered:

"temp" environment variable setting - then it would be:

%temp%\Temporary ASP.NET Files

Permissions and what application/process (VS, IIS, IIS Express) is running the .Net compiler. Accessing the C:\WINDOWS\Microsoft.NET\Framework folders requires elevated permissions and if you are not developing under an account with sufficient permissions then this folder might be used:

c:\Users\[youruserid]\AppData\Local\Temp\Temporary ASP.NET Files

There are also cases where the temp folder can be set via config for a machine or site specific using this:

<compilation tempDirectory="d:\MyTempPlace" />

I even have a funky setup at work where we don't run Admin by default, plus the IT guys have login scripts that set %temp% and I get temp files in 3 different locations depending on what is compiling things! And I'm still not certain about how these paths get picked....sigh.

Still, dthrasher is correct, you can just delete these and VS and IIS will just recompile them as needed.

Convert NaN to 0 in javascript

Something simpler and effective for anything :

function getNum(val) {
   val = +val || 0
   return val;
}

...which will convert a from any "falsey" value to 0.

The "falsey" values are:

  • false
  • null
  • undefined
  • 0
  • "" ( empty string )
  • NaN ( Not a Number )

Format y axis as percent

I'm late to the game but I just realize this: ax can be replaced with plt.gca() for those who are not using axes and just subplots.

Echoing @Mad Physicist answer, using the package PercentFormatter it would be:

import matplotlib.ticker as mtick

plt.gca().yaxis.set_major_formatter(mtick.PercentFormatter(1))
#if you already have ticks in the 0 to 1 range. Otherwise see their answer

PHP sessions default timeout

You can change it in you php-configuration on your webserver. Search in php.ini for

session.gc_maxlifetime() The value is set in Seconds.

need to add a class to an element

You can use result.className = 'red';, but you can also use result.classList.add('red');. The .classList.add(str) way is usually easier if you need to add a class in general, and don't want to check if the class is already in the list of classes.

Http Get using Android HttpURLConnection

Try getting the input stream from this you can then get the text data as so:-

    URL url;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL("http://www.mysite.se/index.asp?data=99");

        urlConnection = (HttpURLConnection) url
                .openConnection();

        InputStream in = urlConnection.getInputStream();

        InputStreamReader isw = new InputStreamReader(in);

        int data = isw.read();
        while (data != -1) {
            char current = (char) data;
            data = isw.read();
            System.out.print(current);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }    
    }

You can probably use other inputstream readers such as buffered reader also.

The problem is that when you open the connection - it does not 'pull' any data.

How can I get the current directory name in Javascript?

In Node.js, you could use:

console.log('Current directory: ' + process.cwd());

How to take off line numbers in Vi?

set number set nonumber

DO work inside .vimrc and make sure you DO NOT precede commands in .vimrc with :

Explanation of <script type = "text/template"> ... </script>

<script type = “text/template”> … </script> is obsolete. Use <template> tag instead.

What's the difference between Apache's Mesos and Google's Kubernetes

I like this short video here mesos learning material

with bare metal clusters, you would need to spawn stacks like HDFS, SPARK, MR etc... so if you launch tasks related to these using only bare metal cluster management, there will be a lot cold starting time.

with mesos, you can install these services on top of the bare metals and you can avoid the bring up time of those base services. This is something mesos does well. and can be utilised by kubernetes building on top of it.

Make hibernate ignore class variables that are not mapped

For folks who find this posting through the search engines, another possible cause of this problem is from importing the wrong package version of @Transient. Make sure that you import javax.persistence.transient and not some other package.

How to get Last record from Sqlite?

Another option is to use SQLites LAST_VALUE() function in the following way.

Given this table:

+--------+---------+-------+
| OBJECT |  STATUS |  TIME |
+--------+---------+-------+
|        |         |       |
| 1      |  ON     |  100  |
|        |         |       |
| 1      |  OFF    |  102  |
|        |         |       |
| 1      |  ON     |  103  |
|        |         |       |
| 2      |  ON     |  101  |
|        |         |       |
| 2      |  OFF    |  102  |
|        |         |       |
| 2      |  ON     |  103  |
|        |         |       |
| 3      |  OFF    |  102  |
|        |         |       |
| 3      |  ON     |  103  |
+--------+---------+-------+

You can get the last status of every object with the following query

SELECT                           
    DISTINCT OBJECT,             -- Only unique rows
    LAST_VALUE(STATUS) OVER (    -- The last value of the status column
        PARTITION BY OBJECT      -- Taking into account rows with the same value in the object column
        ORDER by time asc        -- "Last" when sorting the rows of every object by the time column in ascending order
        RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING    -- Take all rows in the patition
    ) as lastStatus
FROM
    TABLE

The result would look like:

+--------+--------------+
| OBJECT |  LAST_STATUS |
+--------+--------------+
|        |              |
| 1      |  ON          |
|        |              |
| 2      |  ON          |
|        |              |
| 3      |  ON          |
+--------+--------------+

How do I get Fiddler to stop ignoring traffic to localhost?

Go to Tools, Fiddler Options ..., select the Connections tab, then make sure Monitor all connections is ticked. Like Antony Scott said, but also make sure that the "Web Sessions" pane is set to "Capturing" and [ "Web Browsers" OR "All Processes" ]. Looks like the default is "Non-Browser".

Bootstrap Modal immediately disappearing

The problem can also occurs if using jquery you attach an event listener twice. For exemple you would set without unbinding :

            $("body").on("click","#fixerror",function(event){
                $("#fixerrormodal").modal('toggle')
            })

If this happens the event is fired twice in a row and the modal disapears.

            $("body").on("click","#fixerror",function(event){
                $("#fixerrormodal").modal()
                $("#fixerrormodal").modal('toggle')
            })

See exemple : http://embed.plnkr.co/i5xB1WbX7zgXrbDMhNAW/preview

How to change pivot table data source in Excel?

In case of Excel 2007 You can change datasource in Options menu /Change Data Source

Transmitting newline character "\n"

Use %0A (URL encoding) instead of \n (C encoding).

How to remove single character from a String

           BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
   String line1=input.readLine();
   String line2=input.readLine();
         char[]  a=line2.toCharArray();
          char[] b=line1.toCharArray();
           loop: for(int t=0;t<a.length;t++) {

            char a1=a[t];
           for(int t1=0;t1<b.length;t1++) {
               char b1=b[t1];  
               if(a1==b1) {
                   StringBuilder sb = new StringBuilder(line1);
                   sb.deleteCharAt(t1);
                   line1=sb.toString();
                   b=line1.toCharArray();
                   list.add(a1);
                   continue  loop;   
               }


            }

frequent issues arising in android view, Error parsing XML: unbound prefix

For me, I got the "unbound prefix" error on first line here, although I had misspelled android on the fourth line.

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
anrdoid:fillViewport="true"
>

Removing certain characters from a string in R

try: gsub('\\$', '', '$5.00$')

Complexities of binary tree traversals

O(n), because you traverse each node once. Or rather - the amount of work you do for each node is constant (does not depend on the rest of the nodes).

How to error handle 1004 Error with WorksheetFunction.VLookup?

Instead of WorksheetFunction.Vlookup, you can use Application.Vlookup. If you set a Variant equal to this it returns Error 2042 if no match is found. You can then test the variant - cellNum in this case - with IsError:

Sub test()
Dim ws As Worksheet: Set ws = Sheets("2012")
Dim rngLook As Range: Set rngLook = ws.Range("A:M")
Dim currName As String
Dim cellNum As Variant

'within a loop
currName = "Example"
cellNum = Application.VLookup(currName, rngLook, 13, False)
If IsError(cellNum) Then
    MsgBox "no match"
Else
    MsgBox cellNum
End If
End Sub

The Application versions of the VLOOKUP and MATCH functions allow you to test for errors without raising the error. If you use the WorksheetFunction version, you need convoluted error handling that re-routes your code to an error handler, returns to the next statement to evaluate, etc. With the Application functions, you can avoid that mess.

The above could be further simplified using the IIF function. This method is not always appropriate (e.g., if you have to do more/different procedure based on the If/Then) but in the case of this where you are simply trying to determinie what prompt to display in the MsgBox, it should work:

cellNum = Application.VLookup(currName, rngLook, 13, False)
MsgBox IIF(IsError(cellNum),"no match", cellNum)

Consider those methods instead of On Error ... statements. They are both easier to read and maintain -- few things are more confusing than trying to follow a bunch of GoTo and Resume statements.

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

Convert XmlDocument to String

If you are using Windows.Data.Xml.Dom.XmlDocument version of XmlDocument (used in UWP apps for example), you can use yourXmlDocument.GetXml() to get the XML as a string.

Removing packages installed with go get

You can delete the archive files and executable binaries that go install (or go get) produces for a package with go clean -i importpath.... These normally reside under $GOPATH/pkg and $GOPATH/bin, respectively.

Be sure to include ... on the importpath, since it appears that, if a package includes an executable, go clean -i will only remove that and not archive files for subpackages, like gore/gocode in the example below.

Source code then needs to be removed manually from $GOPATH/src.

go clean has an -n flag for a dry run that prints what will be run without executing it, so you can be certain (see go help clean). It also has a tempting -r flag to recursively clean dependencies, which you probably don't want to actually use since you'll see from a dry run that it will delete lots of standard library archive files!

A complete example, which you could base a script on if you like:

$ go get -u github.com/motemen/gore

$ which gore
/Users/ches/src/go/bin/gore

$ go clean -i -n github.com/motemen/gore...
cd /Users/ches/src/go/src/github.com/motemen/gore
rm -f gore gore.exe gore.test gore.test.exe commands commands.exe commands_test commands_test.exe complete complete.exe complete_test complete_test.exe debug debug.exe helpers_test helpers_test.exe liner liner.exe log log.exe main main.exe node node.exe node_test node_test.exe quickfix quickfix.exe session_test session_test.exe terminal_unix terminal_unix.exe terminal_windows terminal_windows.exe utils utils.exe
rm -f /Users/ches/src/go/bin/gore
cd /Users/ches/src/go/src/github.com/motemen/gore/gocode
rm -f gocode.test gocode.test.exe
rm -f /Users/ches/src/go/pkg/darwin_amd64/github.com/motemen/gore/gocode.a

$ go clean -i github.com/motemen/gore...

$ which gore

$ tree $GOPATH/pkg/darwin_amd64/github.com/motemen/gore
/Users/ches/src/go/pkg/darwin_amd64/github.com/motemen/gore

0 directories, 0 files

# If that empty directory really bugs you...
$ rmdir $GOPATH/pkg/darwin_amd64/github.com/motemen/gore

$ rm -rf $GOPATH/src/github.com/motemen/gore

Note that this information is based on the go tool in Go version 1.5.1.

Finishing current activity from a fragment

try to use this

yes Fragment.class does not implement finish()

When working with fragments, instead of using this or refering to the context, always use getActivity(). You should call

Check play state of AVPlayer

A more reliable alternative to NSNotification is to add yourself as observer to player's rate property.

[self.player addObserver:self
              forKeyPath:@"rate"
                 options:NSKeyValueObservingOptionNew
                 context:NULL];

Then check if the new value for observed rate is zero, which means that playback has stopped for some reason, like reaching the end or stalling because of empty buffer.

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSString *,id> *)change
                       context:(void *)context {
    if ([keyPath isEqualToString:@"rate"]) {
        float rate = [change[NSKeyValueChangeNewKey] floatValue];
        if (rate == 0.0) {
            // Playback stopped
        } else if (rate == 1.0) {
            // Normal playback
        } else if (rate == -1.0) {
            // Reverse playback
        }
    }
}

For rate == 0.0 case, to know what exactly caused the playback to stop, you can do the following checks:

if (self.player.error != nil) {
    // Playback failed
}
if (CMTimeGetSeconds(self.player.currentTime) >=
    CMTimeGetSeconds(self.player.currentItem.duration)) {
    // Playback reached end
} else if (!self.player.currentItem.playbackLikelyToKeepUp) {
    // Not ready to play, wait until enough data is loaded
}

And don't forget to make your player stop when it reaches the end:

self.player.actionAtItemEnd = AVPlayerActionAtItemEndPause;

Convert Json string to Json object in Swift 4

I used below code and it's working fine for me. :

let jsonText = "{\"userName\":\"Bhavsang\"}"
var dictonary:NSDictionary?
    
if let data = jsonText.dataUsingEncoding(NSUTF8StringEncoding) {
        
     do {
            dictonary =  try NSJSONSerialization.JSONObjectWithData(data, options: [.allowFragments]) as? [String:AnyObject]
        
            if let myDictionary = dictonary
              {
                  print(" User name is: \(myDictionary["userName"]!)")
              }
            } catch let error as NSError {
            
            print(error)
         }
}

Set The Window Position of an application via command line

You'll need an additional utility such as cmdow.exe to accomplish this. Look specifically at the /mov switch. You can either launch your program from cmdow or run it separately and then invoke cmdow to move/resize it as desired.

JQuery Event for user pressing enter in a textbox?

Another subtle variation. I went for a slight separation of powers, so I have a plugin to enable catching the enter key, then I just bind to events normally:

(function($) { $.fn.catchEnter = function(sel) {  
    return this.each(function() { 
        $(this).on('keyup',sel,function(e){
            if(e.keyCode == 13)
              $(this).trigger("enterkey");
        })
    });  
};
})(jQuery);

And then in use:

$('.input[type="text"]').catchEnter().on('enterkey',function(ev) { });

This variation allows you to use event delegation (to bind to elements you haven't created yet).

$('body').catchEnter('.onelineInput').on('enterkey',function(ev) { /*process input */ });

How can I create an array with key value pairs?

You can use this function in your application to add keys to indexed array.

public static function convertIndexedArrayToAssociative($indexedArr, $keys)
{
    $resArr = array();
    foreach ($indexedArr as $item)
    {
        $tmpArr = array();
        foreach ($item as $key=>$value)
        {
            $tmpArr[$keys[$key]] = $value;
        }
        $resArr[] = $tmpArr;
    }
    return $resArr;
}

Count number of iterations in a foreach loop

There's a few different ways you can tackle this one.

You can set a counter before the foreach() and then just iterate through which is the easiest approach.

$counter = 0;
foreach ($Contents as $item) {
      $counter++;
       $item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
}

How do I drop a foreign key constraint only if it exists in sql server?

The more simple solution is provided in Eric Isaacs's answer. However, it will find constraints on any table. If you want to target a foreign key constraint on a specific table, use this:

IF EXISTS (SELECT * 
  FROM sys.foreign_keys 
   WHERE object_id = OBJECT_ID(N'dbo.FK_TableName_TableName2')
   AND parent_object_id = OBJECT_ID(N'dbo.TableName')
)
  ALTER TABLE [dbo.TableName] DROP CONSTRAINT [FK_TableName_TableName2]

WCF Exception: Could not find a base address that matches scheme http for the endpoint

My issue was caused by missing bindings in IIS, in the left tree view "Connections", under Sites, Right click on your site > edit bindings > add > https

Choose 'IIS Express Development Certificate' and set port to 443 Then I added another binding to the webconfig:

<endpoint address="wsHttps" binding="wsHttpBinding" bindingConfiguration="DefaultWsHttpBinding" name="Your.bindingname" contract="Your.contract" />

Also added to serviceBehaviours: <serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" />

And eventually it worked, none of the solutions I checked on stackoverflow for this error was applicable to my specific scenario, so including here in case it helps others

XAMPP Object not found error

Make sure you also start the MySQL service in Xampp control panel. This might resolve this.

Color different parts of a RichTextBox string

I think modifying a "selected text" in a RichTextBox isn't the right way to add colored text. So here a method to add a "color block" :

        Run run = new Run("This is my text");
        run.Foreground = new SolidColorBrush(Colors.Red); // My Color
        Paragraph paragraph = new Paragraph(run);
        MyRichTextBlock.Document.Blocks.Add(paragraph);

From MSDN :

The Blocks property is the content property of RichTextBox. It is a collection of Paragraph elements. Content in each Paragraph element can contain the following elements:

  • Inline

  • InlineUIContainer

  • Run

  • Span

  • Bold

  • Hyperlink

  • Italic

  • Underline

  • LineBreak

So I think you have to split your string depending on parts color, and create as many Run objects as needed.

Unity Scripts edited in Visual studio don't provide autocomplete

I found an another way to fix this issue in a more convenient manner:

  1. Select the broken file in Solution Explorer.
  2. Open its Properties.
  3. Switch field "Build Action" from "Compile" to "None".
  4. Then switch it back to "Compile".

This will kill the synchronization between Unity and Visual Studio somehow.

The next time Visual Studio will reload the project, it will prompt a warning. Just click on "Discard".

How to generate keyboard events?

I tried lib keyboard and it works good on Windows, Mac and Linux. Below line helps me switch tabs in browser:

keyboard.press_and_release('ctrl+tab')
    

DataAdapter.Fill(Dataset)

leDbConnection connection = 
new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Inventar.accdb");
DataSet1 DS = new DataSet1();
connection.Open();

OleDbDataAdapter DBAdapter = new OleDbDataAdapter(
@"SELECT tbl_Computer.*,  tbl_Besitzer.*
  FROM tbl_Computer 
  INNER JOIN tbl_Besitzer ON tbl_Computer.FK_Benutzer = tbl_Besitzer.ID 
  WHERE (((tbl_Besitzer.Vorname)='ma'));", 
connection);

What is the difference between H.264 video and MPEG-4 video?

They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"

jQuery .attr("disabled", "disabled") not working in Chrome

if you are removing all disabled attributes from input, then why not just do:

$("input").removeAttr('disabled');

Then after ajax success:

$("input[type='text']").attr('disabled', true);

Make sure you use remove the disabled attribute before submit, or it won't submit that data. If you need to submit it before changing, you need to use readonly instead.

oracle SQL how to remove time from date

If your column with DATE datatype has value like below : -

value in column : 10-NOV-2005 06:31:00

Then, You can Use TRUNC function in select query to convert your date-time value to only date like - DD/MM/YYYY or DD-MON-YYYY

select TRUNC(column_1) from table1;

result : 10-NOV-2005

You will see above result - Provided that NLS_DATE_FORMAT is set as like below :-

Alter session NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';

NSRange from Swift Range?

Swift 4

I think, there are two ways.

1. NSRange(range, in: )

2. NSRange(location:, length: )

Sample code:

let attributedString = NSMutableAttributedString(string: "Sample Text 12345", attributes: [.font : UIFont.systemFont(ofSize: 15.0)])

// NSRange(range, in: )
if let range = attributedString.string.range(of: "Sample")  {
    attributedString.addAttribute(.foregroundColor, value: UIColor.orange, range: NSRange(range, in: attributedString.string))
}

// NSRange(location: , length: )
if let range = attributedString.string.range(of: "12345") {
    attributedString.addAttribute(.foregroundColor, value: UIColor.green, range: NSRange(location: range.lowerBound.encodedOffset, length: range.upperBound.encodedOffset - range.lowerBound.encodedOffset))
}

Screen Shot: enter image description here

Pass row number as variable in excel sheet

Assuming your row number is in B1, you can use INDIRECT:

=INDIRECT("A" & B1)

This takes a cell reference as a string (in this case, the concatenation of A and the value of B1 - 5), and returns the value at that cell.

How to convert a Bitmap to Drawable in android?

covert bit map to drawable in sketchware app using code

    android.graphics.drawable.BitmapDrawable d = new android.graphics.drawable.BitmapDrawable(getResources(), bitmap);

jquery, find next element by class

You cannot use next() in this scenario, if you look at the documentation it says:
Next() Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling that matches the selector.

so if the second DIV was in the same TD then you could code:


// Won't work in your case
$(obj).next().filter('.class');

But since it's not, I don't see a point to use next(). You can instead code:

$(obj).parents('table').find('.class')

CakePHP 3.0 installation: intl extension missing from system

If you are using latest version Ubuntu 16.04 or later just do

sudo apt-get install php-intl

Then restart your apache

sudo service apache2 restart

How to enumerate an object's properties in Python?

for one-liners:

print vars(theObject)

How to Bootstrap navbar static to fixed on scroll?

/** * Scroll management */ $(document).ready(function () {

// Define the menu we are working with
var menu = $('.navbar.navbar-default.navbar-inverse');

// Get the menus current offset
var origOffsetY = menu.offset().top;

/**
 * scroll
 * Perform our menu mod
 */
function scroll() {

    // Check the menus offset. 
    if ($(window).scrollTop() >= origOffsetY) {

        //If it is indeed beyond the offset, affix it to the top.
        $(menu).addClass('navbar-fixed-top');

    } else {

        // Otherwise, un affix it.
        $(menu).removeClass('navbar-fixed-top');

    }
}

// Anytime the document is scrolled act on it
document.onscroll = scroll;

});

What's the best way to get the current URL in Spring MVC?

If you need the URL till hostname and not the path use Apache's Common Lib StringUtil, and from URL extract the substring till third indexOf /.

public static String getURL(HttpServletRequest request){
   String fullURL = request.getRequestURL().toString();
   return fullURL.substring(0,StringUtils.ordinalIndexOf(fullURL, "/", 3)); 
}

Example: If fullURL is https://example.com/path/after/url/ then Output will be https://example.com

Adding multiple columns AFTER a specific column in MySQL

ALTER TABLE listing ADD count INT(5), ADD log VARCHAR(200), ADD status VARCHAR(20) AFTER stat

It will give good results.

Rails: How can I set default values in ActiveRecord?

If the column happens to be a 'status' type column, and your model lends itself to the use of state machines, consider using the aasm gem, after which you can simply do

  aasm column: "status" do
    state :available, initial: true
    state :used
    # transitions
  end

It still doesn't initialize the value for unsaved records, but it's a bit cleaner than rolling your own with init or whatever, and you reap the other benefits of aasm such as scopes for all your statuses.

What is SOA "in plain english"?

I see many answers explaining a Service Oriented Architecture (SOA) using even more advanced words and technical terms. I'd like to give a shot at explaining it for the layman, using an analogy in plain english.

But first a description of a SOA
SOA could be described in three layers as seen in the picture below. On one side we have the Provider and on the other side we have the Consumer, separated by a Bridge where the two sides communicate.

The consumer uses a number of Applications necessary for it's business and the provider uses Components that provide these applications with information. They communicate through a set of Services using a common architecture.


enter image description here


The analogy
Imagine a house on the country side, that in many ways is part of a larger community, like a city or town. The city has it's own complex systems for providing water and electricity, handling sanitation, providing transportation and other utilities. The House is the consumer in this model, the City (or community) is the provider and the pipes, sewers, powerlines, optical fibers etc. is the Infrastructure in which they communicate.

This model could loosely be compared to a SOA. The people in the house uses a number of different "applications" like radiators, computers, toilets, lamps, underfloor heating, bathtubs etc. These applications don't care how the city generates the water, creates the electricity or handles the waste as long as it works. The components of the city are generators, water pumps and sanitation areas. It provides the house with all these needs but it's up to the house to use it in what ever way it sees fit.

I hope this gave at least someone a better picture of a SOA.

How to iterate through a DataTable

foreach (DataRow row in myDataTable.Rows)
{
   Console.WriteLine(row["ImagePath"]);
}

I am writing this from memory.
Hope this gives you enough hint to understand the object model.

DataTable -> DataRowCollection -> DataRow (which one can use & look for column contents for that row, either using columnName or ordinal).

-> = contains.

Razor View Engine : An expression tree may not contain a dynamic operation

It seems to me that you have an untyped view. By default, Razor views in MVC3 RC are typed as dynamic. However, lambdas do not support dynamic members. You have to strongly type your model. At the top of your view file add

@model SampleModel

Remove .php extension with .htaccess

Apache mod_rewrite

What you're looking for is mod_rewrite,

Description: Provides a rule-based rewriting engine to rewrite requested URLs on the fly.

Generally speaking, mod_rewrite works by matching the requested document against specified regular expressions, then performs URL rewrites internally (within the apache process) or externally (in the clients browser). These rewrites can be as simple as internally translating example.com/foo into a request for example.com/foo/bar.

The Apache docs include a mod_rewrite guide and I think some of the things you want to do are covered in it. Detailed mod_rewrite guide.

Force the www subdomain

I would like it to force "www" before every url, so its not domain.com but www.domain.com/page

The rewrite guide includes instructions for this under the Canonical Hostname example.

Remove trailing slashes (Part 1)

I would like to remove all trailing slashes from pages

I'm not sure why you would want to do this as the rewrite guide includes an example for the exact opposite, i.e., always including a trailing slash. The docs suggest that removing the trailing slash has great potential for causing issues:

Trailing Slash Problem

Description:

Every webmaster can sing a song about the problem of the trailing slash on URLs referencing directories. If they are missing, the server dumps an error, because if you say /~quux/foo instead of /~quux/foo/ then the server searches for a file named foo. And because this file is a directory it complains. Actually it tries to fix it itself in most of the cases, but sometimes this mechanism need to be emulated by you. For instance after you have done a lot of complicated URL rewritings to CGI scripts etc.

Perhaps you could expand on why you want to remove the trailing slash all the time?

Remove .php extension

I need it to remove the .php

The closest thing to doing this that I can think of is to internally rewrite every request document with a .php extension, i.e., example.com/somepage is instead processed as a request for example.com/somepage.php. Note that proceeding in this manner would would require that each somepage actually exists as somepage.php on the filesystem.

With the right combination of regular expressions this should be possible to some extent. However, I can foresee some possible issues with index pages not being requested correctly and not matching directories correctly.

For example, this will correctly rewrite example.com/test as a request for example.com/test.php:

RewriteEngine  on
RewriteRule ^(.*)$ $1.php

But will make example.com fail to load because there is no example.com/.php

I'm going to guess that if you're removing all trailing slashes, then picking a request for a directory index from a request for a filename in the parent directory will become almost impossible. How do you determine a request for the directory 'foobar':

example.com/foobar

from a request for a file called foobar (which is actually foobar.php)

example.com/foobar

It might be possible if you used the RewriteBase directive. But if you do that then this problem gets way more complicated as you're going to require RewriteCond directives to do filesystem level checking if the request maps to a directory or a file.

That said, if you remove your requirement of removing all trailing slashes and instead force-add trailing slashes the "no .php extension" problem becomes a bit more reasonable.

# Turn on the rewrite engine
RewriteEngine  on
# If the request doesn't end in .php (Case insensitive) continue processing rules
RewriteCond %{REQUEST_URI} !\.php$ [NC]
# If the request doesn't end in a slash continue processing the rules
RewriteCond %{REQUEST_URI} [^/]$
# Rewrite the request with a .php extension. L means this is the 'Last' rule
RewriteRule ^(.*)$ $1.php [L]

This still isn't perfect -- every request for a file still has .php appended to the request internally. A request for 'hi.txt' will put this in your error logs:

[Tue Oct 26 18:12:52 2010] [error] [client 71.61.190.56] script '/var/www/test.peopleareducks.com/rewrite/hi.txt.php' not found or unable to stat

But there is another option, set the DefaultType and DirectoryIndex directives like this:

DefaultType application/x-httpd-php
DirectoryIndex index.php index.html

Update 2013-11-14 - Fixed the above snippet to incorporate nicorellius's observation

Now requests for hi.txt (and anything else) are successful, requests to example.com/test will return the processed version of test.php, and index.php files will work again.

I must give credit where credit is due for this solution as I found it Michael J. Radwins Blog by searching Google for php no extension apache.

Remove trailing slashes

Some searching for apache remove trailing slashes brought me to some Search Engine Optimization pages. Apparently some Content Management Systems (Drupal in this case) will make content available with and without a trailing slash in URls, which in the SEO world will cause your site to incur a duplicate content penalty. Source

The solution seems fairly trivial, using mod_rewrite we rewrite on the condition that the requested resource ends in a / and rewrite the URL by sending back the 301 Permanent Redirect HTTP header.

Here's his example which assumes your domain is blamcast.net and allows the the request to optionally be prefixed with www..

#get rid of trailing slashes
RewriteCond %{HTTP_HOST} ^(www.)?blamcast\.net$ [NC]
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]

Now we're getting somewhere. Lets put it all together and see what it looks like.

Mandatory www., no .php, and no trailing slashes

This assumes the domain is foobar.com and it is running on the standard port 80.

# Process all files as PHP by default
DefaultType application/x-httpd-php
# Fix sub-directory requests by allowing 'index' as a DirectoryIndex value
DirectoryIndex index index.html

# Force the domain to load with the www subdomain prefix
# If the request doesn't start with www...
RewriteCond %{HTTP_HOST}   !^www\.foobar\.com [NC]
# And the site name isn't empty
RewriteCond %{HTTP_HOST}   !^$
# Finally rewrite the request: end of rules, don't escape the output, and force a 301 redirect
RewriteRule ^/?(.*)         http://www.foobar.com/$1 [L,R,NE]

#get rid of trailing slashes
RewriteCond %{HTTP_HOST} ^(www.)?foobar\.com$ [NC]
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]

The 'R' flag is described in the RewriteRule directive section. Snippet:

redirect|R [=code] (force redirect) Prefix Substitution with http://thishost[:thisport]/ (which makes the new URL a URI) to force a external redirection. If no code is given, a HTTP response of 302 (MOVED TEMPORARILY) will be returned.

Final Note

I wasn't able to get the slash removal to work successfully. The redirect ended up giving me infinite redirect loops. After reading the original solution closer I get the impression that the example above works for them because of how their Drupal installation is configured. He mentions specifically:

On a normal Drupal site, with clean URLs enabled, these two addresses are basically interchangeable

In reference to URLs ending with and without a slash. Furthermore,

Drupal uses a file called .htaccess to tell your web server how to handle URLs. This is the same file that enables Drupal's clean URL magic. By adding a simple redirect command to the beginning of your .htaccess file, you can force the server to automatically remove any trailing slashes.

Recursively find files with a specific extension

This q/a shows how to use find with regular expression: How to use regex with find command?

Pattern could be something like

'^Robert\\.\\(h|cgg\\)$'

How to use zIndex in react-native

I believe there are different ways to do this based on what you need exactly, but one way would be to just put both Elements A and B inside Parent A.

    <View style={{ position: 'absolute' }}>    // parent of A
        <View style={{ zIndex: 1 }} />  // element A
        <View style={{ zIndex: 1 }} />  // element A
        <View style={{ zIndex: 0, position: 'absolute' }} />  // element B
    </View>

Pip Install not installing into correct directory?

This is what worked for me on Windows. The cause being multiple python installations

  1. update path with correct python
  2. uninstall pip using python -m pip uninstall pip setuptools
  3. restart windows didn't work until a restart

Thread Safe C# Singleton Pattern

Jeffrey Richter recommends following:



    public sealed class Singleton
    {
        private static readonly Object s_lock = new Object();
        private static Singleton instance = null;
    
        private Singleton()
        {
        }
    
        public static Singleton Instance
        {
            get
            {
                if(instance != null) return instance;
                Monitor.Enter(s_lock);
                Singleton temp = new Singleton();
                Interlocked.Exchange(ref instance, temp);
                Monitor.Exit(s_lock);
                return instance;
            }
        }
    }

Using DISTINCT along with GROUP BY in SQL Server

Perhaps not in the context that you have it, but you could use

SELECT DISTINCT col1,
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1),
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1, col3),
FROM TableA

You would use this to return different levels of aggregation returned in a single row. The use case would be for when a single grouping would not suffice all of the aggregates needed.

Dependency Injection vs Factory Pattern

I believe, 3 important aspects govern objects and their usage:
1. Instantiation (of a class together with initialisation if any).
2. Injection (of the instance so created) where it's required.
3. Life cycle management (of the instance so created).

Using Factory pattern, the first aspect (instantiation) is achieved but the remaining two is questionable. The class that uses other instances must hardcode the factories (instead of instances being created) which hinders loose coupling abilities. Moreover, life cycle management of instances becomes a challenge in a large application where a factory is used in multiple places (particularly, if the factory doesn't manage the life cycle of the instance it returns, it gets ugly).

Using a DI (of IoC pattern) on the other hand, all the 3 are abstracted outside the code (to the DI container) and the managed bean needs nothing about this complexity. Loose Coupling, a very important architectural goal can be achieved quiet comfortably. Another important architectural goal, the separation of concerns can be achieved much better than factories.

Whereas the Factories may be suitable for small applications, large ones would be better to chose DI over factories.

Node Sass couldn't find a binding for your current environment

I had the same problem

    throw new Error(errors.missingBinary());
    ^

Error: Missing binding /path/to/project/node_modules/node-sass/vendor/linux-x64-47/binding.node
Node Sass could not find a binding for your current environment: Linux 64-bit with Node.js 5.x

Found bindings for the following environments:
  - Linux 64-bit with Node 0.10.x
  - Linux 64-bit with Node.js 5.x

That was because I did npm install using a different nodejs version, try deleting node_modules folder installing and starting

cd your_project
rm -rf node_modules
npm install
npm start or gulp or whatever

If you are using nvm do

nvm use stable // or your favorite version
// remove node_module directory
npm install
npm start or gulp or whatever

How to check if a variable exists in a FreeMarker template?

Also I think if_exists was used like:

Hi ${userName?if_exists}, How are you?

which will not break if userName is null, the result if null would be:

Hi , How are you?

if_exists is now deprecated and has been replaced with the default operator ! as in

Hi ${userName!}, How are you?

the default operator also supports a default value, such as:

Hi ${userName!"John Doe"}, How are you?

Find multiple files and rename them in Linux

with bash:

shopt -s globstar nullglob
rename _dbg.txt .txt **/*dbg*

Can I change the viewport meta tag in mobile safari on the fly?

in your <head>

<meta id="viewport"
      name="viewport"
      content="width=1024, height=768, initial-scale=0, minimum-scale=0.25" />

somewhere in your javascript

document.getElementById("viewport").setAttribute("content",
      "initial-scale=0.5; maximum-scale=1.0; user-scalable=0;");

... but good luck with tweaking it for your device, fiddling for hours... and i'm still not there!

source

How to run Visual Studio post-build events for debug build only

Pre- and Post-Build Events run as a batch script. You can do a conditional statement on $(ConfigurationName).

For instance

if $(ConfigurationName) == Debug xcopy something somewhere

Play infinitely looping video on-load in HTML5

The loop attribute should do it:

<video width="320" height="240" autoplay loop>
  <source src="movie.mp4" type="video/mp4" />
  <source src="movie.ogg" type="video/ogg" />
  Your browser does not support the video tag.
</video>

Should you have a problem with the loop attribute (as we had in the past), listen to the videoEnd event and call the play() method when it fires.

Note1: I'm not sure about the behavior on Apple's iPad/iPhone, because they have some restrictions against autoplay.

Note2: loop="true" and autoplay="autoplay" are deprecated

Mobile website "WhatsApp" button to send message to a specific number

This answer is useful to them who want click to chat whatsapp in website to redirect web.whatsapp.com with default content or message and in mobile device to open in whatsapp in mobile app with default content to text bar in app.

also add jquery link.

<a  target="_blank" title="Contact Us On WhatsApp" href="https://web.whatsapp.com/send?phone=+91xxxxxxxxx&amp;text=Hi, I would like to get more information.." class="whatsapplink hidemobile" style="background-color:#2DC100">
<i class="fa fa-fw fa-whatsapp" style="color:#fff"></i>
<span style="color:#fff">
    Contact Us On WhatsApp        </span>
</a>
<a  target="_blank" title="Contact Us On WhatsApp" href="https://api.whatsapp.com/send?phone=+91xxxxxxxxx&text=Hi,%20I%20would%20like%20to%20get%20more%20information.." class="whatsapplink hideweb" style="background-color:#2DC100">
<i class="fa fa-fw fa-whatsapp" style="color:#fff"></i>
<span style="color:#fff">
    Contact Us On WhatsApp        </span>
</a>

<script type="text/javascript"> 
var mobile = (/iphone|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));  
if (mobile) { 

$('.hidemobile').css('display', 'none'); // OR you can use $('.hidemobile').hide();
} 
else 
{ 
$('.hideweb').css('display', 'none'); // OR you can use $('.hideweb').hide();
}
</script>

Attach (open) mdf file database with SQL Server Management Studio

I had the same problem.

system configuration:-single system with window 7 sp1 server and client both are installed on same system

I was trying to access the window desktop. As some the answer say that your Sqlserver service don't have full access to the directory. This is totally right.

I solved this problem by doing a few simple steps

  1. Go to All Programs->microsoft sql server 2008 -> configuration tools and then select sql server configuration manager.
  2. Select the service and go to properties. In the build in Account dialog box select local system and then select ok button.

enter image description here

Steps 3 and 4 in image are demo with accessing the folder

How do I rewrite URLs in a proxy response in NGINX

You can use the following nginx configuration example:

upstream adminhost {
  server adminhostname:8080;
}

server {
  listen 80;

  location ~ ^/admin/(.*)$ {
    proxy_pass http://adminhost/$1$is_args$args;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Host $server_name;
  }
}

How can I set a website image that will show as preview on Facebook?

If you're using Weebly, start by viewing the published site and right-clicking the image to Copy Image Address. Then in Weebly, go to Edit Site, Pages, click the page you wish to use, SEO Settings, under Header Code enter the code from Shef's answer:

<meta property="og:image" content="/uploads/..." />

just replacing /uploads/... with the copied image address. Click Publish to apply the change.

You can skip the part of Shef's answer about namespace, because that's already set by default in Weebly.

Crop image in PHP

imagecopyresampled() will take a rectangular area from $src_image of width $src_w and height $src_h at position ($src_x, $src_y) and place it in a rectangular area of $dst_image of width $dst_w and height $dst_h at position ($dst_x, $dst_y).

If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner.

This function can be used to copy regions within the same image. But if the regions overlap, the results will be unpredictable.

- Edit -

If $src_w and $src_h are smaller than $dst_w and $dst_h respectively, thumb image will be zoomed in. Otherwise it will be zoomed out.

<?php
$dst_x = 0;   // X-coordinate of destination point
$dst_y = 0;   // Y-coordinate of destination point
$src_x = 100; // Crop Start X position in original image
$src_y = 100; // Crop Srart Y position in original image
$dst_w = 160; // Thumb width
$dst_h = 120; // Thumb height
$src_w = 260; // Crop end X position in original image
$src_h = 220; // Crop end Y position in original image

// Creating an image with true colors having thumb dimensions (to merge with the original image)
$dst_image = imagecreatetruecolor($dst_w, $dst_h);
// Get original image
$src_image = imagecreatefromjpeg('images/source.jpg');
// Cropping
imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
// Saving
imagejpeg($dst_image, 'images/crop.jpg');
?>

Heroku deployment error H10 (App crashed)

I solved this problem by pushing to Git:

git add .
git commit -am "some text"
git push

then push to Heroku:

git push heroku

then rake db:migrate on Heroku:

heroku run rake db:migrate

Sort dataGridView columns in C# ? (Windows Form)

There's a method on the DataGridView called "Sort":

this.dataGridView1.Sort(this.dataGridView1.Columns["Name"], ListSortDirection.Ascending);

This will programmatically sort your datagridview.

Static methods - How to call a method from another method?

NOTE - it looks like the question has changed some. The answer to the question of how you call an instance method from a static method is that you can't without passing an instance in as an argument or instantiating that instance inside the static method.

What follows is mostly to answer "how do you call a static method from another static method":

Bear in mind that there is a difference between static methods and class methods in Python. A static method takes no implicit first argument, while a class method takes the class as the implicit first argument (usually cls by convention). With that in mind, here's how you would do that:

If it's a static method:

test.dosomethingelse()

If it's a class method:

cls.dosomethingelse()

How to run Ruby code from terminal?

You can run ruby commands in one line with the -e flag:

ruby -e "puts 'hi'"

Check the man page for more information.

Can you recommend a free light-weight MySQL GUI for Linux?

i suggest using phpmyadmin

it’s definitely the best free tool out there and it works on every system with php+mysql

How to pass a variable to the SelectCommand of a SqlDataSource?

Just add a custom property to the page which will return the variable of your choice. You can then use the built-in "control" parameter type.

In the code behind, add:

Dim MyVariable as Long


ReadOnly Property MyCustomProperty As Long
    Get
        Return MyVariable
    End Get
End Property

In the select parameters section add:

<asp:ControlParameter ControlID="__Page" Name="MyParameter" 
PropertyName="MyCustomProperty" Type="Int32" />

Trying to make bootstrap modal wider

You could try:

.modal.modal-wide .modal-dialog {
  width: 90%;
}

.modal-wide .modal-body {
  overflow-y: auto;
}

Just add .modal-wide to your classes

ALTER TABLE DROP COLUMN failed because one or more objects access this column

I had the same problem and this was the script that worked for me with a table with a two part name separated by a period ".".

USE [DATABASENAME] GO ALTER TABLE [TableNamePart1].[TableNamePart2] DROP CONSTRAINT [DF__ TableNamePart1D__ColumnName__5AEE82B9] GO ALTER TABLE [TableNamePart1].[ TableNamePart1] DROP COLUMN [ColumnName] GO

XML element with attribute and content using JAXB

The correct scheme should be:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" 
targetNamespace="http://www.example.org/Sport"
xmlns:tns="http://www.example.org/Sport" 
elementFormDefault="qualified"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" 
jaxb:version="2.0">

<complexType name="sportType">
    <simpleContent>
        <extension base="string">
            <attribute name="type" type="string" />
            <attribute name="gender" type="string" />
        </extension>
    </simpleContent>
</complexType>

<element name="sports">
    <complexType>
        <sequence>
            <element name="sport" minOccurs="0" maxOccurs="unbounded"
                type="tns:sportType" />
        </sequence>
    </complexType>
</element>

Code generated for SportType will be:

package org.example.sport;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;


@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sportType")
public class SportType {
    @XmlValue
    protected String value;
    @XmlAttribute
    protected String type;
    @XmlAttribute
    protected String gender;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getType() {
    return type;
    }


    public void setType(String value) {
        this.type = value;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String value) {
        this.gender = value;
    }
}

How do I install the babel-polyfill library?

For Babel version 7, if your are using @babel/preset-env, to include polyfill all you have to do is add a flag 'useBuiltIns' with the value of 'usage' in your babel configuration. There is no need to require or import polyfill at the entry point of your App.

With this flag specified, babel@7 will optimize and only include the polyfills you needs.

To use this flag, after installation:

npm install --save-dev  @babel/core @babel/cli @babel/preset-env
npm install --save @babel/polyfill

Simply add the flag:

useBuiltIns: "usage" 

to your babel configuration file called "babel.config.js" (also new to Babel@7), under the "@babel/env" section:

// file: babel.config.js

module.exports = () => {
   const presets = [
      [
         "@babel/env", 
         { 
             targets: { /* your targeted browser */ },
             useBuiltIns: "usage"  // <-----------------*** add this
         }
      ]
   ];

   return { presets };
};

Reference:


Update Aug 2019:

With the release of Babel 7.4.0 (March 19, 2019) @babel/polyfill is deprecated. Instead of installing @babe/polyfill, you will install core-js:

npm install --save core-js@3

A new entry corejs is added to your babel.config.js

// file: babel.config.js

module.exports = () => {
   const presets = [
      [
         "@babel/env", 
         { 
             targets: { /* your targeted browser */ },
             useBuiltIns: "usage",
             corejs: 3  // <----- specify version of corejs used
         }
      ]
   ];

   return { presets };
};

see example: https://github.com/ApolloTang/stackoverflow-eg--babel-v7.4.0-polyfill-w-core-v3

Reference:

Newline character in StringBuilder

I would make use of the Environment.NewLine property.

Something like:

StringBuilder sb = new StringBuilder();
sb.AppendFormat("Foo{0}Bar", Environment.NewLine);
string s = sb.ToString();

Or

StringBuilder sb = new StringBuilder();
sb.Append("Foo");
sb.Append("Foo2");
sb.Append(Environment.NewLine);
sb.Append("Bar");
string s = sb.ToString();

If you wish to have a new line after each append, you can have a look at Ben Voigt's answer.

SQL Query with Join, Count and Where

SELECT COUNT(*), table1.category_id, table2.category_name 
FROM table1 
INNER JOIN table2 ON table1.category_id=table2.category_id 
WHERE table1.colour <> 'red'
GROUP BY table1.category_id, table2.category_name 

How to display all elements in an arraylist?

Set for each loop to get all values

for (String member : members){
    Log.i("Member name: ", member);
}

File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?

change

import{observable} from 'rxjs/observable'; 

to

import{observable} from 'rxjs';

make sure you have save .TS file before compiling.

Better way to get type of a Javascript variable?

function getType(obj) {
    if(obj && obj.constructor && obj.constructor.name) {
        return obj.constructor.name;
    }
    return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}

In my preliminary tests, this is working pretty well. The first case will print the name of any object created with "new", and the 2nd case should catch everything else.

I'm using (8, -1) because I'm assuming that the result is always going to start with [object and end with ] but I'm not certain that's true in every scenario.

TypeError: $(...).on is not a function

The problem may be if you are using older version of jQuery. Because older versions of jQuery have 'live' method instead of 'on'

Prompt Dialog in Windows Forms

It's generally not a real good idea to import the VisualBasic libraries into C# programs (not because they won't work, but just for compatibility, style, and ability to upgrade), but you can call Microsoft.VisualBasic.Interaction.InputBox() to display the kind of box you're looking for.

If you can create a Windows.Forms object, that would be best, but you say you cannot do that.

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

Updating the value of data attribute using jQuery

$('.toggle img').data('block', 'something').attr('src', 'something.jpg');

How do you auto format code in Visual Studio?

Right click:

enter image description here

Works in VS 2015, maybe earlier version.

How to implement a Map with multiple keys?

A dirty and a simple solution, if you use the maps just for sorting lets say, is to add a very small value to a key until the value does not exist, but do not add the minimum (for example Double.MIN_VALUE) because it will cause a bug. Like I said, this is a very dirty solution but it makes the code simpler.

HTML5 canvas ctx.fillText won't do line breaks?

I created a tiny library for this scenario here: Canvas-Txt

It renders text in multi-line and it offers decent alignment modes.

In order to use this, you will need to either install it or use a CDN.

Installation

npm install canvas-txt --save

JavaScript

import canvasTxt from 'canvas-txt'

var c = document.getElementById('myCanvas')
var ctx = c.getContext('2d')

var txt = 'Lorem ipsum dolor sit amet'

canvasTxt.fontSize = 24

canvasTxt.drawText(ctx, txt, 100, 200, 200, 200)

This will render text in an invisible box with position/dimensions of:

{ x: 100, y: 200, height: 200, width: 200 }

Example Fiddle

_x000D_
_x000D_
/* https://github.com/geongeorge/Canvas-Txt  */_x000D_
_x000D_
const canvasTxt = window.canvasTxt.default;_x000D_
const ctx = document.getElementById('myCanvas').getContext('2d');_x000D_
_x000D_
const txt = "Lorem ipsum dolor sit amet";_x000D_
const bounds = { width: 240, height: 80 };_x000D_
_x000D_
let origin = { x: ctx.canvas.width / 2, y: ctx.canvas.height / 2, };_x000D_
let offset = { x: origin.x - (bounds.width / 2), y: origin.y - (bounds.height / 2) };_x000D_
_x000D_
canvasTxt.fontSize = 20;_x000D_
_x000D_
ctx.fillStyle = '#C1A700';_x000D_
ctx.fillRect(offset.x, offset.y, bounds.width, bounds.height);_x000D_
_x000D_
ctx.fillStyle = '#FFFFFF';_x000D_
canvasTxt.drawText(ctx, txt, offset.x, offset.y, bounds.width, bounds.height);
_x000D_
body {_x000D_
  background: #111;_x000D_
}_x000D_
_x000D_
canvas {_x000D_
  border: 1px solid #333;_x000D_
  background: #222; /* Could alternatively be painted on the canvas */_x000D_
}
_x000D_
<script src="https://unpkg.com/[email protected]/build/index.js"></script>_x000D_
_x000D_
<canvas id="myCanvas" width="300" height="160"></canvas>
_x000D_
_x000D_
_x000D_

Pass mouse events through absolutely-positioned element

Also nice to know...
Pointer-events can be disabled for a parent element (probably transparent div) and yet be enabled for child elements. This is helpful if you work with multiple overlapping div layers, where you want to be able click the child elements of any layer. For this all parenting divs get pointer-events: none and click-children get pointer-events reenabled by pointer-events: all

.parent {
    pointer-events:none;        
}
.child {
    pointer-events:all;
}

<div class="some-container">
   <ul class="layer-0 parent">
     <li class="click-me child"></li>
     <li class="click-me child"></li>
   </ul>

   <ul class="layer-1 parent">
     <li class="click-me-also child"></li>
     <li class="click-me-also child"></li>
   </ul>
</div>

How to insert data into elasticsearch

To avoid using curl or Chrome plugins you can just use the the built in windows Powershell. From the Powershell command window run

Invoke-WebRequest -UseBasicParsing "http://127.0.0.1:9200/sampleindex/sampleType/" -
Method POST -ContentType "application/json" -Body '{
"user" : "Test",
"post_date" : "2017/11/13 11:07:00",
"message" : "trying out Elasticsearch"
}'

Note the Index name MUST be in lowercase.

Multiline editing in Visual Studio Code

You can just Alt + click for additional cursors. And as already mentioned, Ctrl + Alt + ? or ?.

Setting network adapter metric priority in Windows 7

Windows has two different settings in which priority is established. There is the metric value which you have already set in the adapter settings, and then there is the connection priority in the network connections settings.

To change the priority of the connections:

  • Open your Adapter Settings (Control Panel\Network and Internet\Network Connections)
  • Click Alt to pull up the menu bar
  • Select Advanced -> Advanced Settings
  • Change the order of the connections so that the connection you want to have priority is top on the list

jQuery rotate/transform

I came up with some kind of solution to the problem. It involves jquery and css. This works like toggle but instead of toggling the display of elements it just changes its properties upon alternate clicks. Upon clicking the div it rotates the element with tag 180 degrees and when you click it again the element with tag returns to its original position. If you want to change the animation duration just change transition-duration property.

CSS

#example1{
transition-duration:1s;
}

jQuery

$(document).ready( function ()  {  var toggle = 1;
  $('div').click( function () {
      toggle++;
      if ( (toggle%2)==0){
          $('#example1').css( {'transform': 'rotate(180deg)'});
      }
      else{
          $('#example1').css({'transform': 'rotate(0deg)'});
      }
  });

});

Protractor : How to wait for page complete after click a button?

you can do something like this

_x000D_
_x000D_
emailEl.sendKeys('jack');_x000D_
passwordEl.sendKeys('123pwd');_x000D_
_x000D_
btnLoginEl.click().then(function(){_x000D_
browser.wait(5000);_x000D_
});
_x000D_
_x000D_
_x000D_

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

Try This.

$stmt->bindValue(':v1', null, PDO::PARAM_NULL); // --> insert null

Convert nullable bool? to bool

System.Convert works fine by me.

using System; ... Bool fixed = Convert.ToBoolean(NullableBool);

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result

Try this query -

SELECT 
  t2.company_name,
  t2.expose_new,
  t2.expose_used,
  t1.title,
  t1.seller,
  t1.status,
  CASE status
      WHEN 'New' THEN t2.expose_new
      WHEN 'Used' THEN t2.expose_used
      ELSE NULL
  END as 'expose'
FROM
  `products` t1
JOIN manufacturers t2
  ON
    t2.id = t1.seller
WHERE
  t1.seller = 4238

How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

Attempting to provide a concise update, based on Enzero's answer.

  • Install the Bootstrap.Datepicker package.

    PM> install-package Bootstrap.Datepicker
    ...
    Successfully installed 'Bootstrap.Datepicker 1.7.1' to ...
    
  • In AppStart/BundleConfig.cs, add the related scripts and styles in the bundles.

    bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
          //...,
          "~/Scripts/bootstrap-datepicker.js",
          "~/Scripts/locales/bootstrap-datepicker.YOUR-LOCALE-CODE-HERE.min.js"));
    
    bundles.Add(new StyleBundle("~/Content/css").Include(
          ...,
          "~/Content/bootstrap-datepicker3.css"));
    
  • In the related view, in the scripts' section, enable and customize datepicker.

    @section scripts{
        <script type="text/javascript">
            //...
            $('.datepicker').datepicker({
                format: 'dd/mm/yyyy', //choose the date format you prefer
                language: "YOUR-LOCALE-CODE-HERE",
                orientation: 'left bottom'
            });
        </script>
    
  • Eventually add the datepicker class in the related control. For instance, in a TextBox and for a date format in the like of "31/12/2018" this would be:

    @Html.TextBox("YOUR-STRING-FOR-THE-DATE", "{0:dd/MM/yyyy}", new { @class = "datepicker" })
    

How to post data in PHP using file_get_contents?

An alternative, you can also use fopen

$params = array('http' => array(
    'method' => 'POST',
    'content' => 'toto=1&tata=2'
));

$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if (!$fp)
{
    throw new Exception("Problem with $sUrl, $php_errormsg");
}

$response = @stream_get_contents($fp);
if ($response === false) 
{
    throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}

Reading from file using read() function

I am reading some data from a file using read. Here I am reading data in a 2d char pointer but the method is the same for the 1d also. Just read character by character and do not worry about the exceptions because the condition in the while loop is handling the exceptions :D

  while ( (n = read(fd, buffer,1)) > 0 )
{   

if(buffer[0] == '\n')
{
  r++;
  char**tempData=(char**)malloc(sizeof(char*)*r);

  for(int a=0;a<r;a++)
  {
    tempData[a]=(char*)malloc(sizeof(char)*BUF_SIZE);
    memset(tempData[a],0,BUF_SIZE);
  }

  for(int a=0;a<r-1;a++)
  {
    strcpy(tempData[a],data[a]);
  }

   data=tempData;

   c=0;
}

else
{
  data[r-1][c]=buffer[0];
  c++;
  buffer[1]='\0';
}

   }

How to use if, else condition in jsf to display image

Instead of using the "c" tags, you could also do the following:

<h:outputLink value="Images/thumb_02.jpg" target="_blank" rendered="#{not empty user or user.userId eq 0}" />
<h:graphicImage value="Images/thumb_02.jpg" rendered="#{not empty user or user.userId eq 0}" />

<h:outputLink value="/DisplayBlobExample?userId=#{user.userId}" target="_blank" rendered="#{not empty user and user.userId neq 0}" />
<h:graphicImage value="/DisplayBlobExample?userId=#{user.userId}" rendered="#{not empty user and user.userId neq 0}"/>

I think that's a little more readable alternative to skuntsel's alternative answer and is utilizing the JSF rendered attribute instead of nesting a ternary operator. And off the answer, did you possibly mean to put your image in between the anchor tags so the image is clickable?

Close iOS Keyboard by touching anywhere using Swift

As a novice programmer it can be confusing when people produce more skilled and unnecessary responses...You do not have to do any of the complicated stuff shown above!...

Here is the simplest option...In the case your keyboard appears in response to the textfield - Inside your touch screen function just add the resignFirstResponder function. As shown below - the keyboard will close because the First Responder is released (exiting the Responder chain)...

override func touchesBegan(_: Set<UITouch>, with: UIEvent?){
    MyTextField.resignFirstResponder()
}

How can I rollback an UPDATE query in SQL server 2005?

Once an update is committed you can't rollback just the single update. Your best bet is to roll back to a previous backup of the database.

How can prevent a PowerShell window from closing so I can see the error?

this will make the powershell window to wait until you press any key:

pause

Update One

Thanks to Stein. it is the Enter key not any key.

C# how to wait for a webpage to finish loading before continuing

This code was very helpful for me. Maybe it could be for you also

wb.Navigate(url);
while(wb.ReadyState != WebBrowserReadyState.Complete)
{
     Application.DoEvents();
}
MessageBox.Show("Loaded");

How do I iterate over an NSArray?

Add each method in your NSArray category, you gonna need it a lot

Code taken from ObjectiveSugar

- (void)each:(void (^)(id object))block {
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        block(obj);
    }];
}

Bootstrap 3 .col-xs-offset-* doesn't work?

The problem is that you're putting .name class instead of nameclass

PyCharm shows unresolved references error for valid code

In my case it was the directories structure. My project looks like this:

+---dir_A
    +---dir_B
        +app
        |
        \-run.py

So right click on dir_b > "mark directory as" > "project root"

Bootstrap4 adding scrollbar to div

_x000D_
_x000D_
.Scroll {
  height:600px;
  overflow-y: scroll;
}
_x000D_
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
</script>
</head>
<body>

<h1>Smooth Scroll</h1>

<div class="Scroll">
  <div class="main" id="section1">
    <h2>Section 1</h2>
    <p>Click on the link to see the "smooth" scrolling effect.</p>
    <p>Note: Remove the scroll-behavior property to remove smooth scrolling.</p>
  </div>
  <div class="main" id="section2">
    <h2>Section 2</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section3">
    <h2>Section 3</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section4">
    <h2>Section 4</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>

  <div class="main" id="section5">
    <h2>Section 5</h2>
    <a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
  </div>
  <div class="main" id="section6">
    <h2>Section 6</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section7">
    <h2>Section 7</h2>
    <a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
  </div>
</div>
</body>
</html>
_x000D_
_x000D_
_x000D_

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

I am getting similar errors recently because recent JDKs (and browsers, and the Linux TLS stack, etc.) refuse to communicate with some servers in my customer's corporate network. The reason of this is that some servers in this network still have SHA-1 certificates.

Please see: https://www.entrust.com/understanding-sha-1-vulnerabilities-ssl-longer-secure/ https://blog.qualys.com/ssllabs/2014/09/09/sha1-deprecation-what-you-need-to-know

If this would be your current case (recent JDK vs deprecated certificate encription) then your best move is to update your network to the proper encription technology.

In case that you should provide a temporal solution for that, please see another answers to have an idea about how to make your JDK trust or distrust certain encription algorithms:

How to force java server to accept only tls 1.2 and reject tls 1.0 and tls 1.1 connections

Anyway I insist that, in case that I have guessed properly your problem, this is not a good solution to the problem and that your network admin should consider removing these deprecated certificates and get a new one.

How to format DateTime to 24 hours time?

Console.WriteLine(curr.ToString("HH:mm"));

Reading a single char in Java

You can use a Scanner for this. It's not clear what your exact requirements are, but here's an example that should be illustrative:

    Scanner sc = new Scanner(System.in).useDelimiter("\\s*");
    while (!sc.hasNext("z")) {
        char ch = sc.next().charAt(0);
        System.out.print("[" + ch + "] ");
    }

If you give this input:

123 a b c x   y   z

The output is:

[1] [2] [3] [a] [b] [c] [x] [y] 

So what happens here is that the Scanner uses \s* as delimiter, which is the regex for "zero or more whitespace characters". This skips spaces etc in the input, so you only get non-whitespace characters, one at a time.

Sort array by firstname (alphabetically) in Javascript

Shortest possible code with ES6!

users.sort((a, b) => a.firstname.localeCompare(b.firstname))

String.prototype.localeCompare() basic support is universal!

Clearing an HTML file upload field via JavaScript

If you have the following:

<input type="file" id="FileSelect">

then just do:

$("#FileSelect").val('');

to reset or clear last selected file.

Check if a variable is a string in JavaScript

var a = new String('')
var b = ''
var c = []

function isString(x) {
  return x !== null && x !== undefined && x.constructor === String
}

console.log(isString(a))
console.log(isString(b))
console.log(isString(c))

Difference between links and depends_on in docker_compose.yml

This answer is for docker-compose version 2 and it also works on version 3

You can still access the data when you use depends_on.

If you look at docker docs Docker Compose and Django, you still can access the database like this:

version: '2'
services:
  db:
    image: postgres
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

What is the difference between links and depends_on?

links:

When you create a container for a database, for example:

docker run -d --name=test-mysql --env="MYSQL_ROOT_PASSWORD=mypassword" -P mysql

docker inspect d54cf8a0fb98 |grep HostPort

And you may find

"HostPort": "32777"

This means you can connect the database from your localhost port 32777 (3306 in container) but this port will change every time you restart or remove the container. So you can use links to make sure you will always connect to the database and don't have to know which port it is.

web:
  links:
   - db

depends_on:

I found a nice blog from Giorgio Ferraris Docker-compose.yml: from V1 to V2

When docker-compose executes V2 files, it will automatically build a network between all of the containers defined in the file, and every container will be immediately able to refer to the others just using the names defined in the docker-compose.yml file.

And

So we don’t need links anymore; links were used to start a network communication between our db container and our web-server container, but this is already done by docker-compose

Update

depends_on

Express dependency between services, which has two effects:

  • docker-compose up will start services in dependency order. In the following example, db and redis will be started before web.
  • docker-compose up SERVICE will automatically include SERVICE’s dependencies. In the following example, docker-compose up web will also create and start db and redis.

Simple example:

version: '2'
services:
  web:
    build: .
    depends_on:
      - db
      - redis
  redis:
    image: redis
  db:
    image: postgres

Note: depends_on will not wait for db and redis to be “ready” before starting web - only until they have been started. If you need to wait for a service to be ready, see Controlling startup order for more on this problem and strategies for solving it.

Where is svn.exe in my machine?

Generally, you can find the svn.exe on this location:

C:\Program Files\TortoiseSVN\bin

If you have already installed TortoiseSVN and still can't find the file the svn.exe on the given location, then you need to rerun the TortoiseSVN installer, click on 'Modify' and select Command Line Tools and after installation is successfully finished, you can now find the 'svn.exe' on given location on your drive.

Linq Select Group By

var result = priceLog.GroupBy(s => s.LogDateTime.ToString("MMM yyyy")).Select(grp => new PriceLog() { LogDateTime = Convert.ToDateTime(grp.Key), Price = (int)grp.Average(p => p.Price) }).ToList();

I have converted it to int because my Price field was int and Average method return double .I hope this will help

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

WORKING Method { if there is no problem other than configuration }

By Default Appache is not restricting access from ipv4. (common external ip)

What may restrict is the configurations in 'httpd.conf' (or 'apache2.conf' depending on your apache configuration)

Solution:

Replace all:

<Directory />
     AllowOverride none
    Require all denied

</Directory>

with

<Directory />
     AllowOverride none
#    Require all denied

</Directory>

hence removing out all restriction given to Apache

Replace Require local with Require all granted at C:/wamp/www/ directory

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

Center a button in a Linear layout

As per the Android documentation for XML Attributes of android:layout_gravity, we can do it easily :)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageButton android:id="@+id/btnFindMe" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"

        android:layout_gravity="center"

        android:background="@drawable/findme"></ImageButton>

</LinearLayout>

What are the differences between if, else, and else if?

Those are the basic decision orders that you have in most of the programming language; it helps you to decide the flow of actions that your program is gonna do. The if is telling the compiler that you have a question, and the question is the condition between parenthesis

if (condition) {
    thingsToDo()..
}

the else part is an addition to this structure to tell the compiler what to do if the condition is false

if (condition) {
    thingsToDo()..
} else {
    thingsToDoInOtherCase()..
}

you can combine those to form a else if which is when the first condition is false but you want to do another question before to decide what to do.

if (condition) {
    thingsToDo()..
} else if (condition2) {
    thingsToDoInTheSecondCase()..
}else {
    thingsToDoInOtherCase()..
}

How to fix: Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

To fix this on a Windows 8.1 Professional machine do the following.

  1. Install the Web Platform Installer. http://www.microsoft.com/web/downloads/platform.aspx

  2. In Web Platform Installer install ASP.NET 4.5 (This feature has one dependency).

If you simply try the aforementioned cmd prompt command from the most popular answer you will get the following error/warning message:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -i Microsoft (R) ASP.NET RegIIS version 4.0.30319.33440 Administration utility to install and uninstall ASP.NET on the local machine. Copyright (C) Microsoft Corporation. All rights reserved. Start installing ASP.NET (4.0.30319.33440). This option is not supported on this version of the operating system. Administr ators should instead install/uninstall ASP.NET 4.5 with IIS8 using the "Turn Win dows Features On/Off" dialog, the Server Manager management tool, or the dism.e xe command line tool. For more details please see http://go.microsoft.com/fwlin k/?LinkID=216771. Finished installing ASP.NET (4.0.30319.33440).

Javascript Append Child AFTER Element

You can use:

if (parentGuest.nextSibling) {
  parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
}
else {
  parentGuest.parentNode.appendChild(childGuest);
}

But as Pavel pointed out, the referenceElement can be null/undefined, and if so, insertBefore behaves just like appendChild. So the following is equivalent to the above:

parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);

What is the difference between call and apply?

Both call and apply the same way. It calls immediately when we use call and apply.

Both call and apply takes "this" parameter as the first argument and the second argument only differs.

the call takes the arguments of the functions as a list (comma ) Apply takes the arguments of the functions as an array.

You can find the complete difference between bind, call, and apply in the bellow youtube video.

https://www.youtube.com/watch?v=G-EfxnG0DtY&t=180s

How to get active user's UserDetails

@Controller
public abstract class AbstractController {
    @ModelAttribute("loggedUser")
    public User getLoggedUser() {
        return (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }
}

height style property doesn't work in div elements

Set positioning to absolute. That will solve the problem immediately, but might cause some problems in layout later. You can always figure out a way around them ;)

Example:

position:absolute;

How to pass data from 2nd activity to 1st activity when pressed back? - android

Other answers were not working when I put setResult in onBackPressed. Commenting call to super onBackPressed and calling finish manually solves the problem:

@Override
public void onBackPressed() {
    //super.onBackPressed();
    Intent i = new Intent();
    i.putExtra(EXTRA_NON_DOWNLOADED_PAGES, notDownloaded);
    setResult(RESULT_OK, i);
    finish();
}

And in first activity:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == QUEUE_MSG) {
        if (resultCode == RESULT_OK) {
            Serializable tmp = data.getSerializableExtra(MainActivity.EXTRA_NON_DOWNLOADED_PAGES);
            if (tmp != null)
                serializable = tmp;
        }
    }
}

What is difference between Errors and Exceptions?

An Error "indicates serious problems that a reasonable application should not try to catch."

while

An Exception "indicates conditions that a reasonable application might want to catch."

Error along with RuntimeException & their subclasses are unchecked exceptions. All other Exception classes are checked exceptions.

Checked exceptions are generally those from which a program can recover & it might be a good idea to recover from such exceptions programmatically. Examples include FileNotFoundException, ParseException, etc. A programmer is expected to check for these exceptions by using the try-catch block or throw it back to the caller

On the other hand we have unchecked exceptions. These are those exceptions that might not happen if everything is in order, but they do occur. Examples include ArrayIndexOutOfBoundException, ClassCastException, etc. Many applications will use try-catch or throws clause for RuntimeExceptions & their subclasses but from the language perspective it is not required to do so. Do note that recovery from a RuntimeException is generally possible but the guys who designed the class/exception deemed it unnecessary for the end programmer to check for such exceptions.

Errors are also unchecked exception & the programmer is not required to do anything with these. In fact it is a bad idea to use a try-catch clause for Errors. Most often, recovery from an Error is not possible & the program should be allowed to terminate. Examples include OutOfMemoryError, StackOverflowError, etc.

Do note that although Errors are unchecked exceptions, we shouldn't try to deal with them, but it is ok to deal with RuntimeExceptions(also unchecked exceptions) in code. Checked exceptions should be handled by the code.

How to set the background image of a html 5 canvas to .png image

You can draw the image on the canvas and let the user draw on top of that.

The drawImage() function will help you with that, see https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images

"Failed to install the following Android SDK packages as some licences have not been accepted" error

If you are getting this error while using Flutter then please run the below command on command prompt.

flutter doctor --android-licenses

If you get below error after running the above command

Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
    at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
    at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
    at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
    at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
    at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)

Then please do the below steps

  1. Open android studio
  2. Go to SDK manager
  3. Click on SDK tools tab
  4. Install Android SDK command line tool
  5. Run flutter doctor --android-licenses again

How to select a column name with a space in MySQL

Generally the first step is to not do that in the first place, but if this is already done, then you need to resort to properly quoting your column names:

SELECT `Business Name` FROM annoying_table

Usually these sorts of things are created by people who have used something like Microsoft Access and always use a GUI to do their thing.

How to set a header for a HTTP GET request, and trigger file download?

i want to post my solution here which was done AngularJS, ASP.NET MVC. The code illustrates how to download file with authentication.

WebApi method along with helper class:

[RoutePrefix("filess")]
class FileController: ApiController
{
    [HttpGet]
    [Route("download-file")]
    [Authorize(Roles = "admin")]
    public HttpResponseMessage DownloadDocument([FromUri] int fileId)
    {
        var file = "someFile.docx"// asking storage service to get file path with id
        return Request.ReturnFile(file);
    }
}

static class DownloadFIleFromServerHelper
{
    public static HttpResponseMessage ReturnFile(this HttpRequestMessage request, string file)
    {
        var result = request.CreateResponse(HttpStatusCode.OK);

        result.Content = new StreamContent(new FileStream(file, FileMode.Open, FileAccess.Read));
        result.Content.Headers.Add("x-filename", Path.GetFileName(file)); // letters of header names will be lowercased anyway in JS.
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = Path.GetFileName(file)
        };

        return result;
    }
}

Web.config file changes to allow sending file name in custom header.

<configuration>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Methods" value="POST,GET,PUT,PATCH,DELETE,OPTIONS" />
                <add name="Access-Control-Allow-Headers" value="Authorization,Content-Type,x-filename" />
                <add name="Access-Control-Expose-Headers" value="Authorization,Content-Type,x-filename" />
                <add name="Access-Control-Allow-Origin" value="*" />

Angular JS Service Part:

function proposalService($http, $cookies, config, FileSaver) {
        return {
                downloadDocument: downloadDocument
        };

    function downloadFile(documentId, errorCallback) {
    $http({
        url: config.apiUrl + "files/download-file?documentId=" + documentId,
        method: "GET",
        headers: {
            "Content-type": "application/json; charset=utf-8",
            "Authorization": "Bearer " + $cookies.get("api_key")
        },
        responseType: "arraybuffer"  
        })
    .success( function(data, status, headers) {
        var filename = headers()['x-filename'];

        var blob = new Blob([data], { type: "application/octet-binary" });
        FileSaver.saveAs(blob, filename);
    })
    .error(function(data, status) {
        console.log("Request failed with status: " + status);
        errorCallback(data, status);
    });
};
};

Module dependency for FileUpload: angular-file-download (gulp install angular-file-download --save). Registration looks like below.

var app = angular.module('cool',
[
    ...
    require('angular-file-saver'),
])
. // other staff.

Best XML parser for Java

In addition to SAX and DOM there is STaX parsing available using XMLStreamReader which is an xml pull parser.

Using BeautifulSoup to extract text without tags

Just loop through all the <strong> tags and use next_sibling to get what you want. Like this:

for strong_tag in soup.find_all('strong'):
    print(strong_tag.text, strong_tag.next_sibling)

Demo:

from bs4 import BeautifulSoup

html = '''
<p>
  <strong class="offender">YOB:</strong> 1987<br />
  <strong class="offender">RACE:</strong> WHITE<br />
  <strong class="offender">GENDER:</strong> FEMALE<br />
  <strong class="offender">HEIGHT:</strong> 5'05''<br />
  <strong class="offender">WEIGHT:</strong> 118<br />
  <strong class="offender">EYE COLOR:</strong> GREEN<br />
  <strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
'''

soup = BeautifulSoup(html)

for strong_tag in soup.find_all('strong'):
    print(strong_tag.text, strong_tag.next_sibling)

This gives you:

YOB:  1987
RACE:  WHITE
GENDER:  FEMALE
HEIGHT:  5'05''
WEIGHT:  118
EYE COLOR:  GREEN
HAIR COLOR:  BROWN

How to center a "position: absolute" element

You can try this way :

_x000D_
_x000D_
* { margin: 0px; padding: 0px; }_x000D_
#body { height: 100vh; width: 100vw; position: relative; _x000D_
        text-align: center; _x000D_
        background-image: url('https://s-media-cache-ak0.pinimg.com/originals/96/2d/ff/962dff2247ad680c542622e20f44a645.jpg'); _x000D_
         background-size: cover; background-repeat: no-repeat; }_x000D_
.text { position: absolute; top: 0; bottom: 0; left: 0; right: 0; height:100px; _x000D_
        display: inline-block; margin: auto; z-index: 999999; }
_x000D_
<html>_x000D_
<body>_x000D_
 <div id="body" class="container-fluid">_x000D_
   <!--Background-->_x000D_
     <!--Text-->_x000D_
    <div class="text">_x000D_
      <p>Random</p>_x000D_
    </div>   _x000D_
 </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

jQuery Validation plugin: disable validation for specified submit buttons

Add formnovalidate attribute to input

    <input type="submit" name="go" value="Submit"> 
    <input type="submit" formnovalidate name="cancel" value="Cancel"> 

Adding class="cancel" is now deprecated

See docs for Skipping validation on submit on this link

Running Jupyter via command line on Windows

Add system variable path, this path is where jupyter and other scripts are located

PATH -->

`C:\Users\<userName>\AppData\Roaming\Python\Python39\Scripts`

Like in my laptop PATH is:

"C:\Users\developer\AppData\Roaming\Python\Python39\Scripts"

After that, You will be able to run jupyter from any folder & any directory by running the below command

jupyter notebook

Using an HTTP PROXY - Python

Python 3:

import urllib.request

htmlsource = urllib.request.FancyURLopener({"http":"http://127.0.0.1:8080"}).open(url).read().decode("utf-8")

Multi-Column Join in Hibernate/JPA Annotations

Hibernate is not going to make it easy for you to do what you are trying to do. From the Hibernate documentation:

Note that when using referencedColumnName to a non primary key column, the associated class has to be Serializable. Also note that the referencedColumnName to a non primary key column has to be mapped to a property having a single column (other cases might not work). (emphasis added)

So if you are unwilling to make AnEmbeddableObject the Identifier for Bar then Hibernate is not going to lazily, automatically retrieve Bar for you. You can, of course, still use HQL to write queries that join on AnEmbeddableObject, but you lose automatic fetching and life cycle maintenance if you insist on using a multi-column non-primary key for Bar.

Python error: AttributeError: 'module' object has no attribute

When you import lib, you're importing the package. The only file to get evaluated and run in this case is the 0 byte __init__.py in the lib directory.

If you want access to your function, you can do something like this from lib.mod1 import mod1 and then run the mod12 function like so mod1.mod12().

If you want to be able to access mod1 when you import lib, you need to put an import mod1 inside the __init__.py file inside the lib directory.

Java math function to convert positive int to negative and negative to positive?

We can reverse Java number int or double using this :

int x = 5;
int y = -7;

x = x - (x*2); // reverse to negative
y = y - (y*2); // reverse to positif

Simple algorithm to reverse number :)

How do I break a string across more than one line of code in JavaScript?

ECMAScript 6 introduced template strings:

Template strings are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.

For example:

alert(`Please Select file   
to delete`);

will alert:

Please Select file   
to delete

Fatal error: Call to undefined function: ldap_connect()

  • [Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:

    extension=php_ldap.dll

  • Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin Restart Apache. You can now use functions of the LDAP Module!

How to convert a currency string to a double with jQuery or Javascript?

    $ 150.00
    Fr. 150.00
    € 689.00

I have tested for above three currency symbols .You can do it for others also.

    var price = Fr. 150.00;
    var priceFloat = price.replace(/[^\d\.]/g, '');

Above regular expression will remove everything that is not a digit or a period.So You can get the string without currency symbol but in case of " Fr. 150.00 " if you console for output then you will get price as

    console.log('priceFloat : '+priceFloat);

    output will be like  priceFloat : .150.00

which is wrong so you check the index of "." then split that and get the proper result.

    if (priceFloat.indexOf('.') == 0) {
            priceFloat = parseFloat(priceFloat.split('.')[1]);
    }else{
            priceFloat = parseFloat(priceFloat);
    }

MySQL 'create schema' and 'create database' - Is there any difference

So, there is no difference between MySQL "database" and MySQL "schema": these are two names for the same thing - a namespace for tables and other DB objects.

For people with Oracle background: MySQL "database" a.k.a. MySQL "schema" corresponds to Oracle schema. The difference between MySQL and Oracle CREATE SCHEMA commands is that in Oracle the CREATE SCHEMA command does not actually create a schema but rather populates it with tables and views. And Oracle's CREATE DATABASE command does a very different thing than its MySQL counterpart.

How can I use a reportviewer control in an asp.net mvc 3 razor view?

I am using ASP.NET MVC3 with SSRS 2008 and I couldn't get @Adrian's to work 100% for me when trying to get reports from a remote server.

Finally, I found that I needed to change the Page_Load method in ViewUserControl1.ascx to look like this:

ReportViewer1.ProcessingMode = ProcessingMode.Remote;
ServerReport serverReport = ReportViewer1.ServerReport;
serverReport.ReportServerUrl = new Uri("http://<Server Name>/reportserver");
serverReport.ReportPath = "/My Folder/MyReport";
serverReport.Refresh();

I had been missing the ProcessingMode.Remote.

References:

http://msdn.microsoft.com/en-us/library/aa337091.aspx - ReportViewer

Python csv string to array

You can convert a string to a file object using io.StringIO and then pass that to the csv module:

from io import StringIO
import csv

scsv = """text,with,Polish,non-Latin,letters
1,2,3,4,5,6
a,b,c,d,e,f
ges,zólty,waz,idzie,waska,drózka,
"""

f = StringIO(scsv)
reader = csv.reader(f, delimiter=',')
for row in reader:
    print('\t'.join(row))

simpler version with split() on newlines:

reader = csv.reader(scsv.split('\n'), delimiter=',')
for row in reader:
    print('\t'.join(row))

Or you can simply split() this string into lines using \n as separator, and then split() each line into values, but this way you must be aware of quoting, so using csv module is preferred.

On Python 2 you have to import StringIO as

from StringIO import StringIO

instead.

Comparing strings, c++

.compare() returns an integer, which is a measure of the difference between the two strings.

  • A return value of 0 indicates that the two strings compare as equal.
  • A positive value means that the compared string is longer, or the first non-matching character is greater.
  • A negative value means that the compared string is shorter, or the first non-matching character is lower.

operator== simply returns a boolean, indicating whether the strings are equal or not.

If you don't need the extra detail, you may as well just use ==.

IN Clause with NULL or IS NULL

The question as answered by Daniel is perfctly fine. I wanted to leave a note regarding NULLS. We should be carefull about using NOT IN operator when a column contains NULL values. You won't get any output if your column contains NULL values and you are using the NOT IN operator. This is how it's explained over here http://www.oraclebin.com/2013/01/beware-of-nulls.html , a very good article which I came across and thought of sharing it.

how to set active class to nav menu from twitter bootstrap

$( ".nav li" ).click(function() {
        $('.nav li').removeClass('active');
        $(this).addClass('active');
    });

check this out.

Split a string into array in Perl

Having $line as it is now, you can simply split the string based on at least one whitespace separator

my @answer = split(' ', $line); # creates an @answer array

then

print("@answer\n");               # print array on one line

or

print("$_\n") for (@answer);      # print each element on one line

I prefer using () for split, print and for.

How to truncate string using SQL server

I think the answers here are great, but I would like to add a scenario.

Several times I've wanted to take a certain amount of characters off the front of a string, without worrying about it's length. There are several ways of doing this with RIGHT() and SUBSTRING(), but they all need to know the length of the string which can sometimes slow things down.

I've use the STUFF() function instead:

SET @Result = STUFF(@Result, 1, @LengthToRemove, '')

This replaces the length of unneeded string with an empty string.

how to log in to mysql and query the database from linux terminal

To your first question:

mysql -u root -p

or

mysqladmin -u root -p "your_command"

depending on what you want to do. The password will be asked of you once you hit enter! I'm guessing you really want to use mysql and not mysqladmin.

For restarting or stopping the MySQL-server on linux, it depends on your installation, but in the common debian derivatives this will work for starting, stopping and restarting the service:

sudo /etc/init.d/mysql start
sudo /etc/init.d/mysql stop
sudo /etc/init.d/mysql restart
sudo /etc/init.d/mysql status

In some newer distros this might work as well if MySQL is set up as a deamon/service.

sudo service mysql start
sudo service mysql stop
sudo service mysql restart
sudo service mysql status

But the question is really impossible to answer without knowing your particular setup.

html5 input for money/currency

Enabling Fractions/Cents/Decimals for Number Input

In order to allow fractions (cents) on an HTML5 number input, you need to specify the "step" attribute to = "any":

<input type="number" min="1" step="any" />

This will specifically keep Chrome from displaying an error when a decimal/fractional currency is entered into the input. Mozilla, IE, etc... don't error out if you forget to specify step="any". W3C spec states that step="any" should, indeed, be needed to allow for decimals. So, you should definitely use it. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#step

Note that if you want the up/down buttons to do a specific granularity, then you must specify a numeric step such as ".01".

Also, the number input is now pretty widely supported (>90% of users).


What Input Options are there for Money/Currency?

The title of the question has since changed and takes on a slightly different meaning. One could use both number or text input in order to accept money/decimals.

For an input field for currency/money, it is recommended to use input type of number and specify appropriate attributes as outlined above. As of 2020, there is not a W3C spec for an actual input type of currency or money.

Main reason being it automatically coerces the users into entering a valid standard currency format and disallows any alphanumeric text. With that said, you could certainly use the regular text input and do some post processing to only grab the numeric/decimal value (there should be server side validation on this at some point as well).

The OP detailed a requirement of currency symbols and commas. If you want fancier logic/formatting like that, (as of 2020) you'll need to create custom JS logic for a text input or find a plugin.

What is the difference between an IntentService and a Service?

In short, a Service is a broader implementation for the developer to set up background operations, while an IntentService is useful for "fire and forget" operations, taking care of background Thread creation and cleanup.

From the docs:

Service A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.

IntentService Service is a base class for IntentService Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

Refer this doc - http://developer.android.com/reference/android/app/IntentService.html

Read a XML (from a string) and get some fields - Problems reading XML

The other answers are several years old (and do not work for Windows Phone 8.1) so I figured I'd drop in another option. I used this to parse an RSS response for a Windows Phone app:

XDocument xdoc = new XDocument();
xdoc = XDocument.Parse(xml_string);

Mark error in form using Bootstrap

For Bootstrap v4 use:
has-danger for form-group wrapper,
form-control-danger for input to show icon (will display ? at the end of input),
form-control-feedback to message wrapper

Example:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
_x000D_
<div class="form-group has-danger">_x000D_
  <input type="text" class="form-control form-control-danger">_x000D_
  <div class="form-control-feedback">Not valid :(</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

background:none vs background:transparent what is the difference?

As aditional information on @Quentin answer, and as he rightly says, background CSS property itself, is a shorthand for:

background-color
background-image
background-repeat
background-attachment
background-position

That's mean, you can group all styles in one, like:

background: red url(../img.jpg) 0 0 no-repeat fixed;

This would be (in this example):

background-color: red;
background-image: url(../img.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 0 0;

So... when you set: background:none;
you are saying that all the background properties are set to none...
You are saying that background-image: none; and all the others to the initial state (as they are not being declared).
So, background:none; is:

background-color: initial;
background-image: none;
background-repeat: initial;
background-attachment: initial;
background-position: initial;

Now, when you define only the color (in your case transparent) then you are basically saying:

background-color: transparent;
background-image: initial;
background-repeat: initial;
background-attachment: initial;
background-position: initial;

I repeat, as @Quentin rightly says the default transparent and none values in this case are the same, so in your example and for your original question, No, there's no difference between them.

But!.. if you say background:none Vs background:red then yes... there's a big diference, as I say, the first would set all properties to none/default and the second one, will only change the color and remains the rest in his default state.

So in brief:

Short answer: No, there's no difference at all (in your example and orginal question)
Long answer: Yes, there's a big difference, but depends directly on the properties granted to attribute.


Upd1: Initial value (aka default)

Initial value the concatenation of the initial values of its longhand properties:

background-image: none
background-position: 0% 0%
background-size: auto auto
background-repeat: repeat
background-origin: padding-box
background-style: is itself a shorthand, its initial value is the concatenation of its own longhand properties
background-clip: border-box
background-color: transparent

See more background descriptions here


Upd2: Clarify better the background:none; specification.

How do I compare two string variables in an 'if' statement in Bash?

For string equality comparison, use:

if [[ "$s1" == "$s2" ]]

For string does NOT equal comparison, use:

if [[ "$s1" != "$s2" ]]

For the a contains b, use:

if [[ $s1 == *"$s2"* ]]

(and make sure to add spaces between the symbols):

Bad:

if [["$s1" == "$s2"]]

Good:

if [[ "$s1" == "$s2" ]]

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

I know this thread is very old, but I'll leave here my own implementation:

$(function () {
  // some initialization code

  addTabBehavior()
})

// Initialize events and change tab on first page load.
function addTabBehavior() {
  $('.nav-tabs a').on('show.bs.tab', e => {
    window.location.hash = e.target.hash.replace('nav-', '')
  })

  $(window).on('popstate', e => {
    changeTab()
  })

  changeTab()
}

// Change the current tab and URL hash; if don't have any hash
// in URL, so activate the first tab and update the URL hash.
function changeTab() {
  const hash = getUrlHash()

  if (hash) {
    $(`.nav-tabs a[href="#nav-${hash}"]`).tab('show')
  } else {
    $('.nav-tabs a').first().tab('show')
  }
}

// Get the hash from URL. Ex: www.example.com/#tab1
function getUrlHash() {
  return window.location.hash.slice(1)
}

Note that I'm using a nav- class prefix to nav links.

Call one constructor from another

Constructor chaining i.e you can use "Base" for Is a relationship and "This" you can use for same class, when you want call multiple Constructor in single call.

  class BaseClass
{
    public BaseClass():this(10)
    {
    }
    public BaseClass(int val)
    {
    }
}
    class Program
    {
        static void Main(string[] args)
        {
            new BaseClass();
            ReadLine();
        }
    }