Programs & Examples On #Outliers

An outlier is an observation that appears to be unusual or not well described relative to a simple characterization of a dataset.

How to remove outliers in boxplot in R?

See ?boxplot for all the help you need.

 outline: if ‘outline’ is not true, the outliers are not drawn (as
          points whereas S+ uses lines).

boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)

And for extending the range of the whiskers and suppressing the outliers inside this range:

   range: this determines how far the plot whiskers extend out from the
          box.  If ‘range’ is positive, the whiskers extend to the most
          extreme data point which is no more than ‘range’ times the
          interquartile range from the box. A value of zero causes the
          whiskers to extend to the data extremes.

# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)

Detect and exclude outliers in Pandas data frame

My function for dropping outliers

def drop_outliers(df, field_name):
    distance = 1.5 * (np.percentile(df[field_name], 75) - np.percentile(df[field_name], 25))
    df.drop(df[df[field_name] > distance + np.percentile(df[field_name], 75)].index, inplace=True)
    df.drop(df[df[field_name] < np.percentile(df[field_name], 25) - distance].index, inplace=True)

How to remove outliers from a dataset

Outliers are quite similar to peaks, so a peak detector can be useful for identifying outliers. The method described here has quite good performance using z-scores. The animation part way down the page illustrates the method signaling on outliers, or peaks.

Peaks are not always the same as outliers, but they're similar frequently.

An example is shown here: This dataset is read from a sensor via serial communications. Occasional serial communication errors, sensor error or both lead to repeated, clearly erroneous data points. There is no statistical value in these point. They are arguably not outliers, they are errors. The z-score peak detector was able to signal on spurious data points and generated a clean resulting dataset: enter image description here

How do I change button size in Python?

Configuring a button (or any widget) in Tkinter is done by calling a configure method "config"

To change the size of a button called button1 you simple call

button1.config( height = WHATEVER, width = WHATEVER2 )

If you know what size you want at initialization these options can be added to the constructor.

button1 = Button(self, text = "Send", command = self.response1, height = 100, width = 100) 

Facebook Oauth Logout

For Python developers that want to log user out straight from the backend

At the moment I'm writing this, the trick with m.facebook.com no longer works (at least for me) and user is redirected to the mobile FB login page which obviously is not good for UX.

Fortunately, FB PHP SDK has a semi-documented solution (in case the link doesn't lead to getLogoutUrl() function, just search look for it on that page). This is also mentioned in at least one other on StackOverflow: Facebook php SDK getLogoutUrl() problem.

BTW I've just noticed that Zach Greenberg got it right in this question, but I'm adding my answer as a summary for Python developers.

Can't push image to Amazon ECR - fails with "no basic auth credentials"

After run this command:

(aws ecr get-login --no-include-email --region us-west-2)

just run the docker login command from the output

docker login -u AWS -p epJ....

is the way that docker login into ECR

Config Error: This configuration section cannot be used at this path

The error says that the configuration section is locked at the parent level. So it will not be directly 1 config file which will resolve the issue, we need to go through the hierarchy of the config files to see the inheritance Check the below link to go through the File hierarchy and inheritance in IIS

https://msdn.microsoft.com/en-us/library/ms178685.aspx

So you need to check for the app config settings in the below order

  1. ApplicationHost.config in C:windows\system32\inetsrv\config. Change the overrideModeDefault attribute to be Allow.
  2. ApplicationName.config or web.config in the applications directory
  3. Web.config in the root directory.
  4. Web.config in the specific website (My issue was found at this place).
  5. Web.config of the root web (server's configuration)
  6. machine.config of the machine (Root's web.config and machine.config can be found at - systemroot\MicrosoftNET\Framework\versionNumber\CONFIG\Machine.config)

Go carefully through all these configs in the order of 1 to 6 and you should find it.

In Mongoose, how do I sort by date? (node.js)

Sorting in Mongoose has evolved over the releases such that some of these answers are no longer valid. As of the 4.1.x release of Mongoose, a descending sort on the date field can be done in any of the following ways:

    Room.find({}).sort('-date').exec((err, docs) => { ... });
    Room.find({}).sort({date: -1}).exec((err, docs) => { ... });
    Room.find({}).sort({date: 'desc'}).exec((err, docs) => { ... });
    Room.find({}).sort({date: 'descending'}).exec((err, docs) => { ... });
    Room.find({}).sort([['date', -1]]).exec((err, docs) => { ... });
    Room.find({}, null, {sort: '-date'}, (err, docs) => { ... });
    Room.find({}, null, {sort: {date: -1}}, (err, docs) => { ... });

For an ascending sort, omit the - prefix on the string version or use values of 1, asc, or ascending.

Is there a way to force npm to generate package-lock.json?

This is answered in the comments; package-lock.json is a feature in npm v5 and higher. npm shrinkwrap is how you create a lockfile in all versions of npm.

vba: get unique values from array

This post contains 2 examples. I like the 2nd one:

Sub unique() 
  Dim arr As New Collection, a 
  Dim aFirstArray() As Variant 
  Dim i As Long 
 
  aFirstArray() = Array("Banana", "Apple", "Orange", "Tomato", "Apple", _ 
  "Lemon", "Lime", "Lime", "Apple") 
 
  On Error Resume Next 
  For Each a In aFirstArray 
     arr.Add a, a 
  Next
  On Error Goto 0 ' added to original example by PEH
 
  For i = 1 To arr.Count 
     Cells(i, 1) = arr(i) 
  Next 
 
End Sub 

LINQ syntax where string value is not null or empty

This won't fail on Linq2Objects, but it will fail for Linq2SQL, so I am assuming that you are talking about the SQL provider or something similar.

The reason has to do with the way that the SQL provider handles your lambda expression. It doesn't take it as a function Func<P,T>, but an expression Expression<Func<P,T>>. It takes that expression tree and translates it so an actual SQL statement, which it sends off to the server.

The translator knows how to handle basic operators, but it doesn't know how to handle methods on objects. It doesn't know that IsNullOrEmpty(x) translates to return x == null || x == string.empty. That has to be done explicitly for the translation to SQL to take place.

CSS background image in :after element

A couple things

(a) you cant have both background-color and background, background will always win. in the example below, i combined them through shorthand, but this will produce the color only as a fallback method when the image does not show.

(b) no-scroll does not work, i don't believe it is a valid property of a background-image. try something like fixed:

.button:after {
    content: "";
    width: 30px;
    height: 30px;
    background:red url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") no-repeat -30px -50px fixed;
    top: 10px;
    right: 5px;
    position: absolute;
    display: inline-block;
}

I updated your jsFiddle to this and it showed the image.

Performing SQL queries on an Excel Table within a Workbook with VBA Macro

Just answering the second part of your question about getting the name of the sheet where a table is:

Dim name as String

name = Range("Table1").Worksheet.Name

Edit:

To make things more clear: someone suggested that to use Range on a Sheet object. In this case, you need not; the Range where the table lives can be obtained using the table's name; this name is available throughout the book. So, calling Range alone works well.

Why am I getting error for apple-touch-icon-precomposed.png

An alternative solution is to simply add a route to your routes.rb

It basically catches the Apple request and renders a 404 back to the client. This way your log files aren't cluttered.

# routes.rb at the near-end
match '/:png', via: :get, controller: 'application', action: 'apple_touch_not_found', png: /apple-touch-icon.*\.png/

then add a method 'apple_touch_not_found' to your application_controller.rb

# application_controller.rb
def apple_touch_not_found
  render  plain: 'apple-touch icons not found', status: 404
end

How to calculate percentage when old value is ZERO

There is no rate of growth from 0 to any other number. That is to say, there is no percentage of increase from zero to greater than zero and there is no percentage of decrease from zero to less than zero (a negative number). What you have to decide is what to put as an output when this situation happens. Here are two possibilities I am comfortable with:

  1. Any time you have to show a rate of increase from zero, output the infinity symbol (8). That's Alt + 236 on your number pad, in case you're wondering. You could also use negative infinity (-8) for a negative growth rate from zero.
  2. Output a statement such as "[Increase/Decrease] From Zero" or something along those lines.

Unfortunately, if you need the growth rate for further calculations, the above options will not work, but, on the other hand, any number would give your following calculations incorrect data any way so the point is moot. You'd need to update your following calculations to account for this eventuality.

As an aside, the ((New-Old)/Old) function will not work when your new and old values are both zero. You should create an initial check to see if both values are zero and, if they are, output zero percent as the growth rate.

Radio Buttons "Checked" Attribute Not Working

You're using non-standard xhtml code (values should be framed with double quotes, not single quotes)

Try this:

<form>
  <label>Do you want to accept American Express?</label>
  Yes<input id="amex" style="width: 20px;" type="radio" name="Contact0_AmericanExpress"  />  
  No<input style="width: 20px;" type="radio" name="Contact0_AmericanExpress" class="check" checked="checked" />
</form>

Call break in nested if statements

In the most languages, break does only cancel loops like for, while etc.

What is the Swift equivalent of respondsToSelector?

It seems you need to define your protocol as as subprotocol of NSObjectProtocol ... then you'll get respondsToSelector method

@objc protocol YourDelegate : NSObjectProtocol
{
    func yourDelegateMethod(passObject: SomeObject)
}

note that only specifying @objc was not enough. You should be also careful that the actual delegate is a subclass of NSObject - which in Swift might not be.

Array Size (Length) in C#

If it's a one-dimensional array a,

a.Length

will give the number of elements of a.

If b is a rectangular multi-dimensional array (for example, int[,] b = new int[3, 5];)

b.Rank

will give the number of dimensions (2) and

b.GetLength(dimensionIndex)

will get the length of any given dimension (0-based indexing for the dimensions - so b.GetLength(0) is 3 and b.GetLength(1) is 5).

See System.Array documentation for more info.

As @Lucero points out in the comments, there is a concept of a "jagged array", which is really nothing more than a single-dimensional array of (typically single-dimensional) arrays.

For example, one could have the following:

int[][] c = new int[3][];
c[0] = new int[] {1, 2, 3};
c[1] = new int[] {3, 14};
c[2] = new int[] {1, 1, 2, 3, 5, 8, 13};

Note that the 3 members of c all have different lengths. In this case, as before c.Length will indicate the number of elements of c, (3) and c[0].Length, c[1].Length, and c[2].Length will be 3, 2, and 7, respectively.

How to load specific image from assets with Swift

You can easily pick image from asset without UIImage(named: "green-square-Retina").

Instead use the image object directly from bundle.
Start typing the image name and you will get suggestions with actual image from bundle. It is advisable practice and less prone to error.

See this Stackoverflow answer for reference.

Failed to locate the winutils binary in the hadoop binary path

In Pyspark, to run local spark application using Pycharm use below lines

os.environ['HADOOP_HOME'] = "C:\\winutils"
print os.environ['HADOOP_HOME']

Numpy where function multiple conditions

Try:

import numpy as np
dist = np.array([1,2,3,4,5])
r = 2
dr = 3
np.where(np.logical_and(dist> r, dist<=r+dr))

Output: (array([2, 3]),)

You can see Logic functions for more details.

Python using enumerate inside list comprehension

If you're using long lists, it appears the list comprehension's faster, not to mention more readable.

~$ python -mtimeit -s"mylist = ['a','b','c','d']" "list(enumerate(mylist))"
1000000 loops, best of 3: 1.61 usec per loop
~$ python -mtimeit -s"mylist = ['a','b','c','d']" "[(i, j) for i, j in enumerate(mylist)]"
1000000 loops, best of 3: 0.978 usec per loop
~$ python -mtimeit -s"mylist = ['a','b','c','d']" "[t for t in enumerate(mylist)]"
1000000 loops, best of 3: 0.767 usec per loop

How to create a density plot in matplotlib?

Maybe try something like:

import matplotlib.pyplot as plt
import numpy
from scipy import stats
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
density = stats.kde.gaussian_kde(data)
x = numpy.arange(0., 8, .1)
plt.plot(x, density(x))
plt.show()

You can easily replace gaussian_kde() by a different kernel density estimate.

Postgresql: Scripting psql execution with password

Use -w in the command: psql -h localhost -p 5432 -U user -w

JavaScript onclick redirect

Change the onclick from

onclick="javascript:SubmitFrm()"

to

onclick="SubmitFrm()"

Spring Boot: How can I set the logging level with application.properties?

If you want to set more detail, please add a log config file name "logback.xml" or "logback-spring.xml".

in your application.properties file, input like this:

logging.config: classpath:logback-spring.xml

in the loback-spring.xml, input like this:

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <include resource="org/springframework/boot/logging/logback/base.xml"/>

        <appender name="ROOT_APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">

            <filter class="ch.qos.logback.classic.filter.LevelFilter">
                <level>INFO</level>
                <onMatch>ACCEPT</onMatch>
                <onMismatch>DENY</onMismatch>
            </filter>

            <file>sys.log</file>

            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">


                <fileNamePattern>${LOG_DIR}/${SYSTEM_NAME}/system.%d{yyyy-MM-dd}.%i.log</fileNamePattern>

                <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                    <maxFileSize>500MB</maxFileSize>
                </timeBasedFileNamingAndTriggeringPolicy>
            </rollingPolicy>

            <encoder>
                <pattern>%-20(%d{yyy-MM-dd HH:mm:ss.SSS} [%X{requestId}]) %-5level - %logger{80} - %msg%n
                </pattern>
            </encoder>
        </appender>


        <appender name="BUSINESS_APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <filter class="ch.qos.logback.classic.filter.LevelFilter">
                <level>TRACE</level>
                <onMatch>ACCEPT</onMatch>
                <onMismatch>DENY</onMismatch>
            </filter>

            <file>business.log</file>

            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">

                <fileNamePattern>${LOG_DIR}/${SYSTEM_NAME}/business.%d{yyyy-MM-dd}.%i.log</fileNamePattern>

                <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                    <maxFileSize>500MB</maxFileSize>
                </timeBasedFileNamingAndTriggeringPolicy>
            </rollingPolicy>

            <encoder>
                <pattern>%-20(%d{yyy-MM-dd HH:mm:ss.SSS} [%X{requestId}]) %-5level - %logger{80} - %msg%n
                </pattern>
            </encoder>
        </appender>


        <logger name="{project-package-name}" level="TRACE">
            <appender-ref ref="BUSINESS_APPENDER" />
        </logger>

        <root level="INFO">
            <appender-ref ref="ROOT_APPENDER" />
        </root>

    </configuration>

How to get a Fragment to remove itself, i.e. its equivalent of finish()?

If you are using the new Navigation Component, is simple as

findNavController().popBackStack()

It will do all the FragmentTransaction in behind for you.

A 'for' loop to iterate over an enum in Java

Try to use a for each

for ( Direction direction : Direction.values()){
  System.out.println(direction.toString());
}

How to convert a String to CharSequence?

CharSequence is an interface and String is its one of the implementations other than StringBuilder, StringBuffer and many other.

So, just as you use InterfaceName i = new ItsImplementation(), you can use CharSequence cs = new String("string") or simply CharSequence cs = "string";

When increasing the size of VARCHAR column on a large table could there be any problems?

Changing to Varchar(1200) from Varchar(200) should cause you no issue as it is only a metadata change and as SQL server 2008 truncates excesive blank spaces you should see no performance differences either so in short there should be no issues with making the change.

Swift: Sort array of objects alphabetically

let sortArray =  array.sorted(by: { $0.name.lowercased() < $1.name.lowercased() })

Search and replace in bash using regular expressions

This actually can be done in pure bash:

hello=ho02123ware38384you443d34o3434ingtod38384day
re='(.*)[0-9]+(.*)'
while [[ $hello =~ $re ]]; do
  hello=${BASH_REMATCH[1]}${BASH_REMATCH[2]}
done
echo "$hello"

...yields...

howareyoudoingtodday

Iteration ng-repeat only X times in AngularJs

Angular comes with a limitTo:limit filter, it support limiting first x items and last x items:

<div ng-repeat="item in items|limitTo:4">{{item}}</div>

Link to the issue number on GitHub within a commit message

Just include #xxx in your commit message to reference an issue without closing it.

With new GitHub issues 2.0 you can use these synonyms to reference an issue and close it (in your commit message):

  • fix #xxx
  • fixes #xxx
  • fixed #xxx
  • close #xxx
  • closes #xxx
  • closed #xxx
  • resolve #xxx
  • resolves #xxx
  • resolved #xxx

You can also substitute #xxx with gh-xxx.

Referencing and closing issues across repos also works:

fixes user/repo#xxx

Check out the documentation available in their Help section.

jQuery creating objects

You can always make it a function

function writeObject(color){
    $('body').append('<div style="color:'+color+';">Hello!</div>')
}

writeObject('blue') ? enter image description here

Using Python's list index() method on a list of tuples or objects?

Python's list.index(x) returns index of the first occurrence of x in the list. So we can pass objects returned by list compression to get their index.

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> [tuple_list.index(t) for t in tuple_list if t[1] == 7]
[1]
>>> [tuple_list.index(t) for t in tuple_list if t[0] == 'kumquat']
[2]

With the same line, we can also get the list of index in case there are multiple matched elements.

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11), ("banana", 7)]
>>> [tuple_list.index(t) for t in tuple_list if t[1] == 7]
[1, 4]

Div vertical scrollbar show

Have you tried overflow-y:auto ? It is not exactly what you want, as the scrollbar will appear only when needed.

boolean in an if statement

If you write: if(x === true) , It will be true for only x = true

If you write: if(x) , it will be true for any x that is not: '' (empty string), false, null, undefined, 0, NaN.

Passing variable number of arguments around

I'm unsure if this works for all compilers, but it has worked so far for me.

void inner_func(int &i)
{
  va_list vars;
  va_start(vars, i);
  int j = va_arg(vars);
  va_end(vars); // Generally useless, but should be included.
}

void func(int i, ...)
{
  inner_func(i);
}

You can add the ... to inner_func() if you want, but you don't need it. It works because va_start uses the address of the given variable as the start point. In this case, we are giving it a reference to a variable in func(). So it uses that address and reads the variables after that on the stack. The inner_func() function is reading from the stack address of func(). So it only works if both functions use the same stack segment.

The va_start and va_arg macros will generally work if you give them any var as a starting point. So if you want you can pass pointers to other functions and use those too. You can make your own macros easily enough. All the macros do is typecast memory addresses. However making them work for all the compilers and calling conventions is annoying. So it's generally easier to use the ones that come with the compiler.

Python Set Comprehension

You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.

The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.

With an appropriate predicate in hand, problem 1 simplifies to:

 low_primes = {x for x in range(1, 100) if is_prime(x)}

And problem 2 simplifies to:

 low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}

Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."

P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.

Find duplicate lines in a file and count how many time each line was duplicated?

To find duplicate counts use below command as requested by you :

sort filename | uniq -c | awk '{print $2, $1}'

User Authentication in ASP.NET Web API

I am working on a MVC5/Web API project and needed to be able to get authorization for the Web Api methods. When my index view is first loaded I make a call to the 'token' Web API method which I believe is created automatically.

The client side code (CoffeeScript) to get the token is:

getAuthenticationToken = (username, password) ->
    dataToSend = "username=" + username + "&password=" + password
    dataToSend += "&grant_type=password"
    $.post("/token", dataToSend).success saveAccessToken

If successful the following is called, which saves the authentication token locally:

saveAccessToken = (response) ->
    window.authenticationToken = response.access_token

Then if I need to make an Ajax call to a Web API method that has the [Authorize] tag I simply add the following header to my Ajax call:

{ "Authorization": "Bearer " + window.authenticationToken }

CS0234: Mvc does not exist in the System.Web namespace

I had this problem, but all the applications in IIS were broken when they had been working previously. None of the marked solutions helped me. The problem ended up being an extra copy of web.config had been introduced to my root directory. I removed that file and problem solved.

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

I got the same error while working with mnist data set, looks like a problem with the dimensions of X_train. I added another dimension and it solved the purpose.

X_train, X_test, \ y_train, y_test = train_test_split(X_reshaped, y_labels, train_size = 0.8, random_state = 42)

X_train = X_train.reshape(-1,28, 28, 1)

X_test = X_test.reshape(-1,28, 28, 1)

jQuery + client-side template = "Syntax error, unrecognized expression"

I had the same error:
"Syntax error, unrecognized expression: // "
It is known bug at JQuery, so i needed to think on workaround solution,
What I did is:
I changed "script" tag to "div"
and added at angular this code
and the error is gone...

app.run(['$templateCache', function($templateCache) {
    var url = "survey-input.html";
    content = angular.element(document.getElementById(url)).html()
    $templateCache.put(url, content);
}]);

Calculating width from percent to pixel then minus by pixel in LESS CSS

I think width: -moz-calc(25% - 1em); is what you are looking for. And you may want to give this Link a look for any further assistance

How to query for Xml values and attributes from table in SQL Server?

I've been trying to do something very similar but not using the nodes. However, my xml structure is a little different.

You have it like this:

<Metrics>
    <Metric id="TransactionCleanupThread.RefundOldTrans" type="timer" ...>

If it were like this instead:

<Metrics>
    <Metric>
        <id>TransactionCleanupThread.RefundOldTrans</id>
        <type>timer</type>
        .
        .
        .

Then you could simply use this SQL statement.

SELECT
    Sqm.SqmId,
    Data.value('(/Sqm/Metrics/Metric/id)[1]', 'varchar(max)') as id,
    Data.value('(/Sqm/Metrics/Metric/type)[1]', 'varchar(max)') AS type,
    Data.value('(/Sqm/Metrics/Metric/unit)[1]', 'varchar(max)') AS unit,
    Data.value('(/Sqm/Metrics/Metric/sum)[1]', 'varchar(max)') AS sum,
    Data.value('(/Sqm/Metrics/Metric/count)[1]', 'varchar(max)') AS count,
    Data.value('(/Sqm/Metrics/Metric/minValue)[1]', 'varchar(max)') AS minValue,
    Data.value('(/Sqm/Metrics/Metric/maxValue)[1]', 'varchar(max)') AS maxValue,
    Data.value('(/Sqm/Metrics/Metric/stdDeviation)[1]', 'varchar(max)') AS stdDeviation,
FROM Sqm

To me this is much less confusing than using the outer apply or cross apply.

I hope this helps someone else looking for a simpler solution!

Multiple lines of text in UILabel

Use story borad : select the label to set number of lines to zero......Or Refer this

enter image description here

Button inside of anchor link works in Firefox but not in Internet Explorer?

This is very simple actually, no javascript required.

First, put the anchor inside the button

<button><a href="#">Bar</a></button>

Then, turn the anchor tag into a block type element and fill its container

button a {
  display:block;
  height:100%;
  width:100%;
}

Finally, add other styles as necessary.

Running code after Spring Boot starts

Why not just create a bean that starts your monitor on initialization, something like:

@Component
public class Monitor {
    @Autowired private SomeService service

    @PostConstruct
    public void init(){
        // start your monitoring in here
    }
}

the init method will not be called until any autowiring is done for the bean.

How do I convert a Django QuerySet into list of dicts?

Type Cast to List

    job_reports = JobReport.objects.filter(job_id=job_id, status=1).values('id', 'name')

    json.dumps(list(job_reports))

Turning a Comma Separated string into individual rows

Nice to see that it have been solved in the 2016 version, but for all of those that is not on that, here are two generalized and simplified versions of the methods above.

The XML-method is shorter, but of course requires the string to allow for the xml-trick (no 'bad' chars.)

XML-Method:

create function dbo.splitString(@input Varchar(max), @Splitter VarChar(99)) returns table as
Return
    SELECT Split.a.value('.', 'VARCHAR(max)') AS Data FROM
    ( SELECT CAST ('<M>' + REPLACE(@input, @Splitter, '</M><M>') + '</M>' AS XML) AS Data 
    ) AS A CROSS APPLY Data.nodes ('/M') AS Split(a); 

Recursive method:

create function dbo.splitString(@input Varchar(max), @Splitter Varchar(99)) returns table as
Return
  with tmp (DataItem, ix) as
   ( select @input  , CHARINDEX('',@Input)  --Recu. start, ignored val to get the types right
     union all
     select Substring(@input, ix+1,ix2-ix-1), ix2
     from (Select *, CHARINDEX(@Splitter,@Input+@Splitter,ix+1) ix2 from tmp) x where ix2<>0
   ) select DataItem from tmp where ix<>0

Function in action

Create table TEST_X (A int, CSV Varchar(100));
Insert into test_x select 1, 'A,B';
Insert into test_x select 2, 'C,D';

Select A,data from TEST_X x cross apply dbo.splitString(x.CSV,',') Y;

Drop table TEST_X

XML-METHOD 2: Unicode Friendly (Addition courtesy of Max Hodges) create function dbo.splitString(@input nVarchar(max), @Splitter nVarchar(99)) returns table as Return SELECT Split.a.value('.', 'NVARCHAR(max)') AS Data FROM ( SELECT CAST ('<M>' + REPLACE(@input, @Splitter, '</M><M>') + '</M>' AS XML) AS Data ) AS A CROSS APPLY Data.nodes ('/M') AS Split(a);

MySQL Select all columns from one table and some from another table

select a.* , b.Aa , b.Ab, b.Ac from table1 a left join table2 b on a.id=b.id

this should select all columns from table 1 and only the listed columns from table 2 joined by id.

How to sort two lists (which reference each other) in the exact same way

I would like to suggest a solution if you need to sort more than 2 lists in sync:

def SortAndSyncList_Multi(ListToSort, *ListsToSync):
    y = sorted(zip(ListToSort, zip(*ListsToSync)))
    w = [n for n in zip(*y)]
    return list(w[0]), tuple(list(a) for a in zip(*w[1]))

What are the pros and cons of parquet format compared to other formats?

Choosing the right file format is important to building performant data applications. The concepts outlined in this post carry over to Pandas, Dask, Spark, and Presto / AWS Athena.

Column pruning

Column pruning is a big performance improvement that's possible for column-based file formats (Parquet, ORC) and not possible for row-based file formats (CSV, Avro).

Suppose you have a dataset with 100 columns and want to read two of them into a DataFrame. Here's how you can perform this with Pandas if the data is stored in a Parquet file.

import pandas as pd

pd.read_parquet('some_file.parquet', columns = ['id', 'firstname'])

Parquet is a columnar file format, so Pandas can grab the columns relevant for the query and can skip the other columns. This is a massive performance improvement.

If the data is stored in a CSV file, you can read it like this:

import pandas as pd

pd.read_csv('some_file.csv', usecols = ['id', 'firstname'])

usecols can't skip over entire columns because of the row nature of the CSV file format.

Spark doesn't require users to explicitly list the columns that'll be used in a query. Spark builds up an execution plan and will automatically leverage column pruning whenever possible. Of course, column pruning is only possible when the underlying file format is column oriented.

Popularity

Spark and Pandas have built-in readers writers for CSV, JSON, ORC, Parquet, and text files. They don't have built-in readers for Avro.

Avro is popular within the Hadoop ecosystem. Parquet has gained significant traction outside of the Hadoop ecosystem. For example, the Delta Lake project is being built on Parquet files.

Arrow is an important project that makes it easy to work with Parquet files with a variety of different languages (C, C++, Go, Java, JavaScript, MATLAB, Python, R, Ruby, Rust), but doesn't support Avro. Parquet files are easier to work with because they are supported by so many different projects.

Schema

Parquet stores the file schema in the file metadata. CSV files don't store file metadata, so readers need to either be supplied with the schema or the schema needs to be inferred. Supplying a schema is tedious and inferring a schema is error prone / expensive.

Avro also stores the data schema in the file itself. Having schema in the files is a huge advantage and is one of the reasons why a modern data project should not rely on JSON or CSV.

Column metadata

Parquet stores metadata statistics for each column and lets users add their own column metadata as well.

The min / max column value metadata allows for Parquet predicate pushdown filtering that's supported by the Dask & Spark cluster computing frameworks.

Here's how to fetch the column statistics with PyArrow.

import pyarrow.parquet as pq

parquet_file = pq.ParquetFile('some_file.parquet')
print(parquet_file.metadata.row_group(0).column(1).statistics)
<pyarrow._parquet.Statistics object at 0x11ac17eb0>
  has_min_max: True
  min: 1
  max: 9
  null_count: 0
  distinct_count: 0
  num_values: 3
  physical_type: INT64
  logical_type: None
  converted_type (legacy): NONE

Complex column types

Parquet allows for complex column types like arrays, dictionaries, and nested schemas. There isn't a reliable method to store complex types in simple file formats like CSVs.

Compression

Columnar file formats store related types in rows, so they're easier to compress. This CSV file is relatively hard to compress.

first_name,age
ken,30
felicia,36
mia,2

This data is easier to compress when the related types are stored in the same row:

ken,felicia,mia
30,36,2

Parquet files are most commonly compressed with the Snappy compression algorithm. Snappy compressed files are splittable and quick to inflate. Big data systems want to reduce file size on disk, but also want to make it quick to inflate the flies and run analytical queries.

Mutable nature of file

Parquet files are immutable, as described here. CSV files are mutable.

Adding a row to a CSV file is easy. You can't easily add a row to a Parquet file.

Data lakes

In a big data environment, you'll be working with hundreds or thousands of Parquet files. Disk partitioning of the files, avoiding big files, and compacting small files is important. The optimal disk layout of data depends on your query patterns.

How to change environment's font size?

As of mid 2017 To quickly get to the settings files press ctrl + shift + p and enter settings, there you will find the user settings and the workspace settings, be aware that the workspace settings will override the user settings, so it's better to use the latter directly to make it a global change (workspace settings will create a folder in your project root), from there you will have the option to add the option "editor.fontSize": 14 to your settings as a quick suggestion, but you can do it yourself and change the value to your preferred font size.

To sum it up:

  1. ctrl + shift + p

  2. select "user settings"

  3. add "editor.fontSize": 14

How can I have linebreaks in my long LaTeX equations?

SIMPLE ANSWER HERE

\begin{equation}
\begin{split}

equation \\
here

\end{split}
\end{equation}

How to do a simple file search in cmd

dir /s *foo* searches in current folder and sub folders.

It finds directories as well as files.

where /s means(documentation):

/s Lists every occurrence of the specified file name within the specified directory and all subdirectories.

How do I loop through a list by twos?

You can use for in range with a step size of 2:

Python 2

for i in xrange(0,10,2):
  print(i)

Python 3

for i in range(0,10,2):
  print(i)

Note: Use xrange in Python 2 instead of range because it is more efficient as it generates an iterable object, and not the whole list.

How do I find the length (or dimensions, size) of a numpy matrix in python?

matrix.size according to the numpy docs returns the Number of elements in the array. Hope that helps.

When should use Readonly and Get only properties

readonly properties are used to create a fail-safe code. i really like the Encapsulation posts series of Mark Seemann about properties and backing fields:

http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx

taken from Mark's example:

public class Fragrance : IFragrance
{
    private readonly string name;

    public Fragrance(string name)
    {
        if (name == null)
        {
            throw new ArgumentNullException("name");
        }

        this.name = name;
    }

    public string Spread()
    {
        return this.name;
    }
}

in this example you use the readonly name field to make sure the class invariant is always valid. in this case the class composer wanted to make sure the name field is set only once (immutable) and is always present.

Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

  1. Open File Menu > Project Structure > Module > Select Dependency > +
  2. Select one from given option
    • Jar
    • Library
    • Module dependency
  3. Apply + Ok
  4. Import into java class

How to load an ImageView by URL in Android?

imageView.setImageBitmap(BitmapFactory.decodeStream(imageUrl.openStream()));//try/catch IOException and MalformedURLException outside

Converting unix timestamp string to readable date

timestamp ="124542124"
value = datetime.datetime.fromtimestamp(timestamp)
exct_time = value.strftime('%d %B %Y %H:%M:%S')

Get the readable date from timestamp with time also, also you can change the format of the date.

Oracle SqlPlus - saving output in a file but don't show on screen

Try this:

SET TERMOUT OFF; 
spool M:\Documents\test;
select * from employees;
/
spool off;

Xpath: select div that contains class AND whose specific child element contains text

You could use the xpath :

//div[@class="measure-tab" and .//span[contains(., "someText")]]

Input :

<root>
<div class="measure-tab">
  <td> someText</td>
</div>
<div class="measure-tab">
  <div>
    <div2>
       <span>someText2</span>
   </div2>
  </div>
</div>
</root>

Output :

    Element='<div class="measure-tab">
  <div>
    <div2>
      <span>someText2</span>
    </div2>
  </div>
</div>'

How can I convert an image into Base64 string using JavaScript?

Here is the way you can do with Javascript Promise.

const getBase64 = (file) => new Promise(function (resolve, reject) {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject('Error: ', error);
})

Now, use it in event handler.

const _changeImg = (e) => {
        const file = e.target.files[0];
        let encoded;
        getBase64(file)
          .then((result) => {
            encoded = result;
           })
          .catch(e => console.log(e))
    }

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

I normally differentiate these two via this diagram:

Use PrimaryKeyJoinColumn

enter image description here

Use JoinColumn

enter image description here

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

Adding one more answer for Windows users. If none of this solves the problems.

Do not add space before or after =

-DgroupId= com.company.module //Wrong , Watch the space after the equal to 
-DgroupId=com.company.module //Right 

Its better to put everything inside double quotes, like "-DgroupId=com.." This will give you exact error rather than some random error.

Weird that , maven does not even care to mention this in the documentation.

Visual Studio 64 bit?

For numerous reasons, No.

Why is explained in this MSDN post.

First, from a performance perspective the pointers get larger, so data structures get larger, and the processor cache stays the same size. That basically results in a raw speed hit (your mileage may vary). So you start in a hole and you have to dig yourself out of that hole by using the extra memory above 4G to your advantage. In Visual Studio this can happen in some large solutions but I think a preferable thing to do is to just use less memory in the first place. Many of VS’s algorithms are amenable to this. Here’s an old article that discusses the performance issues at some length: https://docs.microsoft.com/archive/blogs/joshwil/should-i-choose-to-take-advantage-of-64-bit

Secondly, from a cost perspective, probably the shortest path to porting Visual Studio to 64 bit is to port most of it to managed code incrementally and then port the rest. The cost of a full port of that much native code is going to be quite high and of course all known extensions would break and we’d basically have to create a 64 bit ecosystem pretty much like you do for drivers. Ouch.

How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on 0.0.0.0:80 which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:

listen 127.0.0.1:80;

In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

Read XML Attribute using XmlDocument

Assuming your example document is in the string variable doc

> XDocument.Parse(doc).Root.Attribute("SuperNumber")
1

How do you add UI inside cells in a google spreadsheet using app script?

Status 2018:

There seems to be no way to place buttons (drawings, images) within cells in a way that would allow them to be linked to Apps Script functions.


This being said, there are some things that you can indeed do:

You can...

You can place images within cells using IMAGE(URL), but they cannot be linked to Apps Script functions.

You can place images within cells and link them to URLs using:
=HYPERLINK("http://example.com"; IMAGE("http://example.com/myimage.png"; 1))

You can create drawings as described in the answer of @Eduardo and they can be linked to Apps Script functions, but they will be stand-alone items that float freely "above" the spreadsheet and cannot be positioned in cells. They cannot be copied from cell to cell and they do not have a row or col position that the script function could read.

HTTP response code for POST when resource already exists

"302 Found" sounds logical for me. And the RFC 2616 says that it CAN be answered for other requests than GET and HEAD (and this surely includes POST)

But it still keeps the visitor going to this URL to get this "Found" resource, by the RFC. To make it to go directly to the real "Found" URL one should be using "303 See Other", which makes sense, but forces another call to GET its following URL. On the good side, this GET is cacheable.

I think that I would use "303 See Other". I dont know if I can respond with the "thing" found in the body, but I would like to do so to save one roundtrip to the server.

UPDATE: After re-reading the RFC, I still think that an inexistent "4XX+303 Found" code should be the correct. However, the "409 Conflict" is the best existing answer code (as pointed by @Wrikken), maybe including a Location header pointing to the existing resource.

JavaScript - populate drop down list with array

<form id="myForm">
<select id="selectNumber">
    <option>Choose a number</option>
    <script>
        var myArray = new Array("1", "2", "3", "4", "5" . . . . . "N");
        for(i=0; i<myArray.length; i++) {  
            document.write('<option value="' + myArray[i] +'">' + myArray[i] + '</option>');
        }
    </script>
</select>
</form>

an attempt was made to access a socket in a way forbbiden by its access permissions. why?

Well I don't even understand the culprit of this problem. But in my case the problem is totally different. I've tried running netstat -o or netstat -ab, both show that there is not any app currently listening on port 62434 which is the one my app tries to listen on. So it's really confusing to me.

I just tried thinking of what I had made so that it stopped working (it did work before). Well then I thought of the Internet sharing I made on my Ethernet adapter with a private virtual LAN (using Hyper-v in Windows 10). I just needed to turn off the sharing and it worked just fine again.

Hope this helps someone else having the same issue. And of course if someone could explain this, please add more detail in your own answer or maybe as some comment to my answer.

R Language: How to print the first or last rows of a data set?

If you want to print the last 10 lines, use

tail(dataset, 10)

for the first 10, you could also do

head(dataset, 10)

pandas dataframe create new columns and fill with calculated values from same df

In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])

In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]: 
          A         B         C         D
1  0.319124  0.296653  0.138206  0.246017
2  0.376994  0.326481  0.230464  0.066062
3  0.036134  0.192954  0.430341  0.340571

Create two blank lines in Markdown

&nbsp;

This HTML entity which means "non-breaking space" will help you for each line break

Smooth GPS data

You can also use a spline. Feed in the values you have and interpolate points between your known points. Linking this with a least-squares fit, moving average or kalman filter (as mentioned in other answers) gives you the ability to calculate the points inbetween your "known" points.

Being able to interpolate the values between your knowns gives you a nice smooth transition and a /reasonable/ approximation of what data would be present if you had a higher-fidelity. http://en.wikipedia.org/wiki/Spline_interpolation

Different splines have different characteristics. The one's I've seen most commonly used are Akima and Cubic splines.

Another algorithm to consider is the Ramer-Douglas-Peucker line simplification algorithm, it is quite commonly used in the simplification of GPS data. (http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm)

How do I tell if a regular file does not exist in Bash?

To reverse a test, use "!". That is equivalent to the "not" logical operator in other languages. Try this:

if [ ! -f /tmp/foo.txt ];
then
    echo "File not found!"
fi

Or written in a slightly different way:

if [ ! -f /tmp/foo.txt ]
    then echo "File not found!"
fi

Or you could use:

if ! [ -f /tmp/foo.txt ]
    then echo "File not found!"
fi

Or, presing all together:

if ! [ -f /tmp/foo.txt ]; then echo "File not found!"; fi

Which may be written (using then "and" operator: &&) as:

[ ! -f /tmp/foo.txt ] && echo "File not found!"

Which looks shorter like this:

[ -f /tmp/foo.txt ] || echo "File not found!"

How do I check what version of Python is running my script?

Here's a short commandline version which exits straight away (handy for scripts and automated execution):

python -c "print(__import__('sys').version)"

Or just the major, minor and micro:

python -c "print(__import__('sys').version_info[:1])" # (2,)
python -c "print(__import__('sys').version_info[:2])" # (2, 7)
python -c "print(__import__('sys').version_info[:3])" # (2, 7, 6)

Pandas left outer join multiple dataframes on multiple columns

Merge them in two steps, df1 and df2 first, and then the result of that to df3.

In [33]: s1 = pd.merge(df1, df2, how='left', on=['Year', 'Week', 'Colour'])

I dropped year from df3 since you don't need it for the last join.

In [39]: df = pd.merge(s1, df3[['Week', 'Colour', 'Val3']],
                       how='left', on=['Week', 'Colour'])

In [40]: df
Out[40]: 
   Year Week Colour  Val1  Val2 Val3
0  2014    A    Red    50   NaN  NaN
1  2014    B    Red    60   NaN   60
2  2014    B  Black    70   100   10
3  2014    C    Red    10    20  NaN
4  2014    D  Green    20   NaN   20

[5 rows x 6 columns]

How to correctly link php-fpm and Nginx Docker containers?

Don't hardcode ip of containers in nginx config, docker link adds the hostname of the linked machine to the hosts file of the container and you should be able to ping by hostname.

EDIT: Docker 1.9 Networking no longer requires you to link containers, when multiple containers are connected to the same network, their hosts file will be updated so they can reach each other by hostname.

Every time a docker container spins up from an image (even stop/start-ing an existing container) the containers get new ip's assigned by the docker host. These ip's are not in the same subnet as your actual machines.

see docker linking docs (this is what compose uses in the background)

but more clearly explained in the docker-compose docs on links & expose

links

links:
 - db
 - db:database
 - redis

An entry with the alias' name will be created in /etc/hosts inside containers for this service, e.g:

172.17.2.186  db
172.17.2.186  database
172.17.2.187  redis

expose

Expose ports without publishing them to the host machine - they'll only be accessible to linked services. Only the internal port can be specified.

and if you set up your project to get the ports + other credentials through environment variables, links automatically set a bunch of system variables:

To see what environment variables are available to a service, run docker-compose run SERVICE env.

name_PORT

Full URL, e.g. DB_PORT=tcp://172.17.0.5:5432

name_PORT_num_protocol

Full URL, e.g. DB_PORT_5432_TCP=tcp://172.17.0.5:5432

name_PORT_num_protocol_ADDR

Container's IP address, e.g. DB_PORT_5432_TCP_ADDR=172.17.0.5

name_PORT_num_protocol_PORT

Exposed port number, e.g. DB_PORT_5432_TCP_PORT=5432

name_PORT_num_protocol_PROTO

Protocol (tcp or udp), e.g. DB_PORT_5432_TCP_PROTO=tcp

name_NAME

Fully qualified container name, e.g. DB_1_NAME=/myapp_web_1/myapp_db_1

Yes or No confirm box using jQuery

You can reuse your confirm:

    function doConfirm(body, $_nombrefuncion)
    {   var param = undefined;
        var $confirm = $("<div id='confirm' class='hide'></div>").dialog({
            autoOpen: false,
            buttons: {
                Yes: function() {
                param = true;
                $_nombrefuncion(param);
                $(this).dialog('close');
            },
                No: function() {
                param = false;
                $_nombrefuncion(param);
                $(this).dialog('close');
            }
                                    }
        });
        $confirm.html("<h3>"+body+"<h3>");
        $confirm.dialog('open');                                     
    };

// for this form just u must change or create a new function for to reuse the confirm
    function resultadoconfirmresetVTyBFD(param){
        $fecha = $("#asigfecha").val();
        if(param ==true){
              // DO THE CONFIRM
        }
    }

//Now just u must call the function doConfirm
    doConfirm('body message',resultadoconfirmresetVTyBFD);

How do I get the name of the active user via the command line in OS X?

The question has not been completely answered, IMHO. I will try to explain: I have a crontab entry that schedules a bash shell command procedure, that in turn does some cleanup of my files; and, when done, sends a notification to me using the OS X notification center (with the command osascript -e 'display notification ...). If someone (e.g. my wife or my daughter) switches the current user of the computer to her, leaving me in the background, the cron script fails when sending the notification.

So, Who is the current user means Has some other people become the effective user leaving me in the background? Do stat -f "%Su" /dev/console returns the current active user name?

The answer is yes; so, now my crontab shell script has been modified in the following way:

...
if [ "$(/usr/bin/stat -f ""%Su"" /dev/console)" = "loreti" ]
then /usr/bin/osascript -e \
  'display notification "Cleanup done" sound name "sosumi" with title "myCleanup"'
fi

ssh: connect to host github.com port 22: Connection timed out

I had this issue for 2 hours and it turns out removing the "s" from https and just do:

git clone -b <branchName> http:<projecturl>

Fixed it.

Is there a label/goto in Python?

Though there isn't any code equivalent to goto/label in Python, you could still get such functionality of goto/label using loops.

Lets take a code sample shown below where goto/label can be used in a arbitrary language other than python.

String str1 = 'BACK'

label1:
    print('Hello, this program contains goto code\n')
    print('Now type BACK if you want the program to go back to the above line of code. Or press the ENTER key if you want the program to continue with further lines of code')
    str1 = input()

if str1 == 'BACK'
    {
        GoTo label1
    }
print('Program will continue\nBla bla bla...\nBla bla bla...\nBla bla bla...')

Now the same functionality of the above code sample can be achieved in python by using a while loop as shown below.

str1 = 'BACK'

while str1 == 'BACK':
        print('Hello, this is a python program containing python equivalent code for goto code\n')
        print('Now type BACK if you want the program to go back to the above line of code. Or press the ENTER key if you want the program to continue with further lines of code')
        str1 = input()
print('Program will continue\nBla bla bla...\nBla bla bla...\nBla bla bla...')

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

VSCommands didn't work for me and caused a problem when I installed Visual Studio 2010 aside of Visual Studio 2012.

After some experimentations I found the trick:

Go to HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers and add an entry with the name "C:\Program Files (x86)\Common Files\Microsoft Shared\MSEnv\VSLauncher.exe" and the value "RUNASADMIN".

This should solve your issue. I've also blogged about that.

How to show two figures using matplotlib?

You should call plt.show() only at the end after creating all the plots.

jQuery-- Populate select from json

fiddle

var $select = $('#down'); 
$select.find('option').remove();  
$.each(temp,function(key, value) 
{
    $select.append('<option value=' + key + '>' + value + '</option>');
});

What are the differences between git remote prune, git prune, git fetch --prune, etc

git remote prune and git fetch --prune do the same thing: deleting the refs to the branches that don't exist on the remote, as you said. The second command connects to the remote and fetches its current branches before pruning.

However it doesn't touch the local branches you have checked out, that you can simply delete with

git branch -d  random_branch_I_want_deleted

Replace -d by -D if the branch is not merged elsewhere

git prune does something different, it purges unreachable objects, those commits that aren't reachable in any branch or tag, and thus not needed anymore.

Copy a table from one database to another in Postgres

Check this python script

python db_copy_table.py "host=192.168.1.1 port=5432 user=admin password=admin dbname=mydb" "host=localhost port=5432 user=admin password=admin dbname=mydb" alarmrules -w "WHERE id=19" -v
Source number of rows = 2
INSERT INTO alarmrules (id,login,notifybyemail,notifybysms) VALUES (19,'mister1',true,false);
INSERT INTO alarmrules (id,login,notifybyemail,notifybysms) VALUES (19,'mister2',true,false);

Large WCF web service request failing with (400) HTTP Bad Request

Try setting maxReceivedMessageSize on the server too, e.g. to 4MB:

    <binding name="MyService.MyServiceBinding" 
           maxReceivedMessageSize="4194304">

The main reason the default (65535 I believe) is so low is to reduce the risk of Denial of Service (DoS) attacks. You need to set it bigger than the maximum request size on the server, and the maximum response size on the client. If you're in an Intranet environment, the risk of DoS attacks is probably low, so it's probably safe to use a value much higher than you expect to need.

By the way a couple of tips for troubleshooting problems connecting to WCF services:

  • Enable tracing on the server as described in this MSDN article.

  • Use an HTTP debugging tool such as Fiddler on the client to inspect the HTTP traffic.

Enable 'xp_cmdshell' SQL Server

While the accepted answer will work most of the times, I have encountered (still do not know why) some cases that is does not. A slight modification of the query by using the WITH OVERRIDE in RECONFIGURE gives the solution

Use Master
GO

EXEC master.dbo.sp_configure 'show advanced options', 1
RECONFIGURE WITH OVERRIDE
GO

EXEC master.dbo.sp_configure 'xp_cmdshell', 1
RECONFIGURE WITH OVERRIDE
GO

The expected output is

Configuration option 'show advanced options' changed from 0 to 1. Run the RECONFIGURE statement to install.
Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install.

How to read fetch(PDO::FETCH_ASSOC);

PDOStatement::fetch returns a row from the result set. The parameter PDO::FETCH_ASSOC tells PDO to return the result as an associative array.

The array keys will match your column names. If your table contains columns 'email' and 'password', the array will be structured like:

Array
(
    [email] => '[email protected]'
    [password] => 'yourpassword'
)

To read data from the 'email' column, do:

$user['email'];

and for 'password':

$user['password'];

403 - Forbidden: Access is denied. ASP.Net MVC

Are you hosting the site on iis? if so make sure the account your website runs under has access to local file system?

Straight from msdn .....

The Network Service account has Read and Execute permissions on the IIS server root folder by default. The IIS server root folder is named Wwwroot. This means that an ASP.NET application deployed inside the root folder already has Read and Execute permissions to its application folders. However, if your ASP.NET application needs to use files or folders in other locations, you must specifically enable access.

To provide access to an ASP.NET application running as Network Service, you must grant access to the Network Service account.

To grant read, write, and modify permissions to a specific file

  • In Windows Explorer, locate and select the required file.
  • Right-click the file, and then click Properties.
  • In the Properties dialog box, click the Security tab.
  • On the Security tab, examine the list of users. If the Network Service
  • account is not listed, add it.
  • In the Properties dialog box, click the Network Service user name, and in the Permissions for NETWORK SERVICE section, select the Read, Write, and Modify permissions.
  • Click Apply, and then click OK.

Click here for more

Server cannot set status after HTTP headers have been sent IIS7.5

You are actually trying to redirect a page which has some response to throw. So first you keep the information you have throw in a buffer using response.buffer = true in beginning of the page and then flush it when required using response.flush this error will get fixed

How to drop all tables in a SQL Server database?

The fasted way is:

  1. New Database Diagrams
  2. Add all table
  3. Ctrl + A to select all
  4. Right Click "Remove from Database"
  5. Ctrl + S to save
  6. Enjoy

Hide strange unwanted Xcode logs

This is still not fixed in Xcode Version 8.0 beta 2 (8S162m) for me and extra logs are also appearing in the Xcode console

** EDIT 8/1/16: This has been acknowledged in the release notes for Xcode 8 Beta 4 (8S188o) as an issues still persisting.

Known Issues in Xcode 8 beta 4 – IDE

Debugging

• Xcode Debug Console shows extra logging from system frameworks when debugging applications in the Simulator. (27331147, 26652255)

Presumably this will be resolved by the GM release. Until then patience and although not ideal but a workaround I'm using is below...

Similar to the previous answer I am having to:

  • prefix my print logs with some kind of special character (eg * or ^ or ! etc etc)

  • Then use the search box on the bottom right of the console pane to filter my console logs by inputing my chosen special character to get the console to display my print logs as intended

console

Objective-C Static Class Level variables

u can rename the class as classA.mm and add C++ features in it.

Typescript es6 import module "File is not a module error"

How can I accomplish that?

Your example declares a TypeScript < 1.5 internal module, which is now called a namespace. The old module App {} syntax is now equivalent to namespace App {}. As a result, the following works:

// test.ts
export namespace App {
    export class SomeClass {
        getName(): string {
            return 'name';
        }
    }
}

// main.ts
import { App } from './test';
var a = new App.SomeClass();

That being said...

Try to avoid exporting namespaces and instead export modules (which were previously called external modules). If needs be you can use a namespace on import with the namespace import pattern like this:

// test.ts
export class SomeClass {
    getName(): string {
        return 'name';
    }
}

// main.ts
import * as App from './test'; // namespace import pattern
var a = new App.SomeClass();

Detect user scroll down or scroll up in jQuery

To differentiate between scroll up/down in jQuery, you could use:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
    }
    else{
        //scroll down
    }   
});

This method also works in divs that have overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

how to prevent "directory already exists error" in a makefile when using mkdir

On Windows

if not exist "$(OBJDIR)" mkdir $(OBJDIR)

On Unix | Linux

if [ ! -d "$(OBJDIR)" ]; then mkdir $(OBJDIR); fi

To show error message without alert box in Java Script

try this

<html>
  <head>
  <script type="text/javascript">
  function validate() {
  if(myform.fname.value.length==0)
  {
   document.getElementById("error").innerHTML="this is invalid name ";
   document.myform.fname.value="";
   document.myform.fname.focus();
  }
  }
  </script>
  </head>
  <body>
  <form name="myform">
  First_Name
  <input type="text" id="fname" name="fname" onblur="validate()"> </input>
<span style="color:red;" id="error" > </span>
  <br> <br>
  Last_Name
  <input type="text" id="lname" name="lname" onblur="validate()"> </input>

  <br>
  <input type=button value=check> 

  </form>
  </body>
</html>

nginx- duplicate default server error

You likely have other files (such as the default configuration) located in /etc/nginx/sites-enabled that needs to be removed.

This issue is caused by a repeat of the default_server parameter supplied to one or more listen directives in your files. You'll likely find this conflicting directive reads something similar to:

listen 80 default_server;

As the nginx core module documentation for listen states:

The default_server parameter, if present, will cause the server to become the default server for the specified address:port pair. If none of the directives have the default_server parameter then the first server with the address:port pair will be the default server for this pair.

This means that there must be another file or server block defined in your configuration with default_server set for port 80. nginx is encountering that first before your mysite.com file so try removing or adjusting that other configuration.

If you are struggling to find where these directives and parameters are set, try a search like so:

grep -R default_server /etc/nginx

Git workflow and rebase vs merge questions

DO NOT use git push origin --mirror UNDER ALMOST ANY CIRCUMSTANCE.

It does not ask if you're sure you want to do this, and you'd better be sure, because it will erase all of your remote branches that are not on your local box.

http://twitter.com/dysinger/status/1273652486

Variables within app.config/web.config

I don't think you can declare and use variables to define appSettings keys within a configuration file. I've always managed concatenations in code like you.

What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?

You could either validate every ID before using it in your queries (which I think is the best practice),

// Assuming you are using Express, this can return 404 automatically.
app.post('/resource/:id([0-9a-f]{24})', function(req, res){
  const id = req.params.id;
  // ...
});

... or you could monkey patch Mongoose to ignore those casting errors and instead use a string representation to carry on the query. Your query will of course not find anything, but that is probably what you want to have happened anyway.

import { SchemaType }  from 'mongoose';

let patched = false;

export const queryObjectIdCastErrorHandler = {
  install,
};

/**
 * Monkey patches `mongoose.SchemaType.prototype.castForQueryWrapper` to catch
 * ObjectId cast errors and return string instead so that the query can continue
 * the execution. Since failed casts will now use a string instead of ObjectId
 * your queries will not find what they are looking for and may actually find
 * something else if you happen to have a document with this id using string
 * representation. I think this is more or less how MySQL would behave if you
 * queried a document by id and sent a string instead of a number for example.
 */
function install() {
  if (patched) {
    return;
  }

  patch();

  patched = true;
}

function patch() {
  // @ts-ignore using private api.
  const original = SchemaType.prototype.castForQueryWrapper;

  // @ts-ignore using private api.
  SchemaType.prototype.castForQueryWrapper = function () {
    try {
      return original.apply(this, arguments);
    } catch (e) {
      if ((e.message as string).startsWith('Cast to ObjectId failed')) {
        return arguments[0].val;
      }

      throw e;
    }
  };
}

How can I create objects while adding them into a vector?

You cannot insert a class into a vector, you can insert an object (provided that it is of the proper type or convertible) of a class though.

If the type Player has a default constructor, you can create a temporary object by doing Player(), and that should work for your case:

vectorOfGamers.push_back(Player());

Clearing NSUserDefaults

If you need it while developing, you can also reset your simulator, deleting all the NSUserDefaults.

iOS Simulator -> Reset Content and Settings...

Bear in mind that it will also delete all the apps and files on simulator.

Can I fade in a background image (CSS: background-image) with jQuery?

This is what worked for my, and its pure css


css

html {
    padding: 0;
    margin: 0;
    width: 100%;
    height: 100%;
  }

  body {
    padding: 0;
    margin: 0;
    width: 100%;
    height: 100%;
  }

  #bg {
    width: 100%;
    height: 100%;
    background: url('/image.jpg/') no-repeat center center fixed;

    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;

    -webkit-animation: myfirst 5s ; /* Chrome, Safari, Opera */
    animation: myfirst 5s ;
  }

  /* Chrome, Safari, Opera */
  @-webkit-keyframes myfirst {
    from {opacity: 0.2;}
    to {opacity: 1;}
  }

  /* Standard syntax */
  @keyframes myfirst {
    from {opacity: 0.2;}
    to {opacity: 1;}
  }

html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
  <div id="bg">
    <!-- content here -->
  </div> <!-- end bg -->
</body>
</html>

Changing MongoDB data store directory

Create a file called mongod.cfg in MongoDB folder if you dont have it. In my case: C:\Users\ivanbtrujillo\MongoDB

Then, edit mongod.cfg with notepad and add a line with the following (our custom dbpath):

dbpath=C:\Users\ivanbtrujillo\MongoDB\data\db

In this file you should especify the logpath too. My mongod.cfg file is:

logpath=C:\Users\ivanbtrujillo\MongoDB\log\mongo.log
dbpath=C:\Users\ivanbtrujillo\MongoDB\data\db

If you uses mongoDB as a windows service, you have to change this key and especify the mongod.cfg file.

To install mongodb as a windows service run this command:

**"C:\Users\ivanbtrujillo\MongoDB\bin\mongod.exe" --config "C:\Users\ivanbtrujillo\MongoDB\mongod.cfg" –install**

Open regedit.exe and go to the following route:

HKEYLOCALMACHINE\SYSTEM\CurrentControlSet\services\MongoDB

MongoDB service does not work, we have to edit the ImagePath key, delete its content and put the following:

**"C:\Users\ivanbtrujillo\MongoDB\bin\mongod.exe" --config "C:\Users\ivanbtrujillo\MongoDB\mongod.cfg" 
--logpath="C:\Users\ivanbtrujillo\MongoDB\log\mongo.log" –service**

We indicates to mongo it's config file and its logpath.

Then when you init the mongodb service, it works.

Here is a full tutorial to install mongoDB in windows: http://ivanbtrujillo.herokuapp.com/2014/07/24/installing-mongodb-as-a-service-windows/

Hope it helps,

How can I process each letter of text using Javascript?

In today's JavaScript you can

Array.prototype.map.call('This is my string', (c) => c+c)

Obviously, c+c represents whatever you want to do with c.

This returns

["TT", "hh", "ii", "ss", " ", "ii", "ss", " ", "mm", "yy", " ", "ss", "tt", "rr", "ii", "nn", "gg"]

Detect rotation of Android phone in the browser with JavaScript

You could always listen to the window resize event. If, on that event, the window went from being taller than it is wide to wider than it is tall (or vice versa), you can be pretty sure the phone orientation was just changed.

Android Min SDK Version vs. Target SDK Version

The comment posted by the OP to the question (basically stating that the targetSDK doesn't affect the compiling of an app) is entirely wrong! Sorry to be blunt.

In short, here is the purpose to declaring a different targetSDK from the minSDK: It means you are using features from a higher level SDK than your minimum, but you have ensured backwards compatibility. In other words, imagine that you want to use a feature that was only recently introduced, but that isn't critical to your application. You would then set the targetSDK to the version where this new feature was introduced and the minimum to something lower so that everyone could still use your app.

To give an example, let's say you're writing an app that makes extensive use of gesture detection. However, every command that can be recognised by a gesture can also be done by a button or from the menu. In this case, gestures are a 'cool extra' but aren't required. Therefore you would set the target sdk to 7 ("Eclair" when the GestureDetection library was introduced), and the minimumSDK to level 3 ("Cupcake") so that even people with really old phones could use your app. All you'd have to do is make sure that your app checked the version of Android it was running on before trying to use the gesture library, to avoid trying to use it if it didn't exist. (Admittedly this is a dated example since hardly anyone still has a v1.5 phone, but there was a time when maintaining compatibility with v1.5 was really important.)

To give another example, you could use this if you wanted to use a feature from Gingerbread or Honeycomb. Some people will get the updates soon, but many others, particularly with older hardware, might stay stuck with Eclair until they buy a new device. This would let you use some of the cool new features, but without excluding part of your possible market.

There is a really good article from the Android developer's blog about how to use this feature, and in particular, how to design the "check the feature exists before using it" code I mentioned above.

To the OP: I've written this mainly for the benefit of anyone who happens to stumble upon this question in the future, as I realise your question was asked a long time ago.

How to use count and group by at the same select statement

if You Want to use Select All Query With Count Option, try this...

 select a.*, (Select count(b.name) from table_name as b where Condition) as totCount from table_name  as a where where Condition

How to filter WooCommerce products by custom attribute

On one of my sites I had to make a custom search by a lot of data some of it from custom fields here is how my $args look like for one of the options:

$args = array(
    'meta_query' => $meta_query,
    'tax_query' => array(
        $query_tax
    ),
    'posts_per_page' => 10,
    'post_type' => 'ad_listing',
    'orderby' => $orderby,
    'order' => $order,
    'paged' => $paged
);

where "$meta_query" is:

$key = "your_custom_key"; //custom_color for example
$value = "blue";//or red or any color
$query_color = array('key' => $key, 'value' => $value);
$meta_query[] = $query_color;

and after that:

query_posts($args);

so you would probably get more info here: http://codex.wordpress.org/Class_Reference/WP_Query and you can search for "meta_query" in the page to get to the info

How to insert close button in popover for Bootstrap

I was running into the problem of the tooltip doing some funky stuff when the close button became clicked. To work around this I used a span instead of using a button. Also, when the close button was clicked I would have to click the tooltip twice after it closed in order to get it to open again. To work around this I simply used the .click() method, as seen below.

<span tabindex='0' class='tooltip-close close'>×</span>

$('#myTooltip').tooltip({
    html: true,
    title: "Hello From Tooltip",
    trigger: 'click'
});    

$("body").on("click", ".tooltip-close", function (e) {
    else {
        $('.tooltip').remove();
        $('#postal-premium-tooltip').click();
    }
});

Where does Jenkins store configuration files for the jobs it runs?

Jenkins 1.627, OS X 10.10.5 /Users/Shared/Jenkins/Home/jobs/{project_name}/config.xml

Connecting to Microsoft SQL server using Python

here's the one that works for me:

from sqlalchemy import create_engine
import urllib

conn_str = (
r'Driver=ODBC Driver 13 for SQL Server;'
r'Server=DefinitelyNotProd;'
r'Database=PlayPen;'
r'Trusted_Connection=Yes;')

quoted_conn_str = urllib.parse.quote_plus(conn_str)
engine = create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted_conn_str))

Does Java support structs?

Yes, Java doesn't have struct/value type yet. But, in the upcoming version of Java, we are going to get inline class which is similar to struct in C# and will help us write allocation free code.


inline class point { 
  int x;
  int y;
}

Haskell: Converting Int to String

An example based on Chuck's answer:

myIntToStr :: Int -> String
myIntToStr x
    | x < 3     = show x ++ " is less than three"
    | otherwise = "normal"

Note that without the show the third line will not compile.

Gets byte array from a ByteBuffer in java

Note that the bb.array() doesn't honor the byte-buffers position, and might be even worse if the bytebuffer you are working on is a slice of some other buffer.

I.e.

byte[] test = "Hello World".getBytes("Latin1");
ByteBuffer b1 = ByteBuffer.wrap(test);
byte[] hello = new byte[6];
b1.get(hello); // "Hello "
ByteBuffer b2 = b1.slice(); // position = 0, string = "World"
byte[] tooLong = b2.array(); // Will NOT be "World", but will be "Hello World".
byte[] world = new byte[5];
b2.get(world); // world = "World"

Which might not be what you intend to do.

If you really do not want to copy the byte-array, a work-around could be to use the byte-buffer's arrayOffset() + remaining(), but this only works if the application supports index+length of the byte-buffers it needs.

'ssh' is not recognized as an internal or external command

Actually you have 2 problems here: First is that you don't have ssh installed, second is that you don't know how to deploy

Install SSH

It seems that ssh is not installed on your computer.

You can install openssh from here : http://openssh.en.softonic.com/download

Generate your key

Than you will have to geneate your ssh-key. There's a good tutorial about this here:

https://help.github.com/articles/generating-ssh-keys#platform-windows

Deploy

To deploy, you just have to push your code over git. Something like this:

git push fort master

If you get permission denied, be sure that you have put your public_key in the dashboard in the git tab.

SSH

The ssh command gives you access to your remote node. You should have received a password by email and now that you have ssh installed, you should be asked for a password when trying to connect. just input that password. If you want to use your private ssh key to connect to your server rather then typing that password, you can follow this : http://fortrabbit.com/docs/how-to/ssh-sftp/enable-public-key-authentication

differences in application/json and application/x-www-form-urlencoded

webRequest.ContentType = "application/x-www-form-urlencoded";

  1. Where does application/x-www-form-urlencoded's name come from?

    If you send HTTP GET request, you can use query parameters as follows:

    http://example.com/path/to/page?name=ferret&color=purple

    The content of the fields is encoded as a query string. The application/x-www-form- urlencoded's name come from the previous url query parameter but the query parameters is in where the body of request instead of url.

    The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character

    e.g. field1=value1&field2=value2

  2. It can be simple request called simple - don't trigger a preflight check

    Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests

    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.

request.ContentType = "application/json; charset=utf-8";

  1. The data will be json format.

axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.

{
  "id": 1,
  "name": "Foo",
  "price": 123,
  "tags": [
    "Bar",
    "Eek"
  ],
  "stock": {
    "warehouse": 300,
    "retail": 20
  }
}
  1. "application/json" Content-Type is one of the Preflighted requests.

Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.

  1. application/json is beginner-friendly. URL encoded arrays can be a nightmare!

C# DateTime to UTC Time without changing the time

Use the DateTime.SpecifyKind static method.

Creates a new DateTime object that has the same number of ticks as the specified DateTime, but is designated as either local time, Coordinated Universal Time (UTC), or neither, as indicated by the specified DateTimeKind value.

Example:

DateTime dateTime = DateTime.Now;
DateTime other = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);

Console.WriteLine(dateTime + " " + dateTime.Kind); // 6/1/2011 4:14:54 PM Local
Console.WriteLine(other + " " + other.Kind);       // 6/1/2011 4:14:54 PM Utc

Proper usage of Java -D command-line parameters

That should be:

java -Dtest="true" -jar myApplication.jar

Then the following will return the value:

System.getProperty("test");

The value could be null, though, so guard against an exception using a Boolean:

boolean b = Boolean.parseBoolean( System.getProperty( "test" ) );

Note that the getBoolean method delegates the system property value, simplifying the code to:

if( Boolean.getBoolean( "test" ) ) {
   // ...
}

Select distinct using linq

You should override Equals and GetHashCode meaningfully, in this case to compare the ID:

public class LinqTest
{
    public int id { get; set; }
    public string value { get; set; }

    public override bool Equals(object obj)
    {
        LinqTest obj2 = obj as LinqTest;
        if (obj2 == null) return false;
        return id == obj2.id;
    }

    public override int GetHashCode()
    {
        return id;
    }
}

Now you can use Distinct:

List<LinqTest> uniqueIDs = myList.Distinct().ToList();

Extracting extension from filename in Python

New in version 3.4.

import pathlib

print(pathlib.Path('yourPath.example').suffix) # '.example'

I'm surprised no one has mentioned pathlib yet, pathlib IS awesome!

If you need all the suffixes (eg if you have a .tar.gz), .suffixes will return a list of them!

Return JSON for ResponseEntity<String>

An alternative solution is to use a wrapper for the String, for instances this:

public class StringResponse {
    private String response;
    public StringResponse(String response) {
        this.response = response;
    }
    public String getResponse() {
        return response;
    }
}

Then return this in your controller's methods:

ResponseEntity<StringResponse>

Hiding a button in Javascript

<script>
    $('#btn_hide').click( function () {
      $('#btn_hide').hide();
    });
</script>
<input type="button" id="btn_hide"/>

this will be enough

What are the main performance differences between varchar and nvarchar SQL Server data types?

There'll be exceptional instances when you'll want to deliberately restrict the data type to ensure it doesn't contain characters from a certain set. For example, I had a scenario where I needed to store the domain name in a database. Internationalisation for domain names wasn't reliable at the time so it was better to restrict the input at the base level, and help to avoid any potential issues.

Delete a closed pull request from GitHub

5 step to do what you want if you made the pull request from a forked repository:

  1. reopen the pull request
  2. checkout to the branch which you made the pull request
  3. reset commit to the last master commit(that means remove all you new code)
  4. git push --force
  5. delete your forked repository which made the pull request

And everything is done, good luck!

Does JavaScript guarantee object property order?

The iteration order for objects follows a certain set of rules since ES2015, but it does not (always) follow the insertion order. Simply put, the iteration order is a combination of the insertion order for strings keys, and ascending order for number-like keys:

// key order: 1, foo, bar
const obj = { "foo": "foo", "1": "1", "bar": "bar" }

Using an array or a Map object can be a better way to achieve this. Map shares some similarities with Object and guarantees the keys to be iterated in order of insertion, without exception:

The keys in Map are ordered while keys added to object are not. Thus, when iterating over it, a Map object returns keys in order of insertion. (Note that in the ECMAScript 2015 spec objects do preserve creation order for string and Symbol keys, so traversal of an object with ie only string keys would yield keys in order of insertion)

As a note, properties order in objects weren’t guaranteed at all before ES2015. Definition of an Object from ECMAScript Third Edition (pdf):

4.3.3 Object

An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

'' is not recognized as an internal or external command, operable program or batch file

When you want to run an executable file from the Command prompt, (cmd.exe), or a batch file, it will:

  • Search the current working directory for the executable file.
  • Search all locations specified in the %PATH% environment variable for the executable file.

If the file isn't found in either of those options you will need to either:

  1. Specify the location of your executable.
  2. Change the working directory to that which holds the executable.
  3. Add the location to %PATH% by apending it, (recommended only with extreme caution).

You can see which locations are specified in %PATH% from the Command prompt, Echo %Path%.

Because of your reported error we can assume that Mobile.exe is not in the current directory or in a location specified within the %Path% variable, so you need to use 1., 2. or 3..

Examples for 1.

C:\directory_path_without_spaces\My-App\Mobile.exe

or:

"C:\directory path with spaces\My-App\Mobile.exe"

Alternatively you may try:

Start C:\directory_path_without_spaces\My-App\Mobile.exe

or

Start "" "C:\directory path with spaces\My-App\Mobile.exe"

Where "" is an empty title, (you can optionally add a string between those doublequotes).

Examples for 2.

CD /D C:\directory_path_without_spaces\My-App
Mobile.exe

or

CD /D "C:\directory path with spaces\My-App"
Mobile.exe

You could also use the /D option with Start to change the working directory for the executable to be run by the start command

Start /D C:\directory_path_without_spaces\My-App Mobile.exe

or

Start "" /D "C:\directory path with spaces\My-App" Mobile.exe

How to decrypt a password from SQL server?

I believe pwdencrypt is using a hash so you cannot really reverse the hashed string - the algorithm is designed so it's impossible.

If you are verifying the password that a user entered the usual technique is to hash it and then compare it to the hashed version in the database.

This is how you could verify a usered entered table

SELECT password_field FROM mytable WHERE password_field=pwdencrypt(userEnteredValue)

Replace userEnteredValue with (big surprise) the value that the user entered :)

Auto-size dynamic text to fill fixed size container

Here's an improved looping method that uses binary search to find the largest possible size that fits into the parent in the fewest steps possible (this is faster and more accurate than stepping by a fixed font size). The code is also optimized in several ways for performance.

By default, 10 binary search steps will be performed, which will get within 0.1% of the optimal size. You could instead set numIter to some value N to get within 1/2^N of the optimal size.

Call it with a CSS selector, e.g.: fitToParent('.title-span');

/**
 * Fit all elements matching a given CSS selector to their parent elements'
 * width and height, by adjusting the font-size attribute to be as large as
 * possible. Uses binary search.
 */
var fitToParent = function(selector) {
    var numIter = 10;  // Number of binary search iterations
    var regexp = /\d+(\.\d+)?/;
    var fontSize = function(elem) {
        var match = elem.css('font-size').match(regexp);
        var size = match == null ? 16 : parseFloat(match[0]);
        return isNaN(size) ? 16 : size;
    }
    $(selector).each(function() {
        var elem = $(this);
        var parentWidth = elem.parent().width();
        var parentHeight = elem.parent().height();
        if (elem.width() > parentWidth || elem.height() > parentHeight) {
            var maxSize = fontSize(elem), minSize = 0.1;
            for (var i = 0; i < numIter; i++) {
                var currSize = (minSize + maxSize) / 2;
                elem.css('font-size', currSize);
                if (elem.width() > parentWidth || elem.height() > parentHeight) {
                    maxSize = currSize;
                } else {
                    minSize = currSize;
                }
            }
            elem.css('font-size', minSize);
        }
    });
};

HTML set image on browser tab

<link rel="SHORTCUT ICON" href="favicon.ico" type="image/x-icon" />
<link rel="ICON" href="favicon.ico" type="image/ico" />

Excellent tool for cross-browser favicon - http://www.convertico.com/

How to find current transaction level?

SELECT CASE  
          WHEN transaction_isolation_level = 1 
             THEN 'READ UNCOMMITTED' 
          WHEN transaction_isolation_level = 2 
               AND is_read_committed_snapshot_on = 1 
             THEN 'READ COMMITTED SNAPSHOT' 
          WHEN transaction_isolation_level = 2 
               AND is_read_committed_snapshot_on = 0 THEN 'READ COMMITTED' 
          WHEN transaction_isolation_level = 3 
             THEN 'REPEATABLE READ' 
          WHEN transaction_isolation_level = 4 
             THEN 'SERIALIZABLE' 
          WHEN transaction_isolation_level = 5 
             THEN 'SNAPSHOT' 
          ELSE NULL
       END AS TRANSACTION_ISOLATION_LEVEL 
FROM   sys.dm_exec_sessions AS s
       CROSS JOIN sys.databases AS d
WHERE  session_id = @@SPID
  AND  d.database_id = DB_ID();

Can't escape the backslash with regex?

This solution fixed my problem while replacing br tag to '\n' .

alert(content.replace(/<br\/\>/g,'\n'));

Generate war file from tomcat webapp folder

There is a way to create war file of your project from eclipse.

First a create an xml file with the following code,

Replace HistoryCheck with your project name.

<?xml version="1.0" encoding="UTF-8"?>
<project name="HistoryCheck" basedir="." default="default">
    <target name="default" depends="buildwar,deploy"></target>
    <target name="buildwar">
        <war basedir="war" destfile="HistoryCheck.war" webxml="war/WEB-INF/web.xml">
            <exclude name="WEB-INF/**" />
            <webinf dir="war/WEB-INF/">
                <include name="**/*.jar" />
            </webinf>
        </war>
    </target>
    <target name="deploy">
        <copy file="HistoryCheck.war" todir="." />
    </target>
</project>

Now, In project explorer right click on that xml file and Run as-> ant build

You can see the war file of your project in your project folder.

How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

You can access any LayoutParams from code using View.getLayoutParams. You just have to be very aware of what LayoutParams your accessing. This is normally achieved by checking the containing ViewGroup if it has a LayoutParams inner child then that's the one you should use. In your case it's RelativeLayout.LayoutParams. You'll be using RelativeLayout.LayoutParams#addRule(int verb) and RelativeLayout.LayoutParams#addRule(int verb, int anchor)

You can get to it via code:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)button.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.LEFT_OF, R.id.id_to_be_left_of);

button.setLayoutParams(params); //causes layout update

Pass accepts header parameter to jquery ajax

You had already identified the accepts parameter as the one you wanted and keyur is right in showing you the correct way to set it, but if you set DataType to "json" then it will automatically set the default value of accepts to the value you want as per the jQuery reference. So all you need is:

jQuery.ajax({
    url: _this.attr('href'),
    dataType: "json"
});

Prevent cell numbers from incrementing in a formula in Excel

There is something called 'locked reference' in excel which you can use for this, and you use $ symbols to lock a range. For your example, you would use:

=IF(B4<>"",B4/B$1,"")

This locks the 1 in B1 so that when you copy it to rows below, 1 will remain the same.

If you use $B$1, the range will not change when you copy it down a row or across a column.

Clang vs GCC for my Linux Development project

For student level programs, Clang has the benefit that it is, by default, stricter wrt. the C standard. For example, the following K&R version of Hello World is accepted without warning by GCC, but rejected by Clang with some pretty descriptive error messages:

main()
{
    puts("Hello, world!");
}

With GCC, you have to give it -Werror to get it to really make a point about this not being a valid C89 program. Also, you still need to use c99 or gcc -std=c99 to get the C99 language.

Resize Cross Domain Iframe Height

It is only possible to do this cross domain if you have access to implement JS on both domains. If you have that, then here is a little library that solves all the problems with sizing iFrames to their contained content.

https://github.com/davidjbradshaw/iframe-resizer

It deals with the cross domain issue by using the post-message API, and also detects changes to the content of the iFrame in a few different ways.

Works in all modern browsers and IE8 upwards.

jQuery UI - Close Dialog When Clicked Outside

It's simple actually you don't need any plugins, just jquery or you can do it with simple javascript.

$('#dialog').on('click', function(e){
  e.stopPropagation();
});
$(document.body).on('click', function(e){
  master.hide();
});

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

If you want a table where only the columns scroll horizontally, you can position: absolute the first column (and specify its width explicitly), and then wrap the entire table in an overflow-x: scroll block. Don't bother trying this in IE7, however...

Relevant HTML & CSS:

_x000D_
_x000D_
table {_x000D_
  border-collapse: separate;_x000D_
  border-spacing: 0;_x000D_
  border-top: 1px solid grey;_x000D_
}_x000D_
_x000D_
td, th {_x000D_
  margin: 0;_x000D_
  border: 1px solid grey;_x000D_
  white-space: nowrap;_x000D_
  border-top-width: 0px;_x000D_
}_x000D_
_x000D_
div {_x000D_
  width: 500px;_x000D_
  overflow-x: scroll;_x000D_
  margin-left: 5em;_x000D_
  overflow-y: visible;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
.headcol {_x000D_
  position: absolute;_x000D_
  width: 5em;_x000D_
  left: 0;_x000D_
  top: auto;_x000D_
  border-top-width: 1px;_x000D_
  /*only relevant for first row*/_x000D_
  margin-top: -1px;_x000D_
  /*compensate for top border*/_x000D_
}_x000D_
_x000D_
.headcol:before {_x000D_
  content: 'Row ';_x000D_
}_x000D_
_x000D_
.long {_x000D_
  background: yellow;_x000D_
  letter-spacing: 1em;_x000D_
}
_x000D_
<div>_x000D_
<table>_x000D_
        <tr><th class="headcol">1</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
        <tr><th class="headcol">2</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
        <tr><th class="headcol">3</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
        <tr><th class="headcol">4</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
        <tr><th class="headcol">5</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
        <tr><th class="headcol">6</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
</table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

I am using dateformat at Nodejs and angularjs, so good

install

$ npm install dateformat
$ dateformat --help

demo

var dateFormat = require('dateformat');
var now = new Date();

// Basic usage
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM

// You can use one of several named masks
dateFormat(now, "isoDateTime");
// 2007-06-09T17:46:21

// ...Or add your own
dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';
dateFormat(now, "hammerTime");
// 17:46! Can't touch this!

// You can also provide the date as a string
dateFormat("Jun 9 2007", "fullDate");
// Saturday, June 9, 2007
...

How to rename a class and its corresponding file in Eclipse?

Just right click on the class in the project explorer and select "Refactor" -> "Rename". That it is is under the "Refactor" submenu.

Spark - SELECT WHERE or filtering?

As Yaron mentioned, there isn't any difference between where and filter.

filter is an overloaded method that takes a column or string argument. The performance is the same, regardless of the syntax you use.

filter overloaded method

We can use explain() to see that all the different filtering syntaxes generate the same Physical Plan. Suppose you have a dataset with person_name and person_country columns. All of the following code snippets will return the same Physical Plan below:

df.where("person_country = 'Cuba'").explain()
df.where($"person_country" === "Cuba").explain()
df.where('person_country === "Cuba").explain()
df.filter("person_country = 'Cuba'").explain()

These all return this Physical Plan:

== Physical Plan ==
*(1) Project [person_name#152, person_country#153]
+- *(1) Filter (isnotnull(person_country#153) && (person_country#153 = Cuba))
   +- *(1) FileScan csv [person_name#152,person_country#153] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:/Users/matthewpowers/Documents/code/my_apps/mungingdata/spark2/src/test/re..., PartitionFilters: [], PushedFilters: [IsNotNull(person_country), EqualTo(person_country,Cuba)], ReadSchema: struct<person_name:string,person_country:string>

The syntax doesn't change how filters are executed under the hood, but the file format / database that a query is executed on does. Spark will execute the same query differently on Postgres (predicate pushdown filtering is supported), Parquet (column pruning), and CSV files. See here for more details.

Android: How to stretch an image to the screen width while maintaining aspect ratio?

This working fine as per my requirement

<ImageView android:id="@+id/imgIssue" android:layout_width="fill_parent" android:layout_height="wrap_content" android:adjustViewBounds="true" android:scaleType="fitXY"/>

How to add new column to an dataframe (to the front not end)?

The previous answers show 3 approaches

  1. By creating a new data frame
  2. By using "cbind"
  3. By adding column "a", and sort data frame by columns using column names or indexes

Let me show #4 approach "By using "cbind" and "rename" that works for my case

1. Create data frame

df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))

2. Get values for "new" column

new_column = c(0, 0, 0)

3. Combine "new" column with existed

df <- cbind(new_column, df)

4. Rename "new" column name

colnames(df)[1] <- "a"

No generated R.java file in my project

I just had a problem where a previously working project stopped working with everything that referenced R being posted as errors because R.java was not being generated.

** * CHECK THE CONSOLE VIEW TOO **

I had (using finder) made a backup of the main icon (not even used) so one of the res folders (hdpi) had

icon.png copy of icon.png

Console indicated that "copy of icon.png" was not a valid file name. No errors were flagged anywhere else - no red X in the res folders....

but replacing the spaces with "_" and it is all back to normal....

Remove all occurrences of a value from a list?

Remove all occurrences of a value from a Python list

lists = [6.9,7,8.9,3,5,4.9,1,2.9,7,9,12.9,10.9,11,7]
def remove_values_from_list():
    for list in lists:
      if(list!=7):
         print(list)
remove_values_from_list()

Result: 6.9 8.9 3 5 4.9 1 2.9 9 12.9 10.9 11

Alternatively,

lists = [6.9,7,8.9,3,5,4.9,1,2.9,7,9,12.9,10.9,11,7]
def remove_values_from_list(remove):
    for list in lists:
      if(list!=remove):
        print(list)
remove_values_from_list(7)

Result: 6.9 8.9 3 5 4.9 1 2.9 9 12.9 10.9 11

How to checkout a specific Subversion revision from the command line?

You could try

TortoiseProc.exe /command:checkout /rev:1234

to get revision 1234.

I'm not 100% sure the /rev option is compatible with checkout, but I got the idea from some TortoiseProc documentation.

Convert Java Date to UTC String

If XStream is a dependency, try:

new com.thoughtworks.xstream.converters.basic.DateConverter().toString(date)

How to close TCP and UDP ports via windows command line

Yes, this is possible. You don't have to be the current process owning the socket to close it. Consider for a moment that the remote machine, the network card, the network cable, and your OS can all cause the socket to close.

Consider also that Fiddler and Desktop VPN software can insert themselves into the network stack and show you all your traffic or reroute all your traffic.

So all you really need is either for Windows to provide an API that allows this directly, or for someone to have written a program that operates somewhat like a VPN or Fiddler and gives you a way to close sockets that pass through it.

There is at least one program (CurrPorts) that does exactly this and I used it today for the purpose of closing specific sockets on a process that was started before CurrPorts was started. To do this you must run it as administrator, of course.

Note that it is probably not easily possible to cause a program to not listen on a port (well, it is possible but that capability is referred to as a firewall...), but I don't think that was being asked here. I believe the question is "how do I selectively close one active connection (socket) to the port my program is listening on?". The wording of the question is a bit off because a port number for the undesired inbound client connection is given and it was referred to as "port" but it's pretty clear that it was a reference to that one socket and not the listening port.

How do you run a script on login in *nix?

If you wish to run one script and only one script, you can make it that users default shell.

echo "/usr/bin/uptime" >> /etc/shells
vim /etc/passwd  
  * username:x:uid:grp:message:homedir:/usr/bin/uptime

can have interesting effects :) ( its not secure tho, so don't trust it too much. nothing like setting your default shell to be a script that wipes your drive. ... although, .. I can imagine a scenario where that could be amazingly useful )

how to destroy bootstrap modal window completely?

If modal shadow remains darker and not going for showing more than one modal then this will be helpful

$('.modal').live('hide',function(){
    if($('.modal-backdrop').length>1){
        $('.modal-backdrop')[0].remove();
    }
});

MongoDB Show all contents from all collections

I prefer another approach if you are using mongo shell:

First as the another answers: use my_database_name then:

db.getCollectionNames().map( (name) => ({[name]: db[name].find().toArray().length}) )

This query will show you something like this:

[
        {
                "agreements" : 60
        },
        {
                "libraries" : 45
        },
        {
                "templates" : 9
        },
        {
                "users" : 19
        }
]

You can use similar approach with db.getCollectionInfos() it is pretty useful if you have so much data & helpful as well.

What are metaclasses in Python?

I think the ONLamp introduction to metaclass programming is well written and gives a really good introduction to the topic despite being several years old already.

http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html (archived at https://web.archive.org/web/20080206005253/http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html)

In short: A class is a blueprint for the creation of an instance, a metaclass is a blueprint for the creation of a class. It can be easily seen that in Python classes need to be first-class objects too to enable this behavior.

I've never written one myself, but I think one of the nicest uses of metaclasses can be seen in the Django framework. The model classes use a metaclass approach to enable a declarative style of writing new models or form classes. While the metaclass is creating the class, all members get the possibility to customize the class itself.

The thing that's left to say is: If you don't know what metaclasses are, the probability that you will not need them is 99%.

Update Item to Revision vs Revert to Revision

The text from the Tortoise reference:

Update item to revision Update your working copy to the selected revision. Useful if you want to have your working copy reflect a time in the past, or if there have been further commits to the repository and you want to update your working copy one step at a time. It is best to update a whole directory in your working copy, not just one file, otherwise your working copy could be inconsistent.

If you want to undo an earlier change permanently, use Revert to this revision instead.

Revert to this revision Revert to an earlier revision. If you have made several changes, and then decide that you really want to go back to how things were in revision N, this is the command you need. The changes are undone in your working copy so this operation does not affect the repository until you commit the changes. Note that this will undo all changes made after the selected revision, replacing the file/folder with the earlier version.

If your working copy is in an unmodified state, after you perform this action your working copy will show as modified. If you already have local changes, this command will merge the undo changes into your working copy.

What is happening internally is that Subversion performs a reverse merge of all the changes made after the selected revision, undoing the effect of those previous commits.

If after performing this action you decide that you want to undo the undo and get your working copy back to its previous unmodified state, you should use TortoiseSVN ? Revert from within Windows Explorer, which will discard the local modifications made by this reverse merge action.

If you simply want to see what a file or folder looked like at an earlier revision, use Update to revision or Save revision as... instead.

Running a command as Administrator using PowerShell?

Here's a self-elevating snippet for Powershell scripts which preserves the working directory:

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"";
    exit;
}

# Your script here

Preserving the working directory is important for scripts that perform path-relative operations. Almost all of the other answers do not preserve this path, which can cause unexpected errors in the rest of the script.

If you'd rather not use a self-elevating script/snippet, and instead just want an easy way to launch a script as adminstrator (eg. from the Explorer context-menu), see my other answer here: https://stackoverflow.com/a/57033941/2441655

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(),script,  true );

The "true" param value at the end of the ScriptManager.RegisterStartupScript will add a JavaScript tag inside your page:

<script language='javascript' defer='defer'>your script</script >

If the value will be "false" it will inject only the script witout the --script-- tag.

Getting the first character of a string with $str[0]

The {} syntax is deprecated as of PHP 5.3.0. Square brackets are recommended.

Assign format of DateTime with data annotations?

Apply DataAnnotation like:

[DisplayFormat(DataFormatString = "{0:MMM dd, yyyy}")]

Jackson serialization: ignore empty values (or null)

I was having similar problem recently with version 2.6.6.

@JsonInclude(JsonInclude.Include.NON_NULL)

Using above annotation either on filed or class level was not working as expected. The POJO was mutable where I was applying the annotation. When I changed the behaviour of the POJO to be immutable the annotation worked its magic.

I am not sure if its down to new version or previous versions of this lib had similar behaviour but for 2.6.6 certainly you need to have Immutable POJO for the annotation to work.

objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

Above option mentioned in various answers of setting serialisation inclusion in ObjectMapper directly at global level works as well but, I prefer controlling it at class or filed level.

So if you wanted all the null fields to be ignored while JSON serialisation then use the annotation at class level but if you want only few fields to ignored in a class then use it over those specific fields. This way its more readable & easy for maintenance if you wanted to change behaviour for specific response.

What's "this" in JavaScript onclick?

Here (this) is a object which contains all features/properties of the dom element. you can see by

console.log(this);

This will display all attributes properties of the dom element with hierarchy. You can manipulate the dom element by this.

Also describe on the below link:-

http://www.quirksmode.org/js/this.html

Routing with multiple Get methods in ASP.NET Web API

There are lots of good answers already for this question. However nowadays Route configuration is sort of "deprecated". The newer version of MVC (.NET Core) does not support it. So better to get use to it :)

So I agree with all the answers which uses Attribute style routing. But I keep noticing that everyone repeated the base part of the route (api/...). It is better to apply a [RoutePrefix] attribute on top of the Controller class and don't repeat the same string over and over again.

[RoutePrefix("api/customers")]
public class MyController : Controller
{
 [HttpGet]
 public List<Customer> Get()
 {
   //gets all customer logic
 }

 [HttpGet]
 [Route("currentMonth")]
 public List<Customer> GetCustomerByCurrentMonth()
 {
     //gets some customer 
 }

 [HttpGet]
 [Route("{id}")]
 public Customer GetCustomerById(string id)
 {
  //gets a single customer by specified id
 }
 [HttpGet]
 [Route("customerByUsername/{username}")]
 public Customer GetCustomerByUsername(string username)
 {
    //gets customer by its username
 }
}

Passing parameter via url to sql server reporting service

As per this link you may also have to prefix your param with &rp if not using proxy syntax

iOS8 Beta Ad-Hoc App Download (itms-services)

Specify a 'display-image' and 'full-size-image' as described here: http://www.informit.com/articles/article.aspx?p=1829415&seqNum=16

iOS8 requires these images

Purge Kafka Topic

Could not add as comment because of size: Not sure if this is true, besides updating retention.ms and retention.bytes, but I noticed topic cleanup policy should be "delete" (default), if "compact", it is going to hold on to messages longer, i.e., if it is "compact", you have to specify delete.retention.ms also.

./bin/kafka-configs.sh --zookeeper localhost:2181 --describe --entity-name test-topic-3-100 --entity-type topics
Configs for topics:test-topic-3-100 are retention.ms=1000,delete.retention.ms=10000,cleanup.policy=delete,retention.bytes=1

Also had to monitor earliest/latest offsets should be same to confirm this successfully happened, can also check the du -h /tmp/kafka-logs/test-topic-3-100-*

./bin/kafka-run-class.sh kafka.tools.GetOffsetShell --broker-list "BROKER:9095" --topic test-topic-3-100 --time -1 | awk -F ":" '{sum += $3} END {print sum}' 26599762

./bin/kafka-run-class.sh kafka.tools.GetOffsetShell --broker-list "BROKER:9095" --topic test-topic-3-100 --time -2 | awk -F ":" '{sum += $3} END {print sum}' 26599762

The other problem is, you have to get current config first so you remember to revert after deletion is successful: ./bin/kafka-configs.sh --zookeeper localhost:2181 --describe --entity-name test-topic-3-100 --entity-type topics

Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery

simply we can check e.relatedTarget has child class and if true return the function.

    if ($(e.relatedTarget).hasClass("ctrl-btn")){
        return;
    }

this is code worked for me, i used for html5 video play,pause button toggle hover video element

element.on("mouseover mouseout", function(e) {

    if(e.type === "mouseout"){

        if ($(e.relatedTarget).hasClass("child-class")){
            return;
        }

    }

});

Swift_TransportException Connection could not be established with host smtp.gmail.com

If you have hosted your website already it advisable to use the email or create an offical mail to send the email Let say your url is www.example.com. Then go to the cpanel create an email which will be [email protected]. Then request for the setting of the email. Change the email address to [email protected]. Then change your smtp which will be mail.example.com. The ssl will remain 465

Pass element ID to Javascript function

In jsFiddle by default the code you type into the script block is wrapped in a function executed on window.onload:

<script type='text/javascript'>//<![CDATA[ 
    window.onload = function () {
        function myFunc(id){
            alert(id);     
        }
    }
//]]>  
</script>

Because of this, your function myFunc is not in the global scope so is not available to your html buttons. By changing the option to No-wrap in <head> as Sergio suggests your code isn't wrapped:

<script type='text/javascript'>//<![CDATA[ 
    function myFunc(id){
       alert(id);     
    }
//]]>  
</script>

and so the function is in the global scope and available to your html buttons.

git - remote add origin vs remote set-url origin

below is used to a add a new remote:

git remote add origin [email protected]:User/UserRepo.git

below is used to change the url of an existing remote repository:

git remote set-url origin [email protected]:User/UserRepo.git

below will push your code to the master branch of the remote repository defined with origin and -u let you point your current local branch to the remote master branch:

git push -u origin master

Documentation

How to set button click effect in Android?

Create bounce.xml file for animation

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <scale
        android:duration="100"
        android:fromXScale="0.9"
        android:fromYScale="0.9"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="1.0"
        android:toYScale="1.0" />

</set>

Add this line in onClick to initialize

final Animation myAnim = AnimationUtils.loadAnimation(this, R.anim.bounce); button.startAnimation(myAnim);

You get the shrink effect in a button click.

Git : fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists

This usually happens when you use two ssh keys to access two different GitHub account.

Follow these steps to fix this it look too long but trust me it won't take more than 5 minutes:

Step-1: Create two ssh key pairs:

ssh-keygen -t rsa -C "[email protected]"

Step-2: It will create two ssh keys here:

~/.ssh/id_rsa_account1
~/.ssh/id_rsa_account2

Step-3: Now we need to add these keys:

ssh-add ~/.ssh/id_rsa_account2
ssh-add ~/.ssh/id_rsa_account1
  • You can see the added keys list by using this command: ssh-add -l
  • You can remove old cached keys by this command: ssh-add -D

Step-4: Modify the ssh config

cd ~/.ssh/
touch config

subl -a config or code config or nano config

Step-5: Add this to config file:

#Github account1
Host github.com-account1
    HostName github.com
    User account1
    IdentityFile ~/.ssh/id_rsa_account1

#Github account2
Host github.com-account2
    HostName github.com
    User account2
    IdentityFile ~/.ssh/id_rsa_account2

Step-6: Update your .git/config file:

Step-6.1: Navigate to account1's project and update host:

[remote "origin"]
        url = [email protected]:account1/gfs.git

If you are invited by some other user in their git Repository. Then you need to update the host like this:

[remote "origin"]
            url = [email protected]:invitedByUserName/gfs.git

Step-6.2: Navigate to account2's project and update host:

[remote "origin"]
        url = [email protected]:account2/gfs.git

Step-7: Update user name and email for each repository separately if required this is not an amendatory step:

Navigate to account1 project and run these:

git config user.name "account1"
git config user.email "[email protected]" 

Navigate to account2 project and run these:

git config user.name "account2"
git config user.email "[email protected]" 

How to Create a real one-to-one relationship in SQL Server

I'm pretty sure it is technically impossible in SQL Server to have a True 1 to 1 relationship, as that would mean you would have to insert both records at the same time (otherwise you'd get a constraint error on insert), in both tables, with both tables having a foreign key relationship to each other.

That being said, your database design described with a foreign key is a 1 to 0..1 relationship. There is no constrain possible that would require a record in tableB. You can have a pseudo-relationship with a trigger that creates the record in tableB.

So there are a few pseudo-solutions

First, store all the data in a single table. Then you'll have no issues in EF.

Or Secondly, your entity must be smart enough to not allow an insert unless it has an associated record.

Or thirdly, and most likely, you have a problem you are trying to solve, and you are asking us why your solution doesn't work instead of the actual problem you are trying to solve (an XY Problem).

UPDATE

To explain in REALITY how 1 to 1 relationships don't work, I'll use the analogy of the Chicken or the egg dilemma. I don't intend to solve this dilemma, but if you were to have a constraint that says in order to add a an Egg to the Egg table, the relationship of the Chicken must exist, and the chicken must exist in the table, then you couldn't add an Egg to the Egg table. The opposite is also true. You cannot add a Chicken to the Chicken table without both the relationship to the Egg and the Egg existing in the Egg table. Thus no records can be every made, in a database without breaking one of the rules/constraints.

Database nomenclature of a one-to-one relationship is misleading. All relationships I've seen (there-fore my experience) would be more descriptive as one-to-(zero or one) relationships.

"unmappable character for encoding" warning in Java

This worked for me -

    <?xml version="1.0" encoding="utf-8" ?>
<project name="test" default="compile">
    <target name="compile">
        <javac srcdir="src" destdir="classes" 
                           encoding="iso-8859-1" debug="true" />
    </target>
</project>

How to set standard encoding in Visual Studio

What

It is possible with EditorConfig.

EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs.

This also includes file encoding.

EditorConfig is built-in Visual Studio 2017 by default, and I there were plugins available for versions as old as VS2012. Read more from EditorConfig Visual Studio Plugin page.

How

You can set up a EditorConfig configuration file high enough in your folder structure to span all your intended repos (up to your drive root should your files be really scattered everywhere) and configure the setting charset:

charset: set to latin1, utf-8, utf-8-bom, utf-16be or utf-16le to control the character set.

You can add filters and exceptions etc on every folder level or by file name/type should you wish for finer control.

Once configured then compatible IDEs should automatically do it's thing to make matching files comform to set rules. Note that Visual Studio does not automatically convert all your files but do its bit when you work with files in IDE (open and save).

What next

While you could have a Visual-studio-wide setup, I strongly suggest to still include an EditorConfig root to your solution version control, so that explicit settings are automatically synced to all team members as well. Your drive root editorconfig file can be the fallback should some project not have their own editorconfig files set up yet.

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

You module and class AthleteList have the same name. Change:

import AthleteList

to:

from AthleteList import AthleteList

This now means that you are importing the module object and will not be able to access any module methods you have in AthleteList

Understanding the main method of python

Python does not have a defined entry point like Java, C, C++, etc. Rather it simply executes a source file line-by-line. The if statement allows you to create a main function which will be executed if your file is loaded as the "Main" module rather than as a library in another module.

To be clear, this means that the Python interpreter starts at the first line of a file and executes it. Executing lines like class Foobar: and def foobar() creates either a class or a function and stores them in memory for later use.

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist


Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit


There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

Javascript onclick hide div

just add onclick handler for anchor tag

onclick="this.parentNode.style.display = 'none'"

or change onclick handler for img tag

onclick="this.parentNode.parentNode.style.display = 'none'"

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted

I had everything fine. Less secure app option was also enabled. Still, I was getting the error. What I have done is:

  • Google will send you Critical security alert
  • Then you have to authorize that activity. ( Clicking on 'YES, THAT WAS ME' type thing )
  • Then you can try sending email again.

nano error: Error opening terminal: xterm-256color

I, too, have this problem on an older Mac that I upgraded to Lion.

Before reading the terminfo tip, I was able to get vi and less working by doing "export TERM=xterm".

After reading the tip, I grabbed /usr/share/terminfo from a newer Mac that has fresh install of Lion and does not exhibit this problem.

Now, even though echo $TERM still yields xterm-256color, vi and less now work fine.

Escape quotes in JavaScript

You need to escape the string you are writing out into DoEdit to scrub out the double-quote characters. They are causing the onclick HTML attribute to close prematurely.

Using the JavaScript escape character, \, isn't sufficient in the HTML context. You need to replace the double-quote with the proper XML entity representation, &quot;.

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

How to register multiple servlets in web.xml in one Spring application

Use config something like this:

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
  <servlet-name>myservlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet>
  <servlet-name>user-webservice</servlet-name>
  <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  <load-on-startup>2</load-on-startup>
</servlet>

and then you'll need three files:

  • applicationContext.xml;
  • myservlet-servlet.xml; and
  • user-webservice-servlet.xml.

The *-servlet.xml files are used automatically and each creates an application context for that servlet.

From the Spring documentation, 13.2. The DispatcherServlet:

The framework will, on initialization of a DispatcherServlet, look for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and create the beans defined there (overriding the definitions of any beans defined with the same name in the global scope).

Is there a command line utility for rendering GitHub flavored Markdown?

Another option is AllMark - the markdown server.
Docker images available for ready-to-go setup.

$ allmark serve .

Note: It recursively scans directories to serve website from markdown files. So for faster processing of single file, move it to a separate directory.

Javascript setInterval not working

Change setInterval("func",10000) to either setInterval(funcName, 10000) or setInterval("funcName()",10000). The former is the recommended method.

Regex to extract substring, returning 2 results for some reason

I think your problem is that the match method is returning an array. The 0th item in the array is the original string, the 1st thru nth items correspond to the 1st through nth matched parenthesised items. Your "alert()" call is showing the entire array.

event.preventDefault() function not working in IE

return false in your listener should work in all browsers.

$('orderNowForm').addEvent('submit', function () {
    // your code
    return false;
}