Programs & Examples On #Directsound

DirectSound is a software component of the multimedia API collection known as Microsoft DirectX. It is geared to play audio.

How to do Base64 encoding in node.js?

crypto now supports base64 (reference):

cipher.final('base64') 

So you could simply do:

var cipher = crypto.createCipheriv('des-ede3-cbc', encryption_key, iv);
var ciph = cipher.update(plaintext, 'utf8', 'base64');
ciph += cipher.final('base64');

var decipher = crypto.createDecipheriv('des-ede3-cbc', encryption_key, iv);
var txt = decipher.update(ciph, 'base64', 'utf8');
txt += decipher.final('utf8');

Function for 'does matrix contain value X?'

you can do:

A = randi(10, [3 4]);      %# a random matrix
any( A(:)==5 )             %# does A contain 5?

To do the above in a vectorized way, use:

any( bsxfun(@eq, A(:), [5 7 11] )

or as @woodchips suggests:

ismember([5 7 11], A)

How can I write to the console in PHP?

As of 2017, Firebug and hence FirePHP has been disabled.

I wrote some little modifications to the ChromePHP tool to allow seamless migration from FirePHP to Firebug for debugging via the console.

This article explains in clear easy steps

Migrate from FirePHP to ChromePHP in 5 minutes (without breaking existing code)

What is the difference between a token and a lexeme?

Using "Compilers Principles, Techniques, & Tools, 2nd Ed." (WorldCat) by Aho, Lam, Sethi and Ullman, AKA the Purple Dragon Book,

Lexeme pg. 111

A lexeme is a sequence of characters in the source program that matches the pattern for a token and is identified by the lexical analyzer as an instance of that token.

Token pg. 111

A token is a pair consisting of a token name and an optional attribute value. The token name is an abstract symbol representing a kind of lexical unit, e.g., a particular keyword, or sequence of input characters denoting an identifier. The token names are the input symbols that the parser processes.

Pattern pg. 111

A pattern is a description of the form that the lexemes of a token may take. In the case of a keyword as a token, the pattern is just the sequence of characters that form the keyword. For identifiers and some other tokens, the pattern is more complex structure that is matched by many strings.

Figure 3.2: Examplesof tokens pg.112

[Token]       [Informal Description]                  [Sample Lexemes]
if            characters i, f                         if
else          characters e, l, s, e                   else
comparison    < or > or <= or >= or == or !=          <=, !=
id            letter followed by letters and digits   pi, score, D2
number        any numeric constant                    3.14159, 0, 6.02e23
literal       anything but ", surrounded by "'s       "core dumped"

To better understand this relation to a lexer and parser we will start with the parser and work backwards to the input.

To make it easier to design a parser, a parser does not work with the input directly but takes in a list of tokens generated by a lexer. Looking at the token column in Figure 3.2 we see tokens such as if, else, comparison, id, number and literal; these are names of tokens. Typically with a lexer/parser a token is a structure that holds not only the name of the token, but the characters/symbols that make up the token and the start and end position of the string of characters that make up the token, with the start and end position being used for error reporting, highlighting, etc.

Now the lexer takes the input of characters/symbols and using the rules of the lexer converts the input characters/symbols into tokens. Now people who work with lexer/parser have their own words for things they use often. What you think of as a sequence of characters/symbols that make up a token are what people who use lexer/parsers call lexeme. So when you see lexeme, just think of a sequence of characters/symbols representing a token. In the comparison example, the sequence of characters/symbols can be different patterns such as < or > or else or 3.14, etc.

Another way to think of the relation between the two is that a token is a programming structure used by the parser that has a property called lexeme that holds the character/symbols from the input. Now if you look at most definitions of token in code you may not see lexeme as one of the properties of the token. This is because a token will more likely hold the start and end position of the characters/symbols that represent the token and the lexeme, sequence of characters/symbols can be derived from the start and end position as needed because the input is static.

How to create a file in a directory in java?

Create New File in Specified Path

import java.io.File;
import java.io.IOException;

public class CreateNewFile {

    public static void main(String[] args) {
        try {
            File file = new File("d:/sampleFile.txt");
            if(file.createNewFile())
                System.out.println("File creation successfull");
            else
                System.out.println("Error while creating File, file already exists in specified path");
        }
        catch(IOException io) {
            io.printStackTrace();
        }
    }

}

Program Output:

File creation successfull

How set maximum date in datepicker dialog in android?

You can create Custom date picker, that is work for all api levels.

public class CustomDatePickerDialog extends DatePickerDialog {

    int maxYear;
    int maxMonth;
    int maxDay;

    public CustomDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
        super(context, callBack, year, monthOfYear, dayOfMonth);
    }

    public void setMaxDate(long maxDate) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getDatePicker().setMaxDate(System.currentTimeMillis());
        } else {
            final Calendar c = Calendar.getInstance();
            c.setTimeInMillis(maxDate);
            maxYear = c.get(Calendar.YEAR);
            maxMonth = c.get(Calendar.MONTH);
            maxDay = c.get(Calendar.DAY_OF_MONTH);
        }
    }

    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            super.onDateChanged(view, year, monthOfYear, dayOfMonth);
        } else {
            if (year > maxYear)
                view.updateDate(maxYear, maxMonth, maxDay);

            if (monthOfYear > maxMonth && year == maxYear)
                view.updateDate(maxYear, maxMonth, maxDay);

            if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
                view.updateDate(maxYear, maxMonth, maxDay);
        }
    }

set max date

final CustomDatePickerDialog pickerDialog = new CustomDatePickerDialog(getActivity(),
        myDateListener, year, month, day);
pickerDialog.setMaxDate(System.currentTimeMillis());
pickerDialog.show();

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

I can't give an authoritative answer, but provide an overview of a likely cause. This reference shows pretty clearly that for the instructions in the body of your loop there is a 3:1 ratio between latency and throughput. It also shows the effects of multiple dispatch. Since there are (give-or-take) three integer units in modern x86 processors, it's generally possible to dispatch three instructions per cycle.

So between peak pipeline and multiple dispatch performance and failure of these mechanisms, we have a factor of six in performance. It's pretty well known that the complexity of the x86 instruction set makes it quite easy for quirky breakage to occur. The document above has a great example:

The Pentium 4 performance for 64-bit right shifts is really poor. 64-bit left shift as well as all 32-bit shifts have acceptable performance. It appears that the data path from the upper 32 bits to the lower 32 bit of the ALU is not well designed.

I personally ran into a strange case where a hot loop ran considerably slower on a specific core of a four-core chip (AMD if I recall). We actually got better performance on a map-reduce calculation by turning that core off.

Here my guess is contention for integer units: that the popcnt, loop counter, and address calculations can all just barely run at full speed with the 32-bit wide counter, but the 64-bit counter causes contention and pipeline stalls. Since there are only about 12 cycles total, potentially 4 cycles with multiple dispatch, per loop body execution, a single stall could reasonably affect run time by a factor of 2.

The change induced by using a static variable, which I'm guessing just causes a minor reordering of instructions, is another clue that the 32-bit code is at some tipping point for contention.

I know this is not a rigorous analysis, but it is a plausible explanation.

How to render a DateTime in a specific format in ASP.NET MVC 3?

this will display in dd/MM/yyyy format in your View

In View:

instead of DisplayFor use this code

<td>

@(item.Startdate.HasValue ? item.Startdate.Value.ToString("dd/MM/yyyy") : "Date is Empty")

</td

it also checks if the value is null in date column, if true then it will display Date is Empty or the actual formatted date from the column.

Hope helps someone.

How to edit an Android app?

Generally speaking, a software product isn't your "property already", as you said in the comment. Most of the times (I won't be irresponsible to say anything in open), it's licensed to you. A license to use some thing is not the same thing as owning (property rights) that very same thing.

That's because there are authorship, copyright, intellectual property rights applicable to it. I don't know how things work in United States (or in your country), but it's generally accepted that the work of a mind, a creative work, must not be changed in its nature as such to make the expression of art to be different than that expression that the author intended. That applies for example, in some cases, to architectural work (in most countries, you can't change the appearance of a building to "desfigure" the work of art of the architect, without his prior consent). Exceptions are made, obviously, when the author expressly authorizes such changes (e.g., Creative Commons licenses, open source licenses etc.).

Anyway, that's why you see in most EULAs the typical sentence: "this software is licensed, not sold". That's the purpose and reason why.

Now that you understand the reasons why you can't wander around changing other people's art, let me be technical.

There are possible ways to decompile Java programs. You can use dex2jar, it provides a somewhat good start for you to start looking for things and changes. And perhaps rebuild the code by mounting back the pieces together. Good luck, as most people obfuscate their codes to make that harder.

However, let me say that it's still forbidden to change programs, as I said above. And it's extremely unethical. It makes me sad that people do that with no scruples (not saying it's your case, just warning you). It shouldn't need people to be at the other side to understand that. Or maybe that's just me, who lives in a country where piracy is rampant.

The tools are always out there. But the conscience, unfortunately, not always.

edit: in case it isn't clear enough already, I do NOT approve the use of these programs. I use them myself to check how hard my own applications are to be reverse engineered. But I also think that explaning is always better than denial (better be here).

On duplicate key ignore?

Mysql has this handy UPDATE INTO command ;)

edit Looks like they renamed it to REPLACE

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted

equivalent to push() or pop() for arrays?

You can use Arrays.copyOf() with a little reflection to make a nice helper function.

public class ArrayHelper {
    public static <T> T[] push(T[] arr, T item) {
        T[] tmp = Arrays.copyOf(arr, arr.length + 1);
        tmp[tmp.length - 1] = item;
        return tmp;
    }

    public static <T> T[] pop(T[] arr) {
        T[] tmp = Arrays.copyOf(arr, arr.length - 1);
        return tmp;
    }
}

Usage:

String[] items = new String[]{"a", "b", "c"};

items = ArrayHelper.push(items, "d");
items = ArrayHelper.push(items, "e");

items = ArrayHelper.pop(items);

Results

Original: a,b,c

Array after push calls: a,b,c,d,e

Array after pop call: a,b,c,d

How to remove carriage returns and new lines in Postgresql?

OP asked specifically about regexes since it would appear there's concern for a number of other characters as well as newlines, but for those just wanting strip out newlines, you don't even need to go to a regex. You can simply do:

select replace(field,E'\n','');

I think this is an SQL-standard behavior, so it should extend back to all but perhaps the very earliest versions of Postgres. The above tested fine for me in 9.4 and 9.2

Reshaping data.frame from wide to long format

Since this answer is tagged with , I felt it would be useful to share another alternative from base R: stack.

Note, however, that stack does not work with factors--it only works if is.vector is TRUE, and from the documentation for is.vector, we find that:

is.vector returns TRUE if x is a vector of the specified mode having no attributes other than names. It returns FALSE otherwise.

I'm using the sample data from @Jaap's answer, where the values in the year columns are factors.

Here's the stack approach:

cbind(wide[1:2], stack(lapply(wide[-c(1, 2)], as.character)))
##    Code     Country values  ind
## 1   AFG Afghanistan 20,249 1950
## 2   ALB     Albania  8,097 1950
## 3   AFG Afghanistan 21,352 1951
## 4   ALB     Albania  8,986 1951
## 5   AFG Afghanistan 22,532 1952
## 6   ALB     Albania 10,058 1952
## 7   AFG Afghanistan 23,557 1953
## 8   ALB     Albania 11,123 1953
## 9   AFG Afghanistan 24,555 1954
## 10  ALB     Albania 12,246 1954

How to resolve merge conflicts in Git repository?

Well, all the answers already given seem to explain which tools you can use to detect merge conflicts or how to initiate merge reqests...

The answer to your question however is both simple and frustrating. Merge conflicts are almost always to solve by hand manually. If you use a tool like e.g. GitLab, the GUI might help you to find differences in two code versions but at the end of the day, you have to decide which line should be kept and which should be erased.

A simple example: Programmer A and programmer B both push the same - differently modified - file to a remote repository. Programmer A opens a merge request and GitLab highlights several lines of code where conflicts occur between the two versions. Now it is up to Programmer A and B to decide, who wrote better code in these specific lines. They have to make compromises.

How do you manually execute SQL commands in Ruby On Rails using NuoDB

res = ActiveRecord::Base.connection_pool.with_connection { |con| con.exec_query( "SELECT 1;" ) }

The above code is an example for

  1. executing arbitrary SQL on your database-connection
  2. returning the connection back to the connection pool afterwards

How to use pip on windows behind an authenticating proxy

This is how I set it up:

  1. Open the command prompt(CMD) as administrator.
  2. Export the proxy settings :

    set http_proxy=http://username:password@proxyAddress:port

    set https_proxy=https://username:password@proxyAddress:port

  3. Install the package you want to install:

    pip install PackageName

For example:

Example

How to set aliases in the Git Bash for Windows?

To configure bash aliases, it's the same as if you were on a Unix platform: put them in a .bashrc in your home:

cd
echo alias ll=\'ls -l\' >> .bashrc

To have this change taken into account you should then either source this file (ie: run source .bashrc) or restart your terminal

(In some cases* you can find equivalent for .bashrc file in C:\Users\<username>\AppData\Local\GitHub\PortableGit_\etc\profile.d\aliases.sh. And you should add aliases in aliases.sh.)

(*this case is when you install Git for Windows GUI release from https://git-scm.com/download/win that contains GitBash)

Predict() - Maybe I'm not understanding it

To avoid error, an important point about the new dataset is the name of independent variable. It must be the same as reported in the model. Another way is to nest the two function without creating a new dataset

model <- lm(Coupon ~ Total, data=df)
predict(model, data.frame(Total=c(79037022, 83100656, 104299800)))

Pay attention on the model. The next two commands are similar, but for predict function, the first work the second don't work.

model <- lm(Coupon ~ Total, data=df) #Ok
model <- lm(df$Coupon ~ df$Total) #Ko

How to remove the first character of string in PHP?

Use substr:

$str = substr($str, 1); // this is a applepie :)

Creating pdf files at runtime in c#

I have used Gnostice in the past and found them to be very good.

http://www.gnostice.com/PDFOne_dot_Net.asp

How to delete a specific line in a file?

The best and fastest option, rather than storing everything in a list and re-opening the file to write it, is in my opinion to re-write the file elsewhere.

with open("yourfile.txt", "r") as file_input:
    with open("newfile.txt", "w") as output: 
        for line in file_input:
            if line.strip("\n") != "nickname_to_delete":
                output.write(line)

That's it! In one loop and one only you can do the same thing. It will be much faster.

How can I add a string to the end of each line in Vim?

If u want to add Hello world at the end of each line:

:%s/$/HelloWorld/

If you want to do this for specific number of line say, from 20 to 30 use:

:20,30s/$/HelloWorld/

If u want to do this at start of each line then use:

:20,30s/^/HelloWorld/

ProcessStartInfo hanging on "WaitForExit"? Why?

This post maybe outdated but i found out the main cause why it usually hang is due to stack overflow for the redirectStandardoutput or if you have redirectStandarderror.

As the output data or the error data is large, it will cause a hang time as it is still processing for indefinite duration.

so to resolve this issue:

p.StartInfo.RedirectStandardoutput = False
p.StartInfo.RedirectStandarderror = False

How to format LocalDate to string?

System.out.println(LocalDate.now().format(DateTimeFormatter.ofPattern("dd.MMMM yyyy")));

The above answer shows it for today

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

You need to decode data from input string into unicode, before using it, to avoid encoding problems.

field.text = data.decode("utf8")

What does @media screen and (max-width: 1024px) mean in CSS?

In my case I wanted to center my logo on a website when the browser has 800px or less, then I did this by using the @media tag:

@media screen and (max-width: 800px) {
  #logo {
    float: none;
    margin: 0;
    text-align: center;
    display: block;
    width: auto;
  }
}

It worked for me, hope somebody find this solution useful. :) For more information see this.

Flexbox: center horizontally and vertically

Add

.container {
    display: flex;
    justify-content: center;
    align-items: center;
}

to the container element of whatever you want to center. Documentation: justify-content and align-items.

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

Restricting JTextField input to Integers

I used to use the Key Listener for this but I failed big time with that approach. Best approach as recommended already is to use a DocumentFilter. Below is a utility method I created for building textfields with only number input. Just beware that it'll also take single '.' character as well since it's usable for decimal input.

public static void installNumberCharacters(AbstractDocument document) {
        document.setDocumentFilter(new DocumentFilter() {
            @Override
            public void insertString(FilterBypass fb, int offset,
                    String string, AttributeSet attr)
                    throws BadLocationException {
                try {
                    if (string.equals(".")
                            && !fb.getDocument()
                                    .getText(0, fb.getDocument().getLength())
                                    .contains(".")) {
                        super.insertString(fb, offset, string, attr);
                        return;
                    }
                    Double.parseDouble(string);
                    super.insertString(fb, offset, string, attr);
                } catch (Exception e) {
                    Toolkit.getDefaultToolkit().beep();
                }

            }

            @Override
            public void replace(FilterBypass fb, int offset, int length,
                    String text, AttributeSet attrs)
                    throws BadLocationException {
                try {
                    if (text.equals(".")
                            && !fb.getDocument()
                                    .getText(0, fb.getDocument().getLength())
                                    .contains(".")) {
                        super.insertString(fb, offset, text, attrs);
                        return;
                    }
                    Double.parseDouble(text);
                    super.replace(fb, offset, length, text, attrs);
                } catch (Exception e) {
                    Toolkit.getDefaultToolkit().beep();
                }
            }
        });
    }

Create a List that contain each Line of a File

my_list = [line.split(',') for line in open("filename.txt")]

SQL query: Delete all records from the table except latest N?

If your id is incremental then use something like

delete from table where id < (select max(id) from table)-N

Why doesn't importing java.util.* include Arrays and Lists?

I have just compile it and it compiles fine without the implicit import, probably you're seeing a stale cache or something of your IDE.

Have you tried compiling from the command line?

I have the exact same version:

here it is

Probably you're thinking the warning is an error.

UPDATE

It looks like you have a Arrays.class file in the directory where you're trying to compile ( probably created before ). That's why the explicit import solves the problem. Try copying your source code to a clean new directory and try again. You'll see there is no error this time. Or, clean up your working directory and remove the Arrays.class

Convert xlsx file to csv using batch

You need an external tool, in example: SoftInterface.com - Convert XLSX to CSV.

After installing it, you can use following command in your batch:

"c:\Program Files\Softinterface, Inc\Convert XLS\ConvertXLS.EXE" /S"C:\MyExcelFile.xlsx" /F51 /N"Sheet1" /T"C:\MyExcelFile.CSV" /C6 /M1 /V

Remove duplicates from a dataframe in PySpark

if you have a data frame and want to remove all duplicates -- with reference to duplicates in a specific column (called 'colName'):

count before dedupe:

df.count()

do the de-dupe (convert the column you are de-duping to string type):

from pyspark.sql.functions import col
df = df.withColumn('colName',col('colName').cast('string'))

df.drop_duplicates(subset=['colName']).count()

can use a sorted groupby to check to see that duplicates have been removed:

df.groupBy('colName').count().toPandas().set_index("count").sort_index(ascending=False)

How to get the path of src/test/resources directory in JUnit?

I would simply use Path from Java 7

Path resourceDirectory = Paths.get("src","test","resources");

Neat and clean!

SQL Query with Join, Count and Where

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

Why do some functions have underscores "__" before and after the function name?

This convention is used for special variables or methods (so-called “magic method”) such as __init__ and __len__. These methods provides special syntactic features or do special things.

For example, __file__ indicates the location of Python file, __eq__ is executed when a == b expression is executed.

A user of course can make a custom special method, which is a very rare case, but often might modify some of the built-in special methods (e.g. you should initialize the class with __init__ that will be executed at first when an instance of a class is created).

class A:
    def __init__(self, a):  # use special method '__init__' for initializing
        self.a = a
    def __custom__(self):  # custom special method. you might almost do not use it
        pass

JSTL if tag for equal strings

You can use scriptlets, however, this is not the way to go. Nowdays inline scriplets or JAVA code in your JSP files is considered a bad habit.

You should read up on JSTL a bit more. If the ansokanInfo object is in your request or session scope, printing the object (toString() method) like this: ${ansokanInfo} can give you some base information. ${ansokanInfo.pSystem} should call the object getter method. If this all works, you can use this:

<c:if test="${ ansokanInfo.pSystem  == 'NAT'}"> tataa </c:if>

Oracle pl-sql escape character (for a " ' ")

Instead of worrying about every single apostrophe in your statement. You can easily use the q' Notation.

Example

SELECT q'(Alex's Tea Factory)' FROM DUAL;

Key Components in this notation are

  • q' which denotes the starting of the notation
  • ( an optional symbol denoting the starting of the statement to be fully escaped.
  • Alex's Tea Factory (Which is the statement itself)
  • )' A closing parenthesis with a apostrophe denoting the end of the notation.

And such that, you can stuff how many apostrophes in the notation without worrying about each single one of them, they're all going to be handled safely.

IMPORTANT NOTE

Since you used ( you must close it with )', and remember it's optional to use any other symbol, for instance, the following code will run exactly as the previous one

SELECT q'[Alex's Tea Factory]' FROM DUAL;

Can I obtain method parameter name using Java reflection?

In Java 8 you can do the following:

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;

public final class Methods {

    public static List<String> getParameterNames(Method method) {
        Parameter[] parameters = method.getParameters();
        List<String> parameterNames = new ArrayList<>();

        for (Parameter parameter : parameters) {
            if(!parameter.isNamePresent()) {
                throw new IllegalArgumentException("Parameter names are not present!");
            }

            String parameterName = parameter.getName();
            parameterNames.add(parameterName);
        }

        return parameterNames;
    }

    private Methods(){}
}

So for your class Whatever we can do a manual test:

import java.lang.reflect.Method;

public class ManualTest {
    public static void main(String[] args) {
        Method[] declaredMethods = Whatever.class.getDeclaredMethods();

        for (Method declaredMethod : declaredMethods) {
            if (declaredMethod.getName().equals("aMethod")) {
                System.out.println(Methods.getParameterNames(declaredMethod));
                break;
            }
        }
    }
}

which should print [aParam] if you have passed -parameters argument to your Java 8 compiler.

For Maven users:

<properties>
    <!-- PLUGIN VERSIONS -->
    <maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>

    <!-- OTHER PROPERTIES -->
    <java.version>1.8</java.version>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>${maven-compiler-plugin.version}</version>
            <configuration>
                <!-- Original answer -->
                <compilerArgument>-parameters</compilerArgument>
                <!-- Or, if you use the plugin version >= 3.6.2 -->
                <parameters>true</parameters>
                <testCompilerArgument>-parameters</testCompilerArgument>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>
    </plugins>
</build>

For more information see following links:

  1. Official Java Tutorial: Obtaining Names of Method Parameters
  2. JEP 118: Access to Parameter Names at Runtime
  3. Javadoc for Parameter class

What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

That's called a closure. It basically seals the code inside the function so that other libraries don't interfere with it. It's similar to creating a namespace in compiled languages.

Example. Suppose I write:

(function() {

    var x = 2;

    // do stuff with x

})();

Now other libraries cannot access the variable x I created to use in my library.

Lombok added but getters and setters not recognized in Intellij IDEA

It's possible that you already have the Lombok plugin, and still the generated methods are not recognised by Android Studio. In such case the plugin might be out of date, so the solution is to simply update it.

Preferences -> Plugins -> Lombok Plugin -> Update Plugin

What is the best way to implement a "timer"?

Use the Timer class.

public static void Main()
{
    System.Timers.Timer aTimer = new System.Timers.Timer();
    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
    aTimer.Interval = 5000;
    aTimer.Enabled = true;

    Console.WriteLine("Press \'q\' to quit the sample.");
    while(Console.Read() != 'q');
}

 // Specify what you want to happen when the Elapsed event is raised.
 private static void OnTimedEvent(object source, ElapsedEventArgs e)
 {
     Console.WriteLine("Hello World!");
 }

The Elapsed event will be raised every X amount of milliseconds, specified by the Interval property on the Timer object. It will call the Event Handler method you specify. In the example above, it is OnTimedEvent.

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

How do you embed binary data in XML?

Any binary-to-text encoding will do the trick. I use something like that

<data encoding="yEnc>
<![CDATA[ encoded binary data ]]>
</data>

How to convert a list into data table

private DataTable CreateDataTable(IList<T> item)
{
    Type type = typeof(T);
    var properties = type.GetProperties();

    DataTable dataTable = new DataTable();
    foreach (PropertyInfo info in properties)
    {
        dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
    }

    foreach (T entity in item)
    {
        object[] values = new object[properties.Length];
        for (int i = 0; i < properties.Length; i++)
        {
            values[i] = properties[i].GetValue(entity);
        }

        dataTable.Rows.Add(values);
    }
    return dataTable;
}

how to read value from string.xml in android?

I'm using this:

String URL = Resources.getSystem().getString(R.string.mess_1);

Twitter Bootstrap modal: How to remove Slide down effect

Wanted to update this. Most of you have not completed this issue. I'm using Bootstrap 3. none of the fixes above worked.

to remove the slide effect but keep the fade in. I went into bootstrap css and (noted out the following selectors) - this resolved the issue.

 .modal.fade .modal-dialog{/*-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);transform:translate(0,-25%);-webkit-transition:-webkit-transform .3s ease-out;-moz-transition:-moz-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out*/}

 .modal.in .modal-dialog{/*-webkit-transform:translate(0,0);-ms-transform:translate(0,0);transform:translate(0,0)*/}

How to make a script wait for a pressed key?

os.system seems to always invoke sh, which does not recognize the s and n options for read. However the read command can be passed to bash:

 os.system("""bash -c 'read -s -n 1 -p "Press any key to continue..."'""")

Can anyone recommend a simple Java web-app framework?

I am really grooving to Stripes. Total setup includes some cut-and-paste XML into your app's web.xml, and then you're off. No configuration is required, since Stripes is a convention-over-configuration framework. Overriding the default behavior is accomplished via Java 1.5 annotations. Documentation is great. I spent about 1-2 hours reading the tutorial and setting up my first app.

I can't do an in-depth comparison to Struts or Spring-MVC yet, since I haven't built a full-scale in it yet (as I have in Struts), but it looks like it would scale to that level of architecture quite well.

Environment.GetFolderPath(...CommonApplicationData) is still returning "C:\Documents and Settings\" on Vista

I was looking for a listing of macOS but found nothing, maybe this helps someone.

Output on macOS Catalina (10.15.7) using net5.0

# SpecialFolders (Only with value)
SpecialFolder.ApplicationData: /Users/$USER/.config
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.Desktop: /Users/$USER/Desktop
SpecialFolder.DesktopDirectory: /Users/$USER/Desktop
SpecialFolder.Favorites: /Users/$USER/Library/Favorites
SpecialFolder.Fonts: /Users/$USER/Library/Fonts
SpecialFolder.InternetCache: /Users/$USER/Library/Caches
SpecialFolder.LocalApplicationData: /Users/$USER/.local/share
SpecialFolder.MyDocuments: /Users/$USER
SpecialFolder.MyMusic: /Users/$USER/Music
SpecialFolder.MyPictures: /Users/$USER/Pictures
SpecialFolder.ProgramFiles: /Applications
SpecialFolder.System: /System
SpecialFolder.UserProfile: /Users/$USER

# SpecialFolders (All)
SpecialFolder.AdminTools: 
SpecialFolder.ApplicationData: /Users/$USER/.config
SpecialFolder.CDBurning: 
SpecialFolder.CommonAdminTools: 
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.CommonDesktopDirectory: 
SpecialFolder.CommonDocuments: 
SpecialFolder.CommonMusic: 
SpecialFolder.CommonOemLinks: 
SpecialFolder.CommonPictures: 
SpecialFolder.CommonProgramFiles: 
SpecialFolder.CommonProgramFilesX86: 
SpecialFolder.CommonPrograms: 
SpecialFolder.CommonStartMenu: 
SpecialFolder.CommonStartup: 
SpecialFolder.CommonTemplates: 
SpecialFolder.CommonVideos: 
SpecialFolder.Cookies: 
SpecialFolder.Desktop: /Users/$USER/Desktop
SpecialFolder.DesktopDirectory: /Users/$USER/Desktop
SpecialFolder.Favorites: /Users/$USER/Library/Favorites
SpecialFolder.Fonts: /Users/$USER/Library/Fonts
SpecialFolder.History: 
SpecialFolder.InternetCache: /Users/$USER/Library/Caches
SpecialFolder.LocalApplicationData: /Users/$USER/.local/share
SpecialFolder.LocalizedResources: 
SpecialFolder.MyComputer: 
SpecialFolder.MyDocuments: /Users/$USER
SpecialFolder.MyMusic: /Users/$USER/Music
SpecialFolder.MyPictures: /Users/$USER/Pictures
SpecialFolder.MyVideos: 
SpecialFolder.NetworkShortcuts: 
SpecialFolder.PrinterShortcuts: 
SpecialFolder.ProgramFiles: /Applications
SpecialFolder.ProgramFilesX86: 
SpecialFolder.Programs: 
SpecialFolder.Recent: 
SpecialFolder.Resources: 
SpecialFolder.SendTo: 
SpecialFolder.StartMenu: 
SpecialFolder.Startup: 
SpecialFolder.System: /System
SpecialFolder.SystemX86: 
SpecialFolder.Templates: 
SpecialFolder.UserProfile: /Users/$USER
SpecialFolder.Windows: 

I have replaced my username with $USER.

Code Snippet from pogosama.

foreach(Environment.SpecialFolder f in Enum.GetValues(typeof(Environment.SpecialFolder)))
{
    string commonAppData = Environment.GetFolderPath(f);
    Console.WriteLine("{0}: {1}", f, commonAppData);
}
Console.ReadLine();

Oracle query to identify columns having special characters

Compare the length using lengthB and length function in oracle.

SELECT * FROM test WHERE length(sampletext) <> lengthb(sampletext)

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

'simple' code that works and can be read by a ten year old:

function deleteNonEmptyDir($dir) 
{
   if (is_dir($dir)) 
   {
        $objects = scandir($dir);

        foreach ($objects as $object) 
        {
            if ($object != "." && $object != "..") 
            {
                if (filetype($dir . "/" . $object) == "dir")
                {
                    deleteNonEmptyDir($dir . "/" . $object); 
                }
                else
                {
                    unlink($dir . "/" . $object);
                }
            }
        }

        reset($objects);
        rmdir($dir);
    }
}

Please note that all I did was expand/simplify and fix (didn't work for non empty dir) the solution here: In PHP how do I recursively remove all folders that aren't empty?

How to get the file name from a full path using JavaScript?

I use:

var lastPart = path.replace(/\\$/,'').split('\\').pop();

It replaces the last \ so it also works with folders.

How to find when a web page was last updated

Open your browsers console(?) and enter the following:

javascript:alert(document.lastModified)

Split a large pandas dataframe

I wanted to do the same, and I had first problems with the split function, then problems with installing pandas 0.15.2, so I went back to my old version, and wrote a little function that works very well. I hope this can help!

# input - df: a Dataframe, chunkSize: the chunk size
# output - a list of DataFrame
# purpose - splits the DataFrame into smaller chunks
def split_dataframe(df, chunk_size = 10000): 
    chunks = list()
    num_chunks = len(df) // chunk_size + 1
    for i in range(num_chunks):
        chunks.append(df[i*chunk_size:(i+1)*chunk_size])
    return chunks

insert password into database in md5 format?

if you want to use md5 encryptioon you can do it in your php script

$pass = $_GET['pass'];

$newPass = md5($pass)

and then insert it into the database that way, however MD5 is a one way encryption method and is near on impossible to decrypt without difficulty

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

You map your dispatcher on *.do:

<servlet-mapping>
   <servlet-name>Dispatcher</servlet-name>
   <url-pattern>*.do</url-pattern>
</servlet-mapping>

but your controller is mapped on an url without .do:

@RequestMapping("/editPresPage")

Try changing this to:

@RequestMapping("/editPresPage.do")

How can I turn a List of Lists into a List in Java 8?

List<List> list = map.values().stream().collect(Collectors.toList());

    List<Employee> employees2 = new ArrayList<>();
    
     list.stream().forEach(
             
             n-> employees2.addAll(n));

C# An established connection was aborted by the software in your host machine

This problem appear if two software use same port for connecting to the server
try to close the port by cmd according to your operating system
then reboot your Android studio or your Eclipse or your Software.

Disable the postback on an <ASP:LinkButton>

call java script function on onclick event.

Difference between CLOB and BLOB from DB2 and Oracle Perspective?

They can be considered as equivalent. The limits in size are the same:

  • Maximum length of CLOB (in bytes or OCTETS)) 2 147 483 647
  • Maximum length of BLOB (in bytes) 2 147 483 647

There is also the DBCLOBs, for double byte characters.

References:

How to check if a std::thread is still running?

You can always check if the thread's id is different than std::thread::id() default constructed. A Running thread has always a genuine associated id. Try to avoid too much fancy stuff :)

import error: 'No module named' *does* exist

In case this is of interest to anyone, I had the same problem when I was running Python in Cygwin, in my case it was complaning that pandas wasn't installed even though it was. The problem was that I had 2 installations of python - one in windows and another one in cygwin (using the cygwin installer) and although both were the same versions of Python, the Cygwin installation was confused about where Pandas was installed. When i uninstalled cygwin's Python and pointed Cygwin at the windows installation everything was fine

Angular ui-grid dynamically calculate height of the grid

UPDATE:

The HTML was requested so I've pasted it below.

<div ui-grid="gridOptions" class="my-grid"></div>

ORIGINAL:

We were able to adequately solve this problem by using responsive CSS (@media) that sets the height and width based on screen real estate. Something like (and clearly you can add more based on your needs):

@media (min-width: 1024px) {
  .my-grid {
    width: 772px;
  }
}

@media (min-width: 1280px) {
  .my-grid {
    width: 972px;
  }
}

@media (min-height: 768px) {
  .my-grid {
    height: 480px;
  }
}

@media (min-height: 900px) {
  .my-grid {
    height: 615px;
  }
}

The best part about this solution is that we need no resize event handling to monitor for grid size changes. It just works.

Use of "instanceof" in Java

instanceof can be used to determine the actual type of an object:

class A { }  
class C extends A { } 
class D extends A { } 

public static void testInstance(){
    A c = new C();
    A d = new D();
    Assert.assertTrue(c instanceof A && d instanceof A);
    Assert.assertTrue(c instanceof C && d instanceof D);
    Assert.assertFalse(c instanceof D);
    Assert.assertFalse(d instanceof C);
}

Android Studio Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

When you upgrade to the latest version of the gradle in the gradle-wrapper.properties file i.e. distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-bin.zip please do not forget to change the gradle version in the build.gradle file as well

wrapper {
    gradleVersion = '6.6.1'
}

How to convert flat raw disk image to vmdk for virtualbox or vmplayer?

Since the question mentions VirtualBox, this one works currently:

VBoxManage convertfromraw imagefile.dd vmdkname.vmdk --format VMDK

Run it without arguments for a few interesting details (notably the --variant flag):

VBoxManage convertfromraw

What should be the package name of android app?

As you stated, package names are usually in the form of 'com.organizationName.appName' - all lowercase and no spaces. It sounds like the package name that you entered when uploading the app was different from the one declared in the AndroidManifest.

SQL Column definition : default value and not null redundant?

Even with a default value, you can always override the column data with null.

The NOT NULL restriction won't let you update that row after it was created with null value

CURRENT_DATE/CURDATE() not working as default DATE value

Currently from MySQL 8 you can set the following to a DATE column:

In MySQL Workbench, in the Default field next to the column, write: (curdate())

If you put just curdate() it will fail. You need the extra ( and ) at the beginning and end.

How do I call a specific Java method on a click/submit event of a specific button in JSP?

<form method="post" action="servletName">   
     <input type="submit" id="btn1" name="btn1"/>
     <input type="submit" id="btn2" name="btn2"/>
</form>  

on pressing it request will go to servlet on the servlet page check which button is pressed and then accordingly call the needed method as objectName.method

Split (explode) pandas dataframe string entry to separate rows

Just used jiln's excellent answer from above, but needed to expand to split multiple columns. Thought I would share.

def splitDataFrameList(df,target_column,separator):
''' df = dataframe to split,
target_column = the column containing the values to split
separator = the symbol used to perform the split

returns: a dataframe with each entry for the target column separated, with each element moved into a new row. 
The values in the other columns are duplicated across the newly divided rows.
'''
def splitListToRows(row, row_accumulator, target_columns, separator):
    split_rows = []
    for target_column in target_columns:
        split_rows.append(row[target_column].split(separator))
    # Seperate for multiple columns
    for i in range(len(split_rows[0])):
        new_row = row.to_dict()
        for j in range(len(split_rows)):
            new_row[target_columns[j]] = split_rows[j][i]
        row_accumulator.append(new_row)
new_rows = []
df.apply(splitListToRows,axis=1,args = (new_rows,target_column,separator))
new_df = pd.DataFrame(new_rows)
return new_df

Add to Array jQuery

For JavaScript arrays, you use Both push() and concat() function.

var array = [1, 2, 3];
array.push(4, 5);         //use push for appending a single array.




var array1 = [1, 2, 3];
var array2 = [4, 5, 6];

var array3 = array1.concat(array2);   //It is better use concat for appending more then one array.

How do I read text from the clipboard?

I've seen many suggestions to use the win32 module, but Tkinter provides the shortest and easiest method I've seen, as in this post: How do I copy a string to the clipboard on Windows using Python?

Plus, Tkinter is in the python standard library.

Setting a max character length in CSS

HTML

<div id="dash">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi ligula, dapibus a volutpat sit amet, mattis et dui. Nunc porttitor accumsan orci id luctus. Phasellus ipsum metus, tincidunt non rhoncus id, dictum a lectus. Nam sed ipsum a urna ac
quam.</p>
</div>

jQuery

var p = $('#dash p');
var ks = $('#dash').height();
while ($(p).outerHeight() > ks) {
  $(p).text(function(index, text) {
    return text.replace(/\W*\s(\S)*$/, '...');
  });
}

CSS

#dash {
  width: 400px;
  height: 60px;
  overflow: hidden;
}

#dash p {
  padding: 10px;
  margin: 0;
}

RESULT

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi ligula, dapibus a volutpat sit amet, mattis et...

Jsfiddle

how to append a css class to an element by javascript?

You should be able to set the className property of the element. You could do a += to append it.

Git reset --hard and push to remote repository

For users of GitHub, this worked for me:

  1. In any branch protection rules where you wish to make the change, make sure Allow force pushes is enabled
  2. git reset --hard <full_hash_of_commit_to_reset_to>
  3. git push --force

This will "correct" the branch history on your local machine and the GitHub server, but anyone who has sync'ed this branch with the server since the bad commit will have the history on their local machine. If they have permission to push to the branch directly then these commits will show right back up when they sync.

All everyone else needs to do is the git reset command from above to "correct" the branch on their local machine. Of course they would need to be wary of any local commits made to this branch after the target hash. Cherry pick/backup and reapply those as necessary, but if you are in a protected branch then the number of people who can commit directly to it is likely limited.

What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?

this error basically comes when you use the object before using it.

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

In my case running Yosemite in VMWare Workstation 10.0.5 I had to:

1) Set kext to dev mode (might not be needed anymore .... try first without it)

sudo nvram boot-args="kext-dev-mode=1" 

Then reboot (power down VM) for step 2) below.

Details here: http://www.csell.net/2014/09/03/VTNX_Not_Enabled/

2) Add vhv.enable = "TRUE" to my VMX file and restart the VM

Details discussed here: https://communities.vmware.com/thread/416997?start=15&tstart=0

3) Install HAXM 1.1.1 as discussed above from the Intel 's site

(would love to post more links -> but have limit for 2 -> so vote for me so next time you will gert more .. :-))

Convert ArrayList to String array in Android

try this

List<String> list = new ArrayList<String>();
list.add("List1");
list.add("List2");

String[] listArr = new String[list.size()];
listArr = list.toArray(listArr );

for(String s : listArr )
    System.out.println(s);

Dynamic loading of images in WPF

Here is the extension method to load an image from URI:

public static BitmapImage GetBitmapImage(
    this Uri imageAbsolutePath,
    BitmapCacheOption bitmapCacheOption = BitmapCacheOption.Default)
{
    BitmapImage image = new BitmapImage();
    image.BeginInit();
    image.CacheOption = bitmapCacheOption;
    image.UriSource = imageAbsolutePath;
    image.EndInit();

    return image;
}

Sample of use:

Uri _imageUri = new Uri(imageAbsolutePath);
ImageXamlElement.Source = _imageUri.GetBitmapImage(BitmapCacheOption.OnLoad);

Simple as that!

jQuery how to bind onclick event to dynamically added HTML element

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>    
<script>
    $(document).ready(function(){
        $(document).on('click', '.close', function(){
            var rowid='row'+this.id;
            var sl = '#tblData tr[id='+rowid+']';
            console.log(sl);
            $(sl).remove();
        });
        $("#addrow").click(function(){
            var row='';
            for(var i=0;i<10;i++){
                row=i;
                row='<tr id=row'+i+'>'
                    +   '<td>'+i+'</td>'
                    +   '<td>ID'+i+'</td>'
                    +   '<td>NAME'+i+'</td>'
                    +   '<td><input class=close type=button id='+i+' value=X></td>'
                    +'</tr>';
                console.log(row);
                $('#tblData tr:last').after(row);
            }
        });
    });

</script>
</head>
  <body>
    <br/><input type="button" id="addrow" value="Create Table"/>
    <table id="tblData" border="1" width="40%">
        <thead>
        <tr>
            <th>Sr</th>
            <th>ID</th>
            <th>Name</th>
            <th>Delete</th>
        </tr>
        </thead>
    </table>
    </body>
 </html>

Applying Comic Sans Ms font style

The font may exist with different names, and not at all on some systems, so you need to use different variations and fallback to get the closest possible look on all systems:

font-family: "Comic Sans MS", "Comic Sans", cursive;

Be careful what you use this font for, though. Many consider it as ugly and overused, so it should not be use for something that should look professional.

How to get current CPU and RAM usage in Python?

you can read /proc/meminfo to get used memory

file1 = open('/proc/meminfo', 'r') 

for line in file1: 
    if 'MemTotal' in line: 
        x = line.split()
        memTotal = int(x[1])
        
    if 'Buffers' in line: 
        x = line.split()
        buffers = int(x[1])
        
    if 'Cached' in line and 'SwapCached' not in line: 
        x = line.split()
        cached = int(x[1])
    
    if 'MemFree' in line: 
        x = line.split()
        memFree = int(x[1])

file1.close()

percentage_used = int ( ( memTotal - (buffers + cached + memFree) ) / memTotal * 100 )
print(percentage_used)

How to convert image file data in a byte array to a Bitmap?

The answer of Uttam didnt work for me. I just got null when I do:

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

In my case, bitmapdata only has the buffer of the pixels, so it is imposible for the function decodeByteArray to guess which the width, the height and the color bits use. So I tried this and it worked:

//Create bitmap with width, height, and 4 bytes color (RGBA)    
Bitmap bmp = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
ByteBuffer buffer = ByteBuffer.wrap(bitmapdata);
bmp.copyPixelsFromBuffer(buffer);

Check https://developer.android.com/reference/android/graphics/Bitmap.Config.html for different color options

SQL order string as number

The column I'm sorting with has any combination of alpha and numeric, so I used the suggestions in this post as a starting point and came up with this.

DECLARE @tmp TABLE (ID VARCHAR(50));
INSERT INTO @tmp VALUES ('XYZ300');
INSERT INTO @tmp VALUES ('XYZ1002');
INSERT INTO @tmp VALUES ('106');
INSERT INTO @tmp VALUES ('206');
INSERT INTO @tmp VALUES ('1002');
INSERT INTO @tmp VALUES ('J206');
INSERT INTO @tmp VALUES ('J1002');

SELECT ID, (CASE WHEN ISNUMERIC(ID) = 1 THEN 0 ELSE 1 END) IsNum
FROM @tmp
ORDER BY IsNum, LEN(ID), ID;

Results

ID
------------------------
106
206
1002
J206
J1002
XYZ300
XYZ1002

Hope this helps

Byte[] to InputStream or OutputStream

There is no conversion between InputStream/OutputStream and the bytes they are working with. They are made for binary data, and just read (or write) the bytes one by one as is.

A conversion needs to happen when you want to go from byte to char. Then you need to convert using a character set. This happens when you make String or Reader from bytes, which are made for character data.

How do you use bcrypt for hashing passwords in PHP?

As we all know storing password in clear text in database is not secure. the bcrypt is a hashing password technique.It is used to built password security. one of the amazing function of bcrypt is it save us from hackers it is used to protect the password from hacking attacks because the password is stored in bcrypted form.

the password_hash() function is used to create a new password hash. It uses a strong & robust hashing algorithm.The password_hash() function is very much compatible with the crypt() function. Therefore, password hashes created by crypt() may be used with password_hash() and vice-versa. The functions password_verify() and password_hash() just the wrappers around the function crypt(), and they make it much easier to use it accurately.

SYNTAX

string password_hash($password , $algo , $options)

The following algorithms are currently supported by password_hash() function:

PASSWORD_DEFAULT PASSWORD_BCRYPT PASSWORD_ARGON2I PASSWORD_ARGON2ID

Parameters: This function accepts three parameters as mentioned above and described below:

password: It stores the password of the user. algo: It is the password algorithm constant that is used continuously while denoting the algorithm which is to be used when the hashing of password takes place. options: It is an associative array, which contains the options. If this is removed and doesn’t include, a random salt is going to be used, and the utilization of a default cost will happen. Return Value: It returns the hashed password on success or False on failure.

Example:

Input : echo password_hash("GFG@123", PASSWORD_DEFAULT); Output : $2y$10$.vGA19Jh8YrwSJFDodbfoHJIOFH)DfhuofGv3Fykk1a

Below programs illustrate the password_hash() function in PHP:

<?php echo password_hash("GFG@123", PASSWORD_DEFAULT); ?>

OUTPUT

$2y$10$Z166W1fBdsLcXPVQVfPw/uRq1ueWMA6sLt9bmdUFz9AmOGLdM393G

PostgreSQL: days/months/years between two dates

Simply subtract them:

SELECT ('2015-01-12'::date - '2015-01-01'::date) AS days;

The result:

 days
------
   11

How to convert int to Integer

As mentioned, one way is to use

new Integer(my_int_value)

But you should not call the constructor for wrapper classes directly

So, modify the code accordingly:

mBitmapCache.put(Integer.valueOf(R.drawable.bg1),object);

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

That error message means the server to which you are connecting does not reply to SSH connection attempts on port 22. There are three possible reasons for that:

  1. You're not running an SSH server on the machine. You'll need to install it to be able to ssh to it.

2.You are running an SSH server on that machine, but on a different port. You need to figure out on which port it is running; say it's on port 1234, you then run ssh -p 1234 hostname.

  1. You are running an SSH server on that machine, and it does use the port on which you are trying to connect, but the machine has a firewall that does not allow you to connect to it. You'll need to figure out how to change the firewall, or maybe you need to ssh from a different host to be allowed in.

EDIT: as (correctly) pointed out in the comments, the third is certainly the case; the other two would result in the server sending a TCP "reset" package back upon the client's connection attempt, resulting in a "connection refused" error message, rather than the timeout you're getting. The other two might also be the case, but you need to fix the third first before you can move on.

Making a triangle shape using xml definitions?

The solution of Jacek Milewski works for me and, based on his solution, if you need and inversed triangle you can use this:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <rotate
            android:fromDegrees="45"
            android:toDegrees="45"
            android:pivotX="135%" 
            android:pivotY="15%">
            <shape android:shape="rectangle">    
                <solid android:color="@color/aquamarine" />
            </shape>
        </rotate>
    </item>
</layer-list>

numpy: most efficient frequency counts for unique values in an array

multi-dimentional frequency count, i.e. counting arrays.

>>> print(color_array    )
  array([[255, 128, 128],
   [255, 128, 128],
   [255, 128, 128],
   ...,
   [255, 128, 128],
   [255, 128, 128],
   [255, 128, 128]], dtype=uint8)


>>> np.unique(color_array,return_counts=True,axis=0)
  (array([[ 60, 151, 161],
    [ 60, 155, 162],
    [ 60, 159, 163],
    [ 61, 143, 162],
    [ 61, 147, 162],
    [ 61, 162, 163],
    [ 62, 166, 164],
    [ 63, 137, 162],
    [ 63, 169, 164],
   array([     1,      2,      2,      1,      4,      1,      1,      2,
         3,      1,      1,      1,      2,      5,      2,      2,
       898,      1,      1,  

How to solve npm install throwing fsevents warning on non-MAC OS?

I'm using, Angular CLI: 8.1.2 Node: 12.14.1 OS: win32 x64

Strangely, this helped me

npm cache clean --force
npm uninstall @angular/cli
npm install @angular/[email protected]

XPath to return only elements containing the text, and not its parents

Do you want to find elements that contain "match", or that equal "match"?

This will find elements that have text nodes that equal 'match' (matches none of the elements because of leading and trailing whitespace in random2):

//*[text()='match']

This will find all elements that have text nodes that equal "match", after removing leading and trailing whitespace(matches random2):

//*[normalize-space(text())='match']

This will find all elements that contain 'match' in the text node value (matches random2 and random3):

//*[contains(text(),'match')]

This XPATH 2.0 solution uses the matches() function and a regex pattern that looks for text nodes that contain 'match' and begin at the start of the string(i.e. ^) or a word boundary (i.e. \W) and terminated by the end of the string (i.e. $) or a word boundary. The third parameter i evaluates the regex pattern case-insensitive. (matches random2)

//*[matches(text(),'(^|\W)match($|\W)','i')]

Class constructor type in typescript?

I am not sure if this was possible in TypeScript when the question was originally asked, but my preferred solution is with generics:

class Zoo<T extends Animal> {
    constructor(public readonly AnimalClass: new () => T) {
    }
}

This way variables penguin and lion infer concrete type Penguin or Lion even in the TypeScript intellisense.

const penguinZoo = new Zoo(Penguin);
const penguin = new penguinZoo.AnimalClass(); // `penguin` is of `Penguin` type.

const lionZoo = new Zoo(Lion);
const lion = new lionZoo.AnimalClass(); // `lion` is `Lion` type.

Line Break in XML?

In the XML: use literal line-breaks, nothing else needed there.

The newlines will be preserved for Javascript to read them [1]. Note that any indentation-spaces and preceding or trailing line-breaks are preserved too (the reason you weren't seeing them is that HTML/CSS collapses whitespace into single space-characters by default).

Then the easiest way is: In the HTML: do nothing, just use CSS to preserve the line-breaks

.msg_body {
    white-space: pre-line;
}

But this also preserves your extra lines from the XML document, and doesn't work in IE 6 or 7 [2].

So clean up the whitespace yourself; this is one way to do it (linebreaks for clarity - Javascript is happy with or without them [3]) [4]

[get lyric...].nodeValue
    .replace(/^[\r\n\t ]+|[\r\n\t ]+$/g, '')
    .replace(/[ \t]+/g, ' ')
    .replace(/ ?([\r\n]) ?/g, '$1')

and then preserve those line-breaks with

.msg_body {
    white-space: pre; // for IE 6 and 7
    white-space: pre-wrap; // or pre-line
}

or, instead of that CSS, add a .replace(/\r?\n/g, '<br />') after the other JavaScript .replaces.

(Side note: Using document.write() like that is also not ideal and sometimes vulnerable to cross-site scripting attacks, but that's another subject. In relation to this answer, if you wanted to use the variation that replaces with <br>, you'd have to escape <,&(,>,",') before generating the <br>s.)

--

[1] reference: sections "Element White Space Handling" and "XML Schema White Space Control" http://www.usingxml.com/Basics/XmlSpace#ElementWhiteSpaceHandling

[2] http://www.quirksmode.org/css/whitespace.html

[3] except for a few places in Javascript's syntax where its semicolon insertion is particularly annoying.

[4] I wrote it and tested these regexps in Linux Node.js (which uses the same Javascript engine as Chrome, "V8"). There's a small risk some browser executes regexps differently. (My test string (in javascript syntax) "\n\nfoo bar baz\n\n\tmore lyrics \nare good\n\n")

Selecting an element in iFrame jQuery

var iframe = $('iframe'); // or some other selector to get the iframe
$('[tokenid=' + token + ']', iframe.contents()).addClass('border');

Also note that if the src of this iframe is pointing to a different domain, due to security reasons, you will not be able to access the contents of this iframe in javascript.

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

dataGridView1.Columns is probably of a length less than 5. Accessing dataGridView1.Columns[4] then will be outside the list.

How to get textLabel of selected row in swift?

Maintain an array which stores data in the cellforindexPath method itself :-

[arryname objectAtIndex:indexPath.row];

Using same code in the didselectaAtIndexPath method too.. Good luck :)

Right Align button in horizontal LinearLayout

As mentioned a couple times before: To switch from LinearLayout to RelativeLayout works, but you can also solve the problem instead of avoiding it. Use the tools a LinearLayout provides: Give the TextView a weight=1 (see code below), the weight for your button should remain 0 or none. In this case the TextView will take all the remaining space, which is not used to display the content of your TextView or ButtonView and pushes your button to the right.

<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="35dp">

        <TextView
            android:id="@+id/lblExpenseCancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/cancel"
            android:textColor="#404040"
            android:layout_marginLeft="10dp"
            android:textSize="20sp"
            android:layout_marginTop="9dp"

            **android:layout_weight="1"**

            />

        <Button
            android:id="@+id/btnAddExpense"
            android:layout_width="wrap_content"
            android:layout_height="45dp"
            android:background="@drawable/stitch_button"
            android:layout_marginLeft="10dp"
            android:text="@string/add"
            android:layout_gravity="right"
            android:layout_marginRight="15dp" />

    </LinearLayout>

How can I make my match non greedy in vim?

With \v (as suggested in several comments)

:%s/\v(style|class)\=".{-}"//g

How do I add one month to current date in Java?

Use calander and try this code.

Calendar calendar = Calendar.getInstance();         
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
Date nextMonthFirstDay = calendar.getTime();
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date nextMonthLastDay = calendar.getTime();

How to view UTF-8 Characters in VIM or Gvim

Is this problem solved meanwhile?

I had the problem that gvim didn't display all unicode characters (but only a subset, including the umlauts and accented characters), while :set guifont? was empty; see my question. After reading here, setting the guifont to a sensible value fixed it for me. However, I don't need characters beyond 2 bytes.

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

Implicit and Explicit Waits

Implicit Wait

An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Explicit Wait + Expected Conditions

An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. The worst case of this is Thread.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(
        ExpectedConditions.visibilityOfElementLocated(By.id("someid")));

Gnuplot line types

Until version 4.6

The dash type of a linestyle is given by the linetype, which does also select the line color unless you explicitely set an other one with linecolor.

However, the support for dashed lines depends on the selected terminal:

  1. Some terminals don't support dashed lines, like png (uses libgd)
  2. Other terminals, like pngcairo, support dashed lines, but it is disables by default. To enable it, use set termoption dashed, or set terminal pngcairo dashed ....
  3. The exact dash patterns differ between terminals. To see the defined linetype, use the test command:

Running

set terminal pngcairo dashed
set output 'test.png'
test
set output

gives:

enter image description here

whereas, the postscript terminal shows different dash patterns:

set terminal postscript eps color colortext
set output 'test.eps'
test
set output

enter image description here

Version 5.0

Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:

  • A new dashtype parameter was introduced:

    To get the predefined dash patterns, use e.g.

    plot x dashtype 2
    

    You can also specify custom dash patterns like

    plot x dashtype (3,5,10,5),\
         2*x dashtype '.-_'
    
  • The terminal options dashed and solid are ignored. By default all lines are solid. To change them to dashed, use e.g.

    set for [i=1:8] linetype i dashtype i
    
  • The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic:

enter image description here

sass :first-child not working

I think that it is better (for my expirience) to use: :first-of-type, :nth-of-type(), :last-of-type. It can be done whit a little changing of rules, but I was able to do much more than whit *-of-type, than *-child selectors.

ios simulator: how to close an app

For iOS 7 & above:

  • shift+command+H twice to simulate the double tap of home button
  • swipe your app's screenshot upward to close it

You'll see screenshots representing the apps suspended on your device - those screenshots respond to touch events. Swiping is the gesture you'll make to "fling" the screenshot off of the screen. Note that on machines where your mouse is intended to represent your finger, you'll click and swipe as if it is your finger tapping and making the gesture.

How do I check if a list is empty?

Many answers have been given, and a lot of them are pretty good. I just wanted to add that the check

not a

will also pass for None and other types of empty structures. If you truly want to check for an empty list, you can do this:

if isinstance(a, list) and len(a)==0:
    print("Received an empty list")

How to vertically center an image inside of a div element in HTML using CSS?

Have you tried setting margin on the div? e.g.

div {
    padding: 25px, 0
}

for top and bottom. You may also be able to use a percentage:

div {
    padding: 25%, 0
}

Force Intellij IDEA to reread all maven dependencies

Press Ctrl+Shift+A to find actions, and input "reimport", you will find the "Reimport All Maven Projects".

On a Mac, use ?+?+A instead.

generate days from date range

if you want the list of dates between two dates:

create table #dates ([date] smalldatetime)
while @since < @to
begin
     insert into #dates(dateadd(day,1,@since))
     set @since = dateadd(day,1,@since)
end
select [date] from #dates

*fiddle here: http://sqlfiddle.com/#!6/9eecb/3469

Help needed with Median If in Excel

Expanding on Brian Camire's Answer:

Using =MEDIAN(IF($A$1:$A$6="Airline",$B$1:$B$6,"")) with CTRL+SHIFT+ENTER will include blank cells in the calculation. Blank cells will be evaluated as 0 which results in a lower median value. The same is true if using the average funtion. If you don't want to include blank cells in the calculation, use a nested if statement like so:

=MEDIAN(IF($A$1:$A$6="Airline",IF($B$1:$B$6<>"",$B$1:$B$6)))

Don't forget to press CTRL+SHIFT+ENTER to treat the formula as an "array formula".

How can I get phone serial number (IMEI)

Here is the code:-

telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);


    deviceId = telephonyManager.getDeviceId(); 
    Log.d(TAG, "getDeviceId() " + deviceId);



    phoneType = telephonyManager.getPhoneType();
    Log.d(TAG, "getPhoneType () " + phoneType);

Why doesn't RecyclerView have onItemClickListener()?

I like this way and I'm using it

Inside

public Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)

Put

View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_image_and_text, parent, false);
v.setOnClickListener(new MyOnClickListener());

And create this class anywhere you want it

class MyOnClickListener implements View.OnClickListener {
    @Override
    public void onClick(View v) {
       int itemPosition = recyclerView.indexOfChild(v);
       Log.e("Clicked and Position is ",String.valueOf(itemPosition));
    }
}

I've read before that there is a better way but I like this way is easy and not complicated.

Binary Data in JSON String. Something better than Base64

(Edit 7 years later: Google Gears is gone. Ignore this answer.)


The Google Gears team ran into the lack-of-binary-data-types problem and has attempted to address it:

Blob API

JavaScript has a built-in data type for text strings, but nothing for binary data. The Blob object attempts to address this limitation.

Maybe you can weave that in somehow.

How to SSH to a VirtualBox guest externally through a host?

You can also use a Bridged Network (or "Bridge Adapter", in newer versions) in network settings. This will put your VM in a VLAN with your machine. So you can just ssh into the VM like this.

ssh user@IP_OF_VM

jQuery get an element by its data-id

This worked for me, in my case I had a button with a data-id attribute:

$("a").data("item-id");

Fiddle

Best way to store passwords in MYSQL database

Hashing algorithms such as sha1 and md5 are not suitable for password storing. They are designed to be very efficient. This means that brute forcing is very fast. Even if a hacker obtains a copy of your hashed passwords, it is pretty fast to brute force it. If you use a salt, it makes rainbow tables less effective, but does nothing against brute force. Using a slower algorithm makes brute force ineffective. For instance, the bcrypt algorithm can be made as slow as you wish (just change the work factor), and it uses salts internally to protect against rainbow tables. I would go with such an approach or similar (e.g. scrypt or PBKDF2) if I were you.

how to remove key+value from hash in javascript

You say you don't necessarily know that 'key2' is in position [1]. Well, it's not. Position 1 would be occupied by myHash[1].

You're abusing JavaScript arrays, which (like functions) allow key/value hashes. Even though JavaScript allows it, it does not give you facilities to deal with it, as a language designed for associative arrays would. JavaScript's array methods work with the numbered properties only.

The first thing you should do is switch to objects rather than arrays. You don't have a good reason to use an array here rather than an object, so don't do it. If you want to use an array, just number the elements and give up on the idea of hashes. The intent of an array is to hold information which can be indexed into numerically.

You can, of course, put a hash (object) into an array if you like.

myhash[1]={"key1","brightOrangeMonkey"};

center image in div with overflow hidden

I have been trying to implement Jaap's answer inside this page of my recent site, with one difference : the .main {height:} was set to auto instead of a fixed px value. As responsive developer i am looking for a solution to synchronize the image height with the left floating text element, yet only in case my text height becomes greater then my actual image height. In that case the image should not be rescaled, but cropped and centered as decribed in the original question here above. Can this be done ? You can simulate the behaviour by slowly downsizing the browser's width.

How to make promises work in IE11

If you want this type of code to run in IE11 (which does not support much of ES6 at all), then you need to get a 3rd party promise library (like Bluebird), include that library and change your coding to use ES5 coding structures (no arrow functions, no let, etc...) so you can live within the limits of what older browsers support.

Or, you can use a transpiler (like Babel) to convert your ES6 code to ES5 code that will work in older browsers.

Here's a version of your code written in ES5 syntax with the Bluebird promise library:

<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>

<script>

'use strict';

var promise = new Promise(function(resolve) {
    setTimeout(function() {
        resolve("result");
    }, 1000);
});

promise.then(function(result) {
    alert("Fulfilled: " + result);
}, function(error) {
    alert("Rejected: " + error);
});

</script>

SQL update trigger only when column is modified

Whenever a record has updated a record is "deleted". Here is my example:

ALTER TRIGGER [dbo].[UpdatePhyDate]
   ON  [dbo].[M_ContractDT1]
   AFTER UPDATE
AS 
BEGIN
    -- on ContarctDT1 PhyQty is updated 
    -- I want system date in Phytate automatically saved
    SET NOCOUNT ON;

    declare @dt1ky as int   

    if(update(Phyqty))
    begin
        select @dt1ky = dt1ky from deleted

        update M_ContractDT1 set PhyDate=GETDATE() where Dt1Ky=  @dt1ky     

    end

END

It works fine

how to check and set max_allowed_packet mysql variable

max_allowed_packet is set in mysql config, not on php side

[mysqld]
max_allowed_packet=16M 

You can see it's curent value in mysql like this:

SHOW VARIABLES LIKE 'max_allowed_packet';

You can try to change it like this, but it's unlikely this will work on shared hosting:

SET GLOBAL max_allowed_packet=16777216;

You can read about it here http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html

EDIT

The [mysqld] is necessary to make the max_allowed_packet working since at least mysql version 5.5.

Recently setup an instance on AWS EC2 with Drupal and Solr Search Engine, which required 32M max_allowed_packet. It you set the value under [mysqld_safe] (which is default settings came with the mysql installation) mode in /etc/my.cnf, it did no work. I did not dig into the problem. But after I change it to [mysqld] and restarted the mysqld, it worked.

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

I had this error in my DNN application installed on Windows 2012 R2. It's using some 32 bit dll and only Oracle.DataAccess.dll x32 was working. My solution is:

  1. Uninstall old Oracle Client \ ODAC.
  2. Install Oracle 11 Client x32.
  3. Install Oracle ODAC 12 x64.
  4. Check IIS Application Pool (Classic version) has option "Enable 32-Bit Applications" = true.

Multiple radio button groups in one form

Set equal name attributes to create a group;

_x000D_
_x000D_
<form>_x000D_
  <fieldset id="group1">_x000D_
    <input type="radio" value="value1" name="group1">_x000D_
    <input type="radio" value="value2" name="group1">_x000D_
  </fieldset>_x000D_
_x000D_
  <fieldset id="group2">_x000D_
    <input type="radio" value="value1" name="group2">_x000D_
    <input type="radio" value="value2" name="group2">_x000D_
    <input type="radio" value="value3" name="group2">_x000D_
  </fieldset>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Javascript find json value

First convert this structure to a "dictionary" object:

dict = {}
json.forEach(function(x) {
    dict[x.code] = x.name
})

and then simply

countryName = dict[countryCode]

For a list of countries this doesn't matter much, but for larger lists this method guarantees the instant lookup, while the naive searching will depend on the list size.

How does Access-Control-Allow-Origin header work?

From my own experience, it's hard to find a simple explanation why CORS is even a concern.

Once you understand why it's there, the headers and discussion becomes a lot clearer. I'll give it a shot in a few lines.


It's all about cookies. Cookies are stored on a client by their domain.

An example story: On your computer, there's a cookie for yourbank.com. Maybe your session is in there.

Key point: When a client makes a request to the server, it will send the cookies stored under the domain that the client is on.

You're logged in on your browser to yourbank.com. You request to see all your accounts. yourbank.com receives the pile of cookies and sends back its response (your accounts).

If another client makes a cross origin request to a server, those cookies are sent along, just as before. Ruh roh.

You browse to malicious.com. Malicious makes a bunch of requests to different banks, including yourbank.com.

Since the cookies are validated as expected, the server will authorize the response.

Those cookies get gathered up and sent along - and now, malicious.com has a response from yourbank.

Yikes.


So now, a few questions and answers become apparent:

  • "Why don't we just block the browser from doing that?" Yep. CORS.
  • "How do we get around it?" Have the server tell the request that CORS is OK.

How do I find the mime-type of a file with php?

I haven't used it, but there's a PECL extension for getting a file's mimetype. The official documentation for it is in the manual.

Depending on your purposes, a file extension can be ok, but it's not incredibly reliable since it's so easily changed.

How can I create an array/list of dictionaries in python?

Dictionary:

dict = {'a':'a','b':'b','c':'c'}

array of dictionary

arr = (dict,dict,dict)
arr
({'a': 'a', 'c': 'c', 'b': 'b'}, {'a': 'a', 'c': 'c', 'b': 'b'}, {'a': 'a', 'c': 'c', 'b': 'b'})

How do you revert to a specific tag in Git?

Git tags are just pointers to the commit. So you use them the same way as you do HEAD, branch names or commit sha hashes. You can use tags with any git command that accepts commit/revision arguments. You can try it with git rev-parse tagname to display the commit it points to.

In your case you have at least these two alternatives:

  1. Reset the current branch to specific tag:

    git reset --hard tagname
    
  2. Generate revert commit on top to get you to the state of the tag:

    git revert tag
    

This might introduce some conflicts if you have merge commits though.

How can I declare a global variable in Angular 2 / Typescript?

I think the best way is to share an object with global variables throughout your application by exporting and importing it where you want.

First create a new .ts file for example globals.ts and declare an object. I gave it an Object type but you also could use an any type or {}

export let globalVariables: Object = {
 version: '1.3.3.7',
 author: '0x1ad2',
 everything: 42
};

After that import it

import {globalVariables} from "path/to/your/globals.ts"

And use it

console.log(globalVariables);

How do I check out a remote Git branch?

If the remote branch name begins with special characteres you need to use single quotes around it in the checkout command, or else git won't know which branch you are talking about.

For example, I tried to checkout a remote branch named as #9773 but the command didn't work properly, as shown in the picture below:

enter image description here

For some reason I wondered if the sharp symbol (#) could have something to do with it, and then I tried surrounding the branch name with single quotes, like '#9773' rathen than just #9773, and fortunately it worked fine.

$ git checkout -b '#9773' origin/'#9773'

Creating a procedure in mySql with parameters

I figured it out now. Here's the correct answer

CREATE PROCEDURE checkUser 
(
   brugernavn1 varchar(64),
   password varchar(64)
) 
BEGIN 
   SELECT COUNT(*) FROM bruger 
   WHERE bruger.brugernavn=brugernavn1 
   AND bruger.pass=password; 
END; 

@ points to a global var in mysql. The above syntax is correct.

VB.NET Empty String Array

Not sure why you'd want to, but the C# way would be

string[] newArray = new string[0];

I'm guessing that VB won't be too dissimilar to this.

If you're building an empty array so you can populate it with values later, you really should consider using

List<string>

and converting it to an array (if you really need it as an array) with

newListOfString.ToArray();

Setting up a cron job in Windows

  1. Make sure you logged on as an administrator or you have the same access as an administrator.
  2. Start->Control Panel->System and Security->Administrative Tools->Task Scheduler
  3. Action->Create Basic Task->Type a name and Click Next
  4. Follow through the wizard.

How to check certificate name and alias in keystore files?

You can run the following command to list the content of your keystore file (and alias name):

keytool -v -list -keystore .keystore

If you are looking for a specific alias, you can also specify it in the command:

keytool -list -keystore .keystore -alias foo

If the alias is not found, it will display an exception:

keytool error: java.lang.Exception: Alias does not exist

DELETE ... FROM ... WHERE ... IN

The canonical T-SQL (SqlServer) answer is to use a DELETE with JOIN as such

DELETE o
FROM Orders o
INNER JOIN Customers c
    ON o.CustomerId = c.CustomerId
WHERE c.FirstName = 'sklivvz'

This will delete all orders which have a customer with first name Sklivvz.

Send email using the GMail SMTP server from a PHP page

I tried the suggestion offered by @shasi kanth, but it didn't work out. I read the documentation and there are few changes made. So I managed to send mail via Gmail using this code, where vendor/autoload.php is got by composer with composer require "swiftmailer/swiftmailer:^6.0":

<?php
     require_once 'vendor/autoload.php';
     $transport = (new Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl'))->setUsername ('SendingMail')->setPassword ('Password');

     $mailer = new Swift_Mailer($transport);

     $message = (new Swift_Message('test'))
      ->setFrom(['Sending mail'])
      ->setTo(['Recipient mail'])
      ->setBody('Message')
  ;

     $result = $mailer->send($message);
    ?>

What is float in Java?

In Java, when you type a decimal number as 3.6, its interpreted as a double. double is a 64-bit precision IEEE 754 floating point, while floatis a 32-bit precision IEEE 754 floating point. As a float is less precise than a double, the conversion cannot be performed implicitly.

If you want to create a float, you should end your number with f (i.e.: 3.6f).

For more explanation, see the primitive data types definition of the Java tutorial.

how to set textbox value in jquery

Note that the .value attribute is a JavaScript feature. If you want to use jQuery, use:

$('#pid').val()

to get the value, and:

$('#pid').val('value')

to set it.

http://api.jquery.com/val/

Regarding your second issue, I have never tried automatically setting the HTML value using the load method. For sure, you can do something like this:

$('#subtotal').load( 'compz.php?prodid=' + x + '&qbuys=' + y, function(response){ $('#subtotal').val(response);
});

Note that the code above is untested.

http://api.jquery.com/load/

Uninstalling an MSI file from the command line without using msiexec

The msi file extension is mapped to msiexec (same way typing a .txt filename on a command prompt launches Notepad/default .txt file handler to display the file).

Thus typing in a filename with an .msi extension really runs msiexec with the MSI file as argument and takes the default action, install. For that reason, uninstalling requires you to invoke msiexec with uninstall switch to unstall it.

Moving up one directory in Python

In Python 3.4 pathlib was introduced:

>>> from pathlib import Path
>>> p = Path('/etc/usr/lib')
>>> p
PosixPath('/etc/usr/lib')
>>> p.parent
PosixPath('/etc/usr')

It also comes with many other helpful features e.g. for joining paths using slashes or easily walking the directory tree.

For more information refer to the docs or this blog post, which covers the differences between os.path and pathlib.

Recommended add-ons/plugins for Microsoft Visual Studio

I find Ghost Doc to be very useful.

GhostDoc is a free add-in for Visual Studio that automatically generates XML documentation comments for C#. Either by using existing documentation inherited from base classes or implemented interfaces, or by deducing comments from name and type of e.g. methods, properties or parameters.

how to fix EXE4J_JAVA_HOME, No JVM could be found on your system error?

Leave you stuff there and Try the following as well:

Start > Right-click on My computer > Properties > Advanced system settings > Environment Variables > look for variable name called "Path" in the lower box

set path value value as: (you can just add it to the starting of line, don't forgot semi column in between )

c:\Program Files\java\jre7\bin

C Linking Error: undefined reference to 'main'

You are overwriting your object file runexp.o by running this command :

 gcc -o runexp.o scd.o data_proc.o -lm -fopenmp

In fact, the -o is for the output file. You need to run :

gcc -o runexp.out runexp.o scd.o data_proc.o -lm -fopenmp

runexp.out will be you binary file.

How to remove anaconda from windows completely?

On my machine (Win10), the uninstaller was located at C:\ProgramData\Anaconda3\Uninstall-Anaconda3.exe.

log4j: Log output of a specific class to a specific appender

Here's an answer regarding the XML configuration, note that if you don't give the file appender a ConversionPattern it will create 0 byte file and not write anything:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
    </appender>

    <appender name="bdfile" class="org.apache.log4j.RollingFileAppender">
        <param name="append" value="false"/>
        <param name="maxFileSize" value="1GB"/>
        <param name="maxBackupIndex" value="2"/>
        <param name="file" value="/tmp/bd.log"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
    </appender>

    <logger name="com.example.mypackage" additivity="false">
        <level value="debug"/>
        <appender-ref ref="bdfile"/>
    </logger>

    <root>
        <priority value="info"/>
        <appender-ref ref="bdfile"/>
        <appender-ref ref="console"/>
    </root>

</log4j:configuration>

get size of json object

Consider using underscore.js. It will allow you to check the size i.e. like that:

var data = {one : 1, two : 2, three : 3};
_.size(data);
//=> 3
_.keys(data);
//=> ["one", "two", "three"]
_.keys(data).length;
//=> 3

Pick any kind of file via an Intent in Android

this work for me on galaxy note its show contacts, file managers installed on device, gallery, music player

private void openFile(Int  CODE) {
    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
    i.setType("*/*");
    startActivityForResult(intent, CODE);
}

here get path in onActivityResult of activity.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     String Fpath = data.getDataString();
    // do somthing...
    super.onActivityResult(requestCode, resultCode, data);

}

printf not printing on console

  1. In your project folder, create a “.gdbinit” text file. It will contain your gdb debugger configuration
  2. Edit “.gdbinit”, and add the line (without the quotes) : “set new-console on”
  3. After building the project right click on the project Debug > “Debug Configurations”, as shown below Debug configuration

  4. In the “debugger” tab, ensure the “GDB command file” now points to your “.gdbinit” file. Else, input the path to your “.gdbinit” configuration file : Gdb configuration

  5. Click “Apply” and “Debug”. A native DOS command line should be launched as shown below Console

How exactly do you configure httpOnlyCookies in ASP.NET?

With props to Rick (second comment down in the blog post mentioned), here's the MSDN article on httpOnlyCookies.

Bottom line is that you just add the following section in your system.web section in your web.config:

<httpCookies domain="" httpOnlyCookies="true|false" requireSSL="true|false" />

Error on line 2 at column 1: Extra content at the end of the document

I think you are creating a document that looks like this:

<mycatch>
    ....
</mycatch>
<mycatch>
    ....
</mycatch>

This is not a valid XML document as it has more than one root element. You must have a single top-level element, as in

<mydocument>      
  <mycatch>
      ....
  </mycatch>
  <mycatch>
      ....
  </mycatch>
  ....
</mydocument>

Find if a String is present in an array

If you can organize the values in the array in sorted order, then you can use Arrays.binarySearch(). Otherwise you'll have to write a loop and to a linear search. If you plan to have a large (more than a few dozen) strings in the array, consider using a Set instead.

Bind failed: Address already in use

The error usually means that the port you are trying to open is being already used by another application. Try using netstat to see which ports are open and then use an available port.

Also check if you are binding to the right ip address (I am assuming it would be localhost)

Refresh Part of Page (div)

You need to do that on the client side for instance with jQuery.

Let's say you want to retrieve HTML into div with ID mydiv:

<h1>My page</h1>
<div id="mydiv">
    <h2>This div is updated</h2>
</div>

You can update this part of the page with jQuery as follows:

$.get('/api/mydiv', function(data) {
  $('#mydiv').html(data);
});

In the server-side you need to implement handler for requests coming to /api/mydiv and return the fragment of HTML that goes inside mydiv.

See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/

Visual Studio Code always asking for git credentials

You should be able to set your credentials like this:

git remote set-url origin https://<USERNAME>:<PASSWORD>@bitbucket.org/path/to/repo.git

You can get the remote url like this:

git config --get remote.origin.url

How to switch to another domain and get-aduser

get-aduser -Server "servername" -Identity %username% -Properties *

get-aduser -Server "testdomain.test.net" -Identity testuser -Properties *

These work when you have the username. Also less to type than using the -filter property.

EDIT: Formatting.

Extract values in Pandas value_counts()

The best way to extract the values is to just do the following

json.loads(dataframe[column].value_counts().to_json())

This returns a dictionary which you can use like any other dict. Using values or keys.

 {"apple": 5, "sausage": 2, "banana": 2, "cheese": 1}

Finding all the subsets of a set

It's very simple to do this recursively. The basic idea is that for each element, the set of subsets can be divided equally into those that contain that element and those that don't, and those two sets are otherwise equal.

  • For n=1, the set of subsets is {{}, {1}}
  • For n>1, find the set of subsets of 1,...,n-1 and make two copies of it. For one of them, add n to each subset. Then take the union of the two copies.

Edit To make it crystal clear:

  • The set of subsets of {1} is {{}, {1}}
  • For {1, 2}, take {{}, {1}}, add 2 to each subset to get {{2}, {1, 2}} and take the union with {{}, {1}} to get {{}, {1}, {2}, {1, 2}}
  • Repeat till you reach n

AngularJS - Create a directive that uses ng-model

You only need ng-model when you need to access the model's $viewValue or $modelValue. See NgModelController. And in that case, you would use require: '^ngModel'.

For the rest, see Roys answer.

Is there a short cut for going back to the beginning of a file by vi editor?

To go end of the file: press ESC

1) type capital G (Capital G)

2) press shift + g (small g)

To go top of the file there are the following ways: press ESC

1) press 1G (Capital G)

2) press gg (small g) or 1gg

3) You can jump to the particular line number,e.g wanted to go 1 line number, press 1 + G

Can I add extension methods to an existing static class?

I tried to do this with System.Environment back when I was learning extension methods and was not successful. The reason is, as others mention, because extension methods require an instance of the class.

How to get the request parameters in Symfony 2?

$request = Request::createFromGlobals();
$getParameter = $request->get('getParameter');

What is the difference between old style and new style classes in Python?

New-style classes inherit from object and must be written as such in Python 2.2 onwards (i.e. class Classname(object): instead of class Classname:). The core change is to unify types and classes, and the nice side-effect of this is that it allows you to inherit from built-in types.

Read descrintro for more details.

How to delete all the rows in a table using Eloquent?

Can do a loop too..

$collection = Model::get();

foreach($collection as $c) {

$c->delete();

}

get the titles of all open windows

Something like this:

using System.Diagnostics;

Process[] processlist = Process.GetProcesses();

foreach (Process process in processlist)
{
    if (!String.IsNullOrEmpty(process.MainWindowTitle))
    {
        Console.WriteLine("Process: {0} ID: {1} Window title: {2}", process.ProcessName, process.Id, process.MainWindowTitle);
    }
}

Add a list item through javascript

Try something like this:

var node=document.createElement("LI");
var textnode=document.createTextNode(firstname);
node.appendChild(textnode);
document.getElementById("demo").appendChild(node);

Fiddle: http://jsfiddle.net/FlameTrap/3jDZd/

Tab Escape Character?

Easy one! "\t"

Edit: In fact, here's something official: Escape Sequences

Read specific columns with pandas or other python module

An easy way to do this is using the pandas library like this.

import pandas as pd
fields = ['star_name', 'ra']

df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
# See the keys
print df.keys()
# See content in 'star_name'
print df.star_name

The problem here was the skipinitialspace which remove the spaces in the header. So ' star_name' becomes 'star_name'

Copying files using rsync from remote server to local machine

If you have SSH access, you don't need to SSH first and then copy, just use Secure Copy (SCP) from the destination.

scp user@host:/path/file /localpath/file

Wild card characters are supported, so

scp user@host:/path/folder/* /localpath/folder

will copy all of the remote files in that folder.If copying more then one directory.

note -r will copy all sub-folders and content too.

Best practices for circular shift (rotate) operations in C++

How abt something like this, using the standard bitset ...

#include <bitset> 
#include <iostream> 

template <std::size_t N> 
inline void 
rotate(std::bitset<N>& b, unsigned m) 
{ 
   b = b << m | b >> (N-m); 
} 

int main() 
{ 
   std::bitset<8> b(15); 
   std::cout << b << '\n'; 
   rotate(b, 2); 
   std::cout << b << '\n'; 

   return 0;
}

HTH,

SQL multiple columns in IN clause

In Oracle you can do this:

SELECT * FROM table1 WHERE (col_a,col_b) IN (SELECT col_x,col_y FROM table2)

How to change a text with jQuery

Something like this should do the trick:

$(document).ready(function() {
    $('#toptitle').text(function(i, oldText) {
        return oldText === 'Profil' ? 'New word' : oldText;
    });
});

This only replaces the content when it is Profil. See text in the jQuery API.

Why Is `Export Default Const` invalid?

If the component name is explained in the file name MyComponent.js, just don't name the component, keeps code slim.

import React from 'react'

export default (props) =>
    <div id='static-page-template'>
        {props.children}
    </div>

Update: Since this labels it as unknown in stack tracing, it isn't recommended

Install Qt on Ubuntu

Also take a look at awesome project aqtinstall https://github.com/miurahr/aqtinstall/ (it can install any Qt version on Linux, Mac and Windows machines without any interaction!) and GitHub Action that uses this tool: https://github.com/jurplel/install-qt-action

iTunes Connect Screenshots Sizes for all iOS (iPhone/iPad/Apple Watch) devices

for xcode 11.1which doesn't contain ipad pro iPad Pro (2nd Gen) 12.9" Display run this command in terminal

xcrun simctl create "iPad Pro (12.9-inch) (2nd generation)" "com.apple.CoreSimulator.SimDeviceType.iPad-Pro--12-9-inch---2nd-generation-" "com.apple.CoreSimulator.SimRuntime.iOS-13-1"

look here

Div table-cell vertical align not working

You can vertically align a floated element in a way which works on IE 6+. It doesn't need full table markup either. This method isn't perfectly clean - includes wrappers and there are a few things to be aware of e.g. if you have too much text outspilling the container - but it's pretty good.


Short answer: You just need to apply display: table-cell to an element inside the floated element (table cells don't float), and use a fallback with position: absolute and top for old IE.


Long answer: Here's a jsfiddle showing the basics. The important stuff summarized (with a conditional comment adding an .old-ie class):

    .wrap {
        float: left;
        height: 100px; /* any fixed amount */
    }
    .wrap2 {
        height: inherit;
    }
    .content {
        display: table-cell;
        height: inherit;
        vertical-align: middle;
    }

    .old-ie .wrap{
        position: relative;
    }
    .old-ie .wrap2 {
        position: absolute;
        top: 50%;
    }
    .old-ie .content {
        position: relative;
        top: -50%;
        display: block;
    }

Here's a jsfiddle that deliberately highlight the minor faults with this method. Note how:

  • In standards browsers, content that exceeds the height of the wrapper element stops centering and starts going down the page. This isn't a big problem (probably looks better than creeping up the page), and can be avoided by avoiding content that is too big (note that unless I've overlooked something, overflow methods like overflow: auto; don't seem to work)
  • In old IE, the content element doesn't stretch to fill the available space - the height is the height of the content, not of the container.

Those are pretty minor limitations, but worth being aware of.

Code and idea adapted from here

How to run a python script from IDLE interactive shell?

EASIEST WAY

python -i helloworld.py  #Python 2

python3 -i helloworld.py #Python 3

How to find the foreach index?

You can put a hack in your foreach, such as a field incremented on each run-through, which is exactly what the for loop gives you in a numerically-indexed array. Such a field would be a pseudo-index that needs manual management (increments, etc).

A foreach will give you your index in the form of your $key value, so such a hack shouldn't be necessary.

e.g., in a foreach

$index = 0;
foreach($data as $key=>$val) {
    // Use $key as an index, or...

    // ... manage the index this way..
    echo "Index is $index\n";
    $index++;
}

CSS/HTML: What is the correct way to make text italic?

OK, the first thing to note is that <i> has been deprecated, and shouldn't be used <i> has not been deprecated, but I still do not recommend using it—see the comments for details. This is because it goes entirely against keeping presentation in the presentation layer, which you've pointed out. Similarly, <span class="italic"> seems to break the mold too.

So now we have two real ways of doing things: <em> and <span class="footnote">. Remember that em stands for emphasis. When you wish to apply emphasis to a word, phrase or sentence, stick it in <em> tags regardless of whether you want italics or not. If you want to change the styling in some other way, use CSS: em { font-weight: bold; font-style: normal; }. Of course, you can also apply a class to the <em> tag: if you decide you want certain emphasised phrases to show up in red, give them a class and add it to the CSS:

Fancy some <em class="special">shiny</em> text?

em { font-weight: bold; font-style: normal; }
em.special { color: red; }

If you're applying italics for some other reason, go with the other method and give the section a class. That way, you can change its styling whenever you want without adjusting the HTML. In your example, footnotes should not be emphasised—in fact, they should be de-emphasised, as the point of a footnote is to show unimportant but interesting or useful information. In this case, you're much better off applying a class to the footnote and making it look like one in the presentation layer—the CSS.

Hide div after a few seconds

You can try the .delay()

$(".formSentMsg").delay(3200).fadeOut(300);

call the div set the delay time in milliseconds and set the property you want to change, in this case I used .fadeOut() so it could be animated, but you can use .hide() as well.

http://api.jquery.com/delay/

Get the selected value in a dropdown using jQuery.

Hello guys i am using this technique to get the values from the selected dropdown list and it is working like charm.

var methodvalue = $("#method option:selected").val(); 

jQuery - find child with a specific class

I'm not sure if I understand your question properly, but it shouldn't matter if this div is a child of some other div. You can simply get text from all divs with class bgHeaderH2 by using following code:

$(".bgHeaderH2").text();

How do I create a timeline chart which shows multiple events? Eg. Metallica Band members timeline on wiki

A Stacked bar chart should suffice:

Setup data as follows

Name    Start       End         Duration (End - Start)
Fred    1/01/1981   1/06/1985    1612   
Bill    1/07/1985   1/11/2000    5602  
Joe     1/01/1980   1/12/2001    8005  
Jim     1/03/1999   1/01/2000    306  
  1. Plot Start and Duration as a stacked bar chart
  2. Set the X-Axis minimum to the desired start date
  3. Set the Fill Colour of thestart range to no fill
  4. Set the Fill of individual bars to suit

(example prepared in Excel 2010)

enter image description here

Angular2 - Focusing a textbox on component load

<input id="name" type="text" #myInput />
{{ myInput.focus() }}

this is the best and simplest way, because code "myInput.focus()" runs after input created

WARNING: this solution is acceptable only if you have single element in the form (user will be not able to select other elements)

MySQL: Curdate() vs Now()

CURDATE() will give current date while NOW() will give full date time.

Run the queries, and you will find out whats the difference between them.

SELECT NOW();     -- You will get 2010-12-09 17:10:18
SELECT CURDATE(); -- You will get 2010-12-09

Django - what is the difference between render(), render_to_response() and direct_to_template()?

https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render

render(request, template[, dictionary][, context_instance][, content_type][, status][, current_app])

render() is a brand spanking new shortcut for render_to_response in 1.3 that will automatically use RequestContext that I will most definitely be using from now on.


2020 EDIT: It should be noted that render_to_response() was removed in Django 3.0

https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render-to-response

render_to_response(template[, dictionary][, context_instance][, mimetype])¶

render_to_response is your standard render function used in the tutorials and such. To use RequestContext you'd have to specify context_instance=RequestContext(request)


https://docs.djangoproject.com/en/1.8/ref/generic-views/#django-views-generic-simple-direct-to-template

direct_to_template is a generic view that I use in my views (as opposed to in my urls) because like the new render() function, it automatically uses RequestContext and all its context_processors.

But direct_to_template should be avoided as function based generic views are deprecated. Either use render or an actual class, see https://docs.djangoproject.com/en/1.3/topics/generic-views-migration/

I'm happy I haven't typed RequestContext in a long, long time.

Find the min/max element of an array in JavaScript

If you use the library sugar.js, you can write arr.min() and arr.max() as you suggest. You can also get min and max values from non-numeric arrays.

min( map , all = false ) Returns the element in the array with the lowest value. map may be a function mapping the value to be checked or a string acting as a shortcut. If all is true, will return all min values in an array.

max( map , all = false ) Returns the element in the array with the greatest value. map may be a function mapping the value to be checked or a string acting as a shortcut. If all is true, will return all max values in an array.

Examples:

[1,2,3].min() == 1
['fee','fo','fum'].min('length') == "fo"
['fee','fo','fum'].min('length', true) == ["fo"]
['fee','fo','fum'].min(function(n) { return n.length; }); == "fo"
[{a:3,a:2}].min(function(n) { return n['a']; }) == {"a":2}
['fee','fo','fum'].max('length', true) == ["fee","fum"]

Libraries like Lo-Dash and underscore.js also provide similar powerful min and max functions:

Example from Lo-Dash:

_.max([4, 2, 8, 6]) == 8
var characters = [
  { 'name': 'barney', 'age': 36 },
  { 'name': 'fred',   'age': 40 }
];
_.max(characters, function(chr) { return chr.age; }) == { 'name': 'fred', 'age': 40 }

How to pass a value to razor variable from javascript variable?

Okay, so this question is old... but I wanted to do something similar and I found a solution that works for me. Maybe it might help someone else.

I have a List<QuestionType> that I fill a drop down with. I want to put that selection into the QuestionType property on the Question object that I'm creating in the form. I'm using Knockout.js for the select binding. This sets the self.QuestionType knockout observable property to a QuestionType object when the user selects one.

<select class="form-control form-control-sm"
    data-bind="options: QuestionTypes, optionsText: 'QuestionTypeText', value: QuestionType, optionsCaption: 'Choose...'">
</select>

I have a hidden field that will hold this object:

@Html.Hidden("NewQuestion.QuestionTypeJson", Model.NewQuestion.QuestionTypeJson)

In the subscription for the observable, I set the hidden field to a JSON.stringify-ed version of the object.

self.QuestionType.subscribe(function(newValue) {
    if (newValue !== null && newValue !== undefined) {                       
        document.getElementById('NewQuestion_QuestionTypeJson').value = JSON.stringify(newValue);
    }
});

In the Question object, I have a field called QuestionTypeJson that is filled when the user selects a question type. I use this field to get the QuestionType in the Question object like this:

public string QuestionTypeJson { get; set; }

private QuestionType _questionType = new QuestionType();
public QuestionType QuestionType
{
    get => string.IsNullOrEmpty(QuestionTypeJson) ? _questionType : JsonConvert.DeserializeObject<QuestionType>(QuestionTypeJson);
    set => _questionType = value;
}

So if the QuestionTypeJson field contains something, it will deserialize that and use it for QuestionType, otherwise it'll just use what is in the backing field.

I have essentially 'passed' a JavaScript object to my model without using Razor or an Ajax call. You can probably do something similar to this without using Knockout.js, but that's what I'm using so...

JPA CascadeType.ALL does not delete orphans

you can use @PrivateOwned to delete orphans e.g

@OneToMany(mappedBy = "masterData", cascade = {
        CascadeType.ALL })
@PrivateOwned
private List<Data> dataList;

rename the columns name after cbind the data

It's easy just add the name which you want to use in quotes before adding vector

a_matrix <- cbind(b_matrix,'Name-Change'= c_vector)

Vagrant error : Failed to mount folders in Linux guest

Fix Step by step:

If you not have vbguest plugin, install it:

$ vagrant plugin install vagrant-vbguest

Run Vagrant

It is show a error.

$ vagrant up

Login on VM

$ vagrant ssh

Fix!

In the guest (VM logged).

$ sudo ln -s /opt/VBoxGuestAdditions-4.3.10/lib/VBoxGuestAdditions /usr/lib/VBoxGuestAdditions

Back on the host, reload Vagrant

$ vagrant reload

How to generate serial version UID in Intellij

IntelliJ IDEA Plugins / GenerateSerialVersionUID https://plugins.jetbrains.com/plugin/?idea&id=185

very nice, very easy to install. you can install that from plugins menu, select install from disk, select the jar file you unpacked in the lib folder. restart, control + ins, and it pops up to generate serial UID from menu. love it. :-)

Is it possible to use JS to open an HTML select to show its option list?

This works on Google Chrome

dropDown = function (elementId) {
    var dropdown = document.getElementById(elementId);
    try {
        showDropdown(dropdown);
    } catch(e) {

    }
    return false;
};

showDropdown = function (element) {
    var event;
    event = document.createEvent('MouseEvents');
    event.initMouseEvent('mousedown', true, true, window);
    element.dispatchEvent(event);
};

How to urlencode a querystring in Python?

Try this:

urllib.pathname2url(stringToURLEncode)

urlencode won't work because it only works on dictionaries. quote_plus didn't produce the correct output.

Error: Cannot find module 'ejs'

The error hit me when i was working on goormIDE. This happens basically when node packages arent inside the running file. The place where app.js or home.js is executed.

How to stop execution after a certain time in Java?

you should try the new Java Executor Services. http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

With this you don't need to program the loop the time measuring by yourself.

public class Starter {

    public static void main(final String[] args) {
        final ExecutorService service = Executors.newSingleThreadExecutor();

        try {
            final Future<Object> f = service.submit(() -> {
                // Do you long running calculation here
                Thread.sleep(1337); // Simulate some delay
                return "42";
            });

            System.out.println(f.get(1, TimeUnit.SECONDS));
        } catch (final TimeoutException e) {
            System.err.println("Calculation took to long");
        } catch (final Exception e) {
            throw new RuntimeException(e);
        } finally {
            service.shutdown();
        }
    }
}

ORACLE and TRIGGERS (inserted, updated, deleted)

I've changed my code like this and it works:

CREATE or REPLACE TRIGGER test001
  AFTER INSERT OR UPDATE OR DELETE ON tabletest001
  REFERENCING OLD AS old_buffer NEW AS new_buffer 
  FOR EACH ROW WHEN (new_buffer.field1 = 'HBP00' OR old_buffer.field1 = 'HBP00') 

DECLARE
      Operation       NUMBER;
      CustomerCode    CHAR(10 BYTE);
BEGIN

IF DELETING THEN 
  Operation := 3;
  CustomerCode := :old_buffer.field1;
END IF;

IF INSERTING THEN 
  Operation := 1;
  CustomerCode := :new_buffer.field1;
END IF;

IF UPDATING THEN 
  Operation := 2;
  CustomerCode := :new_buffer.field1;
END IF;    

// DO SOMETHING ...

EXCEPTION
    WHEN OTHERS THEN ErrorCode := SQLCODE;

END;