Programs & Examples On #Intuit

Intuit is a software company based in Mountain View, California. It is the developer of Tax products for consumers and professionals (TurboTax, ProTax) as well as Small Business and Personal Finance management solutions (QuickBooks, Mint).

Accessing AppDelegate from framework?

If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

The binary_crossentropy(y_target, y_predict) doesn't need to apply in binary classification problem. .

In the source code of binary_crossentropy(), the nn.sigmoid_cross_entropy_with_logits(labels=target, logits=output) TensorFlow function was actually used. And, in the documentation, it says that:

Measures the probability error in discrete classification tasks in which each class is independent and not mutually exclusive. For instance, one could perform multilabel classification where a picture can contain both an elephant and a dog at the same time.

Adding default parameter value with type hint in Python

Your second way is correct.

def foo(opts: dict = {}):
    pass

print(foo.__annotations__)

this outputs

{'opts': <class 'dict'>}

It's true that's it's not listed in PEP 484, but type hints are an application of function annotations, which are documented in PEP 3107. The syntax section makes it clear that keyword arguments works with function annotations in this way.

I strongly advise against using mutable keyword arguments. More information here.

How to hide a mobile browser's address bar?

This should be the code you need to hide the address bar:

window.addEventListener("load",function() {
    setTimeout(function(){
        // This hides the address bar:
        window.scrollTo(0, 1);
    }, 0);
});

Also nice looking Pokedex by the way! Hope this helps!

REST API - file (ie images) processing - best practices

Your second solution is probably the most correct. You should use the HTTP spec and mimetypes the way they were intended and upload the file via multipart/form-data. As far as handling the relationships, I'd use this process (keeping in mind I know zero about your assumptions or system design):

  1. POST to /users to create the user entity.
  2. POST the image to /images, making sure to return a Location header to where the image can be retrieved per the HTTP spec.
  3. PATCH to /users/carPhoto and assign it the ID of the photo given in the Location header of step 2.

Best way to get the max value in a Spark dataframe column

I used another solution (by @satprem rath) already present in this chain.

To find the min value of age in the dataframe:

df.agg(min("age")).show()

+--------+
|min(age)|
+--------+
|      29|
+--------+

edit: to add more context.

While the above method printed the result, I faced issues when assigning the result to a variable to reuse later.

Hence, to get only the int value assigned to a variable:

from pyspark.sql.functions import max, min  

maxValueA = df.agg(max("A")).collect()[0][0]
maxValueB = df.agg(max("B")).collect()[0][0]

How to make bootstrap column height to 100% row height?

You can solve that using display table.

Here is the updated JSFiddle that solves your problem.

CSS

.body {
    display: table;
    background-color: green;
}

.left-side {
    background-color: blue;
    float: none;
    display: table-cell;
    border: 1px solid;
}

.right-side {
    background-color: red;
    float: none;
    display: table-cell;
    border: 1px solid;
}

HTML

<div class="row body">
        <div class="col-xs-9 left-side">
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
        </div>
        <div class="col-xs-3 right-side">
            asdfdf
        </div>
    </div>

Iterating through populated rows

I'm going to make a couple of assumptions in my answer. I'm assuming your data starts in A1 and there are no empty cells in the first column of each row that has data.

This code will:

  1. Find the last row in column A that has data
  2. Loop through each row
  3. Find the last column in current row with data
  4. Loop through each cell in current row up to last column found.

This is not a fast method but will iterate through each one individually as you suggested is your intention.


Sub iterateThroughAll()
    ScreenUpdating = False
    Dim wks As Worksheet
    Set wks = ActiveSheet

    Dim rowRange As Range
    Dim colRange As Range

    Dim LastCol As Long
    Dim LastRow As Long
    LastRow = wks.Cells(wks.Rows.Count, "A").End(xlUp).Row

    Set rowRange = wks.Range("A1:A" & LastRow)

    'Loop through each row
    For Each rrow In rowRange
        'Find Last column in current row
        LastCol = wks.Cells(rrow, wks.Columns.Count).End(xlToLeft).Column
        Set colRange = wks.Range(wks.Cells(rrow, 1), wks.Cells(rrow, LastCol))

        'Loop through all cells in row up to last col
        For Each cell In colRange
            'Do something to each cell
            Debug.Print (cell.Value)
        Next cell
    Next rrow
    ScreenUpdating = True
End Sub

3-dimensional array in numpy

You have a truncated array representation. Let's look at a full example:

>>> a = np.zeros((2, 3, 4))
>>> a
array([[[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]],

       [[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]]])

Arrays in NumPy are printed as the word array followed by structure, similar to embedded Python lists. Let's create a similar list:

>>> l = [[[ 0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.]],

          [[ 0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.]]]

>>> l
[[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]], 
 [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]]

The first level of this compound list l has exactly 2 elements, just as the first dimension of the array a (# of rows). Each of these elements is itself a list with 3 elements, which is equal to the second dimension of a (# of columns). Finally, the most nested lists have 4 elements each, same as the third dimension of a (depth/# of colors).

So you've got exactly the same structure (in terms of dimensions) as in Matlab, just printed in another way.

Some caveats:

  1. Matlab stores data column by column ("Fortran order"), while NumPy by default stores them row by row ("C order"). This doesn't affect indexing, but may affect performance. For example, in Matlab efficient loop will be over columns (e.g. for n = 1:10 a(:, n) end), while in NumPy it's preferable to iterate over rows (e.g. for n in range(10): a[n, :] -- note n in the first position, not the last).

  2. If you work with colored images in OpenCV, remember that:

    2.1. It stores images in BGR format and not RGB, like most Python libraries do.

    2.2. Most functions work on image coordinates (x, y), which are opposite to matrix coordinates (i, j).

Print a list of space-separated elements in Python 3

Joining elements in a list space separated:

word = ["test", "crust", "must", "fest"]
word.reverse()
joined_string = ""
for w in word:
   joined_string = w + joined_string + " "
print(joined_string.rstrim())

mysql delete under safe mode

I have a far more simple solution, it is working for me; it is also a workaround but might be usable and you dont have to change your settings. I assume you can use value that will never be there, then you use it on your WHERE clause

DELETE FROM MyTable WHERE MyField IS_NOT_EQUAL AnyValueNoItemOnMyFieldWillEverHave

I don't like that solution either too much, that's why I am here, but it works and it seems better than what it has been answered

Why not inherit from List<T>?

This is a classic example of composition vs inheritance.

In this specific case:

Is the team a list of players with added behavior

or

Is the team an object of its own that happens to contain a list of players.

By extending List you are limiting yourself in a number of ways:

  1. You cannot restrict access (for example, stopping people changing the roster). You get all the List methods whether you need/want them all or not.

  2. What happens if you want to have lists of other things as well. For example, teams have coaches, managers, fans, equipment, etc. Some of those might well be lists in their own right.

  3. You limit your options for inheritance. For example you might want to create a generic Team object, and then have BaseballTeam, FootballTeam, etc. that inherit from that. To inherit from List you need to do the inheritance from Team, but that then means that all the various types of team are forced to have the same implementation of that roster.

Composition - including an object giving the behavior you want inside your object.

Inheritance - your object becomes an instance of the object that has the behavior you want.

Both have their uses, but this is a clear case where composition is preferable.

data.table vs dplyr: can one do something well the other can't or does poorly?

Reading Hadley and Arun's answers one gets the impression that those who prefer dplyr's syntax would have in some cases to switch over to data.table or compromise for long running times.

But as some have already mentioned, dplyr can use data.table as a backend. This is accomplished using the dtplyr package which recently had it's version 1.0.0 release. Learning dtplyr incurs practically zero additional effort.

When using dtplyr one uses the function lazy_dt() to declare a lazy data.table, after which standard dplyr syntax is used to specify operations on it. This would look something like the following:

new_table <- mtcars2 %>% 
  lazy_dt() %>%
  filter(wt < 5) %>% 
  mutate(l100k = 235.21 / mpg) %>% # liters / 100 km
  group_by(cyl) %>% 
  summarise(l100k = mean(l100k))

  new_table

#> Source: local data table [?? x 2]
#> Call:   `_DT1`[wt < 5][, `:=`(l100k = 235.21/mpg)][, .(l100k = mean(l100k)), 
#>     keyby = .(cyl)]
#> 
#>     cyl l100k
#>   <dbl> <dbl>
#> 1     4  9.05
#> 2     6 12.0 
#> 3     8 14.9 
#> 
#> # Use as.data.table()/as.data.frame()/as_tibble() to access results

The new_table object is not evaluated until calling on it as.data.table()/as.data.frame()/as_tibble() at which point the underlying data.table operation is executed.

I've recreated a benchmark analysis done by data.table author Matt Dowle back at December 2018 which covers the case of operations over large numbers of groups. I've found that dtplyr indeed enables for the most part those who prefer the dplyr syntax to keep using it while enjoying the speed offered by data.table.

Difference between Grunt, NPM and Bower ( package.json vs bower.json )

Npm and Bower are both dependency management tools. But the main difference between both is npm is used for installing Node js modules but bower js is used for managing front end components like html, css, js etc.

A fact that makes this more confusing is that npm provides some packages which can be used in front-end development as well, like grunt and jshint.

These lines add more meaning

Bower, unlike npm, can have multiple files (e.g. .js, .css, .html, .png, .ttf) which are considered the main file(s). Bower semantically considers these main files, when packaged together, a component.

Edit: Grunt is quite different from Npm and Bower. Grunt is a javascript task runner tool. You can do a lot of things using grunt which you had to do manually otherwise. Highlighting some of the uses of Grunt:

  1. Zipping some files (e.g. zipup plugin)
  2. Linting on js files (jshint)
  3. Compiling less files (grunt-contrib-less)

There are grunt plugins for sass compilation, uglifying your javascript, copy files/folders, minifying javascript etc.

Please Note that grunt plugin is also an npm package.

Question-1

When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json

It really depends where does this package belong to. If it is a node module(like grunt,request) then it will go in package.json otherwise into bower json.

Question-2

When should I ever install packages explicitly like that without adding them to the file that manages dependencies

It does not matter whether you are installing packages explicitly or mentioning the dependency in .json file. Suppose you are in the middle of working on a node project and you need another project, say request, then you have two options:

  • Edit the package.json file and add a dependency on 'request'
  • npm install

OR

  • Use commandline: npm install --save request

--save options adds the dependency to package.json file as well. If you don't specify --save option, it will only download the package but the json file will be unaffected.

You can do this either way, there will not be a substantial difference.

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

I had the same issue, for me this fixed the issue:
right click on the project ->maven -> update project

maven -> update project

How can I use onItemSelected in Android?

spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

               //check if spinner2 has a selected item and show the value in edittext

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

               // sometimes you need nothing here
            }
        });

spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

               //check if spinner1 has a selected item and show the value in edittext


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

               // sometimes you need nothing here
            }
        });

Integration Testing POSTing an entire object to Spring MVC controller

I believe that I have the simplest answer yet using Spring Boot 1.4, included imports for the test class.:

public class SomeClass {  /// this goes in it's own file
//// fields go here
}

import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.http.MediaType
import org.springframework.test.context.junit4.SpringRunner
import org.springframework.test.web.servlet.MockMvc

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status

@RunWith(SpringRunner.class)
@WebMvcTest(SomeController.class)
public class ControllerTest {

  @Autowired private MockMvc mvc;
  @Autowired private ObjectMapper mapper;

  private SomeClass someClass;  //this could be Autowired
                                //, initialized in the test method
                                //, or created in setup block
  @Before
  public void setup() {
    someClass = new SomeClass(); 
  }

  @Test
  public void postTest() {
    String json = mapper.writeValueAsString(someClass);
    mvc.perform(post("/someControllerUrl")
       .contentType(MediaType.APPLICATION_JSON)
       .content(json)
       .accept(MediaType.APPLICATION_JSON))
       .andExpect(status().isOk());
  }

}

Import Python Script Into Another?

It's worth mentioning that (at least in python 3), in order for this to work, you must have a file named __init__.py in the same directory.

How to git reset --hard a subdirectory?

What about

subdir=thesubdir
for fn in $(find $subdir); do
  git ls-files --error-unmatch $fn 2>/dev/null >/dev/null;
  if [ "$?" = "1" ]; then
    continue;
  fi
  echo "Restoring $fn";
  git show HEAD:$fn > $fn;
done 

How do I disable fail_on_empty_beans in Jackson?

If you use org.codehaus.jackson.map.ObjectMapper, then pls. use the following lines

mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);

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

shape is a property of both numpy ndarray's and matrices.

A.shape

will return a tuple (m, n), where m is the number of rows, and n is the number of columns.

In fact, the numpy matrix object is built on top of the ndarray object, one of numpy's two fundamental objects (along with a universal function object), so it inherits from ndarray

Android: how to handle button click

My sample, Tested in Android studio 2.1

Define button in xml layout

<Button
    android:id="@+id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Java pulsation detect

Button clickButton = (Button) findViewById(R.id.btn1);
if (clickButton != null) {
    clickButton.setOnClickListener( new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            /***Do what you want with the click here***/
        }
    });
}

"Large data" workflows using pandas

I recently came across a similar issue. I found simply reading the data in chunks and appending it as I write it in chunks to the same csv works well. My problem was adding a date column based on information in another table, using the value of certain columns as follows. This may help those confused by dask and hdf5 but more familiar with pandas like myself.

def addDateColumn():
"""Adds time to the daily rainfall data. Reads the csv as chunks of 100k 
   rows at a time and outputs them, appending as needed, to a single csv. 
   Uses the column of the raster names to get the date.
"""
    df = pd.read_csv(pathlist[1]+"CHIRPS_tanz.csv", iterator=True, 
                     chunksize=100000) #read csv file as 100k chunks

    '''Do some stuff'''

    count = 1 #for indexing item in time list 
    for chunk in df: #for each 100k rows
        newtime = [] #empty list to append repeating times for different rows
        toiterate = chunk[chunk.columns[2]] #ID of raster nums to base time
        while count <= toiterate.max():
            for i in toiterate: 
                if i ==count:
                    newtime.append(newyears[count])
            count+=1
        print "Finished", str(chunknum), "chunks"
        chunk["time"] = newtime #create new column in dataframe based on time
        outname = "CHIRPS_tanz_time2.csv"
        #append each output to same csv, using no header
        chunk.to_csv(pathlist[2]+outname, mode='a', header=None, index=None)

Git - push current branch shortcut

The simplest way: run git push -u origin feature/123-sandbox-tests once. That pushes the branch the way you're used to doing it and also sets the upstream tracking info in your local config. After that, you can just git push to push tracked branches to their upstream remote(s).

You can also do this in the config yourself by setting branch.<branch name>.merge to the remote branch name (in your case the same as the local name) and optionally, branch.<branch name>.remote to the name of the remote you want to push to (defaults to origin). If you look in your config, there's most likely already one of these set for master, so you can follow that example.

Finally, make sure you consider the push.default setting. It defaults to "matching", which can have undesired and unexpected results. Most people I know find "upstream" more intuitive, which pushes only the current branch.

Details on each of these settings can be found in the git-config man page.

On second thought, on re-reading your question, I think you know all this. I think what you're actually looking for doesn't exist. How about a bash function something like (untested):

function pushCurrent {
  git config push.default upstream
  git push
  git config push.default matching
}

Array String Declaration

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

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

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

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

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

Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue

For non-preemptive system,

waitingTime = startTime - arrivalTime

turnaroundTime = burstTime + waitingTime = finishTime- arrivalTime

startTime = Time at which the process started executing

finishTime = Time at which the process finished executing

You can keep track of the current time elapsed in the system(timeElapsed). Assign all processors to a process in the beginning, and execute until the shortest process is done executing. Then assign this processor which is free to the next process in the queue. Do this until the queue is empty and all processes are done executing. Also, whenever a process starts executing, recored its startTime, when finishes, record its finishTime (both same as timeElapsed). That way you can calculate what you need.

Preventing an image from being draggable or selectable without using JS

You could set the image as a background image. Since it resides in a div, and the div is undraggable, the image will be undraggable:

<div style="background-image: url("image.jpg");">
</div>

Is it possible to run CUDA on AMD GPUs?

As of 2019_10_10 I have NOT tested it, but there is the "GPU Ocelot" project

http://gpuocelot.gatech.edu/

that according to its advertisement tries to compile CUDA code for a variety of targets, including AMD GPUs.

Hibernate, @SequenceGenerator and allocationSize

I too faced this issue in Hibernate 5:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = SEQUENCE)
@SequenceGenerator(name = SEQUENCE, sequenceName = SEQUENCE)
private Long titId;

Got a warning like this below:

Found use of deprecated [org.hibernate.id.SequenceHiLoGenerator] sequence-based id generator; use org.hibernate.id.enhanced.SequenceStyleGenerator instead. See Hibernate Domain Model Mapping Guide for details.

Then changed my code to SequenceStyleGenerator:

@Id
@GenericGenerator(name="cmrSeq", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
        parameters = {
                @Parameter(name = "sequence_name", value = "SEQUENCE")}
)
@GeneratedValue(generator = "sequence_name")
private Long titId;

This solved my two issues:

  1. The deprecated warning is fixed
  2. Now the id is generated as per the oracle sequence.

Multiple aggregations of the same column using pandas GroupBy.agg()

TLDR; Pandas groupby.agg has a new, easier syntax for specifying (1) aggregations on multiple columns, and (2) multiple aggregations on a column. So, to do this for pandas >= 0.25, use

df.groupby('dummy').agg(Mean=('returns', 'mean'), Sum=('returns', 'sum'))

           Mean       Sum
dummy                    
1      0.036901  0.369012

OR

df.groupby('dummy')['returns'].agg(Mean='mean', Sum='sum')

           Mean       Sum
dummy                    
1      0.036901  0.369012

Pandas >= 0.25: Named Aggregation

Pandas has changed the behavior of GroupBy.agg in favour of a more intuitive syntax for specifying named aggregations. See the 0.25 docs section on Enhancements as well as relevant GitHub issues GH18366 and GH26512.

From the documentation,

To support column-specific aggregation with control over the output column names, pandas accepts the special syntax in GroupBy.agg(), known as “named aggregation”, where

  • The keywords are the output column names
  • The values are tuples whose first element is the column to select and the second element is the aggregation to apply to that column. Pandas provides the pandas.NamedAgg namedtuple with the fields ['column', 'aggfunc'] to make it clearer what the arguments are. As usual, the aggregation can be a callable or a string alias.

You can now pass a tuple via keyword arguments. The tuples follow the format of (<colName>, <aggFunc>).

import pandas as pd

pd.__version__                                                                                                                            
# '0.25.0.dev0+840.g989f912ee'

# Setup
df = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
                   'height': [9.1, 6.0, 9.5, 34.0],
                   'weight': [7.9, 7.5, 9.9, 198.0]
})

df.groupby('kind').agg(
    max_height=('height', 'max'), min_weight=('weight', 'min'),)

      max_height  min_weight
kind                        
cat          9.5         7.9
dog         34.0         7.5

Alternatively, you can use pd.NamedAgg (essentially a namedtuple) which makes things more explicit.

df.groupby('kind').agg(
    max_height=pd.NamedAgg(column='height', aggfunc='max'), 
    min_weight=pd.NamedAgg(column='weight', aggfunc='min')
)

      max_height  min_weight
kind                        
cat          9.5         7.9
dog         34.0         7.5

It is even simpler for Series, just pass the aggfunc to a keyword argument.

df.groupby('kind')['height'].agg(max_height='max', min_height='min')    

      max_height  min_height
kind                        
cat          9.5         9.1
dog         34.0         6.0       

Lastly, if your column names aren't valid python identifiers, use a dictionary with unpacking:

df.groupby('kind')['height'].agg(**{'max height': 'max', ...})

Pandas < 0.25

In more recent versions of pandas leading upto 0.24, if using a dictionary for specifying column names for the aggregation output, you will get a FutureWarning:

df.groupby('dummy').agg({'returns': {'Mean': 'mean', 'Sum': 'sum'}})
# FutureWarning: using a dict with renaming is deprecated and will be removed 
# in a future version

Using a dictionary for renaming columns is deprecated in v0.20. On more recent versions of pandas, this can be specified more simply by passing a list of tuples. If specifying the functions this way, all functions for that column need to be specified as tuples of (name, function) pairs.

df.groupby("dummy").agg({'returns': [('op1', 'sum'), ('op2', 'mean')]})

        returns          
            op1       op2
dummy                    
1      0.328953  0.032895

Or,

df.groupby("dummy")['returns'].agg([('op1', 'sum'), ('op2', 'mean')])

            op1       op2
dummy                    
1      0.328953  0.032895

Problems with Android Fragment back stack

First of all thanks @Arvis for an eye opening explanation.

I prefer different solution to the accepted answer here for this problem. I don't like messing with overriding back behavior any more than absolutely necessary and when I've tried adding and removing fragments on my own without default back stack poping when back button is pressed I found my self in fragment hell :) If you .add f2 over f1 when you remove it f1 won't call any of callback methods like onResume, onStart etc. and that can be very unfortunate.

Anyhow this is how I do it:

Currently on display is only fragment f1.

f1 -> f2

Fragment2 f2 = new Fragment2();
this.getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,f2).addToBackStack(null).commit();

nothing out of the ordinary here. Than in fragment f2 this code takes you to fragment f3.

f2 -> f3

Fragment3 f3 = new Fragment3();
getActivity().getSupportFragmentManager().popBackStack();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content, f3).addToBackStack(null).commit();

I'm not sure by reading docs if this should work, this poping transaction method is said to be asynchronous, and maybe a better way would be to call popBackStackImmediate(). But as far I can tell on my devices it's working flawlessly.

The said alternative would be:

final FragmentActivity activity = getActivity();
activity.getSupportFragmentManager().popBackStackImmediate();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.main_content, f3).addToBackStack(null).commit();

Here there will actually be brief going back to f1 beofre moving on to f3, so a slight glitch there.

This is actually all you have to do, no need to override back stack behavior...

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

I'll try to explain it visually:

_x000D_
_x000D_
/**_x000D_
 * explaining margins_x000D_
 */_x000D_
_x000D_
body {_x000D_
  padding: 3em 15%_x000D_
}_x000D_
_x000D_
.parent {_x000D_
  width: 50%;_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  position: relative;_x000D_
  background: lemonchiffon;_x000D_
}_x000D_
_x000D_
.parent:before,_x000D_
.parent:after {_x000D_
  position: absolute;_x000D_
  content: "";_x000D_
}_x000D_
_x000D_
.parent:before {_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 50%;_x000D_
  border-left: dashed 1px #ccc;_x000D_
}_x000D_
_x000D_
.parent:after {_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  top: 50%;_x000D_
  border-top: dashed 1px #ccc;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  background: rgba(200, 198, 133, .5);_x000D_
}_x000D_
_x000D_
ul {_x000D_
  padding: 5% 20px;_x000D_
}_x000D_
_x000D_
.set1 .child {_x000D_
  margin: 0;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.set2 .child {_x000D_
  margin-left: 75px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.set3 .child {_x000D_
  margin-left: -75px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
_x000D_
/* position absolute */_x000D_
_x000D_
.set4 .child {_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin: 0;_x000D_
  position: absolute;_x000D_
}_x000D_
_x000D_
.set5 .child {_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin-left: 75px;_x000D_
  position: absolute;_x000D_
}_x000D_
_x000D_
.set6 .child {_x000D_
  top: 50%; /* level from which margin-top starts _x000D_
 - downwards, in the case of a positive margin_x000D_
 - upwards, in the case of a negative margin _x000D_
 */_x000D_
  left: 50%; /* level from which margin-left starts _x000D_
 - towards right, in the case of a positive margin_x000D_
 - towards left, in the case of a negative margin _x000D_
 */_x000D_
  margin: -75px;_x000D_
  position: absolute;_x000D_
}
_x000D_
<!-- content to be placed inside <body>…</body> -->_x000D_
<h2><code>position: relative;</code></h2>_x000D_
<h3>Set 1</h3>_x000D_
<div class="parent set 1">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set1 .child {_x000D_
  margin: 0;_x000D_
  position: relative;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 2</h3>_x000D_
<div class="parent set2">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set2 .child {_x000D_
  margin-left: 75px;_x000D_
  position: relative;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 3</h3>_x000D_
<div class="parent set3">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set3 .child {_x000D_
  margin-left: -75px;_x000D_
  position: relative;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h2><code>position: absolute;</code></h2>_x000D_
_x000D_
<h3>Set 4</h3>_x000D_
<div class="parent set4">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set4 .child {_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin: 0;_x000D_
  position: absolute;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 5</h3>_x000D_
<div class="parent set5">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set5 .child {_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin-left: 75px;_x000D_
  position: absolute;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 6</h3>_x000D_
<div class="parent set6">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set6 .child {_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin: -75px;_x000D_
  position: absolute;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why is the time complexity of both DFS and BFS O( V + E )

Time complexity is O(E+V) instead of O(2E+V) because if the time complexity is n^2+2n+7 then it is written as O(n^2).

Hence, O(2E+V) is written as O(E+V)

because difference between n^2 and n matters but not between n and 2n.

Count number of rows within each group

An old question without a data.table solution. So here goes...

Using .N

library(data.table)
DT <- data.table(df)
DT[, .N, by = list(year, month)]

Show history of a file?

The main question for me would be, what are you actually trying to find out? Are you trying to find out, when a certain set of changes was introduced in that file?

You can use git blame for this, it will anotate each line with a SHA1 and a date when it was changed. git blame can also tell you when a certain line was deleted or where it was moved if you are interested in that.

If you are trying to find out, when a certain bug was introduced, git bisect is a very powerfull tool. git bisect will do a binary search on your history. You can use git bisect start to start bisecting, then git bisect bad to mark a commit where the bug is present and git bisect good to mark a commit which does not have the bug. git will checkout a commit between the two and ask you if it is good or bad. You can usually find the faulty commit within a few steps.

Since I have used git, I hardly ever found the need to manually look through patch histories to find something, since most often git offers me a way to actually look for the information I need.

If you try to think less of how to do a certain workflow, but more in what information you need, you will probably many workflows which (in my opinion) are much more simple and faster.

What is the apply function in Scala?

Here is a small example for those who want to peruse quickly

 object ApplyExample01 extends App {


  class Greeter1(var message: String) {
    println("A greeter-1 is being instantiated with message " + message)


  }

  class Greeter2 {


    def apply(message: String) = {
      println("A greeter-2 is being instantiated with message " + message)
    }
  }

  val g1: Greeter1 = new Greeter1("hello")
  val g2: Greeter2 = new Greeter2()

  g2("world")


} 

output

A greeter-1 is being instantiated with message hello

A greeter-2 is being instantiated with message world

Uncaught ReferenceError: jQuery is not defined

jQuery needs to be the first script you import. The first script on your page

<script type="text/javascript" src="/test/wp-content/themes/child/script/jquery.jcarousel.min.js"></script>

appears to be a jQuery plugin, which is likely generating an error since jQuery hasn't been loaded on the page yet.

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

Decision tree:

  1. Frameworks like Qt and SWT need native DLLs. So you have to ask yourself: Are all necessary platforms supported? Can you package the native DLLs with your app?

    See here, how to do this for SWT.

    If you have a choice here, you should prefer Qt over SWT. Qt has been developed by people who understand UI and the desktop while SWT has been developed out of necessity to make Eclipse faster. It's more a performance patch for Java 1.4 than a UI framework. Without JFace, you're missing many major UI components or very important features of UI components (like filtering on tables).

    If SWT is missing a feature that you need, the framework is somewhat hostile to extending it. For example, you can't extend any class in it (the classes aren't final, they just throw exceptions when the package of this.getClass() isn't org.eclipse.swt and you can't add new classes in that package because it's signed).

  2. If you need a native, pure Java solution, that leaves you with the rest. Let's start with AWT, Swing, SwingX - the Swing way.

    AWT is outdated. Swing is outdated (maybe less so but not much work has been done on Swing for the past 10 years). You could argue that Swing was good to begin with but we all know that code rots. And that's especially true for UIs today.

    That leaves you with SwingX. After a longer period of slow progress, development has picked up again. The major drawback with Swing is that it hangs on to some old ideas which very kind of bleeding edge 15 years ago but which feel "clumsy" today. For example, the table views do support filtering and sorting but you still have to configure this. You'll have to write a lot of boiler plate code just to get a decent UI that feels modern.

    Another weak area is theming. As of today, there are a lot of themes around. See here for a top 10. But some are slow, some are buggy, some are incomplete. I hate it when I write a UI and users complain that something doesn't work for them because they selected an odd theme.

  3. JGoodies is another layer on top of Swing, like SwingX. It tries to make Swing more pleasant to use. The web site looks great. Let's have a look at the tutorial ... hm ... still searching ... hang on. It seems that there is no documentation on the web site at all. Google to the rescue. Nope, no useful tutorials at all.

    I'm not feeling confident with a UI framework that tries so hard to hide the documentation from potential new fans. That doesn't mean JGoodies is bad; I just couldn't find anything good to say about it but that it looks nice.

  4. JavaFX. Great, stylish. Support is there but I feel it's more of a shiny toy than a serious UI framework. This feeling roots in the lack of complex UI components like tree tables. There is a webkit-based component to display HTML.

    When it was introduced, my first thought was "five years too late." If your aim is a nice app for phones or web sites, good. If your aim is professional desktop application, make sure it delivers what you need.

  5. Pivot. First time I heard about it. It's basically a new UI framework based on Java2D. So I gave it a try yesterday. No Swing, just tiny bit of AWT (new Font(...)).

    My first impression was a nice one. There is an extensive documentation that helps you getting started. Most of the examples come with live demos (Note: You must have Java enabled in your web browser; this is a security risk) in the web page, so you can see the code and the resulting application side by side.

    In my experience, more effort goes into code than into documentation. By looking at the Pivot docs, a lot of effort must have went into the code. Note that there is currently a bug which prevents some of the examples to work (PIVOT-858) in your browser.

    My second impression of Pivot is that it's easy to use. When I ran into a problem, I could usually solve it quickly by looking at an example. I'm missing a reference of all the styles which each component supports, though.

    As with JavaFX, it's missing some higher level components like a tree table component (PIVOT-306). I didn't try lazy loading with the table view. My impression is that if the underlying model uses lazy loading, then that's enough.

    Promising. If you can, give it a try.

Creating a singleton in Python

Well, other than agreeing with the general Pythonic suggestion on having module-level global, how about this:

def singleton(class_):
    class class_w(class_):
        _instance = None
        def __new__(class2, *args, **kwargs):
            if class_w._instance is None:
                class_w._instance = super(class_w, class2).__new__(class2, *args, **kwargs)
                class_w._instance._sealed = False
            return class_w._instance
        def __init__(self, *args, **kwargs):
            if self._sealed:
                return
            super(class_w, self).__init__(*args, **kwargs)
            self._sealed = True
    class_w.__name__ = class_.__name__
    return class_w

@singleton
class MyClass(object):
    def __init__(self, text):
        print text
    @classmethod
    def name(class_):
        print class_.__name__

x = MyClass(111)
x.name()
y = MyClass(222)
print id(x) == id(y)

Output is:

111     # the __init__ is called only on the 1st time
MyClass # the __name__ is preserved
True    # this is actually the same instance

How to remove focus without setting focus to another control?

You could try turning off the main Activity's ability to save its state (thus making it forget what control had text and what had focus). You will need to have some other way of remembering what your EditText's have and repopulating them onResume(). Launch your sub-Activities with startActivityForResult() and create an onActivityResult() handler in your main Activity that will update the EditText's correctly. This way you can set the proper button you want focused onResume() at the same time you repopulate the EditText's by using a myButton.post(new Runnable(){ run() { myButton.requestFocus(); } });

The View.post() method is useful for setting focus initially because that runnable will be executed after the window is created and things settle down, allowing the focus mechanism to function properly by that time. Trying to set focus during onCreate/Start/Resume() usually has issues, I've found.

Please note this is pseudo-code and non-tested, but it's a possible direction you could try.

Mutex example / tutorial?

SEMAPHORE EXAMPLE ::

sem_t m;
sem_init(&m, 0, 0); // initialize semaphore to 0

sem_wait(&m);
// critical section here
sem_post(&m);

Reference : http://pages.cs.wisc.edu/~remzi/Classes/537/Fall2008/Notes/threads-semaphores.txt

Outline effect to text

Working with thicker strokes gets a bit messy, if you have the pleasure of sass try this mixin, not perfect and depending on stroke weight it generates a fair amount of css.

 @mixin stroke($width, $colour: #000000) {
      $shadow: 0 0 0 $colour; // doesn't do anything but I couldn't work out how to create a blank string and maintain commas
      @for $i from 0 through $width {
          $shadow: $shadow,
          -$i + px -$width + px 0 $colour,
          $i + px -$width + px 0 $colour,
          -$i + px $width + px 0 $colour,
          $i + px $width + px 0 $colour,
          -$width + px -$i + px 0 $colour,
          $width + px -$i + px 0 $colour,
          -$width + px $i + px 0 $colour,
          $width + px $i + px 0 $colour,
      }
      text-shadow: $shadow;
}

When maven says "resolution will not be reattempted until the update interval of MyRepo has elapsed", where is that interval specified?

How I got this problem,

When I changed from Eclipse Juno to Luna, and checkout my maven projects from SVN repo, I got the same issues while building the applications.

What I tried? I tried clean Local repository and then updating all the versions again using -U option. But my problem continued.

Then I went to Window --> Preferences -> Maven --> User Settings --> and clicked on Reindex button under Local Repository and wait for the reindex to happen.

That's all, the issue is resolved.

What's the best way to join on the same table twice?

The first is good unless either Phone1 or (more likely) phone2 can be null. In that case you want to use a Left join instead of an inner join.

It is usually a bad sign when you have a table with two phone number fields. Usually this means your database design is flawed.

Performance of FOR vs FOREACH in PHP

I think but I am not sure : the for loop takes two operations for checking and incrementing values. foreach loads the data in memory then it will iterate every values.

What is newline character -- '\n'

I see a lot of sed answers, but none for vim. To be fair, vim's treatment of newline characters is a little confusing. Search for \n but replace with \r. I recommend RTFM: :help pattern in general and :help NL-used-for-Nul in particular.

To do what you want with a :substitute command,

:%s/\_$/\r

although I think most people would use something like

:g/^/put=''

for the same effect.

Here is a way to find the answer for yourself. Run your file through xxd, which is part of the standard vim distribution.

:%!xxd

You get

0000000: 4361 6c69 666f 726e 6961 0a4d 6173 7361  California.Massa
0000010: 6368 7573 6574 7473 0a41 7269 7a6f 6e61  chusetts.Arizona
0000020: 0a                                       .

This shows that 46 is the hex code for C, 61 is the code for a, and so on. In particular, 0a (decimal 10) is the code for \n. Just for kicks, try

:set ff=dos

before filtering through xxd. You will see 0d0a (CRLF) as the line terminator.

:help /\_$
:help :g
:help :put
:help :!
:help 23.4

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?

LINQ-to-SQL is a remarkable piece of technology that is very simple to use, and by and large generates very good queries to the back end. LINQ-to-EF was slated to supplant it, but historically has been extremely clunky to use and generated far inferior SQL. I don't know the current state of affairs, but Microsoft promised to migrate all the goodness of L2S into L2EF, so maybe it's all better now.

Personally, I have a passionate dislike of ORM tools (see my diatribe here for the details), and so I see no reason to favour L2EF, since L2S gives me all I ever expect to need from a data access layer. In fact, I even think that L2S features such as hand-crafted mappings and inheritance modeling add completely unnecessary complexity. But that's just me. ;-)

CSS "color" vs. "font-color"

I know this is an old post but as MisterZimbu stated, the color property is defining the values of other properties, as the border-color and, with CSS3, of currentColor.

currentColor is very handy if you want to use the font color for other elements (as the background or custom checkboxes and radios of inner elements for example).

Example:

_x000D_
_x000D_
.element {_x000D_
  color: green;_x000D_
  background: red;_x000D_
  display: block;_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
.innerElement1 {_x000D_
  border: solid 10px;_x000D_
  display: inline-block;_x000D_
  width: 60px;_x000D_
  height: 100px;_x000D_
  margin: 10px;_x000D_
}_x000D_
_x000D_
.innerElement2 {_x000D_
  background: currentColor;_x000D_
  display: inline-block;_x000D_
  width: 60px;_x000D_
  height: 100px;_x000D_
  margin: 10px;_x000D_
}
_x000D_
<div class="element">_x000D_
  <div class="innerElement1"></div>_x000D_
  <div class="innerElement2"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Best Practice: Access form elements by HTML id or name attribute?

To supplement the other answers, document.myForm.foo is the so-called DOM level 0, which is the way implemented by Netscape and thus is not really an open standard even though it is supported by most browsers.

Is log(n!) = T(n·log(n))?

This might help:

eln(x) = x

and

(lm)n = lm*n

Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

Try this in a Thread (not the UI-Thread):

final CountDownLatch latch = new CountDownLatch(1);
handler.post(new Runnable() {
  @Override
  public void run() {
    OnClickListener okListener = new OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      dialog.dismiss();
      latch.countDown();
    }
  };

  AlertDialog dialog = new AlertDialog.Builder(context).setTitle(title)
    .setMessage(msg).setPositiveButton("OK", okListener).create();
  dialog.show();
}
});
try {
  latch.await();
} catch (InterruptedException e) {
  e.printStackTrace();
}

MySQL: Large VARCHAR vs. TEXT?

Varchar is for small data like email addresses, while Text is for much bigger data like news articles, Blob for binary data such as images.

The performance of Varchar is more powerful because it runs completely from memory, but this will not be the case if data is too big like varchar(4000) for example.

Text, on the other hand, does not stick to memory and is affected by disk performance, but you can avoid that by separating text data in a separate table and apply a left join query to retrieve text data.

Blob is much slower so use it only if you don't have much data like 10000 images which will cost 10000 records.

Follow these tips for maximum speed and performance:

  1. Use varchar for name, titles, emails

  2. Use Text for large data

  3. Separate text in different tables

  4. Use Left Join queries on an ID such as a phone number

  5. If you are going to use Blob apply the same tips as in Text

This will make queries cost milliseconds on tables with data >10 M and size up to 10GB guaranteed.

Open directory dialog

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Gearplay
{
    /// <summary>
    /// ?????? ?????????????? ??? OpenFolderBrows.xaml
    /// </summary>
    public partial class OpenFolderBrows : Page
    {
        internal string SelectedFolderPath { get; set; }
        public OpenFolderBrows()
        {
            InitializeComponent();
            Selectedpath();
            InputLogicalPathCollection();
             
        }

        internal void Selectedpath()
        {
            Browser.Navigate(@"C:\");
            
            Browser.Navigated += Browser_Navigated;
        }

        private void Browser_Navigated(object sender, NavigationEventArgs e)
        {
            SelectedFolderPath = e.Uri.AbsolutePath.ToString();
            //MessageBox.Show(SelectedFolderPath);
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
          
           
        }
        
        string [] testing { get; set; }
        private void InputLogicalPathCollection()
        {            // add Menu items for Cotrol 
            string[] DirectoryCollection_Path = Environment.GetLogicalDrives(); // Get Local Drives
            testing = new string[DirectoryCollection_Path.Length];
            //MessageBox.Show(DirectoryCollection_Path[0].ToString());
            MenuItem[]  menuItems = new MenuItem[DirectoryCollection_Path.Length]; // Create Empty Collection
            for(int i=0;i<menuItems.Length;i++)
            {
                // Create collection depend how much logical drives 
                menuItems[i] = new MenuItem();
                menuItems[i].Header = DirectoryCollection_Path[i];
                menuItems[i].Name = DirectoryCollection_Path[i].Substring(0,DirectoryCollection_Path.Length-1);
                DirectoryCollection.Items.Add(menuItems[i]);
                menuItems[i].Click += OpenFolderBrows_Click;
                testing[i]= DirectoryCollection_Path[i].Substring(0, DirectoryCollection_Path.Length - 1);
            }

            

        }
        
        private void OpenFolderBrows_Click(object sender, RoutedEventArgs e)
        {

            foreach (string str in testing)
            {
                if (e.OriginalSource.ToString().Contains("Header:"+str)) // Navigate to Local drive
                {
                    Browser.Navigate(str + @":\");
                   
                }


            }


        }

        private void Goback_Click(object sender, RoutedEventArgs e)
        {// Go Back
            try
            {
                Browser.GoBack();
            }catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Goforward_Click(object sender, RoutedEventArgs e)
        { //Go Forward
            try
            {
                Browser.GoForward();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void FolderForSave_Click(object sender, RoutedEventArgs e)
        {
            // Separate Click For Go Back same As Close App With send string var to Main Window ( Main class etc.) 
            this.NavigationService.GoBack();
        }
    }
}

Why does NULL = NULL evaluate to false in SQL server

The answers here all seem to come from a CS perspective so I want to add one from a developer perspective.

For a developer NULL is very useful. The answers here say NULL means unknown, and maybe in CS theory that's true, don't remember, it's been a while. In actual development though, at least in my experience, that happens about 1% of the time. The other 99% it is used for cases where the value is not UNKNOWN but it is KNOWN TO BE ABSENT.

For example:

  • Client.LastPurchase, for a new client. It is not unknown, it is known that he hasn't made a purchase yet.

  • When using an ORM with a Table per Class Hierarchy mapping, some values are just not mapped for certain classes.

  • When mapping a tree structure a root will usually have Parent = NULL

  • And many more...

I'm sure most developers at some point wrote WHERE value = NULL, didn't get any results, and that's how they learned about IS NULL syntax. Just look how many votes this question and the linked ones have.

SQL Databases are a tool, and they should be designed the way which is easiest for their users to understand.

How do you run a single query through mysql from the command line?

here's how you can do it with a cool shell trick:

mysql -uroot -p -hslavedb.mydomain.com mydb_production <<< 'select * from users'

'<<<' instructs the shell to take whatever follows it as stdin, similar to piping from echo.

use the -t flag to enable table-format output

EL access a map value by Integer key

Just another helpful hint in addition to the above comment would be when you have a string value contained in some variable such as a request parameter. In this case, passing this in will also result in JSTL keying the value of say "1" as a sting and as such no match being found in a Map hashmap.

One way to get around this is to do something like this.

<c:set var="longKey" value="${param.selectedIndex + 0}"/>

This will now be treated as a Long object and then has a chance to match an object when it is contained withing the map Map or whatever.

Then, continue as usual with something like

${map[longKey]}

What are the differences between B trees and B+ trees?

The image below helps show the differences between B+ trees and B trees.

Advantages of B+ trees:

  • Because B+ trees don't have data associated with interior nodes, more keys can fit on a page of memory. Therefore, it will require fewer cache misses in order to access data that is on a leaf node.
  • The leaf nodes of B+ trees are linked, so doing a full scan of all objects in a tree requires just one linear pass through all the leaf nodes. A B tree, on the other hand, would require a traversal of every level in the tree. This full-tree traversal will likely involve more cache misses than the linear traversal of B+ leaves.

Advantage of B trees:

  • Because B trees contain data with each key, frequently accessed nodes can lie closer to the root, and therefore can be accessed more quickly.

B and B+ tree

What is a practical, real world example of the Linked List?

In the .NET BCL, the class System.Exception has a property called InnerException, which points to another exception or else is null. This forms a linked list.

In System.Type, the BaseType property points to another type in the same way.

Make code in LaTeX look *nice*

The listings package is quite nice and very flexible (e.g. different sizes for comments and code).

When should I use the Visitor Design Pattern?

There are at least three very good reasons for using the Visitor Pattern:

  1. Reduce proliferation of code which is only slightly different when data structures change.

  2. Apply the same computation to several data structures, without changing the code which implements the computation.

  3. Add information to legacy libraries without changing the legacy code.

Please have a look at an article I've written about this.

How to completely uninstall Android Studio on Mac?

Execute these commands in the terminal (excluding the lines with hashtags - they're comments):

# Deletes the Android Studio application
# Note that this may be different depending on what you named the application as, or whether you downloaded the preview version
rm -Rf /Applications/Android\ Studio.app
# Delete All Android Studio related preferences
# The asterisk here should target all folders/files beginning with the string before it
rm -Rf ~/Library/Preferences/AndroidStudio*
rm -Rf ~/Library/Preferences/Google/AndroidStudio*
# Deletes the Android Studio's plist file
rm -Rf ~/Library/Preferences/com.google.android.*
# Deletes the Android Emulator's plist file
rm -Rf ~/Library/Preferences/com.android.*
# Deletes mainly plugins (or at least according to what mine (Edric) contains)
rm -Rf ~/Library/Application\ Support/AndroidStudio*
rm -Rf ~/Library/Application\ Support/Google/AndroidStudio*
# Deletes all logs that Android Studio outputs
rm -Rf ~/Library/Logs/AndroidStudio*
rm -Rf ~/Library/Logs/Google/AndroidStudio*
# Deletes Android Studio's caches
rm -Rf ~/Library/Caches/AndroidStudio*
# Deletes older versions of Android Studio
rm -Rf ~/.AndroidStudio*

If you would like to delete all projects:

rm -Rf ~/AndroidStudioProjects

To remove gradle related files (caches & wrapper)

rm -Rf ~/.gradle

Use the below command to delete all Android Virtual Devices(AVDs) and keystores.

Note: This folder is used by other Android IDEs as well, so if you still using other IDE you may not want to delete this folder)

rm -Rf ~/.android

To delete Android SDK tools

rm -Rf ~/Library/Android*

Emulator Console Auth Token

rm -Rf ~/.emulator_console_auth_token

Thanks to those who commented/improved on this answer!


Notes

  1. The flags for rm are case-sensitive1 (as with most other commands), which means that the f flag must be in lower case. However, the r flag can also be capitalised.
  2. The flags for rm can be either combined together or separated. They don't have to be combined.

What the flags indicate

  1. The r flag indicates that the rm command should-

    attempt to remove the file hierarchy rooted in each file argument. - DESCRIPTION section on the manpage for rm (See man rm for more info)

  2. The f flag indicates that the rm command should-

    attempt to remove the files without prompting for confirmation, regardless of the file's permissions. - DESCRIPTION section on the manpage for rm (See man rm for more info)

How to check type of files without extensions in python?

In the case of images, you can use the imghdr module.

>>> import imghdr
>>> imghdr.what('8e5d7e9d873e2a9db0e31f9dfc11cf47')  # You can pass a file name or a file object as first param. See doc for optional 2nd param.
'png'

Python 2 imghdr doc
Python 3 imghdr doc

What is the scope of variables in JavaScript?

1) There is a global scope, a function scope, and the with and catch scopes. There is no 'block' level scope in general for variable's -- the with and the catch statements add names to their blocks.

2) Scopes are nested by functions all the way to the global scope.

3) Properties are resolved by going through the prototype chain. The with statement brings object property names into the lexical scope defined by the with block.

EDIT: ECMAAScript 6 (Harmony) is spec'ed to support let, and I know chrome allows a 'harmony' flag, so perhaps it does support it..

Let would be a support for block level scoping, but you have to use the keyword to make it happen.

EDIT: Based on Benjamin's pointing out of the with and catch statements in the comments, I've edited the post, and added more. Both the with and the catch statements introduce variables into their respective blocks, and that is a block scope. These variables are aliased to the properties of the objects passed into them.

 //chrome (v8)

 var a = { 'test1':'test1val' }
 test1   // error not defined
 with (a) { var test1 = 'replaced' }
 test1   // undefined
 a       // a.test1 = 'replaced'

EDIT: Clarifying example:

test1 is scoped to the with block, but is aliased to a.test1. 'Var test1' creates a new variable test1 in the upper lexical context (function, or global), unless it is a property of a -- which it is.

Yikes! Be careful using 'with' -- just like var is a noop if the variable is already defined in the function, it is also a noop with respect to names imported from the object! A little heads up on the name already being defined would make this much safer. I personally will never use with because of this.

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

START "notepad.exe"
echo Will launch the notepad.exe application
PAUSE

To make any cmd file type, all you have to do is save the contents as .bat, i.e.

@echo
TITLE example.bat
PAUSE
taskkill/IM cmd.exe

Make that into an "example.bat" file, save it, then open it and run.

Docker container will automatically stop after "docker run -d"

if you want to operate on the container, you need to run it in foreground to keep it alive.

What is the proper use of an EventEmitter?

Yes, go ahead and use it.

EventEmitter is a public, documented type in the final Angular Core API. Whether or not it is based on Observable is irrelevant; if its documented emit and subscribe methods suit what you need, then go ahead and use it.

As also stated in the docs:

Uses Rx.Observable but provides an adapter to make it work as specified here: https://github.com/jhusain/observable-spec

Once a reference implementation of the spec is available, switch to it.

So they wanted an Observable like object that behaved in a certain way, they implemented it, and made it public. If it were merely an internal Angular abstraction that shouldn't be used, they wouldn't have made it public.

There are plenty of times when it's useful to have an emitter which sends events of a specific type. If that's your use case, go for it. If/when a reference implementation of the spec they link to is available, it should be a drop-in replacement, just as with any other polyfill.

Just be sure that the generator you pass to the subscribe() function follows the linked spec. The returned object is guaranteed to have an unsubscribe method which should be called to free any references to the generator (this is currently an RxJs Subscription object but that is indeed an implementation detail which should not be depended on).

export class MyServiceEvent {
    message: string;
    eventId: number;
}

export class MyService {
    public onChange: EventEmitter<MyServiceEvent> = new EventEmitter<MyServiceEvent>();

    public doSomething(message: string) {
        // do something, then...
        this.onChange.emit({message: message, eventId: 42});
    }
}

export class MyConsumer {
    private _serviceSubscription;

    constructor(private service: MyService) {
        this._serviceSubscription = this.service.onChange.subscribe({
            next: (event: MyServiceEvent) => {
                console.log(`Received message #${event.eventId}: ${event.message}`);
            }
        })
    }

    public consume() {
        // do some stuff, then later...

        this.cleanup();
    }

    private cleanup() {
        this._serviceSubscription.unsubscribe();
    }
}

All of the strongly-worded doom and gloom predictions seem to stem from a single Stack Overflow comment from a single developer on a pre-release version of Angular 2.

How do I make a column unique and index it in a Ruby on Rails migration?

The short answer for old versions of Rails (see other answers for Rails 4+):

add_index :table_name, :column_name, unique: true

To index multiple columns together, you pass an array of column names instead of a single column name,

add_index :table_name, [:column_name_a, :column_name_b], unique: true

If you get "index name... is too long", you can add name: "whatever" to the add_index method to make the name shorter.

For fine-grained control, there's a "execute" method that executes straight SQL.

That's it!

If you are doing this as a replacement for regular old model validations, check to see how it works. The error reporting to the user will likely not be as nice without model-level validations. You can always do both.

How can I initialize an ArrayList with all zeroes in Java?

The 60 you're passing is just the initial capacity for internal storage. It's a hint on how big you think it might be, yet of course it's not limited by that. If you need to preset values you'll have to set them yourself, e.g.:

for (int i = 0; i < 60; i++) {
    list.add(0);
}

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

what's the easiest way to put space between 2 side-by-side buttons in asp.net

If you are using bootstrap, add ml-3 to your second button:

 <div class="row justify-content-center mt-5">
        <button class="btn btn-secondary" type="button">Button1</button>
        <button class="btn btn-secondary ml-3" type="button">Button2</button>
 </div>

Cannot set content-type to 'application/json' in jQuery.ajax

Hi These two lines worked for me.

contentType:"application/json; charset=utf-8", dataType:"json"

 $.ajax({
            type: "POST",
            url: "/v1/candidates",
            data: obj,
            **contentType:"application/json; charset=utf-8",
            dataType:"json",**
            success: function (data) {
                table.row.add([
                    data.name, data.title
                ]).draw(false);
            }

Thanks, Prashant

Specifying trust store information in spring boot application.properties

If you execute your Spring Boot application as a linux service (e.g. init.d script or similar), then you have the following option as well: Create a file called yourApplication.conf and put it next to your executable war/jar file. It's content should be something similar:

JAVA_OPTS="
-Djavax.net.ssl.trustStore=path-to-your-trustStore-file
-Djavax.net.ssl.trustStorePassword=yourCrazyPassword
"

Difference between Hive internal tables and external tables?

Hive tables can be created as EXTERNAL or INTERNAL. This is a choice that affects how data is loaded, controlled, and managed.

Use EXTERNAL tables when:

  1. The data is also used outside of Hive. For example, the data files are read and processed by an existing program that doesn't lock the files.
  2. Data needs to remain in the underlying location even after a DROP TABLE. This can apply if you are pointing multiple schemas (tables or views) at a single data set or if you are iterating through various possible schemas.
  3. You want to use a custom location such as ASV.
  4. Hive should not own data and control settings, dirs, etc., you have another program or process that will do those things.
  5. You are not creating table based on existing table (AS SELECT).

Use INTERNAL tables when:

The data is temporary.

You want Hive to completely manage the lifecycle of the table and data.

Enable binary mode while restoring a Database from an SQL dump

I know the original posters question was solved, but I came here via Google, and the various answers eventually led me to discovering that my SQL was dumped with a different default charset than the one used to import it. I got the same error as the original question, but as our dump was piped into another MySQL client, we couldn't go the route of opening it with another tool and saving it differently.

For us, the solution turned out to be the --default-character-set=utf8mb4 option, to be used both on the call of mysqldump as well as the call to import it via mysql. Of course, the value of the parameter may differ for others facing the same problem, it's just important to keep it the same, as the servers (or the tools) default setting might be any charset.

How to populate options of h:selectOneMenu from database?

Based on your question history, you're using JSF 2.x. So, here's a JSF 2.x targeted answer. In JSF 1.x you would be forced to wrap item values/labels in ugly SelectItem instances. This is fortunately not needed anymore in JSF 2.x.


Basic example

To answer your question directly, just use <f:selectItems> whose value points to a List<T> property which you preserve from the DB during bean's (post)construction. Here's a basic kickoff example assuming that T actually represents a String.

<h:selectOneMenu value="#{bean.name}">
    <f:selectItems value="#{bean.names}" />
</h:selectOneMenu>

with

@ManagedBean
@RequestScoped
public class Bean {

    private String name;
    private List<String> names; 

    @EJB
    private NameService nameService;

    @PostConstruct
    public void init() {
        names = nameService.list();
    }

    // ... (getters, setters, etc)
}

Simple as that. Actually, the T's toString() will be used to represent both the dropdown item label and value. So, when you're instead of List<String> using a list of complex objects like List<SomeEntity> and you haven't overridden the class' toString() method, then you would see com.example.SomeEntity@hashcode as item values. See next section how to solve it properly.

Also note that the bean for <f:selectItems> value does not necessarily need to be the same bean as the bean for <h:selectOneMenu> value. This is useful whenever the values are actually applicationwide constants which you just have to load only once during application's startup. You could then just make it a property of an application scoped bean.

<h:selectOneMenu value="#{bean.name}">
    <f:selectItems value="#{data.names}" />
</h:selectOneMenu>

Complex objects as available items

Whenever T concerns a complex object (a javabean), such as User which has a String property of name, then you could use the var attribute to get hold of the iteration variable which you in turn can use in itemValue and/or itemLabel attribtues (if you omit the itemLabel, then the label becomes the same as the value).

Example #1:

<h:selectOneMenu value="#{bean.userName}">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user.name}" />
</h:selectOneMenu>

with

private String userName;
private List<User> users;

@EJB
private UserService userService;

@PostConstruct
public void init() {
    users = userService.list();
}

// ... (getters, setters, etc)

Or when it has a Long property id which you would rather like to set as item value:

Example #2:

<h:selectOneMenu value="#{bean.userId}">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user.id}" itemLabel="#{user.name}" />
</h:selectOneMenu>

with

private Long userId;
private List<User> users;

// ... (the same as in previous bean example)

Complex object as selected item

Whenever you would like to set it to a T property in the bean as well and T represents an User, then you would need to bake a custom Converter which converts between User and an unique string representation (which can be the id property). Do note that the itemValue must represent the complex object itself, exactly the type which needs to be set as selection component's value.

<h:selectOneMenu value="#{bean.user}" converter="#{userConverter}">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>

with

private User user;
private List<User> users;

// ... (the same as in previous bean example)

and

@ManagedBean
@RequestScoped
public class UserConverter implements Converter {

    @EJB
    private UserService userService;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
        if (submittedValue == null || submittedValue.isEmpty()) {
            return null;
        }

        try {
            return userService.find(Long.valueOf(submittedValue));
        } catch (NumberFormatException e) {
            throw new ConverterException(new FacesMessage(String.format("%s is not a valid User ID", submittedValue)), e);
        }
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
        if (modelValue == null) {
            return "";
        }

        if (modelValue instanceof User) {
            return String.valueOf(((User) modelValue).getId());
        } else {
            throw new ConverterException(new FacesMessage(String.format("%s is not a valid User", modelValue)), e);
        }
    }

}

(please note that the Converter is a bit hacky in order to be able to inject an @EJB in a JSF converter; normally one would have annotated it as @FacesConverter(forClass=User.class), but that unfortunately doesn't allow @EJB injections)

Don't forget to make sure that the complex object class has equals() and hashCode() properly implemented, otherwise JSF will during render fail to show preselected item(s), and you'll on submit face Validation Error: Value is not valid.

public class User {

    private Long id;

    @Override
    public boolean equals(Object other) {
        return (other != null && getClass() == other.getClass() && id != null)
            ? id.equals(((User) other).id)
            : (other == this);
    }

    @Override
    public int hashCode() {
        return (id != null) 
            ? (getClass().hashCode() + id.hashCode())
            : super.hashCode();
    }

}

Complex objects with a generic converter

Head to this answer: Implement converters for entities with Java Generics.


Complex objects without a custom converter

The JSF utility library OmniFaces offers a special converter out the box which allows you to use complex objects in <h:selectOneMenu> without the need to create a custom converter. The SelectItemsConverter will simply do the conversion based on readily available items in <f:selectItem(s)>.

<h:selectOneMenu value="#{bean.user}" converter="omnifaces.SelectItemsConverter">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>

See also:

How to install popper.js with Bootstrap 4?

I had problems installing it Bootstrap as well, so I did:

Install popper.js: npm install popper.js@^1.12.3 --save

Install jQuery: npm install [email protected] --save

Then I had a high severity vulnerability message when installing [email protected] and got this message:

run npm audit fix to fix them, or npm audit for details

So I did npm audit fix, and after another npm audit fix --force it successfully installed!

How to add hours to current date in SQL Server?

declare @hours int = 5;

select dateadd(hour,@hours,getdate())

Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

I believe the responses already posted should get people going in the right direction. However here is what I did that made sense for the legacy code I was updating. The legacy code was using the URI from the gallery to change and then save the images.

Prior to 4.4 (and google drive), the URIs would look like this: content://media/external/images/media/41

As stated in the question, they more often look like this: content://com.android.providers.media.documents/document/image:3951

Since I needed the ability to save images and not disturb the already existing code, I just copied the URI from the gallery into the data folder of the app. Then originated a new URI from the saved image file in the data folder.

Here's the idea:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent), CHOOSE_IMAGE_REQUEST);

public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    File tempFile = new File(this.getFilesDir().getAbsolutePath(), "temp_image");

    //Copy URI contents into temporary file.
    try {
        tempFile.createNewFile();
        copyAndClose(this.getContentResolver().openInputStream(data.getData()),new FileOutputStream(tempFile));
    }
    catch (IOException e) {
        //Log Error
    }

    //Now fetch the new URI
    Uri newUri = Uri.fromFile(tempFile);

    /* Use new URI object just like you used to */
 }

Note - copyAndClose() just does file I/O to copy InputStream into a FileOutputStream. The code is not posted.

How do I get the HTTP status code with jQuery?

I think you should also implement the error function of the $.ajax method.

error(XMLHttpRequest, textStatus, errorThrown)Function

A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    complete: function(xhr, statusText){
        alert(xhr.status); 
    },
    error: function(xhr, statusText, err){
        alert("Error:" + xhr.status); 
    }
});

Getting time span between two times in C#?

Two points:

  1. Check your inputs. I can't imagine a situation where you'd get 2 hours by subtracting the time values you're talking about. If I do this:

        DateTime startTime = Convert.ToDateTime("7:00 AM");
        DateTime endtime = Convert.ToDateTime("2:00 PM");
        TimeSpan duration = startTime - endtime;
    

    ... I get -07:00:00 as the result. And even if I forget to provide the AM/PM value:

        DateTime startTime = Convert.ToDateTime("7:00");
        DateTime endtime = Convert.ToDateTime("2:00");
        TimeSpan duration = startTime - endtime;
    

    ... I get 05:00:00. So either your inputs don't contain the values you have listed or you are in a machine environment where they are begin parsed in an unexpected way. Or you're not actually getting the results you are reporting.

  2. To find the difference between a start and end time, you need to do endTime - startTime, not the other way around.

How to get rid of the "No bootable medium found!" error in Virtual Box?

FIX 1:

Step1: Go to settings > then select the following configuration(Disable Floppy)

Config

Alternatively, you can press F12 while booting the Guest OS and select CD from there, this is a one time setting, good enough for the installation.

Step 2: Place your Existing Guest OS bootable CD in the Disk Drive and start the Guest OS.

FIX 2:

Go to Settings > And Perform the following:

Config1

FIX 3:

Try Fix 1 & 2 together..

How to enable DataGridView sorting when user clicks on the column header?

I suggest using a DataTable.DefaultView as a DataSource. Then the line below.

foreach (DataGridViewColumn column in gridview.Columns)
    {
       column.SortMode = DataGridViewColumnSortMode.Automatic;
    }

After that the gridview itself will manage sorting(Ascending or Descending is supported.)

Reloading submodules in IPython

I hate to add yet another answer to a long thread, but I found a solution that enables recursive reloading of submodules on %run() that others might find useful (I have anyway)

del the submodule you wish to reload on run from sys.modules in iPython:

In[1]: from sys import modules
In[2]: del modules["mymodule.mysubmodule"] # tab completion can be used like mymodule.<tab>!

Now your script will recursively reload this submodule:

In[3]: %run myscript.py

Java String to JSON conversion

You are getting NullPointerException as the "output" is null when the while loop ends. You can collect the output in some buffer and then use it, something like this-

    StringBuilder buffer = new StringBuilder();
    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
        buffer.append(output);
    }
    output = buffer.toString(); // now you have the output
    conn.disconnect();

Extending from two classes

you can't do multiple inheritance in java. consider using interfaces:

interface I1 {}
interface I2 {}
class C implements I1, I2 {}

or inner classes:

class Outer {
    class Inner1 extends Class1 {}
    class Inner2 extends Class2 {}
}

How to convert HH:mm:ss.SSS to milliseconds?

If you want to use SimpleDateFormat, you could write:

private final SimpleDateFormat sdf =
    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    { sdf.setTimeZone(TimeZone.getTimeZone("GMT")); }

private long parseTimeToMillis(final String time) throws ParseException
    { return sdf.parse("1970-01-01 " + time).getTime(); }

But a custom method would be much more efficient. SimpleDateFormat, because of all its calendar support, time-zone support, daylight-savings-time support, and so on, is pretty slow. The slowness is worth it if you actually need some of those features, but since you don't, it might not be. (It depends how often you're calling this method, and whether efficiency is a concern for your application.)

Also, SimpleDateFormat is non-thread-safe, which is sometimes a pain. (Without knowing anything about your application, I can't guess whether that matters.)

Personally, I'd probably write a custom method.

Hibernate: best practice to pull all lazy collections

Use Hibernate.initialize() within @Transactional to initialize lazy objects.

 start Transaction 
      Hibernate.initialize(entity.getAddresses());
      Hibernate.initialize(entity.getPersons());
 end Transaction 

Now out side of the Transaction you are able to get lazy objects.

entity.getAddresses().size();
entity.getPersons().size();

How do you attach and detach from Docker's process?

I had the same issue, ctrl-P and Q would not work, nor ctrl-C... eventually I opened another terminal session and I did "docker stop containerid " and "docker start containerid " and it got the job done. Weird.

List of macOS text editors and code editors

I have installed both Smultron and Textwrangler, but find myself using Smultron most of the time.

How to kill a process in MacOS?

I have experienced that if kill -9 PID doesn't work and you own the process, you can use kill -s kill PID which is kind of surprising as the man page says you can kill -signal_number PID.

No connection could be made because the target machine actively refused it 127.0.0.1:3446

You don't have to restart the PC. Restart IIS instead.

Run -> 'cmd'(as admin) and type "iisreset"

How to create a .jar file or export JAR in IntelliJ IDEA (like Eclipse Java archive export)?

You didn't specify your IDEA version. Before 9.0 use Build | Build Jars, in IDEA 9.0 use Project Structure | Artifacts.

What is the best way to ensure only one instance of a Bash script is running?

i found this in procmail package dependencies:

apt install liblockfile-bin

To run: dotlockfile -l file.lock

file.lock will be created.

To unlock: dotlockfile -u file.lock

Use this to list this package files / command: dpkg-query -L liblockfile-bin

Show and hide divs at a specific time interval using jQuery

here is a jQuery plugin I came up with:

$.fn.cycle = function(timeout){
    var $all_elem = $(this)

    show_cycle_elem = function(index){
        if(index == $all_elem.length) return; //you can make it start-over, if you want
        $all_elem.hide().eq(index).fadeIn()
        setTimeout(function(){show_cycle_elem(++index)}, timeout);
    }
    show_cycle_elem(0);
}

You need to have a common classname for all the divs you wan to cycle, use it like this:

$("div.cycleme").cycle(5000)

CSS: 100% font size - 100% of what?

As you showed convincingly, the font-size: 100%; will not render the same in all browsers. However, you will set your font face in your CSS file, so this will be the same (or a fallback) in all browsers.

I believe font-size: 100%; can be very useful when combining it with em-based design. As this article shows, this will create a very flexible website.

When is this useful? When your site needs to adapt to the visitors' wishes. Take for example an elderly man that puts his default font-size at 24 px. Or someone with a small screen with a large resolution that increases his default font-size because he otherwise has to squint. Most sites would break, but em-based sites are able to cope with these situations.

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

Search all of Git history for a string?

git rev-list --all | (
    while read revision; do
        git grep -F 'password' $revision
    done
)

Increasing the maximum number of TCP/IP connections in Linux

To improve upon the answer given by derobert,

You can determine what your OS connection limit is by catting nf_conntrack_max.

For example: cat /proc/sys/net/netfilter/nf_conntrack_max

You can use the following script to count the number of tcp connections to a given range of tcp ports. By default 1-65535.

This will confirm whether or not you are maxing out your OS connection limit.

Here's the script.

#!/bin/bash
OS=$(uname)

case "$OS" in
    'SunOS')
            AWK=/usr/bin/nawk
            ;;
    'Linux')
            AWK=/bin/awk
            ;;
    'AIX')
            AWK=/usr/bin/awk
            ;;
esac

netstat -an | $AWK -v start=1 -v end=65535 ' $NF ~ /TIME_WAIT|ESTABLISHED/ && $4 !~ /127\.0\.0\.1/ {
    if ($1 ~ /\./)
            {sip=$1}
    else {sip=$4}

    if ( sip ~ /:/ )
            {d=2}
    else {d=5}

    split( sip, a, /:|\./ )

    if ( a[d] >= start && a[d] <= end ) {
            ++connections;
            }
    }
    END {print connections}'

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

For those who are using xampp:

File -> Preferences -> Settings

"php.validate.executablePath": "C:\\xampp\\php\\php.exe",
"php.executablePath": "C:\\xampp\\php\\php.exe"

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

public FileContentResult GetImage(int productId) { 
     Product prod = repository.Products.FirstOrDefault(p => p.ProductID == productId); 
     if (prod != null) { 
         return File(prod.ImageData, prod.ImageMimeType); 
      } else { 
         return null; 
     } 
}

Load dimension value from res/values/dimension.xml from source code

You can use getDimensionPixelOffset() instead of getDimension, so you didn't have to cast to int.

int valueInPixels = getResources().getDimensionPixelOffset(R.dimen.test)

How to get screen width and height

if (Build.VERSION.SDK_INT >= 11) {
        Point size = new Point();
        try {
            this.getWindowManager().getDefaultDisplay().getRealSize(size);
            screenWidth = size.x;
            screenHeight = size.y;
        } catch (NoSuchMethodError e) {
             screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
             screenWidth=this.getWindowManager().getDefaultDisplay().getWidth();
        }

    } else {
        DisplayMetrics metrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        screenWidth = metrics.widthPixels;
        screenHeight = metrics.heightPixels;
    }

How to prevent scientific notation in R?

Try format function:

> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"

How to fix 'sudo: no tty present and no askpass program specified' error?

For Ubuntu 16.04 users

There is a file you have to read with:

cat /etc/sudoers.d/README

Placing a file with mode 0440 in /etc/sudoers.d/myuser with following content:

myuser  ALL=(ALL) NOPASSWD: ALL

Should fix the issue.

Do not forget to:

chmod 0440 /etc/sudoers.d/myuser

How to fix Cannot find module 'typescript' in Angular 4?

If you use yarn instead of npm, you can install typescript package for that workspace by running:

yarn add typescript

or you can install it globally by running:

sudo yarn global add typescript

to be available for any project.

Making an asynchronous task in Flask

Threading is another possible solution. Although the Celery based solution is better for applications at scale, if you are not expecting too much traffic on the endpoint in question, threading is a viable alternative.

This solution is based on Miguel Grinberg's PyCon 2016 Flask at Scale presentation, specifically slide 41 in his slide deck. His code is also available on github for those interested in the original source.

From a user perspective the code works as follows:

  1. You make a call to the endpoint that performs the long running task.
  2. This endpoint returns 202 Accepted with a link to check on the task status.
  3. Calls to the status link returns 202 while the taks is still running, and returns 200 (and the result) when the task is complete.

To convert an api call to a background task, simply add the @async_api decorator.

Here is a fully contained example:

from flask import Flask, g, abort, current_app, request, url_for
from werkzeug.exceptions import HTTPException, InternalServerError
from flask_restful import Resource, Api
from datetime import datetime
from functools import wraps
import threading
import time
import uuid

tasks = {}

app = Flask(__name__)
api = Api(app)


@app.before_first_request
def before_first_request():
    """Start a background thread that cleans up old tasks."""
    def clean_old_tasks():
        """
        This function cleans up old tasks from our in-memory data structure.
        """
        global tasks
        while True:
            # Only keep tasks that are running or that finished less than 5
            # minutes ago.
            five_min_ago = datetime.timestamp(datetime.utcnow()) - 5 * 60
            tasks = {task_id: task for task_id, task in tasks.items()
                     if 'completion_timestamp' not in task or task['completion_timestamp'] > five_min_ago}
            time.sleep(60)

    if not current_app.config['TESTING']:
        thread = threading.Thread(target=clean_old_tasks)
        thread.start()


def async_api(wrapped_function):
    @wraps(wrapped_function)
    def new_function(*args, **kwargs):
        def task_call(flask_app, environ):
            # Create a request context similar to that of the original request
            # so that the task can have access to flask.g, flask.request, etc.
            with flask_app.request_context(environ):
                try:
                    tasks[task_id]['return_value'] = wrapped_function(*args, **kwargs)
                except HTTPException as e:
                    tasks[task_id]['return_value'] = current_app.handle_http_exception(e)
                except Exception as e:
                    # The function raised an exception, so we set a 500 error
                    tasks[task_id]['return_value'] = InternalServerError()
                    if current_app.debug:
                        # We want to find out if something happened so reraise
                        raise
                finally:
                    # We record the time of the response, to help in garbage
                    # collecting old tasks
                    tasks[task_id]['completion_timestamp'] = datetime.timestamp(datetime.utcnow())

                    # close the database session (if any)

        # Assign an id to the asynchronous task
        task_id = uuid.uuid4().hex

        # Record the task, and then launch it
        tasks[task_id] = {'task_thread': threading.Thread(
            target=task_call, args=(current_app._get_current_object(),
                               request.environ))}
        tasks[task_id]['task_thread'].start()

        # Return a 202 response, with a link that the client can use to
        # obtain task status
        print(url_for('gettaskstatus', task_id=task_id))
        return 'accepted', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
    return new_function


class GetTaskStatus(Resource):
    def get(self, task_id):
        """
        Return status about an asynchronous task. If this request returns a 202
        status code, it means that task hasn't finished yet. Else, the response
        from the task is returned.
        """
        task = tasks.get(task_id)
        if task is None:
            abort(404)
        if 'return_value' not in task:
            return '', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
        return task['return_value']


class CatchAll(Resource):
    @async_api
    def get(self, path=''):
        # perform some intensive processing
        print("starting processing task, path: '%s'" % path)
        time.sleep(10)
        print("completed processing task, path: '%s'" % path)
        return f'The answer is: {path}'


api.add_resource(CatchAll, '/<path:path>', '/')
api.add_resource(GetTaskStatus, '/status/<task_id>')


if __name__ == '__main__':
    app.run(debug=True)

List of enum values in java

An enum is just another class in Java, it should be possible.

More accurately, an enum is an instance of Object: http://docs.oracle.com/javase/6/docs/api/java/lang/Enum.html

So yes, it should work.

How to overwrite files with Copy-Item in PowerShell

Robocopy is designed for reliable copying with many copy options, file selection restart, etc.

/xf to excludes files and /e for subdirectories:

robocopy $copyAdmin $AdminPath /e /xf "web.config" "Deploy"

Find rows that have the same value on a column in MySQL

select email from mytable group by email having count(*) >1

How to stop/terminate a python script from running?

  • To stop a python script just press Ctrl + C.
  • Inside a script with exit(), you can do it.
  • You can do it in an interactive script with just exit.
  • You can use pkill -f name-of-the-python-script.

MySQL: Can't create/write to file '/tmp/#sql_3c6_0.MYI' (Errcode: 2) - What does it even mean?

it's very easy, you just grant the /tmp folder as 777 permission. just type:

chmod -R 777 /tmp

How to check Grants Permissions at Run-Time?

For Location runtime Permission

ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);

public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d("yes","yes");

            } else {
                Log.d("yes","no");
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }
        // other 'case' lines to check for other
        // permissions this app might request
    }
}

How do I create a folder in a GitHub repository?

Click on new file in github repo online. Then write file name as myfolder/myfilename then give file contents and commit. Then file will be created within that new folder.

Why does JSHint throw a warning if I am using const?

If you are using Webstorm and if you don't have your own config file, then just enable EcmaScript.next in Relaxing options in in

Settings | Languages & Frameworks | JavaScript | Code Quality Tools | JSHint

See this question How-do-I-resolve-these-JSHint-ES6-errors

Twitter Bootstrap - how to center elements horizontally or vertically

I like this solution from a similar question. https://stackoverflow.com/a/25036303/2364401 Use bootstraps text-center class on the actual table data <td> and table header <th> elements. So

<td class="text-center">Cell data</td>

and

<th class="text-center">Header cell data</th>

Android Error [Attempt to invoke virtual method 'void android.app.ActionBar' on a null object reference]

Please add after Toolbar

Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().hide();

How do I fix this "TypeError: 'str' object is not callable" error?

this part :

"Your new price is: $"(float(price)

asks python to call this string:

"Your new price is: $"

just like you would a function: function( some_args) which will ALWAYS trigger the error:

TypeError: 'str' object is not callable

How does numpy.histogram() work?

A bin is range that represents the width of a single bar of the histogram along the X-axis. You could also call this the interval. (Wikipedia defines them more formally as "disjoint categories".)

The Numpy histogram function doesn't draw the histogram, but it computes the occurrences of input data that fall within each bin, which in turns determines the area (not necessarily the height if the bins aren't of equal width) of each bar.

In this example:

 np.histogram([1, 2, 1], bins=[0, 1, 2, 3])

There are 3 bins, for values ranging from 0 to 1 (excl 1.), 1 to 2 (excl. 2) and 2 to 3 (incl. 3), respectively. The way Numpy defines these bins if by giving a list of delimiters ([0, 1, 2, 3]) in this example, although it also returns the bins in the results, since it can choose them automatically from the input, if none are specified. If bins=5, for example, it will use 5 bins of equal width spread between the minimum input value and the maximum input value.

The input values are 1, 2 and 1. Therefore, bin "1 to 2" contains two occurrences (the two 1 values), and bin "2 to 3" contains one occurrence (the 2). These results are in the first item in the returned tuple: array([0, 2, 1]).

Since the bins here are of equal width, you can use the number of occurrences for the height of each bar. When drawn, you would have:

  • a bar of height 0 for range/bin [0,1] on the X-axis,
  • a bar of height 2 for range/bin [1,2],
  • a bar of height 1 for range/bin [2,3].

You can plot this directly with Matplotlib (its hist function also returns the bins and the values):

>>> import matplotlib.pyplot as plt
>>> plt.hist([1, 2, 1], bins=[0, 1, 2, 3])
(array([0, 2, 1]), array([0, 1, 2, 3]), <a list of 3 Patch objects>)
>>> plt.show()

enter image description here

How to update ruby on linux (ubuntu)?

There's really no reason to remove ruby1-8, unless someone else knows better. Execute the commands below to install 1.9 and then link ruby to point to the new version.

sudo apt-get install ruby1-9 rubygems1-9
sudo ln -sf /usr/bin/ruby1-9 /usr/bin/ruby

Failed to find 'ANDROID_HOME' environment variable

In Linux

First of all set ANDROID_HOME in .bashrc file

Run command

sudo gedit ~/.bashrc

set andoid sdk path where you have installed

export ANDROID_HOME=/opt/android-sdk-linux 
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

to reload file run command

source ~/.bashrc

Now check installed platform, run command

ionic platform

Output

Installed platforms:
  android 6.0.0
Available platforms: 
  amazon-fireos ~3.6.3 (deprecated)
  blackberry10 ~3.8.0
  browser ~4.1.0
  firefoxos ~3.6.3
  ubuntu ~4.3.4
  webos ~3.7.0

if android already installed then need to remove and install again

ionic platform rm android
ionic platform add android

If not installed already please add android platform

ionic platform add android

Please make sure you have added android platform without sudo command

if you still getting error in adding android platfrom like following

Error: EACCES: permission denied, open '/home/ubuntu/.cordova/lib/npm_cache/cordova-android/6.0.0/package/package.json'

Please go to /home/ubuntu/ and remove .cordova folder from there

cd /home/ubuntu/
sudo rm -r .cordova

Now run following command again

ionic platform add android

after adding platform successfully you will be able to build andoid in ionic.

Thanks

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

My machine showed me a BIOS update and I wondered if that has something to do with the sudden popping-up of this error. And after I did the update, the error was resolved and the solution built fine.

In LaTeX, how can one add a header/footer in the document class Letter?

This code works to insert both header and footer on the first page with header center aligned and footer left aligned

\makeatletter
\let\old@ps@headings\ps@headings
\let\old@ps@IEEEtitlepagestyle\ps@IEEEtitlepagestyle
\def\confheader#1{%
  % for the first page
  \def\ps@IEEEtitlepagestyle{%
    \old@ps@IEEEtitlepagestyle%
    \def\@oddhead{\strut\hfill#1\hfill\strut}%
    \def\@evenhead{\strut\hfill#1\hfill\strut}%
 \def\@oddfoot{\mycopyrightnotice}
  \def\@evenfoot{}
  }%
  \ps@headings%
}
\makeatother

\confheader{%
  5$^{th}$  IEEE International Conference on Recent Advances and Innovations in Engineering - ICRAIE 2020 (IEEE Record\#51050) %EDIT HERE
}

\def\mycopyrightnotice{
  {\footnotesize XXX-1-7281-8867-6/20/\$31.00~\copyright~2020 IEEE\hfill} % EDIT HERE
  \gdef\mycopyrightnotice{}

}

\newcommand*{\affmark}[1][*]{\textsuperscript{#1}}


\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em
    T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}}
\newcommand{\ma}[1]{\mbox{\boldmath$#1$}} ```

How to do a GitHub pull request

For those of us who have a github.com account, but only get a nasty error message when we type "git" into the command-line, here's how to do it all in your browser :)

  1. Same as Tim and Farhan wrote: Fork your own copy of the project: Step 1: Fork
  2. After a few seconds, you'll be redirected to your own forked copy of the project: Step 2
  3. Navigate to the file(s) you need to change and click "Edit this file" in the toolbar: Step 3: Edit a file
  4. After editing, write a few words describing the changes and then "Commit changes", just as well to the master branch (since this is only your own copy and not the "main" project). Step 4: Commit changes
  5. Repeat steps 3 and 4 for all files you need to edit, and then go back to the root of your copy of the project. There, click the green "Compare, review..." button: Step 5: Start submit
  6. Finally, click "Create pull request" ..and then "Create pull request" again after you've double-checked your request's heading and description: enter image description here

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

Postgres hasn't implemented an equivalent to INSERT OR REPLACE. From the ON CONFLICT docs (emphasis mine):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE applies more generally, since it lets you set new values based on preexisting data. For example:

INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;

How to ignore conflicts in rpm installs

From the context, the conflict was caused by the version of the package.
Let's take a look the manual about rpm:

--force
    Same as using --replacepkgs, --replacefiles, and --oldpackage.

--oldpackage
    Allow an upgrade to replace a newer package with an older one.

So, you can execute the command rpm -Uvh info-4.13a-2.rpm --force to solve your issue.

"Parameter not valid" exception loading System.Drawing.Image

My guess is that byteArrayIn doesn't contain valid image data.

Please give more information though:

  • Which line of code is throwing an exception?
  • What's the message?
  • Where did you get byteArrayIn from, and are you sure it should contain a valid image?

Mongoose: Find, modify, save

If you want to use find, like I would for any validation you want to do on the client side.

find returns an ARRAY of objects

findOne returns only an object

Adding user = user[0] made the save method work for me.

Here is where you put it.

User.find({username: oldUsername}, function (err, user) {
    user = user[0];
    user.username = newUser.username;
    user.password = newUser.password;
    user.rights = newUser.rights;

    user.save(function (err) {
        if(err) {
            console.error('ERROR!');
        }
    });
});

Reset the Value of a Select Box

use the .val('') setter

jsfiddle example

$('select').val('1');

How to include bootstrap css and js in reactjs app?

you can install it dirctly via

$ npm install --save react react-dom
$ npm install --save react-bootstrap

then import what you really need from the bootstrap like :

import Button from 'react-bootstrap/lib/Button';

// or

import  Button  from 'react-bootstrap';

and also you can install :

npm install --save reactstrap@next react react-dom

check this out click here .

and for the CSS you can read this link also carfuly

read here

Questions every good Java/Java EE Developer should be able to answer?

Core: 1. What are checked and unchecked exceptions ? 2. While adding new exception in code what type (Checked/Unchecked) to use when ?

Servlet: 1. What is the difference between response.sendRedirect() and request.forward() ?

How to get jSON response into variable from a jquery script

Your PHP array is defined as:

$arr = array ('resonse'=>'error','comment'=>'test comment here');

Notice the mispelling "resonse". Also, as RaYell has mentioned, you have to use data instead of json in your success function because its parameter is currently data.

Try editing your PHP file to change the spelling form resonse to response. It should work then.

Save bitmap to file function

In kotlin :

private fun File.writeBitmap(bitmap: Bitmap, format: Bitmap.CompressFormat, quality: Int) {
    outputStream().use { out ->
        bitmap.compress(format, quality, out)
        out.flush()
    }
}

usage example:

File(exportDir, "map.png").writeBitmap(bitmap, Bitmap.CompressFormat.PNG, 85)

How to create timer events using C++ 11?

Use RxCpp,

std::cout << "Waiting..." << std::endl;
auto values = rxcpp::observable<>::timer<>(std::chrono::seconds(1));
values.subscribe([](int v) {std::cout << "Called after 1s." << std::endl;});

Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed

It may be that the Windows Credential Manager is holding onto credentials for the network share.

Credential Manager - Windows Credentials

Load up Credential Manager (the easiest way is perhaps just to Search for that in the Start Menu), see if there are any Windows Credentials for your network share, and try deleting/updating them.

DB2 SQL error sqlcode=-104 sqlstate=42601

You miss the from clause

SELECT *  from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME  BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP

Test if characters are in a string

Answer

Sigh, it took me 45 minutes to find the answer to this simple question. The answer is: grepl(needle, haystack, fixed=TRUE)

# Correct
> grepl("1+2", "1+2", fixed=TRUE)
[1] TRUE
> grepl("1+2", "123+456", fixed=TRUE)
[1] FALSE

# Incorrect
> grepl("1+2", "1+2")
[1] FALSE
> grepl("1+2", "123+456")
[1] TRUE

Interpretation

grep is named after the linux executable, which is itself an acronym of "Global Regular Expression Print", it would read lines of input and then print them if they matched the arguments you gave. "Global" meant the match could occur anywhere on the input line, I'll explain "Regular Expression" below, but the idea is it's a smarter way to match the string (R calls this "character", eg class("abc")), and "Print" because it's a command line program, emitting output means it prints to its output string.

Now, the grep program is basically a filter, from lines of input, to lines of output. And it seems that R's grep function similarly will take an array of inputs. For reasons that are utterly unknown to me (I only started playing with R about an hour ago), it returns a vector of the indexes that match, rather than a list of matches.

But, back to your original question, what we really want is to know whether we found the needle in the haystack, a true/false value. They apparently decided to name this function grepl, as in "grep" but with a "Logical" return value (they call true and false logical values, eg class(TRUE)).

So, now we know where the name came from and what it's supposed to do. Lets get back to Regular Expressions. The arguments, even though they are strings, they are used to build regular expressions (henceforth: regex). A regex is a way to match a string (if this definition irritates you, let it go). For example, the regex a matches the character "a", the regex a* matches the character "a" 0 or more times, and the regex a+ would match the character "a" 1 or more times. Hence in the example above, the needle we are searching for 1+2, when treated as a regex, means "one or more 1 followed by a 2"... but ours is followed by a plus!

1+2 as a regex

So, if you used the grepl without setting fixed, your needles would accidentally be haystacks, and that would accidentally work quite often, we can see it even works for the OP's example. But that's a latent bug! We need to tell it the input is a string, not a regex, which is apparently what fixed is for. Why fixed? No clue, bookmark this answer b/c you're probably going to have to look it up 5 more times before you get it memorized.

A few final thoughts

The better your code is, the less history you have to know to make sense of it. Every argument can have at least two interesting values (otherwise it wouldn't need to be an argument), the docs list 9 arguments here, which means there's at least 2^9=512 ways to invoke it, that's a lot of work to write, test, and remember... decouple such functions (split them up, remove dependencies on each other, string things are different than regex things are different than vector things). Some of the options are also mutually exclusive, don't give users incorrect ways to use the code, ie the problematic invocation should be structurally nonsensical (such as passing an option that doesn't exist), not logically nonsensical (where you have to emit a warning to explain it). Put metaphorically: replacing the front door in the side of the 10th floor with a wall is better than hanging a sign that warns against its use, but either is better than neither. In an interface, the function defines what the arguments should look like, not the caller (because the caller depends on the function, inferring everything that everyone might ever want to call it with makes the function depend on the callers, too, and this type of cyclical dependency will quickly clog a system up and never provide the benefits you expect). Be very wary of equivocating types, it's a design flaw that things like TRUE and 0 and "abc" are all vectors.

C# ASP.NET Single Sign-On Implementation

I am late to the party, but for option #1, I would go with IdentityServer3(.NET 4.6 or below) or IdentityServer4 (compatible with Core) .

You can reuse your existing user store in your app and plug that to be IdentityServer's User Store. Then the clients must be pointed to your IdentityServer as the open id provider.

Java FileWriter how to write to next Line

.newLine() is the best if your system property line.separator is proper . and sometime you don't want to change the property runtime . So alternative solution is appending \n

Can Json.NET serialize / deserialize to / from a stream?

I arrived at this question looking for a way to stream an open ended list of objects onto a System.IO.Stream and read them off the other end, without buffering the entire list before sending. (Specifically I'm streaming persisted objects from MongoDB over Web API.)

@Paul Tyng and @Rivers did an excellent job answering the original question, and I used their answers to build a proof of concept for my problem. I decided to post my test console app here in case anyone else is facing the same issue.

using System;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace TestJsonStream {
    class Program {
        static void Main(string[] args) {
            using(var writeStream = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.None)) {
                string pipeHandle = writeStream.GetClientHandleAsString();
                var writeTask = Task.Run(() => {
                    using(var sw = new StreamWriter(writeStream))
                    using(var writer = new JsonTextWriter(sw)) {
                        var ser = new JsonSerializer();
                        writer.WriteStartArray();
                        for(int i = 0; i < 25; i++) {
                            ser.Serialize(writer, new DataItem { Item = i });
                            writer.Flush();
                            Thread.Sleep(500);
                        }
                        writer.WriteEnd();
                        writer.Flush();
                    }
                });
                var readTask = Task.Run(() => {
                    var sw = new Stopwatch();
                    sw.Start();
                    using(var readStream = new AnonymousPipeClientStream(pipeHandle))
                    using(var sr = new StreamReader(readStream))
                    using(var reader = new JsonTextReader(sr)) {
                        var ser = new JsonSerializer();
                        if(!reader.Read() || reader.TokenType != JsonToken.StartArray) {
                            throw new Exception("Expected start of array");
                        }
                        while(reader.Read()) {
                            if(reader.TokenType == JsonToken.EndArray) break;
                            var item = ser.Deserialize<DataItem>(reader);
                            Console.WriteLine("[{0}] Received item: {1}", sw.Elapsed, item);
                        }
                    }
                });
                Task.WaitAll(writeTask, readTask);
                writeStream.DisposeLocalCopyOfClientHandle();
            }
        }

        class DataItem {
            public int Item { get; set; }
            public override string ToString() {
                return string.Format("{{ Item = {0} }}", Item);
            }
        }
    }
}

Note that you may receive an exception when the AnonymousPipeServerStream is disposed, I ignored this as it isn't relevant to the problem at hand.

Test if something is not undefined in JavaScript

response[0] is not defined, check if it is defined and then check for its property title.

if(typeof response[0] !== 'undefined' && typeof response[0].title !== 'undefined'){
    //Do something
}

How do I run Visual Studio as an administrator by default?

windows 8

there is no advanced tab anymore. So, to do it automatically, you need to follow the next steps :

-right click on the shortcut
-click on properties
-under the "Shortcut" tab, click on "Open File Location"
-then, right click on devenv.exe
-Troubleshoot compatibility
-Troubleshoot program
-Check "The program requires additional permissions"
-Then next, next next,...

Solution to INSTALL_FAILED_INSUFFICIENT_STORAGE error on Android

I feel a bit weird writing this, but I can't be 100% sure that it's not true in some cases (it worked for me). If you had the following symptoms:

  • You've been working using a physical device (in my case, Samsung Galaxy Ace),
  • You've been developing for a couple of days straight,
  • Your phone was connected all the time, day and night.
  • You started getting this error after a couple of days, and it kept getting worse.
  • None of the other answers worked for you.
  • You're as resigned as I was...

Then, try this:

  • Unplug your phone when you're not working!

I unplugged my phone and let it rest for ENTIRE DAY. My battery wore off a little. After this, I reconnected it and started debugging again. Everything worked fine this time! And I mean really REALLY fine, just as before.

Is it possible that this error might be due to some battery-related hardware stuff? It still feels weird thinking this way, but now I keep disconnecting my phone every now and then (and for the night) and the problem didn't return.

Removing duplicates from rows based on specific columns in an RDD/Spark DataFrame

I used inbuilt function dropDuplicates(). Scala code given below

val data = sc.parallelize(List(("Foo",41,"US",3),
("Foo",39,"UK",1),
("Bar",57,"CA",2),
("Bar",72,"CA",2),
("Baz",22,"US",6),
("Baz",36,"US",6))).toDF("x","y","z","count")

data.dropDuplicates(Array("x","count")).show()

Output :

+---+---+---+-----+
|  x|  y|  z|count|
+---+---+---+-----+
|Baz| 22| US|    6|
|Foo| 39| UK|    1|
|Foo| 41| US|    3|
|Bar| 57| CA|    2|
+---+---+---+-----+

Use PHP to create, edit and delete crontab jobs?

Check a cronjob

function cronjob_exists($command){

    $cronjob_exists=false;

    exec('crontab -l', $crontab);


    if(isset($crontab)&&is_array($crontab)){

        $crontab = array_flip($crontab);

        if(isset($crontab[$command])){

            $cronjob_exists=true;

        }

    }
    return $cronjob_exists;
}

Append a cronjob

function append_cronjob($command){

    if(is_string($command)&&!empty($command)&&cronjob_exists($command)===FALSE){

        //add job to crontab
        exec('echo -e "`crontab -l`\n'.$command.'" | crontab -', $output);


    }

    return $output;
}

Remove a crontab

exec('crontab -r', $crontab);

Example

exec('crontab -r', $crontab);

append_cronjob('* * * * * curl -s http://localhost/cron/test1.php');

append_cronjob('* * * * * curl -s http://localhost/cron/test2.php');

append_cronjob('* * * * * curl -s http://localhost/cron/test3.php');

Horizontal scroll on overflow of table

The solution for those who cannot or do not want to wrap the table in a div (e.g. if the HTML is generated from Markdown) but still want to have scrollbars:

_x000D_
_x000D_
table {_x000D_
  display: block;_x000D_
  max-width: -moz-fit-content;_x000D_
  max-width: fit-content;_x000D_
  margin: 0 auto;_x000D_
  overflow-x: auto;_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>Especially on mobile, a table can easily become wider than the viewport.</td>_x000D_
    <td>Using the right CSS, you can get scrollbars on the table without wrapping it.</td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>A centered table.</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Explanation: display: block; makes it possible to have scrollbars. By default (and unlike tables), blocks span the full width of the parent element. This can be prevented with max-width: fit-content;, which allows you to still horizontally center tables with less content using margin: 0 auto;. white-space: nowrap; is optional (but useful for this demonstration).

How to iterate over associative arrays in Bash

You can access the keys with ${!array[@]}:

bash-4.0$ echo "${!array[@]}"
foo bar

Then, iterating over the key/value pairs is easy:

for i in "${!array[@]}"
do
  echo "key :" $i
  echo "value:" ${array[$i]}
done

create a text file using javascript

That works better with this :

var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();

http://msdn.microsoft.com/en-us/library/5t9b5c0c(v=vs.84).aspx

Why and when to use angular.copy? (Deep Copy)

Use angular.copy when assigning value of object or array to another variable and that object value should not be changed.

Without deep copy or using angular.copy, changing value of property or adding any new property update all object referencing that same object.

_x000D_
_x000D_
var app = angular.module('copyExample', []);_x000D_
app.controller('ExampleController', ['$scope',_x000D_
  function($scope) {_x000D_
    $scope.printToConsole = function() {_x000D_
      $scope.main = {_x000D_
        first: 'first',_x000D_
        second: 'second'_x000D_
      };_x000D_
_x000D_
      $scope.child = angular.copy($scope.main);_x000D_
      console.log('Main object :');_x000D_
      console.log($scope.main);_x000D_
      console.log('Child object with angular.copy :');_x000D_
      console.log($scope.child);_x000D_
_x000D_
      $scope.child.first = 'last';_x000D_
      console.log('New Child object :')_x000D_
      console.log($scope.child);_x000D_
      console.log('Main object after child change and using angular.copy :');_x000D_
      console.log($scope.main);_x000D_
      console.log('Assing main object without copy and updating child');_x000D_
_x000D_
      $scope.child = $scope.main;_x000D_
      $scope.child.first = 'last';_x000D_
      console.log('Main object after update:');_x000D_
      console.log($scope.main);_x000D_
      console.log('Child object after update:');_x000D_
      console.log($scope.child);_x000D_
    }_x000D_
  }_x000D_
]);_x000D_
_x000D_
// Basic object assigning example_x000D_
_x000D_
var main = {_x000D_
  first: 'first',_x000D_
  second: 'second'_x000D_
};_x000D_
var one = main; // same as main_x000D_
var two = main; // same as main_x000D_
_x000D_
console.log('main :' + JSON.stringify(main)); // All object are same_x000D_
console.log('one :' + JSON.stringify(one)); // All object are same_x000D_
console.log('two :' + JSON.stringify(two)); // All object are same_x000D_
_x000D_
two = {_x000D_
  three: 'three'_x000D_
}; // two changed but one and main remains same_x000D_
console.log('main :' + JSON.stringify(main)); // one and main are same_x000D_
console.log('one :' + JSON.stringify(one)); // one and main are same_x000D_
console.log('two :' + JSON.stringify(two)); // two is changed_x000D_
_x000D_
two = main; // same as main_x000D_
_x000D_
two.first = 'last'; // change value of object's property so changed value of all object property _x000D_
_x000D_
console.log('main :' + JSON.stringify(main)); // All object are same with new value_x000D_
console.log('one :' + JSON.stringify(one)); // All object are same with new value_x000D_
console.log('two :' + JSON.stringify(two)); // All object are same with new value
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="copyExample" ng-controller="ExampleController">_x000D_
  <button ng-click='printToConsole()'>Explain</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to validate an Email in PHP?

You can use the filter_var() function, which gives you a lot of handy validation and sanitization options.

filter_var($email, FILTER_VALIDATE_EMAIL)

If you don't want to change your code that relied on your function, just do:

function isValidEmail($email){ 
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

Note: For other uses (where you need Regex), the deprecated ereg function family (POSIX Regex Functions) should be replaced by the preg family (PCRE Regex Functions). There are a small amount of differences, reading the Manual should suffice.

Update 1: As pointed out by @binaryLV:

PHP 5.3.3 and 5.2.14 had a bug related to FILTER_VALIDATE_EMAIL, which resulted in segfault when validating large values. Simple and safe workaround for this is using strlen() before filter_var(). I'm not sure about 5.3.4 final, but it is written that some 5.3.4-snapshot versions also were affected.

This bug has already been fixed.

Update 2: This method will of course validate bazmega@kapa as a valid email address, because in fact it is a valid email address. But most of the time on the Internet, you also want the email address to have a TLD: [email protected]. As suggested in this blog post (link posted by @Istiaque Ahmed), you can augment filter_var() with a regex that will check for the existence of a dot in the domain part (will not check for a valid TLD though):

function isValidEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) 
        && preg_match('/@.+\./', $email);
}

As @Eliseo Ocampos pointed out, this problem only exists before PHP 5.3, in that version they changed the regex and now it does this check, so you do not have to.

ALTER table - adding AUTOINCREMENT in MySQL

ALTER TABLE `ALLITEMS`
    CHANGE COLUMN `itemid` `itemid` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT;

How to get EditText value and display it on screen through TextView?

in "String.xml" you can notice any String or value you want to use, here are two examples:

<string name="app_name">My Calculator App
    </string>
<color name="color_menu_home">#ffcccccc</color>

Used for the layout.xml: android:text="@string/app_name"

The advantage: you can use them as often you want, you only need to link them in your Layout-xml, and you can change the String-Content easily in the strings.xml, without searching in your source-code for the right position. Important for changing language, you only need to replace the strings.xml - file

Android studio- "SDK tools directory is missing"

I experienced this error when I was installing Android Studio with too little memory to install everything needed. It didn't help freeing up memory or installing Android SDK my self. Re-installing Android studio with sufficient memory, made the download start when I first opened up Android Studio.

Responding with a JSON object in Node.js (converting object/array to JSON string)

Per JamieL's answer to another post:

Since Express.js 3x the response object has a json() method which sets all the headers correctly for you.

Example:

res.json({"foo": "bar"});

Download a file by jQuery.Ajax

The simple way to make the browser downloads a file is to make the request like that:

 function downloadFile(urlToSend) {
     var req = new XMLHttpRequest();
     req.open("GET", urlToSend, true);
     req.responseType = "blob";
     req.onload = function (event) {
         var blob = req.response;
         var fileName = req.getResponseHeader("fileName") //if you have the fileName header available
         var link=document.createElement('a');
         link.href=window.URL.createObjectURL(blob);
         link.download=fileName;
         link.click();
     };

     req.send();
 }

This opens the browser download pop up.

Importing xsd into wsdl

import vs. include

The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import statement with an include statement).

Another area of confusion is how to specify the location or path of the included .xsd file: An XSD import statement has an optional attribute named schemaLocation but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.

When you do chose to use an external .xsd file for your WSDL, the schemaLocation attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:

WSDL:

xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>

XSD:

<xsd:schema targetNamespace="urn:listing3"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 

Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>xmlbeans-maven-plugin</artifactId>
  <executions>
    <execution>
      <id>generate-sources-xmlbeans</id>
      <phase>generate-sources</phase>
      <goals>
    <goal>xmlbeans</goal>
      </goals>
    </execution>
  </executions>
  <version>2.3.3</version>
  <inherited>true</inherited>
  <configuration>
    <schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
  </configuration>
</plugin>

You can read more on this in this great IBM article. It has typos such as xsd:import instead of xs:import but otherwise it's fine.

What is App.config in C#.NET? How to use it?

You can access keys in the App.Config using:

ConfigurationSettings.AppSettings["KeyName"]

Take alook at this Thread

How to play .wav files with java

You can use an event listener to close the clip after it is played

import java.io.File;
import javax.sound.sampled.*;

public void play(File file) 
{
    try
    {
        final Clip clip = (Clip)AudioSystem.getLine(new Line.Info(Clip.class));

        clip.addLineListener(new LineListener()
        {
            @Override
            public void update(LineEvent event)
            {
                if (event.getType() == LineEvent.Type.STOP)
                    clip.close();
            }
        });

        clip.open(AudioSystem.getAudioInputStream(file));
        clip.start();
    }
    catch (Exception exc)
    {
        exc.printStackTrace(System.out);
    }
}

Oracle SELECT TOP 10 records

With regards to the poor performance there are any number of things it could be, and it really ought to be a separate question. However, there is one obvious thing that could be a problem:

WHERE TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') = '06.02.2009') 

If HISTORY_DATE really is a date column and if it has an index then this rewrite will perform better:

WHERE HISTORY_DATE = TO_DATE ('06.02.2009', 'DD.MM.YYYY')  

This is because a datatype conversion disables the use of a B-Tree index.

How do I mock a static method that returns void with PowerMock?

You can stub a static void method like this:

PowerMockito.doNothing().when(StaticResource.class, "getResource", anyString());

Although I'm not sure why you would bother, because when you call mockStatic(StaticResource.class) all static methods in StaticResource are by default stubbed

More useful, you can capture the value passed to StaticResource.getResource() like this:

ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
PowerMockito.doNothing().when(
               StaticResource.class, "getResource", captor.capture());

Then you can evaluate the String that was passed to StaticResource.getResource like this:

String resourceName = captor.getValue();

BSTR to std::string (std::wstring) and vice versa

BSTR to std::wstring:

// given BSTR bs
assert(bs != nullptr);
std::wstring ws(bs, SysStringLen(bs));

 
std::wstring to BSTR:

// given std::wstring ws
assert(!ws.empty());
BSTR bs = SysAllocStringLen(ws.data(), ws.size());

Doc refs:

  1. std::basic_string<typename CharT>::basic_string(const CharT*, size_type)
  2. std::basic_string<>::empty() const
  3. std::basic_string<>::data() const
  4. std::basic_string<>::size() const
  5. SysStringLen()
  6. SysAllocStringLen()

IIS_IUSRS and IUSR permissions in IIS8

I hate to post my own answer, but some answers recently have ignored the solution I posted in my own question, suggesting approaches that are nothing short of foolhardy.

In short - you do not need to edit any Windows user account privileges at all. Doing so only introduces risk. The process is entirely managed in IIS using inherited privileges.

Applying Modify/Write Permissions to the Correct User Account

  1. Right-click the domain when it appears under the Sites list, and choose Edit Permissions

    enter image description here

    Under the Security tab, you will see MACHINE_NAME\IIS_IUSRS is listed. This means that IIS automatically has read-only permission on the directory (e.g. to run ASP.Net in the site). You do not need to edit this entry.

    enter image description here

  2. Click the Edit button, then Add...

  3. In the text box, type IIS AppPool\MyApplicationPoolName, substituting MyApplicationPoolName with your domain name or whatever application pool is accessing your site, e.g. IIS AppPool\mydomain.com

    enter image description here

  4. Press the Check Names button. The text you typed will transform (notice the underline):

    enter image description here

  5. Press OK to add the user

  6. With the new user (your domain) selected, now you can safely provide any Modify or Write permissions

    enter image description here

Using Excel VBA to run SQL query

Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

Singular matrix issue with Numpy

Use SVD or QR-decomposition to calculate exact solution in real or complex number fields:

numpy.linalg.svd numpy.linalg.qr

.NET: Simplest way to send POST with data and read response

I know this is an old thread, but hope it helps some one.

public static void SetRequest(string mXml)
{
    HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp("http://dork.com/service");
    webRequest.Method = "POST";
    webRequest.Headers["SOURCE"] = "WinApp";

    // Decide your encoding here

    //webRequest.ContentType = "application/x-www-form-urlencoded";
    webRequest.ContentType = "text/xml; charset=utf-8";

    // You should setContentLength
    byte[] content = System.Text.Encoding.UTF8.GetBytes(mXml);
    webRequest.ContentLength = content.Length;

    var reqStream = await webRequest.GetRequestStreamAsync();
    reqStream.Write(content, 0, content.Length);

    var res = await httpRequest(webRequest);
}

A reference to the dll could not be added

You can add a DLL (or EXE) to a project only if it is a .NET assembly. If it's not you will see this error message.

regsvr32 also makes certain assumptions about the structure and exported function in the DLL. It has been a while since I used it but it has to do with registering COM servers so certain entry points need to be available. If regsvr32 fails the DLL doesn't provide those entry points and the DLL does not contain a COM component.

You only chance for using the DLL is to import it like any other non-.NET binary, e.g. when you use certain Win32 APIs. There is an old MSDN Magazine Article that might be helpful. See the following update for info where to get the article.

Update 12 March 2018: The link to the MSDN Magazine no longer works as it used to in August 2010. The article by Jason Clark is titled ".NET Column: Calling Win32 DLLs in C# with P/Invoke". It was published in the July 2010 issue of MSDN Magazine. The "Wayback Machine" has the article here at the moment (formatting is limited). The entire MSDN Magazine issue July 2010 is available here (HCM format only, instructions for how to use HCM files here).

How does HTTP file upload work?

Let's take a look at what happens when you select a file and submit your form (I've truncated the headers for brevity):

POST /upload?upload_progress_id=12344 HTTP/1.1
Host: localhost:3000
Content-Length: 1325
Origin: http://localhost:3000
... other headers ...
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryePkpFF7tjBAqx29L

------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="MAX_FILE_SIZE"

100000
------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="uploadedfile"; filename="hello.o"
Content-Type: application/x-object

... contents of file goes here ...
------WebKitFormBoundaryePkpFF7tjBAqx29L--

NOTE: each boundary string must be prefixed with an extra --, just like in the end of the last boundary string. The example above already includes this, but it can be easy to miss. See comment by @Andreas below.

Instead of URL encoding the form parameters, the form parameters (including the file data) are sent as sections in a multipart document in the body of the request.

In the example above, you can see the input MAX_FILE_SIZE with the value set in the form, as well as a section containing the file data. The file name is part of the Content-Disposition header.

The full details are here.

Easy way to prevent Heroku idling?

Easy answer--if you value the service then pay for it.

All these 'tricks' to get the benefits of paid service...well it's essentially like stealing cable. Questionable to even list them here. What's next, tricks on how to pirate games?

Like another poster here, I value the free service for development and testing and I will be greatly annoyed at all you ethics-impaired types if Heroku does away with it because there are too many freeloaders. I just don't think he was direct enough in his criticism.

JavaScript math, round to two decimal places

To handle rounding to any number of decimal places, a function with 2 lines of code will suffice for most needs. Here's some sample code to play with.



    var testNum = 134.9567654;
    var decPl = 2;
    var testRes = roundDec(testNum,decPl);  
    alert (testNum + ' rounded to ' + decPl + ' decimal places is ' + testRes);

    function roundDec(nbr,dec_places){
        var mult = Math.pow(10,dec_places);
        return Math.round(nbr * mult) / mult;
    }

Is there a way to define a min and max value for EditText in Android?

this is my code max=100, min=0

xml

<TextView
                    android:id="@+id/txt_Mass_smallWork"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textColor="#000"
                    android:textSize="20sp"
                    android:textStyle="bold" />

java

EditText ed = findViewById(R.id.txt_Mass_smallWork);
    ed.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {`

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if(!charSequence.equals("")) {
                int massValue = Integer.parseInt(charSequence.toString());
                if (massValue > 10) {
                    ed.setFilters(new InputFilter[]{new InputFilter.LengthFilter(2)});
                } else {
                    ed.setFilters(new InputFilter[]{new InputFilter.LengthFilter(3)});
                }
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

Move it to the Trusted Sites zone by either adding it to a Trusted Sites list or local setting. This will move it out of Intranet Zone and will not be rendered in Compat. View.

C Programming: How to read the whole file contents into a buffer

Here is what I would recommend.

It should conform to C89, and be completely portable. In particular, it works also on pipes and sockets on POSIXy systems.

The idea is that we read the input in large-ish chunks (READALL_CHUNK), dynamically reallocating the buffer as we need it. We only use realloc(), fread(), ferror(), and free():

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

/* Size of each input chunk to be
   read and allocate for. */
#ifndef  READALL_CHUNK
#define  READALL_CHUNK  262144
#endif

#define  READALL_OK          0  /* Success */
#define  READALL_INVALID    -1  /* Invalid parameters */
#define  READALL_ERROR      -2  /* Stream error */
#define  READALL_TOOMUCH    -3  /* Too much input */
#define  READALL_NOMEM      -4  /* Out of memory */

/* This function returns one of the READALL_ constants above.
   If the return value is zero == READALL_OK, then:
     (*dataptr) points to a dynamically allocated buffer, with
     (*sizeptr) chars read from the file.
     The buffer is allocated for one extra char, which is NUL,
     and automatically appended after the data.
   Initial values of (*dataptr) and (*sizeptr) are ignored.
*/
int readall(FILE *in, char **dataptr, size_t *sizeptr)
{
    char  *data = NULL, *temp;
    size_t size = 0;
    size_t used = 0;
    size_t n;

    /* None of the parameters can be NULL. */
    if (in == NULL || dataptr == NULL || sizeptr == NULL)
        return READALL_INVALID;

    /* A read error already occurred? */
    if (ferror(in))
        return READALL_ERROR;

    while (1) {

        if (used + READALL_CHUNK + 1 > size) {
            size = used + READALL_CHUNK + 1;

            /* Overflow check. Some ANSI C compilers
               may optimize this away, though. */
            if (size <= used) {
                free(data);
                return READALL_TOOMUCH;
            }

            temp = realloc(data, size);
            if (temp == NULL) {
                free(data);
                return READALL_NOMEM;
            }
            data = temp;
        }

        n = fread(data + used, 1, READALL_CHUNK, in);
        if (n == 0)
            break;

        used += n;
    }

    if (ferror(in)) {
        free(data);
        return READALL_ERROR;
    }

    temp = realloc(data, used + 1);
    if (temp == NULL) {
        free(data);
        return READALL_NOMEM;
    }
    data = temp;
    data[used] = '\0';

    *dataptr = data;
    *sizeptr = used;

    return READALL_OK;
}

Above, I've used a constant chunk size, READALL_CHUNK == 262144 (256*1024). This means that in the worst case, up to 262145 chars are wasted (allocated but not used), but only temporarily. At the end, the function reallocates the buffer to the optimal size. Also, this means that we do four reallocations per megabyte of data read.

The 262144-byte default in the code above is a conservative value; it works well for even old minilaptops and Raspberry Pis and most embedded devices with at least a few megabytes of RAM available for the process. Yet, it is not so small that it slows down the operation (due to many read calls, and many buffer reallocations) on most systems.

For desktop machines at this time (2017), I recommend a much larger READALL_CHUNK, perhaps #define READALL_CHUNK 2097152 (2 MiB).

Because the definition of READALL_CHUNK is guarded (i.e., it is defined only if it is at that point in the code still undefined), you can override the default value at compile time, by using (in most C compilers) -DREADALL_CHUNK=2097152 command-line option -- but do check your compiler options for defining a preprocessor macro using command-line options.

What is the best project structure for a Python application?

In my experience, it's just a matter of iteration. Put your data and code wherever you think they go. Chances are, you'll be wrong anyway. But once you get a better idea of exactly how things are going to shape up, you're in a much better position to make these kinds of guesses.

As far as extension sources, we have a Code directory under trunk that contains a directory for python and a directory for various other languages. Personally, I'm more inclined to try putting any extension code into its own repository next time around.

With that said, I go back to my initial point: don't make too big a deal out of it. Put it somewhere that seems to work for you. If you find something that doesn't work, it can (and should) be changed.

Why does AngularJS include an empty option in select?

Yes ng-model will create empty option value, when ng-model property undefined. We can avoid this, if we assign object to ng-model

Example

angular coding

$scope.collections = [
    { name: 'Feature', value: 'feature' }, 
    { name: 'Bug', value: 'bug' }, 
    { name: 'Enhancement', value: 'enhancement'}
];

$scope.selectedOption = $scope.collections[0];


<select class='form-control' data-ng-model='selectedOption' data-ng-options='item as item.name for item in collections'></select>

Important Note:

Assign object of array like $scope.collections[0] or $scope.collections[1] to ng-model, dont use object properties. if you are getting select option value from server, using call back function, assign object to ng-model

NOTE from Angular document

Note: ngModel compares by reference, not value. This is important when binding to an array of objects. see an example http://jsfiddle.net/qWzTb/

i have tried lot of times finally i found it.

Insert/Update Many to Many Entity Framework . How do I do it?

I wanted to add my experience on that. Indeed EF, when you add an object to the context, it changes the state of all the children and related entities to Added. Although there is a small exception in the rule here: if the children/related entities are being tracked by the same context, EF does understand that these entities exist and doesn't add them. The problem happens when for example, you load the children/related entities from some other context or a web ui etc and then yes, EF doesn't know anything about these entities and goes and adds all of them. To avoid that, just get the keys of the entities and find them (e.g. context.Students.FirstOrDefault(s => s.Name == "Alice")) in the same context in which you want to do the addition.

How to terminate process from Python using pid?

Using the awesome psutil library it's pretty simple:

p = psutil.Process(pid)
p.terminate()  #or p.kill()

If you don't want to install a new library, you can use the os module:

import os
import signal

os.kill(pid, signal.SIGTERM) #or signal.SIGKILL 

See also the os.kill documentation.


If you are interested in starting the command python StripCore.py if it is not running, and killing it otherwise, you can use psutil to do this reliably.

Something like:

import psutil
from subprocess import Popen

for process in psutil.process_iter():
    if process.cmdline() == ['python', 'StripCore.py']:
        print('Process found. Terminating it.')
        process.terminate()
        break
else:
    print('Process not found: starting it.')
    Popen(['python', 'StripCore.py'])

Sample run:

$python test_strip.py   #test_strip.py contains the code above
Process not found: starting it.
$python test_strip.py 
Process found. Terminating it.
$python test_strip.py 
Process not found: starting it.
$killall python
$python test_strip.py 
Process not found: starting it.
$python test_strip.py 
Process found. Terminating it.
$python test_strip.py 
Process not found: starting it.

Note: In previous psutil versions cmdline was an attribute instead of a method.

Serializing an object to JSON

Download https://github.com/douglascrockford/JSON-js/blob/master/json2.js, include it and do

var json_data = JSON.stringify(obj);

How to disable/enable a button with a checkbox if checked

I recommend using jQuery as it will do all the heavy lifting for you. The code is fairly trivial.

$('input:checkbox').click(function () {
  if ($(this).is(':checked')) {
    $('#sendNewSms').click(function () {
      return false;
    });
  } else {
    $('#sendNewSms').unbind('click');
  }
});

The trick is to override the 'click' event and effectively disable it. You can also follow it up with some CSS magic to make it look "disabled". Here is the code in JavaScript in case you need it. It's not perfect but it gets the point across.

var clickEvent = function () {
  return false;
};
document.getElementById('#checkbox').onclick(function () {
  if (document.getElementById('#checkbox').checked) {
    document
      .getElementById('#sendNewSms')
      .onclick(clickEvent);
  } else {
    document
      .getElementById('#sendNewSms')
      .removeEventListener('click', clickEvent, false);
  }
});

Load CSV file with Spark

When using spark.read.csv, I find that using the options escape='"' and multiLine=True provide the most consistent solution to the CSV standard, and in my experience works the best with CSV files exported from Google Sheets.

That is,

#set inferSchema=False to read everything as string
df = spark.read.csv("myData.csv", escape='"', multiLine=True,
     inferSchema=False, header=True)

Difference in boto3 between resource, client, and session?

Here's some more detailed information on what Client, Resource, and Session are all about.

Client:

  • low-level AWS service access
  • generated from AWS service description
  • exposes botocore client to the developer
  • typically maps 1:1 with the AWS service API
  • all AWS service operations are supported by clients
  • snake-cased method names (e.g. ListBuckets API => list_buckets method)

Here's an example of client-level access to an S3 bucket's objects (at most 1000**):

import boto3

client = boto3.client('s3')
response = client.list_objects_v2(Bucket='mybucket')
for content in response['Contents']:
    obj_dict = client.get_object(Bucket='mybucket', Key=content['Key'])
    print(content['Key'], obj_dict['LastModified'])

** you would have to use a paginator, or implement your own loop, calling list_objects() repeatedly with a continuation marker if there were more than 1000.

Resource:

  • higher-level, object-oriented API
  • generated from resource description
  • uses identifiers and attributes
  • has actions (operations on resources)
  • exposes subresources and collections of AWS resources
  • does not provide 100% API coverage of AWS services

Here's the equivalent example using resource-level access to an S3 bucket's objects (all):

import boto3

s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
for obj in bucket.objects.all():
    print(obj.key, obj.last_modified)

Note that in this case you do not have to make a second API call to get the objects; they're available to you as a collection on the bucket. These collections of subresources are lazily-loaded.

You can see that the Resource version of the code is much simpler, more compact, and has more capability (it does pagination for you). The Client version of the code would actually be more complicated than shown above if you wanted to include pagination.

Session:

  • stores configuration information (primarily credentials and selected region)
  • allows you to create service clients and resources
  • boto3 creates a default session for you when needed

A useful resource to learn more about these boto3 concepts is the introductory re:Invent video.

How do I include a path to libraries in g++

To specify a directory to search for (binary) libraries, you just use -L:

-L/data[...]/lib

To specify the actual library name, you use -l:

-lfoo  # (links libfoo.a or libfoo.so)

To specify a directory to search for include files (different from libraries!) you use -I:

-I/data[...]/lib

So I think what you want is something like

g++ -g -Wall -I/data[...]/lib testing.cpp fileparameters.cpp main.cpp -o test

These compiler flags (amongst others) can also be found at the GNU GCC Command Options manual:

Document directory path of Xcode Device Simulator

iOS 11

if let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,
                                                           .userDomainMask,
                                                           true).first {
    debugPrint("documentsPath = \(documentsPath)")
}

Reading a resource file from within jar

Up until now (December 2017), this is the only solution I found which works both inside and outside the IDE.

Use PathMatchingResourcePatternResolver

Note: it works also in spring-boot

In this example I'm reading some files located in src/main/resources/my_folder:

try {
    // Get all the files under this inner resource folder: my_folder
    String scannedPackage = "my_folder/*";
    PathMatchingResourcePatternResolver scanner = new PathMatchingResourcePatternResolver();
    Resource[] resources = scanner.getResources(scannedPackage);

    if (resources == null || resources.length == 0)
        log.warn("Warning: could not find any resources in this scanned package: " + scannedPackage);
    else {
        for (Resource resource : resources) {
            log.info(resource.getFilename());
            // Read the file content (I used BufferedReader, but there are other solutions for that):
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                // ...
                // ...                      
            }
            bufferedReader.close();
        }
    }
} catch (Exception e) {
    throw new Exception("Failed to read the resources folder: " + e.getMessage(), e);
}

Generate PDF from Swagger API documentation

Handy way: Using Browser Printing/Preview

  1. Hide editor pane
  2. Print Preview (I used firefox, others also fine)
  3. Change its page setup and print to pdf

enter image description here

How to prevent scanf causing a buffer overflow in C?

If you are using gcc, you can use the GNU-extension a specifier to have scanf() allocate memory for you to hold the input:

int main()
{
  char *str = NULL;

  scanf ("%as", &str);
  if (str) {
      printf("\"%s\"\n", str);
      free(str);
  }
  return 0;
}

Edit: As Jonathan pointed out, you should consult the scanf man pages as the specifier might be different (%m) and you might need to enable certain defines when compiling.

What is a stored procedure?

Stored procedures in SQL Server can accept input parameters and return multiple values of output parameters; in SQL Server, stored procedures program statements to perform operations in the database and return a status value to a calling procedure or batch.

The benefits of using stored procedures in SQL Server

They allow modular programming. They allow faster execution. They can reduce network traffic. They can be used as a security mechanism.

Here is an example of a stored procedure that takes a parameter, executes a query and return a result. Specifically, the stored procedure accepts the BusinessEntityID as a parameter and uses this to match the primary key of the HumanResources.Employee table to return the requested employee.

> create procedure HumanResources.uspFindEmployee    `*<<<---Store procedure name`*
@businessEntityID                                     `<<<----parameter`
as
begin
SET NOCOUNT ON;
Select businessEntityId,              <<<----select statement to return one employee row
NationalIdNumber,
LoginID,
JobTitle,
HireData,
From HumanResources.Employee
where businessEntityId =@businessEntityId     <<<---parameter used as criteria
end

I learned this from essential.com...it is very useful.

Remove empty lines in a text file via grep

Simplest Answer -----------------------------------------

[root@node1 ~]# cat /etc/sudoers | grep -v -e ^# -e ^$
Defaults   !visiblepw
Defaults    always_set_home
Defaults    match_group_by_gid
Defaults    always_query_group_plugin
Defaults    env_reset
Defaults    env_keep =  "COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR LS_COLORS"
Defaults    env_keep += "MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE"
Defaults    env_keep += "LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES"
Defaults    env_keep += "LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE"
Defaults    env_keep += "LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY"
Defaults    secure_path = /sbin:/bin:/usr/sbin:/usr/bin
root    ALL=(ALL)       ALL
%wheel  ALL=(ALL)       ALL
[root@node1 ~]#

Calculating Time Difference

time.monotonic() (basically your computer's uptime in seconds) is guarranteed to not misbehave when your computer's clock is adjusted (such as when transitioning to/from daylight saving time).

>>> import time
>>>
>>> time.monotonic()
452782.067158593
>>>
>>> a = time.monotonic()
>>> time.sleep(1)
>>> b = time.monotonic()
>>> print(b-a)
1.001658110995777

Spark: subtract two DataFrames

For me , df1.subtract(df2) was inconsistent. Worked correctly on one dataframe but not on the other . That was because of duplicates . df1.exceptAll(df2) returns a new dataframe with the records from df1 that do not exist in df2 , including any duplicates.

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

You are missing the python mysqldb library. Use this command (for Debian/Ubuntu) to install it: sudo apt-get install python-mysqldb

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

The only solution that worked for me and $.each was definitely causing the error. so i used for loop and it's not throwing error anymore.

Example code

     $.ajax({
            type: 'GET',
            url: 'https://example.com/api',
            data: { get_param: 'value' },
            success: function (data) {
                for (var i = 0; i < data.length; ++i) {
                    console.log(data[i].NameGerman);
                }
            }
        });

Bootstrap-select - how to fire event on change

This is what I did.

$('.selectpicker').on('changed.bs.select', function (e, clickedIndex, newValue, oldValue) {
    var selected = $(e.currentTarget).val();
});

What's the difference between REST & RESTful

REST stands for representational state transfer. That means that state itself is not transferred but a mere representation of it is. The most common example is a pure HTML server based app (no javascript). The browser knows nothing about the application itself but through links and resources, the server is able transfer the state of the application to the browser. Where a button would normally change a state variable (e.g. page open) in a regular windows application, in the browser you have a link that represents such a state change.

The idea is to use hypermedia. And perhaps to create new hypermedia types. Potentially we can expand the browser with javascript/AJAX and create new custom hypermedia types. And we would have a true REST application.

This is my short version of what REST stands for, the problem is that it is hard to implement. I personally say RESTful, when I want to make reference to the REST principles but I know I am not really implementing the whole concept of REST. We don't really say SOAPful, because you either use SOAP or not. I think most people don't do REST the way it was envisioned by it's creator Roy Fielding, we actually implement RESTful or RESTlike architectures. You can see his dissertation, and you will find the REST acronym but not the word RESTful.

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

Angular and Django Rest Framework.

I encountered similar error while making post request to my DRF api. It happened that all I was missing was trailing slash for endpoint.

Edit Crystal report file without Crystal Report software

I wouldn't have thought so.

If you have Visual Studio you could edit them through that. Some versions of Visual Studio has Crystal Reports shipped with them.

If not, you will have to find someone who has Crystal Reports and ask then nicely to amend them for you. Or buy Crystal Reports!

pandas: merge (join) two data frames on multiple columns

Another way of doing this: new_df = A_df.merge(B_df, left_on=['A_c1','c2'], right_on = ['B_c1','c2'], how='left')

What is "string[] args" in Main class for?

For passing in command line parameters. For example args[0] will give you the first command line parameter, if there is one.

T-SQL Cast versus Convert

CONVERT is SQL Server specific, CAST is ANSI.

CONVERT is more flexible in that you can format dates etc. Other than that, they are pretty much the same. If you don't care about the extended features, use CAST.

EDIT:

As noted by @beruic and @C-F in the comments below, there is possible loss of precision when an implicit conversion is used (that is one where you use neither CAST nor CONVERT). For further information, see CAST and CONVERT and in particular this graphic: SQL Server Data Type Conversion Chart. With this extra information, the original advice still remains the same. Use CAST where possible.

What key shortcuts are to comment and uncomment code?

Keyboard accelerators are configurable. You can find out which keyboard accelerators are bound to a command in Tools -> Options on the Environment -> Keyboard page.

These commands are named Edit.CommentSelection and Edit.UncommentSelection.

(With my settings, these are bound to Ctrl+K, Ctrl+C and Ctrl+K, Ctrl+U. I would guess that these are the defaults, at least in the C++ defaults, but I don't know for sure. The best way to find out is to check your settings.)

MySQL LIMIT on DELETE statement

From the documentation:

You cannot use ORDER BY or LIMIT in a multiple-table DELETE.

Is it better practice to use String.format over string Concatenation in Java?

Which one is more readable depends on how your head works.

You got your answer right there.

It's a matter of personal taste.

String concatenation is marginally faster, I suppose, but that should be negligible.

How to read strings from a Scanner in a Java console application?

You are entering a null value to nextInt, it will fail if you give a null value...

i have added a null check to the piece of code

Try this code:

import java.util.Scanner;
class MyClass
{
     public static void main(String args[]){

                Scanner scanner = new Scanner(System.in);
                int eid,sid;
                String ename;
                System.out.println("Enter Employeeid:");
                     eid=(scanner.nextInt());
                System.out.println("Enter EmployeeName:");
                     ename=(scanner.next());
                System.out.println("Enter SupervisiorId:");
                    if(scanner.nextLine()!=null&&scanner.nextLine()!=""){//null check
                     sid=scanner.nextInt();
                     }//null check
        }
}

Rounding BigDecimal to *always* have two decimal places

value = value.setScale(2, RoundingMode.CEILING)

How to check if a class inherits another class without instantiating it?

To check for assignability, you can use the Type.IsAssignableFrom method:

typeof(SomeType).IsAssignableFrom(typeof(Derived))

This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.

To check for strict inheritance, you can use Type.IsSubclassOf:

typeof(Derived).IsSubclassOf(typeof(SomeType))

How do I delete unpushed git commits?

Following command worked for me, all the local committed changes are dropped & local is reset to the same as remote origin/master branch.

git reset --hard origin

How to prevent custom views from losing state across screen orientation changes

I found that this answer was causing some crashes on Android versions 9 and 10. I think it's a good approach but when I was looking at some Android code I found out it was missing a constructor. The answer is quite old so at the time there probably was no need for it. When I added the missing constructor and called it from the creator the crash was fixed.

So here is the edited code:

public class CustomView extends LinearLayout {

    private int stateToSave;

    ...

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState ss = new SavedState(superState);

        // your custom state
        ss.stateToSave = this.stateToSave;

        return ss;
    }

    @Override
    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container)
    {
        dispatchFreezeSelfOnly(container);
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState ss = (SavedState) state;
        super.onRestoreInstanceState(ss.getSuperState());

        // your custom state
        this.stateToSave = ss.stateToSave;
    }

    @Override
    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container)
    {
        dispatchThawSelfOnly(container);
    }

    static class SavedState extends BaseSavedState {
        int stateToSave;

        SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            this.stateToSave = in.readInt();
        }

        // This was the missing constructor
        @RequiresApi(Build.VERSION_CODES.N)
        SavedState(Parcel in, ClassLoader loader)
        {
            super(in, loader);
            this.stateToSave = in.readInt();
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeInt(this.stateToSave);
        }    
        
        public static final Creator<SavedState> CREATOR =
            new ClassLoaderCreator<SavedState>() {
          
            // This was also missing
            @Override
            public SavedState createFromParcel(Parcel in, ClassLoader loader)
            {
                return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? new SavedState(in, loader) : new SavedState(in);
            }

            @Override
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in, null);
            }

            @Override
            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }
}

How to install Android app on LG smart TV?

Here is a great guide how to do that, if your TV is android TV: https://pedronveloso.com/how-to-install-an-apk-on-android-tv/

Have you enabled 'unknown sources' from security and restrictions settings?

How to view hierarchical package structure in Eclipse package explorer

Package Explorer / View Menu / Package Presentation... / Hierarchical

The "View Menu" can be opened with Ctrl + F10, or the small arrow-down icon in the top-right corner of the Package Explorer.

Can we instantiate an abstract class?

= my() {}; means that there's an anonymous implementation, not simple instantiation of an object, which should have been : = my(). You can never instantiate an abstract class.

Should I learn C before learning C++?

I learned C first, and I took a course in data structures which used C, before I learned C++. This has worked well for me. A data structures course in C gave me a solid understanding of pointers and memory management. It also made obvious the benefits of the object oriented paradigm, once I had learned what it was.

On the flip side, by learning C first, I have developed some habits that initially caused me to write bad C++ code, such as excessive use of pointers (when C++ references would do) and the preprocessor.

C++ is really a very complex language with lots of features. It is not really a superset of C, though. Rather there is a subset of C++ consisting of the basic procedural programming constructs (loops, ifs, and functions), which is very similar to C. In your case, I would start with that, and then work my way up to more advanced concepts like classes and templates.

The most important thing, IMHO, is to be exposed to different programming paradigms, like procedural, object-oriented, functional, and logical, early on, before your brain freezes into one way of looking at the world. Incidentally, I would also strongly recommend that you learn a functional programming language, like Scheme. It would really expand your horizons.

Including jars in classpath on commandline (javac or apt)

Using:

apt HelloImpl.java -classpath /sac/tools/thirdparty/jaxws-ri/jaxws-ri-2.1.4/lib/jsr181-api.jar:.

works but it gives me another error, see new question

Foreign Key Django Model

You create the relationships the other way around; add foreign keys to the Person type to create a Many-to-One relationship:

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(
        Anniversary, on_delete=models.CASCADE)
    address = models.ForeignKey(
        Address, on_delete=models.CASCADE)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()

Any one person can only be connected to one address and one anniversary, but addresses and anniversaries can be referenced from multiple Person entries.

Anniversary and Address objects will be given a reverse, backwards relationship too; by default it'll be called person_set but you can configure a different name if you need to. See Following relationships "backward" in the queries documentation.

Use Toast inside Fragment

Making a Toast inside Fragment

 Toast.makeText(getActivity(), "Your Text Here!", Toast.LENGTH_SHORT).show();

OR

    Activity activityObj = this.getActivity();

    Toast.makeText(activityObj, "Your Text Here!", Toast.LENGTH_SHORT).show();

OR

Toast.makeText(this, "Your Text Here!", Toast.LENGTH_SHORT).show();

Get selected value from combo box in C# WPF

private void usuarioBox_TextChanged(object sender, EventArgs e)
{
    string textComboBox = usuarioBox.Text;
}

Is it possible to send a variable number of arguments to a JavaScript function?

This is a sample program for calculating sum of integers for variable arguments and array on integers. Hope this helps.

var CalculateSum = function(){
    calculateSumService.apply( null, arguments );
}

var calculateSumService = function(){
    var sum = 0;

    if( arguments.length === 1){
        var args = arguments[0];

        for(var i = 0;i<args.length; i++){
           sum += args[i]; 
        }
    }else{
        for(var i = 0;i<arguments.length; i++){
           sum += arguments[i]; 
        }        
    }

     alert(sum);

}


//Sample method call

// CalculateSum(10,20,30);         

// CalculateSum([10,20,30,40,50]);

// CalculateSum(10,20);

Jump to function definition in vim

TL;DR:

Modern way is to use COC for intellisense-like completion and one or more language servers (LS) for jump-to-definition (and way way more). For even more functionality (but it's not needed for jump-to-definition) you can install one or more debuggers and get a full blown IDE experience.

Quick-start:

  1. install vim-plug to manage your VIM plug-ins
  2. add COC and (optionally) Vimspector at the top of ~/.vimrc:
    call plug#begin()
    Plug 'neoclide/coc.nvim', {'branch': 'release'}
    Plug 'puremourning/vimspector'
    call plug#end()
    
    " key mappings example
    nmap <silent> gd <Plug>(coc-definition)
    nmap <silent> gD <Plug>(coc-implementation)
    nmap <silent> gr <Plug>(coc-references)
    " there's way more, see `:help coc-key-mappings@en'
    
  3. call :source $MYVIMRC | PlugInstall to reload VIM config and download plug-ins
  4. restart vim and call :CocInstall coc-marketplace to get easy access to COC extensions
  5. call :CocList marketplace and search for language servers, e.g.:
  • type python to find coc-jedi,
  • type php to find coc-phpls, etc.
  1. (optionally) see install_gadget.py --help for available debuggers, e.g.:
  • ./install_gadget.py --enable-python,
  • ./install_gadget.py --force-enable-php, etc.

You can jump to definition with gd, to interface implementation with gD, find all references with gr. More keybindings in :help coc-key-mappings@en.

Full answer:

Language server (LS) is a separate standalone application (one for each programming language) that runs in the background and analyses your whole project in real time exposing extra capabilities to your editor (any editor, not only vim). You get things like:

  • namespace aware tag completion
  • jump to definition
  • jump to next / previous error
  • find all references to an object
  • find all interface implementations
  • rename across a whole project
  • documentation on hover
  • snippets, code actions, formatting, linting and more...

Communication with language servers takes place via Language Server Protocol (LSP). Both nvim and vim8 (or higher) support LSP through plug-ins, the most popular being Conquer of Completion (COC).

List of actively developed language servers and their capabilities is available on Lang Server website. Not all of those are provided by COC extensions. If you want to use one of those you can either write a COC extension yourself or install LS manually and use the combo of following VIM plug-ins as alternative to COC:

Communication with debuggers takes place via Debug Adapter Protocol (DAP). The most popular DAP plug-in for VIM is Vimspector.

Language Server Protocol (LSP) was created by Microsoft for Visual Studio Code and released as an open source project with a permissive MIT license (standardized by collaboration with Red Hat and Codenvy). Later on Microsoft released Debug Adapter Protocol (DAP) as well. Any language supported by VSCode is supported in VIM.

I personally recommend using COC + language servers provided by COC extensions + ALE for extra linting (but with LSP support disabled to avoid conflicts with COC) + Vimspector + debuggers provided by Vimspector (called "gadgets") + following VIM plug-ins:

call plug#begin()
Plug 'neoclide/coc.nvim'
Plug 'dense-analysis/ale'
Plug 'puremourning/vimspector'
Plug 'scrooloose/nerdtree'
Plug 'scrooloose/nerdcommenter'
Plug 'sheerun/vim-polyglot'
Plug 'yggdroot/indentline'
Plug 'tpope/vim-surround'
Plug 'kana/vim-textobj-user'
  \| Plug 'glts/vim-textobj-comment'
Plug 'janko/vim-test'
Plug 'vim-scripts/vcscommand.vim'
Plug 'mhinz/vim-signify'
call plug#end()

You can google each to see what they do.

Also, pipe character | separates VIM commands put in one line which makes it perfect to set up plug-in dependencies, i.e. vim-textobj-comment doesn't work without vim-textobj-user so if installation of vim-textobj-user fails the rest of the line isn't executed. Here pipe is escaped with backslash \ because it's in a new line but for VIM it's still a one-liner.

shorthand c++ if else statement

try this:

bigInt.sign = number < 0 ? 0 : 1

How to convert jsonString to JSONObject in Java

Codehaus Jackson - I have been this awesome API since 2012 for my RESTful webservice and JUnit tests. With their API, you can:

(1) Convert JSON String to Java bean

public static String beanToJSONString(Object myJavaBean) throws Exception {
    ObjectMapper jacksonObjMapper = new ObjectMapper();
    return jacksonObjMapper.writeValueAsString(myJavaBean);
}

(2) Convert JSON String to JSON object (JsonNode)

public static JsonNode stringToJSONObject(String jsonString) throws Exception {
    ObjectMapper jacksonObjMapper = new ObjectMapper();
    return jacksonObjMapper.readTree(jsonString);
}

//Example:
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";   
JsonNode jsonNode = stringToJSONObject(jsonString);
Assert.assertEquals("Phonetype value not legit!", "N95", jsonNode.get("phonetype").getTextValue());
Assert.assertEquals("Cat value is tragic!", "WP", jsonNode.get("cat").getTextValue());

(3) Convert Java bean to JSON String

    public static Object JSONStringToBean(Class myBeanClass, String JSONString) throws Exception {
    ObjectMapper jacksonObjMapper = new ObjectMapper();
    return jacksonObjMapper.readValue(JSONString, beanClass);
}

REFS:

  1. Codehaus Jackson

  2. JsonNode API - How to use, navigate, parse and evaluate values from a JsonNode object

  3. Tutorial - Simple tutorial how to use Jackson to convert JSON string to JsonNode

How to read input with multiple lines in Java

I finally got it, submited it 13 times rejected for whatever reasons, 14th "the judge" accepted my answer, here it is :

import java.io.BufferedInputStream;
import java.util.Scanner;

public class HashmatWarrior {

    public static void main(String args[]) {
        Scanner stdin = new Scanner(new BufferedInputStream(System.in));
        while (stdin.hasNext()) {
            System.out.println(Math.abs(stdin.nextLong() - stdin.nextLong()));
        }
    }
}

Calculating a 2D Vector's Cross Product

In short: It's a shorthand notation for a mathematical hack.

Long explanation:

You can't do a cross product with vectors in 2D space. The operation is not defined there.

However, often it is interesting to evaluate the cross product of two vectors assuming that the 2D vectors are extended to 3D by setting their z-coordinate to zero. This is the same as working with 3D vectors on the xy-plane.

If you extend the vectors that way and calculate the cross product of such an extended vector pair you'll notice that only the z-component has a meaningful value: x and y will always be zero.

That's the reason why the z-component of the result is often simply returned as a scalar. This scalar can for example be used to find the winding of three points in 2D space.

From a pure mathematical point of view the cross product in 2D space does not exist, the scalar version is the hack and a 2D cross product that returns a 2D vector makes no sense at all.

Xcode 9 Swift Language Version (SWIFT_VERSION)

I just got this after creating a new Objective-C project in Xcode 10, after I added a Core Data model file to the project.

I found two ways to fix this:

  1. The Easy Way: Open the Core Data model's File Inspector (??-1) and change the language from Swift to Objective-C

Change Core Data model language

  1. Longer and more dangerous method

The model contains a "contents" file with this line:

<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="14460.32" systemVersion="17G5019" minimumToolsVersion="Automatic" sourceLanguage="Swift" userDefinedModelVersionIdentifier="">

In there is a sourceLanguage="Swift" entry. Change it to sourceLanguage="Objective-C" and the error goes away.

To find the "contents" file, right click on the .xcdatamodeld in Xcode and do "Show in Finder". Right-click on the actual (Finder) file and do "Show Package Contents"

Also: Changing the model's language will stop Xcode from generating managed object subclass files in Swift.

How to change border color of textarea on :focus

.input:focus {
    outline: none !important;
    border:1px solid red;
    box-shadow: 0 0 10px #719ECE;
}

Return value using String result=Command.ExecuteScalar() error occurs when result returns null

Try this one, if null set 0 or something

return command.ExecuteScalar() == DBNull.Value ? 0 : (double)command.ExecuteScalar();

IntelliJ IDEA JDK configuration on Mac OS

The JDK path might change when you update JAVA. For Mac you should go to the following path to check the JAVA version installed.

/Library/Java/JavaVirtualMachines/

Next, say JDK version that you find is jdk1.8.0_151.jdk, the path to home directory within it is the JDK home path.

In my case it was :

/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home

You can configure it by going to File -> Project Structure -> SDKs.

enter image description here enter image description here

How do I embed a mp4 movie into my html?

If you have an mp4 video residing at your server, and you want the visitors to stream that over your HTML page.

<video width="480" height="320" controls="controls">
<source src="http://serverIP_or_domain/location_of_video.mp4" type="video/mp4">
</video>

Timestamp with a millisecond precision: How to save them in MySQL

You can use BIGINT as follows:

CREATE TABLE user_reg (
user_id INT NOT NULL AUTO_INCREMENT,
identifier INT,
phone_number CHAR(11) NOT NULL,
verified TINYINT UNSIGNED NOT NULL,
reg_time BIGINT,
last_active_time BIGINT,
PRIMARY KEY (user_id),
INDEX (phone_number, user_id, identifier)
   );

Getting a union of two arrays in JavaScript

function unite(arr1, arr2, arr3) {
 newArr=arr1.concat(arr2).concat(arr3);

 a=newArr.filter(function(value){
   return !arr1.some(function(value2){
      return value == value2;
   });
 });

console.log(arr1.concat(a));

}//This is for Sorted union following the order :)

How to disable phone number linking in Mobile Safari?

I had the same problem, but on an iPad web app.

Unfortunately, neither...

 <meta name = "format-detection" content = "telephone=no">

nor ...

&#48; = 0
&#57; = 9

... worked.

But, here's three ugly hacks:

  • replacing the number "0" with the letter "O"
  • replacing the number "1" with the letter "l"
  • insert a meaningless span: e.g., 555.5<span>5</span>5.5555

Depending on the font you use, the first two are barely noticeable. The latter obviously involves superfluous code, but is invisible to the user.

Kludgy hacks for sure, and probably not viable if you're generating your code dynamically from data, or if you can't pollute your data this way.

But, sufficient in a pinch.

How to get the current date and time of your timezone in Java?

You would use JodaTime for that. Java.util.Date is very limited regarding TimeZone.

Egit rejected non-fast-forward

In my case I chose the Force Update checkbox while pushing. It worked like a charm.

How to clean project cache in Intellij idea like Eclipse's clean?

Try this:

Go into Settings (File > Settings or ctrl+alt+S). Under Project Settings, select the "Compiler" node. On the left, uncheck "Clear output directory on rebuild".

Note that this is a per project setting. If desired, change it in the project template settigs (Settings > Other Settings > Template Settings).

.NET - How do I retrieve specific items out of a Dataset?

You can do like...

If you want to access using ColumnName

Int32 First = Convert.ToInt32(ds.Tables[0].Rows[0]["column4Name"].ToString());
Int32 Second = Convert.ToInt32(ds.Tables[0].Rows[0]["column5Name"].ToString());

OR, if you want to access using Index

Int32 First = Convert.ToInt32(ds.Tables[0].Rows[0][4].ToString());
Int32 Second = Convert.ToInt32(ds.Tables[0].Rows[0][5].ToString());

Html/PHP - Form - Input as array

If is ok for you to index the array you can do this:

<form>
    <input type="text" class="form-control" placeholder="Titel" name="levels[0][level]">
    <input type="text" class="form-control" placeholder="Titel" name="levels[0][build_time]">

    <input type="text" class="form-control" placeholder="Titel" name="levels[1][level]">
    <input type="text" class="form-control" placeholder="Titel" name="levels[1][build_time]">

    <input type="text" class="form-control" placeholder="Titel" name="levels[2][level]">
    <input type="text" class="form-control" placeholder="Titel" name="levels[2][build_time]">
</form>

... to achieve that:

[levels] => Array ( 
  [0] => Array ( 
    [level] => 1 
    [build_time] => 2 
  ) 
  [1] => Array ( 
    [level] => 234 
   [build_time] => 456 
  )
  [2] => Array ( 
    [level] => 111
    [build_time] => 222 
  )
) 

But if you remove one pair of inputs (dynamically, I suppose) from the middle of the form then you'll get holes in your array, unless you update the input names...

Using Environment Variables with Vue.js

In vue-cli version 3:

There are the three options for .env files: Either you can use .env or:

  • .env.test
  • .env.development
  • .env.production

You can use custom .env variables by using the prefix regex as /^/ instead of /^VUE_APP_/ in /node_modules/@vue/cli-service/lib/util/resolveClientEnv.js:prefixRE

This is certainly not recommended for the sake of developing an open source app in different modes like test, development, and production of .env files. Because every time you npm install .. , it will be overridden.

Select mySQL based only on month and year

you can do it by changing $q to this:

$q="SELECT * FROM projects WHERE YEAR(date) = $year_v AND MONTH(date) = $month_v;

Getting command-line password input in Python

Use getpass.getpass():

from getpass import getpass
password = getpass()

An optional prompt can be passed as parameter; the default is "Password: ".

Note that this function requires a proper terminal, so it can turn off echoing of typed characters – see “GetPassWarning: Can not control echo on the terminal” when running from IDLE for further details.

What is the difference between precision and scale?

Scale is the number of digit after the decimal point (or colon depending your locale)

Precision is the total number of significant digits

scale VS precision

How do I get the last character of a string using an Excel function?

Looks like the answer above was a little incomplete try the following:-

=RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))

Obviously, this is for cell A2...

What this does is uses a combination of Right and Len - Len is the length of a string and in this case, we want to remove all but one from that... clearly, if you wanted the last two characters you'd change the -1 to -2 etc etc etc.

After the length has been determined and the portion of that which is required - then the Right command will display the information you need.

This works well combined with an IF statement - I use this to find out if the last character of a string of text is a specific character and remove it if it is. See, the example below for stripping out commas from the end of a text string...

=IF(RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))=",",LEFT(A2,(LEN(A2)-1)),A2)

Why is there no Constant feature in Java?

const in C++ does not mean that a value is a constant.

const in C++ implies that the client of a contract undertakes not to alter its value.

Whether the value of a const expression changes becomes more evident if you are in an environment which supports thread based concurrency.

As Java was designed from the start to support thread and lock concurrency, it didn't add to confusion by overloading the term to have the semantics that final has.

eg:

#include <iostream>

int main ()
{
    volatile const int x = 42;

    std::cout << x << std::endl;

    *const_cast<int*>(&x) = 7;

    std::cout << x << std::endl;

    return 0;
}

outputs 42 then 7.

Although x marked as const, as a non-const alias is created, x is not a constant. Not every compiler requires volatile for this behaviour (though every compiler is permitted to inline the constant)

With more complicated systems you get const/non-const aliases without use of const_cast, so getting into the habit of thinking that const means something won't change becomes more and more dangerous. const merely means that your code can't change it without a cast, not that the value is constant.

Join vs. sub-query

In the year 2010 I would have joined the author of this questions and would have strongly voted for JOIN, but with much more experience (especially in MySQL) I can state: Yes subqueries can be better. I've read multiple answers here; some stated subqueries are faster, but it lacked a good explanation. I hope I can provide one with this (very) late answer:

First of all, let me say the most important: There are different forms of sub-queries

And the second important statement: Size matters

If you use sub-queries, you should be aware of how the DB-Server executes the sub-query. Especially if the sub-query is evaluated once or for every row! On the other side, a modern DB-Server is able to optimize a lot. In some cases a subquery helps optimizing a query, but a newer version of the DB-Server might make the optimization obsolete.

Sub-queries in Select-Fields

SELECT moo, (SELECT roger FROM wilco WHERE moo = me) AS bar FROM foo

Be aware that a sub-query is executed for every resulting row from foo.
Avoid this if possible; it may drastically slow down your query on huge datasets. However, if the sub-query has no reference to foo it can be optimized by the DB-server as static content and could be evaluated only once.

Sub-queries in the Where-statement

SELECT moo FROM foo WHERE bar = (SELECT roger FROM wilco WHERE moo = me)

If you are lucky, the DB optimizes this internally into a JOIN. If not, your query will become very, very slow on huge datasets because it will execute the sub-query for every row in foo, not just the results like in the select-type.

Sub-queries in the Join-statement

SELECT moo, bar 
  FROM foo 
    LEFT JOIN (
      SELECT MIN(bar), me FROM wilco GROUP BY me
    ) ON moo = me

This is interesting. We combine JOIN with a sub-query. And here we get the real strength of sub-queries. Imagine a dataset with millions of rows in wilco but only a few distinct me. Instead of joining against a huge table, we have now a smaller temporary table to join against. This can result in much faster queries depending on database size. You can have the same effect with CREATE TEMPORARY TABLE ... and INSERT INTO ... SELECT ..., which might provide better readability on very complex queries (but can lock datasets in a repeatable read isolation level).

Nested sub-queries

SELECT moo, bar
  FROM (
    SELECT moo, CONCAT(roger, wilco) AS bar
      FROM foo
      GROUP BY moo
      HAVING bar LIKE 'SpaceQ%'
  ) AS temp_foo
  ORDER BY bar

You can nest sub-queries in multiple levels. This can help on huge datasets if you have to group or sort the results. Usually the DB-Server creates a temporary table for this, but sometimes you do not need sorting on the whole table, only on the resultset. This might provide much better performance depending on the size of the table.

Conclusion

Sub-queries are no replacement for a JOIN and you should not use them like this (although possible). In my humble opinion, the correct use of a sub-query is the use as a quick replacement of CREATE TEMPORARY TABLE .... A good sub-query reduces a dataset in a way you cannot accomplish in an ON statement of a JOIN. If a sub-query has one of the keywords GROUP BY or DISTINCT and is preferably not situated in the select fields or the where statement, then it might improve performance a lot.

In SSRS, why do I get the error "item with same key has already been added" , when I'm making a new report?

I face the same issue. After debug I fixed the same. if the column name in your sql query has multiple times then this issue occur. Hence use alias in sql query to differ the column name. Ex: The below query will work proper in sql query but create issue in SSRS report:

Select P.ID, P.FirstName, P.LastName, D.ID, D.City, D.Area, D.Address From PersonalDetails P Left Join CommunicationDetails D On P.ID = D.PersonalDetailsID

Reason : ID has mentioned twice (Multiple Times)

Correct Query:

Select P.ID As PersonalDetailsID, P.FirstName, P.LastName, D.ID, D.City, D.Area, D.Address From PersonalDetails P Left Join CommunicationDetails D On P.ID = D.PersonalDetailsID

SQL DELETE with INNER JOIN

if the database is InnoDB you dont need to do joins in deletion. only

DELETE FROM spawnlist WHERE spawnlist.type = "monster";

can be used to delete the all the records that linked with foreign keys in other tables, to do that you have to first linked your tables in design time.

CREATE TABLE IF NOT EXIST spawnlist (
  npc_templateid VARCHAR(20) NOT NULL PRIMARY KEY

)ENGINE=InnoDB;

CREATE TABLE IF NOT EXIST npc (
  idTemplate VARCHAR(20) NOT NULL,

  FOREIGN KEY (idTemplate) REFERENCES spawnlist(npc_templateid) ON DELETE CASCADE

)ENGINE=InnoDB;

if you uses MyISAM you can delete records joining like this

DELETE a,b
FROM `spawnlist` a
JOIN `npc` b
ON a.`npc_templateid` = b.`idTemplate`
WHERE a.`type` = 'monster';

in first line i have initialized the two temp tables for delet the record, in second line i have assigned the existance table to both a and b but here i have linked both tables together with join keyword, and i have matched the primary and foreign key for both tables that make link, in last line i have filtered the record by field to delete.

How to use jQuery with TypeScript

This work for me now and today at Angular version 9

  1. Install via npm this: npm i @types/jquery just add --save to setup globally.
  2. Go to tsconfig.app.json and add in the array "types" jquery .
  3. ng serve and done.

Add class to an element in Angular 4

If you want to set only one specific class, you might write a TypeScript function returning a boolean to determine when the class should be appended.

TypeScript

function hideThumbnail():boolean{
    if (/* Your criteria here */)
        return true;
}

CSS:

.request-card-hidden {
    display: none;
}

HTML:

<ion-note [class.request-card-hidden]="hideThumbnail()"></ion-note>

Any easy way to use icons from resources?

choosing that file, will embed the icon in the executable.

@POST in RESTful web service

REST webservice: (http://localhost:8080/your-app/rest/data/post)

package com.yourorg.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response;

    @Path("/data")
public class JSONService {

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createDataInJSON(String data) { 

        String result = "Data post: "+data;

        return Response.status(201).entity(result).build(); 
    }

Client send a post:

package com.yourorg.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientPost {

  public static void main(String[] args) {

    try {

        Client client = Client.create();

        WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");

        String input = "{\"message\":\"Hello\"}";

        ClientResponse response = webResource.type("application/json")
           .post(ClientResponse.class, input);

        if (response.getStatus() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);

      } catch (Exception e) {

        e.printStackTrace();

      }

    }
}

How can I implement the Iterable interface?

Iterable is a generic interface. A problem you might be having (you haven't actually said what problem you're having, if any) is that if you use a generic interface/class without specifying the type argument(s) you can erase the types of unrelated generic types within the class. An example of this is in Non-generic reference to generic class results in non-generic return types.

So I would at least change it to:

public class ProfileCollection implements Iterable<Profile> { 
    private ArrayList<Profile> m_Profiles;

    public Iterator<Profile> iterator() {        
        Iterator<Profile> iprof = m_Profiles.iterator();
        return iprof; 
    }

    ...

    public Profile GetActiveProfile() {
        return (Profile)m_Profiles.get(m_ActiveProfile);
    }
}

and this should work:

for (Profile profile : m_PC) {
    // do stuff
}

Without the type argument on Iterable, the iterator may be reduced to being type Object so only this will work:

for (Object profile : m_PC) {
    // do stuff
}

This is a pretty obscure corner case of Java generics.

If not, please provide some more info about what's going on.

Swift - iOS - Dates and times in different format

extension String {

    func convertDatetring_TopreferredFormat(currentFormat: String, toFormat : String) ->  String {
        let dateFormator = DateFormatter()
        dateFormator.dateFormat = currentFormat
        let resultDate = dateFormator.date(from: self)
        dateFormator.dateFormat = toFormat
        return dateFormator.string(from: resultDate!)
    }

}

Call from your view controller file as below.

"your_date_string".convertDatetring_TopreferredFormat(currentFormat: "yyyy-MM-dd HH:mm:ss.s", toFormat: "dd-MMM-yyyy h:mm a")

'setInterval' vs 'setTimeout'

setInterval fires again and again in intervals, while setTimeout only fires once.

See reference at MDN.

Letsencrypt add domain to existing certificate

You need to specify all of the names, including those already registered.

I used the following command originally to register some certificates:

/opt/certbot/certbot-auto certonly --webroot --agree-tos -w /srv/www/letsencrypt/ \
--email [email protected] \
--expand -d example.com,www.example.com

... and just now I successfully used the following command to expand my registration to include a new subdomain as a SAN:

/opt/certbot/certbot-auto certonly --webroot --agree-tos -w /srv/www/letsencrypt/ \
--expand -d example.com,www.example.com,click.example.com

From the documentation:

--expand "If an existing cert covers some subset of the requested names, always expand and replace it with the additional names."

Don't forget to restart the server to load the new certificates if you are running nginx.

How to parse month full form string using DateFormat in Java?

You are probably using a locale where the month names are not "January", "February", etc. but some other words in your local language.

Try specifying the locale you wish to use, for example Locale.US:

DateFormat fmt = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
Date d = fmt.parse("June 27,  2007");

Also, you have an extra space in the date string, but actually this has no effect on the result. It works either way.

CSS transition shorthand with multiple properties?

This helped me understand / streamline, only what I needed to animate:

// SCSS - Multiple Animation: Properties | durations | etc.
// on hover, animate div (width/opacity) - from: {0px, 0} to: {100vw, 1}

.base {
  max-width: 0vw;
  opacity: 0;

  transition-property: max-width, opacity; // relative order
  transition-duration: 2s, 4s; // effects relatively ordered animation properties
  transition-delay: 6s; // effects delay of all animation properties
  animation-timing-function: ease;

  &:hover {
    max-width: 100vw;
    opacity: 1;

    transition-duration: 5s; // effects duration of all aniomation properties
    transition-delay: 2s, 7s; // effects relatively ordered animation properties
  }
}

~ This applies for all transition properties (duration, transition-timing-function, etc.) within the '.base' class

How to ping an IP address

short recommendation: don't use isReachable(), call the system ping, as proposed in some of the answers above.

long explanation:

  • ping uses the ICMP network protcol. To use ICMP, a 'raw socket' is needed
  • standard users are not allowed by the operating system to use raw sockets
  • the following applies to a fedora 30 linux, windows systems should be similar
  • if java runs as root, isReachable() actually sends ICMP ping requests
  • if java does not run as root, isReachable() tries to connect to TCP port 7, known as the echo port. This service is commonly not used any more, trying to use it might yield improper results
  • any kind of answer to the connection request, also a reject (TCP flag RST) yields a 'true' from isReachable()
  • some firewalls send RST for any port that is not explicitly open. If this happens, you will get isReachable() == true for a host that does not even exist
  • further tries to assign the necessary capabilities to a java process:
  • setcap cap_net_raw+eip java executable (assign the right to use raw sockets)
  • test: getcap java executable -> 'cap_net_raw+eip' (capability is assigned)
  • the running java still sends a TCP request to port 7
  • check of the running java process with getpcaps pid shows that the running java does not have the raw socket capablity. Obviously my setcap has been overridden by some security mechanism
  • as security requirements are increasing, this is likely to become even more restricted, unless s.b. implements an exception especially for ping (but nothing found on the net so far)

The maximum recursion 100 has been exhausted before statement completion

Specify the maxrecursion option at the end of the query:

...
from EmployeeTree
option (maxrecursion 0)

That allows you to specify how often the CTE can recurse before generating an error. Maxrecursion 0 allows infinite recursion.

What is the difference between Nexus and Maven?

This has a good general description: https://gephi.wordpress.com/tag/maven/

Let me make a few statement that can put the difference in focus:

  1. We migrated our code base from Ant to Maven

  2. All 3rd party librairies have been uploaded to Nexus. Maven is using Nexus as a source for libraries.

  3. Basic functionalities of a repository manager like Sonatype are:

    • Managing project dependencies,
    • Artifacts & Metadata,
    • Proxying external repositories
    • and deployment of packaged binaries and JARs to share those artifacts with other developers and end-users.