Programs & Examples On #Chartfx

Chart FX is a commercial package to create visually-rich, lightweight and secure charts that will enhance your enterprise application's display layer.

PDO get the last ID inserted

You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).

Like this $lid = $conn->lastInsertId();

Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php

Task not serializable: java.io.NotSerializableException when calling function outside closure only on classes not objects

Complete talk fully explaining the problem, which proposes a great paradigm shifting way to avoid these serialization problems: https://github.com/samthebest/dump/blob/master/sams-scala-tutorial/serialization-exceptions-and-memory-leaks-no-ws.md

The top voted answer is basically suggesting throwing away an entire language feature - that is no longer using methods and only using functions. Indeed in functional programming methods in classes should be avoided, but turning them into functions isn't solving the design issue here (see above link).

As a quick fix in this particular situation you could just use the @transient annotation to tell it not to try to serialise the offending value (here, Spark.ctx is a custom class not Spark's one following OP's naming):

@transient
val rddList = Spark.ctx.parallelize(list)

You can also restructure code so that rddList lives somewhere else, but that is also nasty.

The Future is Probably Spores

In future Scala will include these things called "spores" that should allow us to fine grain control what does and does not exactly get pulled in by a closure. Furthermore this should turn all mistakes of accidentally pulling in non-serializable types (or any unwanted values) into compile errors rather than now which is horrible runtime exceptions / memory leaks.

http://docs.scala-lang.org/sips/pending/spores.html

A tip on Kryo serialization

When using kyro, make it so that registration is necessary, this will mean you get errors instead of memory leaks:

"Finally, I know that kryo has kryo.setRegistrationOptional(true) but I am having a very difficult time trying to figure out how to use it. When this option is turned on, kryo still seems to throw exceptions if I haven't registered classes."

Strategy for registering classes with kryo

Of course this only gives you type-level control not value-level control.

... more ideas to come.

Can git undo a checkout of unstaged files

Unfortunately your changes are lost. Your private modifications are simply overwritten. Unless you did git stash prior making checkout...

Take it from the brighter side: you can now implement things even better ;)

Boolean operators && and ||

The shorter ones are vectorized, meaning they can return a vector, like this:

((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE  TRUE FALSE FALSE

The longer form evaluates left to right examining only the first element of each vector, so the above gives

((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE

As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."

So you want to use the long forms only when you are certain the vectors are length one.

You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use all and any to reduce it to length one for use in control flow statements, like if.

The functions all and any are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in ifelse.

One final difference: the && and || only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value a; if it didn't short-circuit, as & and | don't, it would give an error.

a
# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
FALSE & a
# Error: object 'a' not found

Finally, see section 8.2.17 in The R Inferno, titled "and and andand".

Cannot use special principal dbo: Error 15405

This is happening because the user 'sarin' is the actual owner of the database "dbemployee" - as such, they can only have db_owner, and cannot be assigned any further database roles.

Nor do they need to be. If they're the DB owner, they already have permission to do anything they want to within this database.

(To see the owner of the database, open the properties of the database. The Owner is listed on the general tab).

To change the owner of the database, you can use sp_changedbowner or ALTER AUTHORIZATION (the latter being apparently the preferred way for future development, but since this kind of thing tends to be a one off...)

Press TAB and then ENTER key in Selenium WebDriver

Using Java:

private WebDriver driver = new FirefoxDriver();
WebElement element = driver.findElement(By.id("<ElementID>"));//Enter ID for the element. You can use Name, xpath, cssSelector whatever you like
element.sendKeys(Keys.TAB);
element.sendKeys(Keys.ENTER);

Using C#:

private IWebDriver driver = new FirefoxDriver();
IWebElement element = driver.FindElement(By.Name("q"));
element.SendKeys(Keys.Tab);
element.SendKeys(Keys.Enter);

Python spacing and aligning strings

Resurrecting another topic, but this may come in handy for some.

With a little bit of inspiration from https://pyformat.info you can build a method to get a Table of Content [TOC] style printout.

# Define parameters
Location = '10-10-10-10'
Revision = 1
District = 'Tower'
MyDate = 'May 16, 2012'
MyUser = 'LOD'
MyTime = '10:15'

# This is just one way to arrange the data
data = [
    ['Location: '+Location, 'Revision:'+str(Revision)],
    ['District: '+District, 'Date: '+MyDate],
    ['User: '+MyUser,'Time: '+MyTime]
]

# The 'Table of Content' [TOC] style print function
def print_table_line(key,val,space_char,val_loc):
    # key:        This would be the TOC item equivalent
    # val:        This would be the TOC page number equivalent
    # space_char: This is the spacing character between key and val (often a dot for a TOC), must be >= 5
    # val_loc:    This is the location in the string where the first character of val would be located

    val_loc = max(5,val_loc)

    if (val_loc <= len(key)):
        # if val_loc is within the space of key, truncate key and
        cut_str =  '{:.'+str(val_loc-4)+'}'
        key = cut_str.format(key)+'...'+space_char

    space_str = '{:'+space_char+'>'+str(val_loc-len(key)+len(str(val)))+'}'
    print(key+space_str.format(str(val)))

# Examples
for d in data:
    print_table_line(d[0],d[1],' ',30)

print('\n')
for d in data:
    print_table_line(d[0],d[1],'_',25)

print('\n')
for d in data:
    print_table_line(d[0],d[1],' ',20)

The resulting output is as follows:

Location: 10-10-10-10         Revision:1
District: Tower               Date: May 16, 2012
User: LOD                     Time: 10:15


Location: 10-10-10-10____Revision:1
District: Tower__________Date: May 16, 2012
User: LOD________________Time: 10:15


Location: 10-10-... Revision:1
District: Tower     Date: May 16, 2012
User: LOD           Time: 10:15

Recursive query in SQL Server

Sample of the Recursive Level:

enter image description here

DECLARE @VALUE_CODE AS VARCHAR(5);

--SET @VALUE_CODE = 'A' -- Specify a level

WITH ViewValue AS
(
    SELECT ValueCode
    , ValueDesc
    , PrecedingValueCode
    FROM ValuesTable
    WHERE PrecedingValueCode IS NULL
    UNION ALL
    SELECT A.ValueCode
    , A.ValueDesc
    , A.PrecedingValueCode 
    FROM ValuesTable A
    INNER JOIN ViewValue V ON
        V.ValueCode = A.PrecedingValueCode
)

SELECT ValueCode, ValueDesc, PrecedingValueCode

FROM ViewValue

--WHERE PrecedingValueCode  = @VALUE_CODE -- Specific level

--WHERE PrecedingValueCode  IS NULL -- Root

React - clearing an input value after form submit

This is the value that i want to clear and create it in state 1st STEP

state={
TemplateCode:"",
}

craete submitHandler function for Button or what you want 3rd STEP

submitHandler=()=>{
this.clear();//this is function i made
}

This is clear function Final STEP

clear = () =>{
  this.setState({
    TemplateCode: ""//simply you can clear Templatecode
  });
}

when click button Templatecode is clear 2nd STEP

<div class="col-md-12" align="right">
  <button id="" type="submit" class="btn btnprimary" onClick{this.submitHandler}> Save 
  </button>
</div>

How to get numeric value from a prompt box?

Working Demo Reading more Info

parseInt(x) it will cast it into integer

x = parseInt(x);
x = parseInt(x,10); //the radix is 10 (decimal)

parseFloat(x) it will cast it into float

Working Demo Reading more Info

x = parseFloat(x);

you can directly use prompt

var x = parseInt(prompt("Enter a Number", "1"), 10)

changing kafka retention period during runtime

I tested and used this command in kafka confluent V4.0.0 and apache kafka V 1.0.0 and 1.0.1

/opt/kafka/confluent-4.0.0/bin/kafka-configs --zookeeper XX.XX.XX.XX:2181 --entity-type topics --entity-name test --alter --add-config  retention.ms=55000

test is the topic name.

I think it works well in other versions too

Assignment inside lambda expression in Python

You cannot really maintain state in a filter/lambda expression (unless abusing the global namespace). You can however achieve something similar using the accumulated result being passed around in a reduce() expression:

>>> f = lambda a, b: (a.append(b) or a) if (b not in a) else a
>>> input = ["foo", u"", "bar", "", "", "x"]
>>> reduce(f, input, [])
['foo', u'', 'bar', 'x']
>>> 

You can, of course, tweak the condition a bit. In this case it filters out duplicates, but you can also use a.count(""), for example, to only restrict empty strings.

Needless to say, you can do this but you really shouldn't. :)

Lastly, you can do anything in pure Python lambda: http://vanderwijk.info/blog/pure-lambda-calculus-python/

How to set minDate to current date in jQuery UI Datepicker?

I set starting date using this method, because aforesaid or other codes didn't work for me

_x000D_
_x000D_
$(document).ready(function() {_x000D_
 $('#dateFrm').datepicker('setStartDate', new Date(yyyy, dd, MM));_x000D_
 });
_x000D_
_x000D_
_x000D_

Send File Attachment from Form Using phpMailer and PHP

This will work perfectly

    <form method='post' enctype="multipart/form-data">
    <input type='file' name='uploaded_file' id='uploaded_file' multiple='multiple' />
    <input type='submit' name='upload'/> 
    </form>

    <?php
           if(isset($_POST['upload']))
        {
             if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK)
                {
                     if (array_key_exists('uploaded_file', $_FILES))
                        { 
                            $mail->Subject = "My Subject";
                            $mail->Body = 'This is the body';
                            $uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['uploaded_file']['name']));
                        if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $uploadfile))
                             $mail->addAttachment($uploadfile,$_FILES['uploaded_file']['name']); 
                            $mail->send();
                            echo 'Message has been sent';
                        }       
                else
                    echo "The file is not uploaded. please try again.";
                }
                else
                    echo "The file is not uploaded. please try again";
        }
    ?>

How to measure time taken by a function to execute

If you want to measure the time between multiple things that aren't nested you could use this:

function timer(lap){ 
    if(lap) console.log(`${lap} in: ${(performance.now()-timer.prev).toFixed(3)}ms`); 
    timer.prev = performance.now();
}

Similar to console.time(), but easier usage if you don't need to keep track of previous timers.

If you like the blue color from console.time(), you can use this line instead

console.log(`${lap} in: %c${(performance.now()-timer.prev).toFixed(3)}ms`, 'color:blue');

// Usage: 
timer()              // set the start
// do something 
timer('built')       // logs 'built in: 591.815ms'
// do something
timer('copied')      // logs 'copied in: 0.065ms'
// do something
timer('compared')    // logs 'compared in: 36.41ms'

set height of imageview as matchparent programmatically

imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

What CSS selector can be used to select the first div within another div

The closest thing to what you're looking for is the :first-child pseudoclass; unfortunately this will not work in your case because you have an <h1> before the <div>s. What I would suggest is that you either add a class to the <div>, like <div class="first"> and then style it that way, or use jQuery if you really can't add a class:

$('#content > div:first')

NSString with \n or line break

In case \n or \r is not working and if you are working with uiwebview and trying to load html using < br > tag to insert new line. Don't just use < br > tag in NSString stringWithFormat.

Instead use the same by appending. i.e by using stringByAppendingString

 yourNSString = [yourNSString stringByAppendingString:@"<br>"];

Keyboard shortcut to "untab" (move a block of code to the left) in eclipse / aptana?

In Visual Studio and most other half decent IDEs you can simply do SHIFT+TAB. It does the opposite of just TAB.

I would think and hope that the IDEs you mention support this as well.

yii2 hidden input value

simple you can write:

<?= $form->field($model, 'hidden1')->hiddenInput(['value'=>'abc value'])->label(false); ?>

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I think there is MID() and maybe LEFT() and RIGHT() in Access.

How to loop through array in jQuery?

Try this:

$.grep(array, function(element) {

})

How to convert NUM to INT in R?

Use as.integer:

set.seed(1)
x <- runif(5, 0, 100)
x
[1] 26.55087 37.21239 57.28534 90.82078 20.16819


as.integer(x)
[1] 26 37 57 90 20

Test for class:

xx <- as.integer(x)
str(xx)
 int [1:5] 26 37 57 90 20

Initializing a static std::map<int, int> in C++

Using C++11:

#include <map>
using namespace std;

map<int, char> m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};

Using Boost.Assign:

#include <map>
#include "boost/assign.hpp"
using namespace std;
using namespace boost::assign;

map<int, char> m = map_list_of (1, 'a') (3, 'b') (5, 'c') (7, 'd');

How do I load a PHP file into a variable?

Theoretically you could just use fopen, then use stream_get_contents.

$stream = fopen("file.php","r");
$string = stream_get_contents($stream);
fclose($stream);

That should read the entire file into $string for you, and should not evaluate it. Though I'm surprised that file_get_contents didn't work when you specified the local path....

How to specify a multi-line shell variable?

Use read with a heredoc as shown below:

read -d '' sql << EOF
select c1, c2 from foo
where c1='something'
EOF

echo "$sql"

How to change background color in android app

You can try this in xml sheet:

android:background="@color/background_color"

Convert string to decimal number with 2 decimal places in Java

Float.parseFloat() is the problem as it returns a new float.

Returns a new float initialized to the value represented by the specified String, as performed by the valueOf method of class Float.

You are formatting just for the purpose of display . It doesn't mean the float will be represented by the same format internally .

You can use java.lang.BigDecimal.

I am not sure why are you using parseFloat() twice. If you want to display the float in a certain format then just format it and display it.

Float litersOfPetrol=Float.parseFloat(stringLitersOfPetrol);
DecimalFormat df = new DecimalFormat("0.00");
df.setMaximumFractionDigits(2);
System.out.println("liters of petrol before putting in editor"+df.format(litersOfPetrol));

split string in two on given index and return both parts

If you want a really hacky one-liner using regular expressions and interpolated strings...

_x000D_
_x000D_
const splitString = (value, idx) => value.split(new RegExp(`(?<=^.{${idx}})`));
console.log(splitString('abcdefgh', 5));
_x000D_
_x000D_
_x000D_

This code says split the string by replacing the value returned in the regex. The regex returns a position, not a character, so we don't lose in characters in the initial string. The way it does this is finding the position, via a look-behind and the ^ anchor, where there were index characters from the start of the string.


To solve your proposed problem of adding commas every third position from the end, the regex would be slightly different and we'd use replace rather than split.

_x000D_
_x000D_
const values = [ 8211, 98700, 1234567890 ];
const addCommas = (value, idx) => value.replace(new RegExp(`(?=(.{${idx}})+$)`, 'g'), ',');

console.log(values.map(v => addCommas(v.toString(), 3)));
_x000D_
_x000D_
_x000D_

Here we find the idxth position from the end by using a look-ahead and the $ anchor, but we also capture any number of those sets of positions from the end. Then we replace the position with a comma. We use the g flag (global) so it replaces every occurrence, not just the first found.

Undo git stash pop that results in merge conflict

Instructions here are a little complicated so I'm going to offer something more straightforward:

  1. git reset HEAD --hard Abandon all changes to the current branch

  2. ... Perform intermediary work as necessary

  3. git stash pop Re-pop the stash again at a later date when you're ready

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

I found out that declaring @PersistenceContext as EXTENDED also solves this problem:

@PersistenceContext(type = PersistenceContextType.EXTENDED)

Github: Can I see the number of downloads for a repo?

To try to make this more clear:
for this github project: stant/mdcsvimporter2015
https://github.com/stant/mdcsvimporter2015
with releases at
https://github.com/stant/mdcsvimporter2015/releases

go to http or https: (note added "api." and "/repos")
https://api.github.com/repos/stant/mdcsvimporter2015/releases

you will get this json output and you can search for "download_count":

    "download_count": 2,
    "created_at": "2015-02-24T18:20:06Z",
    "updated_at": "2015-02-24T18:20:07Z",
    "browser_download_url": "https://github.com/stant/mdcsvimporter2015/releases/download/v18/mdcsvimporter-beta-18.zip"

or on command line do:
wget --no-check-certificate https://api.github.com/repos/stant/mdcsvimporter2015/releases

How do I remove the passphrase for the SSH key without having to create a new key?

$ ssh-keygen -p worked for me

Opened git bash. Pasted : $ ssh-keygen -p

Hit enter for default location.

Enter old passphrase

Enter new passphrase - BLANK

Confirm new passphrase - BLANK

BOOM the pain of entering passphrase for git push was gone.

Thanks!

Java: How can I compile an entire directory structure of code ?

Windows solution: Assuming all files contained in sub-directory 'src', and you want to compile them to 'bin'.

for /r src %i in (*.java) do javac %i -sourcepath src -d bin

If src contains a .java file immediately below it then this is faster

javac src\\*.java -d bin

How to use sbt from behind proxy?

I found that starting IntelliJ IDEA from terminal let me connect and download over the internet. To start from terminal, type in:

$ idea

Maven 3 warnings about build.plugins.plugin.version

Add a <version> element after the <plugin> <artifactId> in your pom.xml file. Find the following text:

<plugin>
  <artifactId>maven-compiler-plugin</artifactId>

Add the version tag to it:

<plugin>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>2.3.2</version>

The warning should be resolved.

Regarding this:

'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing

Many people have mentioned why the issue is happening, but fail to suggest a fix. All I needed to do was to go into my POM file for my project, and add the <version> tag as shown above.

To discover the version number, one way is to look in Maven's output after it finishes running. Where you are missing version numbers, Maven will display its default version:

[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ entities ---

Take that version number (as in the 2.3.2 above) and add it to your POM, as shown.

Example on ToggleButton

You should follow the Google guide;

ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // The toggle is enabled
        } else {
            // The toggle is disabled
        }
    }
});

You can check the documentation here

How to create a zip archive with PowerShell?

If you head on over to CodePlex and grab the PowerShell Community Extensions, you can use their write-zip cmdlet.

Since

CodePlex is in read-only mode in preparation for shutdown

you can go to PowerShell Gallery.

nodejs vs node on ubuntu 12.04

Apparently the solution differs between Ubuntu versions. Following worked for me on Ubuntu 13.10:

sudo apt-get install nodejs-legacy

HTH

Edit: Rule of thumb:

If you have installed nodejs but are missing the /usr/bin/node binary, then also install nodejs-legacy. This just creates the missing softlink.

According to my tests, Ubuntu 17.10 and above already have the compatibility-softlink /usr/bin/node in place after nodejs is installed, so nodejs-legacy is missing from these releases as it is no more needed.

GitHub "fatal: remote origin already exists"

If you need to check which remote repos you have connected with your local repos, theres a cmd:

git remote -v

Now if you want to remove the remote repo (say, origin) then what you can do is:

git remote rm origin

How to write a foreach in SQL Server?

I would say everything probably works except that the column idx doesn't actually exist in the table you're selecting from. Maybe you meant to select from @Practitioner:

WHILE (@i <= (SELECT MAX(idx) FROM @Practitioner))

because that's defined in the code above like that:

DECLARE @Practitioner TABLE (
    idx smallint Primary Key IDENTITY(1,1)
    , PractitionerId int
)

Call JavaScript function on DropDownList SelectedIndexChanged Event:

You can use the ScriptManager.RegisterStartupScript(); to call any of your javascript event/Client Event from the server. For example, to display a message using javascript's alert();, you can do this:

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
Response.write("<script>alert('This is my message');</script>");
 //----or alternatively and to be more proper
 ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "alert('This is my message')", true);
}

To be exact for you, do this...

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
 ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "CalcTotalAmt();", true);
}

Typescript input onchange event.target.value

The target you tried to add in InputProps is not the same target you wanted which is in React.FormEvent

So, the solution I could come up with was, extending the event related types to add your target type, as:

interface MyEventTarget extends EventTarget {
    value: string
}

interface MyFormEvent<T> extends React.FormEvent<T> {
    target: MyEventTarget
}

interface InputProps extends React.HTMLProps<Input> {
    onChange?: React.EventHandler<MyFormEvent<Input>>;
}

Once you have those classes, you can use your input component as

<Input onChange={e => alert(e.target.value)} />

without compile errors. In fact, you can also use the first two interfaces above for your other components.

Git Bash doesn't see my PATH

I know it is an old question but there's two type of environment variables. The one owned with User and the one system wide. Depending how do you open git bash (with user privilege or with administrator privilege) the environment variable PATH used can be from you User variables or from System variables. See below: enter image description here

as said in a previous answer, check with the command env|grep PATH to see which one you are using and update your variable accordingly. BTW, no need to reboot the system. Just close and reopen the git bash

Why does configure say no C compiler found when GCC is installed?

i have same problem at the moment. I just run yum install gcc

Insert a line at specific line number with sed or awk

Perl solutions:

quick and dirty:

perl -lpe 'print "Project_Name=sowstest" if $. == 8' file

  • -l strips newlines and adds them back in, eliminating the need for "\n"
  • -p loops over the input file, printing every line
  • -e executes the code in single quotes

$. is the line number

equivalent to @glenn's awk solution, using named arguments:

perl -slpe 'print $s if $. == $n' -- -n=8 -s="Project_Name=sowstest" file

  • -s enables a rudimentary argument parser
  • -- prevents -n and -s from being parsed by the standard perl argument parser

positional command arguments:

perl -lpe 'BEGIN{$n=shift; $s=shift}; print $s if $. == $n' 8 "Project_Name=sowstest" file

environment variables:

setenv n 8 ; setenv s "Project_Name=sowstest"
echo $n ; echo $s
perl -slpe 'print $ENV{s} if $. == $ENV{n}' file

ENV is the hash which contains all environment variables

Getopt to parse arguments into hash %o:

perl -MGetopt::Std -lpe 'BEGIN{getopt("ns",\%o)}; print $o{s} if $. == $o{n}' -- -n 8 -s "Project_Name=sowstest" file

Getopt::Long and longer option names

perl -MGetopt::Long -lpe 'BEGIN{GetOptions(\%o,"line=i","string=s")}; print $o{string} if $. == $o{line}' -- --line 8 --string "Project_Name=sowstest" file

Getopt is the recommended standard-library solution.
This may be overkill for one-line perl scripts, but it can be done

What is the question mark for in a Typescript parameter name

The ? in the parameters is to denote an optional parameter. The Typescript compiler does not require this parameter to be filled in. See the code example below for more details:

// baz: number | undefined means: the second argument baz can be a number or undefined

// = undefined, is default parameter syntax, 
// if the parameter is not filled in it will default to undefined

// Although default JS behaviour is to set every non filled in argument to undefined 
// we need this default argument so that the typescript compiler
// doesn't require the second argument to be filled in
function fn1 (bar: string, baz: number | undefined = undefined) {
    // do stuff
}

// All the above code can be simplified using the ? operator after the parameter
// In other words fn1 and fn2 are equivalent in behaviour
function fn2 (bar: string, baz?: number) {
    // do stuff
}



fn2('foo', 3); // works
fn2('foo'); // works

fn2();
// Compile time error: Expected 1-2 arguments, but got 0
// An argument for 'bar' was not provided.


fn1('foo', 3); // works
fn1('foo'); // works

fn1();
// Compile time error: Expected 1-2 arguments, but got 0
// An argument for 'bar' was not provided.

How to print all session variables currently set?

Not a simple way, no.

Let's say that by "active" you mean "hasn't passed the maximum lifetime" and hasn't been explicitly destroyed and that you're using the default session handler.

  • First, the maximum lifetime is defined as a php.ini config and is defined in terms of the last activity on the session. So the "expiry" mechanism would have to read the content of the sessions to determine the application-defined expiry.
  • Second, you'd have to manually read the sessions directory and read the files, whose format I don't even know they're in.

If you really need this, you must implement some sort of custom session handler. See session_set_save_handler.

Take also in consideration that you'll have no feedback if the user just closes the browser or moves away from your site without explciitly logging out. Depending on much inactivity you consider the threshold to deem a session "inactive", the number of false positives you'll get may be very high.

Unable to login to SQL Server + SQL Server Authentication + Error: 18456

By default login failed error message is nothing but a client user connection has been refused by the server due to mismatch of login credentials. First task you might check is to see whether that user has relevant privileges on that SQL Server instance and relevant database too, thats good. Obviously if the necessary prvileges are not been set then you need to fix that issue by granting relevant privileges for that user login.

Althought if that user has relevant grants on database & server if the Server encounters any credential issues for that login then it will prevent in granting the authentication back to SQL Server, the client will get the following error message:

Msg 18456, Level 14, State 1, Server <ServerName>, Line 1
Login failed for user '<Name>'

Ok now what, by looking at the error message you feel like this is non-descriptive to understand the Level & state. By default the Operating System error will show 'State' as 1 regardless of nature of the issues in authenticating the login. So to investigate further you need to look at relevant SQL Server instance error log too for more information on Severity & state of this error. You might look into a corresponding entry in log as:

2007-05-17 00:12:00.34 Logon     Error: 18456, Severity: 14, State: 8.
or

2007-05-17 00:12:00.34 Logon     Login failed for user '<user name>'.

As defined above the Severity & State columns on the error are key to find the accurate reflection for the source of the problem. On the above error number 8 for state indicates authentication failure due to password mismatch. Books online refers: By default, user-defined messages of severity lower than 19 are not sent to the Microsoft Windows application log when they occur. User-defined messages of severity lower than 19 therefore do not trigger SQL Server Agent alerts.

Sung Lee, Program Manager in SQL Server Protocols (Dev.team) has outlined further information on Error state description:The common error states and their descriptions are provided in the following table:

ERROR STATE       ERROR DESCRIPTION
------------------------------------------------------------------------------
2 and 5           Invalid userid
6                 Attempt to use a Windows login name with SQL Authentication
7                 Login disabled and password mismatch
8                 Password mismatch
9                 Invalid password
11 and 12         Valid login but server access failure
13                SQL Server service paused
18                Change password required


Well I'm not finished yet, what would you do in case of error:

2007-05-17 00:12:00.34 Logon     Login failed for user '<user name>'.

You can see there is no severity or state level defined from that SQL Server instance's error log. So the next troubleshooting option is to look at the Event Viewer's security log [edit because screen shot is missing but you get the

idea, look in the event log for interesting events].

How to run server written in js with Node.js

You don't need to go in node.js prompt, you just need to use standard command promt and write

node c:/node/server.js

this also works:

node c:\node\server.js

and then in your browser:

http://localhost:1337

Why does the C++ STL not provide any "tree" containers?

The STL's philosophy is that you choose a container based on guarantees and not based on how the container is implemented. For example, your choice of container may be based on a need for fast lookups. For all you care, the container may be implemented as a unidirectional list -- as long as searching is very fast you'd be happy. That's because you're not touching the internals anyhow, you're using iterators or member functions for the access. Your code is not bound to how the container is implemented but to how fast it is, or whether it has a fixed and defined ordering, or whether it is efficient on space, and so on.

How can I set the default timezone in node.js?

According to this google group thread, you can set the TZ environment variable before calling any date functions. Just tested it and it works.

> process.env.TZ = 'Europe/Amsterdam' 
'Europe/Amsterdam'
> d = new Date()
Sat, 24 Mar 2012 05:50:39 GMT
> d.toLocaleTimeString()
'06:50:39'
> ""+d
'Sat Mar 24 2012 06:50:39 GMT+0100 (CET)'

You can't change the timezone later though, since by then Node has already read the environment variable.

Center div on the middle of screen

2018: CSS3

div{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%);
}

This is even shorter. For more information see this: CSS: Centering Things

Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

I got this error while deploying to Virgo. The solution was to add this to my bundle imports:

org.springframework.transaction.config;version="[3.1,3.2)",

I noticed in the Spring jars under META-INF there is a spring.schemas and a spring.handlers section, and the class that they point to (in this case org.springframework.transaction.config.TxNamespaceHandler) must be imported.

Javascript get object key name

Here is a simple example, it will help you to get object key name.

var obj ={parts:{costPart:1000, salesPart: 2000}}; console.log(Object.keys(obj));

the output would be parts.

Converting unix time into date-time via excel

TLDR

=(A1/86400)+25569

...and the format of the cell should be date.

If it doesn't work for you

  • If you get a number you forgot to format the output cell as a date.
  • If you get ##### you probably don't have a real Unix time. Check your timestamps in https://www.epochconverter.com/. Try to divide your input by 10, 100, 1000 or 10000**
  • You work with timestamps outside Excel's (very extended) limits.
  • You didn't replace A1 with the cell containing the timestamp ;-p

Explanation

Unix system represent a point in time as a number. Specifically the number of seconds* since a zero-time called the Unix epoch which is 1/1/1970 00:00 UTC/GMT. This number of seconds is called "Unix timestamp" or "Unix time" or "POSIX time" or just "timestamp" and sometimes (confusingly) "Unix epoch".

In the case of Excel they chose a different zero-time and step (because who wouldn't like variety in technical details?). So Excel counts days since 24 hours before 1/1/0000 UTC/GMT. So 25569 corresponds to 1/1/1970 00:00 UTC/GMT and 25570 to 2/1/1970 00:00.

Now please note that we have 86400 seconds per day (24 hours x60 minutes each x60 seconds) and you can understand what this formula does: A1/86400 converts seconds to days and +25569 adjusts for the offset between what is time-zero for Unix and what is time-zero for Excel.

By the way DATE(1970,1,1) will helpfully return 25569 for you in case you forget all this so a more "self-documenting" way to write our formula is:

=A1/(24*60*60) + DATE(1970,1,1)

P.S.: All these were already present in other answers and comments just not laid out as I like them and I don't feel it's OK to edit the hell out of another answer.


*: that's almost correct because you should not count leap seconds

**: E.g. in the case of this question the number was number of milliseconds since the the Unix epoch.

#1055 - Expression of SELECT list is not in GROUP BY clause and contains nonaggregated column this is incompatible with sql_mode=only_full_group_by

Same thing is happened with 8.0+ versions as well. By default in 8.0+ version it is "enabled" by default. Here is the link official document reference

In case of 5.6+, 5.7+ versions, the property "ONLY_FULL_GROUP_BY" is disabled by default.

To disabled it, follow the same steps suggested by @Miloud BAKTETE

apache redirect from non www to www

Redirect domain.tld to www.

The following lines can be added either in Apache directives or in .htaccess file:

RewriteEngine on    
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  • Other sudomains are still working.
  • No need to adjust the lines. just copy/paste them at the right place.

Don't forget to apply the apache changes if you modify the vhost.

(based on the default Drupal7 .htaccess but should work in many cases)

Operand type clash: uniqueidentifier is incompatible with int

Sounds to me like at least one of those tables has defined UserID as a uniqueidentifier, not an int. Did you check the data in each table? What does SELECT TOP 1 UserID FROM each table yield? An int or a GUID?

EDIT

I think you have built a procedure based on all tables that contain a column named UserID. I think you should not have included the aspnet_Membership table in your script, since it's not really one of "your" tables.

If you meant to design your tables around the aspnet_Membership database, then why are the rest of the columns int when that table clearly uses a uniqueidentifier for the UserID column?

How to determine one year from now in Javascript

You should use getFullYear() instead of getYear(). getYear() returns the actual year minus 1900 (and so is fairly useless).

Thus a date marking exactly one year from the present moment would be:

var oneYearFromNow = new Date();
oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1);

Note that the date will be adjusted if you do that on February 29.

Similarly, you can get a date that's a month from now via getMonth() and setMonth(). You don't have to worry about "rolling over" from the current year into the next year if you do it in December; the date will be adjusted automatically. Same goes for day-of-month via getDate() and setDate().

How to set a Timer in Java?

    new java.util.Timer().schedule(new TimerTask(){
        @Override
        public void run() {
            System.out.println("Executed...");
           //your code here 
           //1000*5=5000 mlsec. i.e. 5 seconds. u can change accordngly 
        }
    },1000*5,1000*5); 

json and empty array

null is a legal value (and reserved word) in JSON, but some environments do not have a "NULL" object (as opposed to a NULL value) and hence cannot accurately represent the JSON null. So they will sometimes represent it as an empty array.

Whether null is a legal value in that particular element of that particular API is entirely up to the API designer.

How can I correctly format currency using jquery?

Use jquery.inputmask 3.x. See demos here

Include files:

<script src="/assets/jquery.inputmask.js" type="text/javascript"></script>
<script src="/assets/jquery.inputmask.extensions.js" type="text/javascript"></script>
<script src="/assets/jquery.inputmask.numeric.extensions.js" type="text/javascript"></script>

And code as

$(selector).inputmask('decimal',
  { 'alias': 'numeric',
    'groupSeparator': '.',
    'autoGroup': true,
    'digits': 2,
    'radixPoint': ",",
    'digitsOptional': false,
    'allowMinus': false,
    'prefix': '$ ',
    'placeholder': '0'
  }
);

Highlights:

  • easy to use
  • optional parts anywere in the mask
  • possibility to define aliases which hide complexity
  • date / datetime masks
  • numeric masks
  • lots of callbacks
  • non-greedy masks
  • many features can be enabled/disabled/configured by options
  • supports readonly/disabled/dir="rtl" attributes
  • support data-inputmask attribute(s)
  • multi-mask support
  • regex-mask support
  • dynamic-mask support
  • preprocessing-mask support
  • value formatting / validating without input element

Display the binary representation of a number in C?

Based on dirkgently's answer, but fixing his two bugs, and always printing a fixed number of digits:

void printbits(unsigned char v) {
  int i; // for C89 compatability
  for(i = 7; i >= 0; i--) putchar('0' + ((v >> i) & 1));
}

How do I get cURL to not show the progress bar?

curl -s http://google.com > temp.html

works for curl version 7.19.5 on Ubuntu 9.10 (no progress bar). But if for some reason that does not work on your platform, you could always redirect stderr to /dev/null:

curl  http://google.com 2>/dev/null > temp.html

Invoking a static method using reflection

public class Add {
    static int add(int a, int b){
        return (a+b);
    }
}

In the above example, 'add' is a static method that takes two integers as arguments.

Following snippet is used to call 'add' method with input 1 and 2.

Class myClass = Class.forName("Add");
Method method = myClass.getDeclaredMethod("add", int.class, int.class);
Object result = method.invoke(null, 1, 2);

Reference link.

Where can I download Eclipse Android bundle?

Google has ended support for eclipse plugin. If you prefer to use eclipse still you can download Eclipse Android Development Tool from

ADT for Eclipse

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

apache ProxyPass: how to preserve original IP address

The answer of JasonW is fine. But since apache httpd 2.4.6 there is a alternative: mod_remoteip

All what you must do is:

  1. May be you must install the mod_remoteip package
  2. Enable the module:

    LoadModule remoteip_module modules/mod_remoteip.so
    
  3. Add the following to your apache httpd config. Note that you must add this line not into the configuration of the proxy server. You must add this to the configuration of the proxy target httpd server (the server behind the proxy):

    RemoteIPHeader X-Forwarded-For
    

See at http://httpd.apache.org/docs/trunk/mod/mod_remoteip.html for more informations and more options.

Joining pandas dataframes by column names

you can use the left_on and right_on options as follows:

pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')

I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in effect do a many to many merge)

pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')

DIV height set as percentage of screen?

If you want it based on the screen height, and not the window height:

const height = 0.7 * screen.height

// jQuery
$('.header').height(height)

// Vanilla JS
document.querySelector('.header').style.height = height + 'px'

// If you have multiple <div class="header"> elements
document.querySelectorAll('.header').forEach(function(node) {
  node.style.height = height + 'px'
})

Using ffmpeg to encode a high quality video

Unless you do some kind of post-processing work, the video will never be better than the original frames. Also just like a flip-book, if you have a big "jump" between keyframes it will look funny. You generally need enough "tweens" in between the keyframes to give smooth animation. HTH

how to make a new line in a jupyter markdown cell

The double space generally works well. However, sometimes the lacking newline in the PDF still occurs to me when using four pound sign sub titles #### in Jupyter Notebook, as the next paragraph is put into the subtitle as a single paragraph. No amount of double spaces and returns fixed this, until I created a notebook copy 'v. PDF' and started using a single backslash '\' which also indents the next paragraph nicely:

#### 1.1 My Subtitle  \

1.1 My Subtitle
    Next paragraph text.

An alternative to this, is to upgrade the level of your four # titles to three # titles, etc. up the title chain, which will remove the next paragraph indent and format the indent of the title itself (#### My Subtitle ---> ### My Subtitle).

### My Subtitle


1.1 My Subtitle

Next paragraph text.

Getting a count of rows in a datatable that meet certain criteria

object count =dtFoo.Compute("count(IsActive)", "IsActive='Y'");

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

Your solution might be to add the original IP and/or hostname also:

ALLOWED_HOSTS = [
  'localhost',
  '127.0.0.1',
  '111.222.333.444',
  'mywebsite.com']

The condition to be satisfied is that the host header (or X-Forwarded-Host if USE_X_FORWARDED_HOST is enabled) should match one of the values in ALLOWED_HOSTS.

Android Emulator sdcard push error: Read-only file system

In adb version 1.0.32 and Eclipse Luna (v 4.4.1).

I found a directory in the avd /mnt/media_rw/sdcard that you can write to using the adb command. adb push {source} /mnt/media_rw/sdcard

There appears to be rw access to this directory.

Hope this helps :-)

correct quoting for cmd.exe for multiple arguments

Spaces are used for separating Arguments. In your case C:\Program becomes argument. If your file path contains spaces then add Double quotation marks. Then cmd will recognize it as single argument.

How to replace part of string by position?

I was looking for a solution with following requirements:

  1. use only a single, one-line expression
  2. use only system builtin methods (no custom implemented utility)

Solution 1

The solution that best suits me is this:

// replace `oldString[i]` with `c`
string newString = new StringBuilder(oldString).Replace(oldString[i], c, i, 1).ToString();

This uses StringBuilder.Replace(oldChar, newChar, position, count)

Solution 2

The other solution that satisfies my requirements is to use Substring with concatenation:

string newString = oldStr.Substring(0, i) + c + oldString.Substring(i+1, oldString.Length);

This is OK too. I guess it's not as efficient as the first one performance wise (due to unnecessary string concatenation). But premature optimization is the root of all evil.

So pick the one that you like the most :)

Javascript: formatting a rounded number to N decimals

If you do not really care about rounding, just added a toFixed(x) and then removing trailing 0es and the dot if necessary. It is not a fast solution.

function format(value, decimals) {
    if (value) {
        value = value.toFixed(decimals);            
    } else {
        value = "0";
    }
    if (value.indexOf(".") < 0) { value += "."; }
    var dotIdx = value.indexOf(".");
    while (value.length - dotIdx <= decimals) { value += "0"; } // add 0's

    return value;
}

Iterate over elements of List and Map using JSTL <c:forEach> tag

Mark, this is already answered in your previous topic. But OK, here it is again:

Suppose ${list} points to a List<Object>, then the following

<c:forEach items="${list}" var="item">
    ${item}<br>
</c:forEach>

does basically the same as as following in "normal Java":

for (Object item : list) {
    System.out.println(item);
}

If you have a List<Map<K, V>> instead, then the following

<c:forEach items="${list}" var="map">
    <c:forEach items="${map}" var="entry">
        ${entry.key}<br>
        ${entry.value}<br>
    </c:forEach>
</c:forEach>

does basically the same as as following in "normal Java":

for (Map<K, V> map : list) {
    for (Entry<K, V> entry : map.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue());
    }
}

The key and value are here not special methods or so. They are actually getter methods of Map.Entry object (click at the blue Map.Entry link to see the API doc). In EL (Expression Language) you can use the . dot operator to access getter methods using "property name" (the getter method name without the get prefix), all just according the Javabean specification.

That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

[Updated to adapt to modern pandas, which has isnull as a method of DataFrames..]

You can use isnull and any to build a boolean Series and use that to index into your frame:

>>> df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])
>>> df.isnull()
       0      1      2
0  False  False  False
1  False   True  False
2  False  False   True
3  False  False  False
4  False  False  False
>>> df.isnull().any(axis=1)
0    False
1     True
2     True
3    False
4    False
dtype: bool
>>> df[df.isnull().any(axis=1)]
   0   1   2
1  0 NaN   0
2  0   0 NaN

[For older pandas:]

You could use the function isnull instead of the method:

In [56]: df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])

In [57]: df
Out[57]: 
   0   1   2
0  0   1   2
1  0 NaN   0
2  0   0 NaN
3  0   1   2
4  0   1   2

In [58]: pd.isnull(df)
Out[58]: 
       0      1      2
0  False  False  False
1  False   True  False
2  False  False   True
3  False  False  False
4  False  False  False

In [59]: pd.isnull(df).any(axis=1)
Out[59]: 
0    False
1     True
2     True
3    False
4    False

leading to the rather compact:

In [60]: df[pd.isnull(df).any(axis=1)]
Out[60]: 
   0   1   2
1  0 NaN   0
2  0   0 NaN

Pip install - Python 2.7 - Windows 7

you have to first download the get-pip.py and then run the command :

python get-pip.py

Generate PDF from HTML using pdfMake in Angularjs

this is what it worked for me I'm using html2pdf from an Angular2 app, so I made a reference to this function in the controller

var html2pdf = (function(html2canvas, jsPDF) {

declared in html2pdf.js.

So I added just after the import declarations in my angular-controller this declaration:

declare function html2pdf(html2canvas, jsPDF): any;

then, from a method of my angular controller I'm calling this function:

generate_pdf(){
    this.someService.loadContent().subscribe(
      pdfContent => {
        html2pdf(pdfContent, {
          margin:       1,
          filename:     'myfile.pdf',
          image:        { type: 'jpeg', quality: 0.98 },
          html2canvas:  { dpi: 192, letterRendering: true },
          jsPDF:        { unit: 'in', format: 'A4', orientation: 'portrait' }
        });
      }
    );
  }

Hope it helps

Function to convert timestamp to human date in javascript

My ES6 variant produces a string like this 2020-04-05_16:39:45.85725. Feel free to modify the return statement to get the format that you need:

const getDateStringServ = timestamp => {

  const plus0 = num => `0${num.toString()}`.slice(-2)

  const d = new Date(timestamp)

  const year = d.getFullYear()
  const monthTmp = d.getMonth() + 1
  const month = plus0(monthTmp)
  const date = plus0(d.getDate())
  const hour = plus0(d.getHours())
  const minute = plus0(d.getMinutes())
  const second = plus0(d.getSeconds())
  const rest = timestamp.toString().slice(-5)

  return `${year}-${month}-${date}_${hour}:${minute}:${second}.${rest}`
}

Replacing a character from a certain index

You can't replace a letter in a string. Convert the string to a list, replace the letter, and convert it back to a string.

>>> s = list("Hello world")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> s[int(len(s) / 2)] = '-'
>>> s
['H', 'e', 'l', 'l', 'o', '-', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello-World'

What is http multipart request?

As the official specification says, "one or more different sets of data are combined in a single body". So when photos and music are handled as multipart messages as mentioned in the question, probably there is some plain text metadata associated as well, thus making the request containing different types of data (binary, text), which implies the usage of multipart.

How can I convert byte size into a human-readable format in Java?

org.springframework.util.unit.DataSize could suit this requirement at least for the calculation. Then a simple decorator will do.

Column standard deviation R

The general idea is to sweep the function across. You have many options, one is apply():

R> set.seed(42)
R> M <- matrix(rnorm(40),ncol=4)
R> apply(M, 2, sd)
[1] 0.835449 1.630584 1.156058 1.115269
R> 

How can I easily add storage to a VirtualBox machine with XP installed?

After resizing and not being able to view the resizing on my windows XP guest machine, I had to

  1. clone it
  2. resize it with "VBoxManage modifyhd winxppro\ Clone.vdi --resize 30720" and everything worked

I saw in other forums that snapshots can interfere for resizing and not being able to remove all snapshots for different errors I got, the only found solution for me was to clone it to remove the snapshots and then resize it, and everything worked. For resizing outside windows, a gparted boot cd that can be found here can help

How to set order of repositories in Maven settings.xml

As far as I know, the order of the repositories in your pom.xml will also decide the order of the repository access.

As for configuring repositories in settings.xml, I've read that the order of repositories is interestingly enough the inverse order of how the repositories will be accessed.

Here a post where someone explains this curiosity:
http://community.jboss.org/message/576851

How to remove Left property when position: absolute?

left:auto;

This will default the left back to the browser default.


So if you have your Markup/CSS as:

<div class="myClass"></div>

.myClass
{
  position:absolute;
  left:0;
}

When setting RTL, you could change to:

<div class="myClass rtl"></div>

.myClass
{
  position:absolute;
  left:0;
}
.myClass.rtl
{
  left:auto;
  right:0;
}

Block Comments in a Shell Script

In bash:

#!/bin/bash
echo before comment
: <<'END'
bla bla
blurfl
END
echo after comment

The ' and ' around the END delimiter are important, otherwise things inside the block like for example $(command) will be parsed and executed.

For an explanation, see this and this question.

Less aggressive compilation with CSS3 calc

There's a tidier way to include variables inside the escaped calc, as explained in this post: CSS3 calc() function doesn't work with Less #974

@variable: 2em;

body{ width: calc(~"100% - @{variable} * 2");}

By using the curly brackets you don't need to close and reopen the escaping quotes.

Is there any native DLL export functions viewer?

DLL Export Viewer by NirSoft can be used to display exported functions in a DLL.

This utility displays the list of all exported functions and their virtual memory addresses for the specified DLL files. You can easily copy the memory address of the desired function, paste it into your debugger, and set a breakpoint for this memory address. When this function is called, the debugger will stop in the beginning of this function.

enter image description here

Install npm (Node.js Package Manager) on Windows (w/o using Node.js MSI)

I also needed to install npm in Windows and got it through the Chocolatey pacakage manager. For those who haven't heard about it, Chocolatey is a package manager for Windows, that gives you the convenience of an apt-get in Windows environments. To get it go to https://chocolatey.org/ where there's a PowerShell script to download it and install it. After that you can run:

chocolatey install npm

and you're good to go.

Note that the standalone npm is no longer being updated and the last version that is out there is known to have problems on Windows. Another option you can look at is extracting npm from the MSI using LessMSI.

php: loop through json array

Decode the JSON string using json_decode() and then loop through it using a regular loop:

$arr = json_decode('[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]');

foreach($arr as $item) { //foreach element in $arr
    $uses = $item['var1']; //etc
}

Get a CSS value with JavaScript

Cross-browser solution to checking CSS values without DOM manipulation:

function get_style_rule_value(selector, style)
{
 for (var i = 0; i < document.styleSheets.length; i++)
 {
  var mysheet = document.styleSheets[i];
  var myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;

  for (var j = 0; j < myrules.length; j++)
  {
   if (myrules[j].selectorText && myrules[j].selectorText.toLowerCase() === selector)
   {
    return myrules[j].style[style];
   }
  }
 }
};

Usage:

get_style_rule_value('.chart-color', 'backgroundColor')

Sanitized version (forces selector input to lowercase, and allows for use case without leading ".")

function get_style_rule_value(selector, style)
{
 var selector_compare=selector.toLowerCase();
 var selector_compare2= selector_compare.substr(0,1)==='.' ?  selector_compare.substr(1) : '.'+selector_compare;

 for (var i = 0; i < document.styleSheets.length; i++)
 {
  var mysheet = document.styleSheets[i];
  var myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;

  for (var j = 0; j < myrules.length; j++)
  {
    if (myrules[j].selectorText)
    {
     var check = myrules[j].selectorText.toLowerCase();
     switch (check)
     {
      case selector_compare  :
      case selector_compare2 : return myrules[j].style[style];
     }
    }
   }
  }
 }

excel delete row if column contains value from to-remove-list

Given sheet 2:

ColumnA
-------
apple
orange

You can flag the rows in sheet 1 where a value exists in sheet 2:

ColumnA  ColumnB
-------  --------------
pear     =IF(ISERROR(VLOOKUP(A1,Sheet2!A:A,1,FALSE)),"Keep","Delete")
apple    =IF(ISERROR(VLOOKUP(A2,Sheet2!A:A,1,FALSE)),"Keep","Delete")
cherry   =IF(ISERROR(VLOOKUP(A3,Sheet2!A:A,1,FALSE)),"Keep","Delete")
orange   =IF(ISERROR(VLOOKUP(A4,Sheet2!A:A,1,FALSE)),"Keep","Delete")
plum     =IF(ISERROR(VLOOKUP(A5,Sheet2!A:A,1,FALSE)),"Keep","Delete")

The resulting data looks like this:

ColumnA  ColumnB
-------  --------------
pear     Keep
apple    Delete
cherry   Keep
orange   Delete
plum     Keep

You can then easily filter or sort sheet 1 and delete the rows flagged with 'Delete'.

Java Immutable Collections

The difference is that you can't have a reference to an immutable collection which allows changes. Unmodifiable collections are unmodifiable through that reference, but some other object may point to the same data through which it can be changed.

e.g.

List<String> strings = new ArrayList<String>();
List<String> unmodifiable = Collections.unmodifiableList(strings);
unmodifiable.add("New string"); // will fail at runtime
strings.add("Aha!"); // will succeed
System.out.println(unmodifiable);

symfony2 : failed to write cache directory

Most likely it means that the directory and/or sub-directories are not writable. Many forget about sub-directories.

Symfony 2

chmod -R 777 app/cache app/logs

Symfony 3 directory structure

chmod -R 777 var/cache var/logs

Additional Resources

Permissions solution by Symfony (mentioned previously).

Permissions solution by KPN University - additionally includes an screen-cast on installation.

Note: If you're using Symfony 3 directory structure, substitute app/cache and app/logs with var/cache and var/logs.

Could not find a version that satisfies the requirement <package>

Try installing flask through the powershell using the following command.

pip install --isolated Flask

This will allow installation to avoide environment variables and user configuration.

The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1

for cordova developers having this issue

try to set

<preference name="deployment-target" value="8.0" />

in confix.xml

Check if a div exists with jquery

As karim79 mentioned, the first is the most concise. However I could argue that the second is more understandable as it is not obvious/known to some Javascript/jQuery programmers that non-zero/false values are evaluated to true in if-statements. And because of that, the third method is incorrect.

Get first row of dataframe in Python Pandas based on criteria

you can take care of the first 3 items with slicing and head:

  1. df[df.A>=4].head(1)
  2. df[(df.A>=4)&(df.B>=3)].head(1)
  3. df[(df.A>=4)&((df.B>=3) * (df.C>=2))].head(1)

The condition in case nothing comes back you can handle with a try or an if...

try:
    output = df[df.A>=6].head(1)
    assert len(output) == 1
except: 
    output = df.sort_values('A',ascending=False).head(1)

How to run different python versions in cmd

Python 3.3 introduces Python Launcher for Windows that is installed into c:\Windows\ as py.exe and pyw.exe by the installer. The installer also creates associations with .py and .pyw. Then add #!python3 or #!python2 as the first lline. No need to add anything to the PATH environment variable.

Update: Just install Python 3.3 from the official python.org/download. It will add also the launcher. Then add the first line to your script that has the .py extension. Then you can launch the script by simply typing the scriptname.py on the cmd line, od more explicitly by py scriptname.py, and also by double clicking on the scipt icon.

The py.exe looks for C:\PythonXX\python.exe where XX is related to the installed versions of Python at the computer. Say, you have Python 2.7.6 installed into C:\Python27, and Python 3.3.3 installed into C:\Python33. The first line in the script will be used by the Python launcher to choose one of the installed versions. The default (i.e. without telling the version explicitly) is to use the highest version of Python 2 that is available on the computer.

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

What you need is to have a controller that responds to the url first which then renders your jsp. See this link for a solution.

How do I launch the Android emulator from the command line?

List all your emulators:

emulator -list-avds

Run one of the listed emulators with -avd flag:

emulator -avd @name-of-your-emulator

where emulator is under:

${ANDROID_SDK}/tools/emulator

Twitter Bootstrap Modal Form Submit

This answer is late, but I'm posting anyway hoping it will help someone. Like you, I also had difficulty submitting a form that was outside my bootstrap modal, and I didn't want to use ajax because I wanted a whole new page to load, not just part of the current page. After much trial and error here's the jQuery that worked for me:

$(function () {
    $('body').on('click', '.odom-submit', function (e) {
        $(this.form).submit();
        $('#myModal').modal('hide');
    });
});

To make this work I did this in the modal footer

<div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary odom-submit">Save changes</button>
</div>

Notice the addition to class of odom-submit. You can, of course, name it whatever suits your particular situation.

How can I make a clickable link in an NSAttributedString?

Minor improvement to ujell's solution: If you use NSURL instead of a NSString, you can use any URL (e.g. custom urls)

NSURL *URL = [NSURL URLWithString: @"whatsapp://app"];
NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:@"start Whatsapp"];
[str addAttribute: NSLinkAttributeName value:URL range: NSMakeRange(0, str.length)];
yourTextField.attributedText = str;

Have fun!

Batch program to to check if process exists

This is a one line solution.

It will run taskkill only if the process is really running otherwise it will just info that it is not running.

tasklist | find /i "notepad.exe" && taskkill /im notepad.exe /F || echo process "notepad.exe" not running.

This is the output in case the process was running:

notepad.exe           1960 Console                   0    112,260 K
SUCCESS: The process "notepad.exe" with PID 1960 has been terminated.

This is the output in case not running:

process "notepad.exe" not running.

How to post query parameters with Axios?

axios signature for post is axios.post(url[, data[, config]]). So you want to send params object within the third argument:

.post(`/mails/users/sendVerificationMail`, null, { params: {
  mail,
  firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));

This will POST an empty body with the two query params:

POST http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName

HTTPS setup in Amazon EC2

First, you need to open HTTPS port (443). To do that, you go to https://console.aws.amazon.com/ec2/ and click on the Security Groups link on the left, then create a new security group with also HTTPS available. Then, just update the security group of a running instance or create a new instance using that group.

After these steps, your EC2 work is finished, and it's all an application problem.

Date difference in minutes in Python

Use datetime.strptime() to parse into datetime instances, and then compute the difference, and finally convert the difference into minutes.

Read int values from a text file in C

A simple solution using fscanf:

void read_ints (const char* file_name)
{
  FILE* file = fopen (file_name, "r");
  int i = 0;

  fscanf (file, "%d", &i);    
  while (!feof (file))
    {  
      printf ("%d ", i);
      fscanf (file, "%d", &i);      
    }
  fclose (file);        
}

how to get vlc logs?

Or you can use the more obvious solution, right in the GUI: Tools -> Messages (set verbosity to 2)...

Can you force Vue.js to reload/re-render?

<router-view :key="$route.params.slug" />

just use key with your any params its auto reload children..

How to set CATALINA_HOME variable in windows 7?

Assuming Java (JDK + JRE) is installed in your system, do the following:

  1. Install Tomcat7
  2. Copy 'tools.jar' from 'C:\Program Files (x86)\Java\jdk1.6.0_27\lib' and pasted it under 'C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\lib'.
  3. Setup paths in your Environment Variables as shown below:

C:/>javap javax.servlet.http.HttpServletRequest

It should show a bunch of classes

The module was expected to contain an assembly manifest

I got the error in the following case:

  1. A .NET EXE file (#1) was referencing another .NET EXE file (#2)
  2. I was trying to obfuscate EXE #2 with Themida
  3. when running the EXE #1 it was crashing with the error "The module was expected to contain an assembly manifest"

I simply avoided the obfuscation and the error is gone. not a real solution, but at least I know what caused it...

Sending a JSON to server and retrieving a JSON in return, without JQuery

Using new api fetch:

_x000D_
_x000D_
const dataToSend = JSON.stringify({"email": "[email protected]", "password": "101010"});
let dataReceived = ""; 
fetch("", {
    credentials: "same-origin",
    mode: "same-origin",
    method: "post",
    headers: { "Content-Type": "application/json" },
    body: dataToSend
})
    .then(resp => {
        if (resp.status === 200) {
            return resp.json()
        } else {
            console.log("Status: " + resp.status)
            return Promise.reject("server")
        }
    })
    .then(dataJson => {
        dataReceived = JSON.parse(dataJson)
    })
    .catch(err => {
        if (err === "server") return
        console.log(err)
    })

console.log(`Received: ${dataReceived}`)                
_x000D_
_x000D_
_x000D_ You need to handle when server sends other status rather than 200(ok), you should reject that result because if you were to left it in blank, it will try to parse the json but there isn't, so it will throw an error

Centering the image in Bootstrap

.img-responsive {
     margin: 0 auto;
 }

you can write like above code in your document so no need to add one another class in image tag.

Remove white space above and below large text in an inline-block element

I'm a designer and our devs had this issue when dealing with Android initially, and our web devs are having the same problem. We found that the spacing between a line of text and another object (either a component like a button, or a separate line of text) that a design program spits out is incorrect. This is because the design program isn't accounting for diacritics when it is defining the "size" of a single line of text.

We ended up adding Êg to every line of text and manually creating spacers (little blue rectangles) that act as the "measurement" from the actual top of the text (ie, the top of the accent mark on the E) or from the descender (the bottom of a "g"). For example, say you have a really boring top navigation that is just a rectangle, and a headline beneath it. The design program will say that the space between the bottom of the top nav and the top of the headline textbox 24px. However, when you measure from the bottom of the nav to the top of an Ê accent mark, the spacing is actually 20px.

While I realize that this isn't a code solution, it should help explain the discrepancies between the design specs and what the build looks like.

See this image for an example of what Sketch does with type

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

In my index.js I added:

app.use((req, res, next) => {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
   next();
}) 

Requested bean is currently in creation: Is there an unresolvable circular reference?

Spring uses an special logic for resolving this kind of circular dependencies with singleton beans. But this won't apply to other scopes. There is no elegant way of breaking this circular dependency, but a clumsy option could be this one:

@Component("bean1")
@Scope("view")
public class Bean1 {

    @Autowired
    private Bean2 bean2;

    @PostConstruct
    public void init() {
        bean2.setBean1(this);
    }
}

@Component("bean2")
@Scope("view")
public class Bean2 {

    private Bean1 bean1;

    public void setBean1(Bean1 bean1) {
        this.bean1 = bean1;
    }
}

Anyway, circular dependencies are usually a symptom of bad design. You would think again if there is some better way of defining your class dependencies.

Select box arrow style

in Firefox 39 I've found that setting a border to the select element will render the arrow as (2). No border set, will render the arrow as (1). I think it's a bug.

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

Maybe Start-Transcript would work for you. First stop it if it's already running, then start it, and stop it when done.

$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
Start-Transcript -path C:\output.txt -append
# Do some stuff
Stop-Transcript

You can also have this running while working on stuff and have it saving your command line sessions for later reference.

If you want to completely suppress the error when attempting to stop a transcript that is not transcribing, you could do this:

$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue" # or "Stop"

Transparent image - background color

If I understand you right, you can do this:

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

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

Mongod complains that there is no /data/db folder

I just wanted to point out here that if you try this and you run into mkdir: /data/db: Read-only file system, please see this comment, which helped me: https://stackoverflow.com/a/58895373.

That way if anyone is on this answer and does Control F for "read only" they will see this

How to change the map center in Leaflet.js

You could also use:

var latLon = L.latLng(40.737, -73.923);
var bounds = latLon.toBounds(500); // 500 = metres
map.panTo(latLon).fitBounds(bounds);

This will set the view level to fit the bounds in the map leaflet.

How can I convert a long to int in Java?

For small values, casting is enough:

long l = 42;
int i = (int) l;

However, a long can hold more information than an int, so it's not possible to perfectly convert from long to int, in the general case. If the long holds a number less than or equal to Integer.MAX_VALUE you can convert it by casting without losing any information.

For example, the following sample code:

System.out.println( "largest long is " + Long.MAX_VALUE );
System.out.println( "largest int is " + Integer.MAX_VALUE );

long x = (long)Integer.MAX_VALUE;
x++;
System.out.println("long x=" + x);

int y = (int) x;
System.out.println("int y=" + y);

produces the following output on my machine:

largest long is 9223372036854775807
largest int is 2147483647
long x=2147483648
int y=-2147483648

Notice the negative sign on y. Because x held a value one larger than Integer.MAX_VALUE, int y was unable to hold it. In this case, it wrapped around to the negative numbers.

If you wanted to handle this case yourself, you might do something like:

if ( x > (long)Integer.MAX_VALUE ) {
    // x is too big to convert, throw an exception or something useful
}
else {
    y = (int)x;
}

All of this assumes positive numbers. For negative numbers, use MIN_VALUE instead of MAX_VALUE.

.jar error - could not find or load main class

I found this question when I was looking for the answer to the above question. But in my case the issue was the use of an 'en dash' rather than a 'dash'. Check which dash you are using, it might be the wrong one. I hope this answer speeds up someone else's search, a comment like this could have saved me a bit of time.

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

I think I've seen something similar when folders were moved on the server but the working copies were still bound to the older SVN folder structure. Not sure if anyone moved things around in your trunk before you had the chance to merge the branch.

Is that a possibility?

adb uninstall failed

I find that adb shell pm uninstall <package> works consistently, where adb uninstall <package> does not.

Chrome/jQuery Uncaught RangeError: Maximum call stack size exceeded

I recently just ran into this issue as well. I had a very large table in the dialog div. It was >15,000 rows. When the .empty() was called on the dialog div, I was getting the error above.

I found a round-about solution where before I call cleaning the dialog box, I would remove every other row from the very large table, then call the .empty(). It seemed to have worked though. It seems that my old version of JQuery can't handle such large elements.

How do I uninstall a Windows service if the files do not exist anymore?

Remove Windows Service via Registry

Its very easy to remove a service from registry if you know the right path. Here is how I did that:

  1. Run Regedit or Regedt32

  2. Go to the registry entry "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services"

  3. Look for the service that you want delete and delete it. You can look at the keys to know what files the service was using and delete them as well (if necessary).

Delete Windows Service via Command Window

Alternatively, you can also use command prompt and delete a service using following command:

sc delete

You can also create service by using following command

sc create "MorganTechService" binpath= "C:\Program Files\MorganTechSPace\myservice.exe"

Note: You may have to reboot the system to get the list updated in service manager.

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

start cmd.exe 

opens a separate window

start file.cmd 

opens the batch file and executes it in another command prompt

Cause of No suitable driver found for

I had the same problem with spring, commons-dbcp and oracle 10g. Using this URL I got the 'no suitable driver' error: jdbc:oracle:[email protected]:1521:kinangop

The above URL is missing a full colon just before the @. After correcting that, the error disappeared.

How to remove part of a string before a ":" in javascript?

There is no need for jQuery here, regular JavaScript will do:

var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);

Or, the .split() and .pop() version:

var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();

Or, the regex version (several variants of this):

var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];

Is there any simple way to convert .xls file to .csv file? (Excel)

This is a modification of nate_weldon's answer with a few improvements:

  • More robust releasing of Excel objects
  • Set application.DisplayAlerts = false; before attempting to save to hide prompts

Also note that the application.Workbooks.Open and ws.SaveAs methods expect sourceFilePath and targetFilePath to be full paths (ie. directory path + filename)

private static void SaveAs(string sourceFilePath, string targetFilePath)
{
    Application application = null;
    Workbook wb = null;
    Worksheet ws = null;

    try
    {
        application = new Application();
        application.DisplayAlerts = false;
        wb = application.Workbooks.Open(sourceFilePath);
        ws = (Worksheet)wb.Sheets[1];
        ws.SaveAs(targetFilePath, XlFileFormat.xlCSV);
    }
    catch (Exception e)
    {
        // Handle exception
    }
    finally
    {
        if (application != null) application.Quit();
        if (ws != null) Marshal.ReleaseComObject(ws);
        if (wb != null) Marshal.ReleaseComObject(wb);
        if (application != null) Marshal.ReleaseComObject(application);
    }
}

Prevent content from expanding grid items

By default, a grid item cannot be smaller than the size of its content.

Grid items have an initial size of min-width: auto and min-height: auto.

You can override this behavior by setting grid items to min-width: 0, min-height: 0 or overflow with any value other than visible.

From the spec:

6.6. Automatic Minimum Size of Grid Items

To provide a more reasonable default minimum size for grid items, this specification defines that the auto value of min-width / min-height also applies an automatic minimum size in the specified axis to grid items whose overflow is visible. (The effect is analogous to the automatic minimum size imposed on flex items.)

Here's a more detailed explanation covering flex items, but it applies to grid items, as well:

This post also covers potential problems with nested containers and known rendering differences among major browsers.


To fix your layout, make these adjustments to your code:

.month-grid {
  display: grid;
  grid-template: repeat(6, 1fr) / repeat(7, 1fr);
  background: #fff;
  grid-gap: 2px;
  min-height: 0;  /* NEW */
  min-width: 0;   /* NEW; needed for Firefox */
}

.day-item {
  padding: 10px;
  background: #DFE7E7;
  overflow: hidden;  /* NEW */
  min-width: 0;      /* NEW; needed for Firefox */
}

jsFiddle demo


1fr vs minmax(0, 1fr)

The solution above operates at the grid item level. For a container level solution, see this post:

Datatables warning(table id = 'example'): cannot reinitialise data table

This problem occurs if we initialize dataTable more than once.Then we have to remove the previous.

On the other hand we can destroy the old datatable in this way also before creating the new datatable use the following code :

$(“#example”).dataTable().fnDestroy();

There is an another scenario ,say you send more than one ajax request which response will access same table in same template then we will get error also.In this case fnDestroy method doesn’t work properly because you don’t know which response comes first or later.Then you have to set bRetrieve TRUE in data table configuration.That’s it.

This is My senario:

<script type="text/javascript">

$(document).ready(function () {

        $('#DatatableNone').dataTable({
            "bDestroy": true
        }).fnDestroy();

        $('#DatatableOne').dataTable({
            "aoColumnDefs": [{
                "bSortable": false,
                "aTargets": ["sorting_disabled"]
            }],
            "bDestroy": true
        }).fnDestroy();

});

</script>

What design patterns are used in Spring framework?

Spring is a collection of best-practise API patterns, you can write up a shopping list of them as long as your arm. The way that the API is designed encourages you (but doesn't force you) to follow these patterns, and half the time you follow them without knowing you are doing so.

How to test enum types?

Usually I would say it is overkill, but there are occasionally reasons for writing unit tests for enums.

Sometimes the values assigned to enumeration members must never change or the loading of legacy persisted data will fail. Similarly, apparently unused members must not be deleted. Unit tests can be used to guard against a developer making changes without realising the implications.

Should black box or white box testing be the emphasis for testers?

  • *Black box testing: Is the test at system level to check the functionality of the system, to ensure that the system performs all the functions that it was designed for, Its mainly to uncover defects found at the user point. Its better to hire a professional tester to black box your system, 'coz the developer usually tests with a perspective that the codes he had written is good and meets the functional requirements of the clients so he could miss out a lot of things (I don't mean to offend anybody)
  • Whitebox is the first test that is done in the SDLC.This is to uncover bugs like runtime errors and compilation errrors It can be done either by testers or by Developer himself, But I think its always better that the person who wrote the code tests it.He understands them more than another person.*

Git: How do I list only local branches?

git branch -a - All branches.

git branch -r - Remote branches only.

git branch -l or git branch - Local branches only.

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

What you are talking about is called dot sourcing. And it's evil. But no worries, there is a better and easier way to do what you are wanting with modules (it sounds way scarier than it is). The major benefit of using modules is that you can unload them from the shell if you need to, and it keeps the variables in the functions from creeping into the shell (once you dot source a function file, try calling one of the variables from a function in the shell, and you'll see what I mean).

So first, rename the .ps1 file that has all your functions in it to MyFunctions.psm1 (you've just created a module!). Now for a module to load properly, you have to do some specific things with the file. First for Import-Module to see the module (you use this cmdlet to load the module into the shell), it has to be in a specific location. The default path to the modules folder is $home\Documents\WindowsPowerShell\Modules.

In that folder, create a folder named MyFunctions, and place the MyFunctions.psm1 file into it (the module file must reside in a folder with exactly the same name as the PSM1 file).

Once that is done, open PowerShell, and run this command:

Get-Module -listavailable

If you see one called MyFunctions, you did it right, and your module is ready to be loaded (this is just to ensure that this is set up right, you only have to do this once).

To use the module, type the following in the shell (or put this line in your $profile, or put this as the first line in a script):

Import-Module MyFunctions

You can now run your functions. The cool thing about this is that once you have 10-15 functions in there, you're going to forget the name of a couple. If you have them in a module, you can run the following command to get a list of all the functions in your module:

Get-Command -module MyFunctions

It's pretty sweet, and the tiny bit of effort that it takes to set up on the front side is WAY worth it.

img onclick call to JavaScript function

In response to the good solution from macek. The solution didn't work for me. I have to bind the values of the datas to the export function. This solution works for me:

function exportToForm(a, b, c, d, e) {
  console.log(a, b, c, d, e);
}

var images = document.getElementsByTagName("img");

for (var i=0, len=images.length, img; i<len; i++) {
  var img = images[i];
  var boundExportToForm = exportToForm.bind(undefined, 
          img.getAttribute("data-a"), 
            img.getAttribute("data-b"),
            img.getAttribute("data-c"),
            img.getAttribute("data-d"),
            img.getAttribute("data-e"))

  img.addEventListener("click", boundExportToForm);
  }

How do I get Bin Path?

var assemblyPath = Assembly.GetExecutingAssembly().CodeBase;

Trim specific character from a string

This can trim several characters at a time:

function trimChars (str, c) {
  var re = new RegExp("^[" + c + "]+|[" + c + "]+$", "g");
  return str.replace(re,"");
}

var x = "|f|oo||"; 
x =  trimChars(x, '|'); // f|oo

var y = "..++|f|oo||++..";
y = trimChars(y, '|.+'); // f|oo

var z = "\\f|oo\\"; // \f|oo\

// For backslash, remember to double-escape:
z = trimChars(z, "\\\\"); // f|oo

For use in your own script and if you don't mind changing the prototype, this can be a convenient "hack":

String.prototype.trimChars = function (c) {
  var re = new RegExp("^[" + c + "]+|[" + c + "]+$", "g");
  return this.replace(re,"");
}

var x = "|f|oo||"; 
x =  x.trimChars('|'); // f|oo

Since I use the trimChars function extensively in one of my scripts, I prefer this solution. But there are potential issues with modifying an object's prototype.

Get img thumbnails from Vimeo?

If you are looking for an alternative solution and can manage the vimeo account there is another way, you simply add every video you want to show into an album and then use the API to request the album details - it then shows all the thumbnails and links. It's not ideal but might help.

API end point (playground)

Twitter convo with @vimeoapi

Manually map column names with class properties

Kaleb Pederson's solution worked for me. I updated the ColumnAttributeTypeMapper to allow a custom attribute (had requirement for two different mappings on same domain object) and updated properties to allow private setters in cases where a field needed to be derived and the types differed.

public class ColumnAttributeTypeMapper<T,A> : FallbackTypeMapper where A : ColumnAttribute
{
    public ColumnAttributeTypeMapper()
        : base(new SqlMapper.ITypeMap[]
            {
                new CustomPropertyTypeMap(
                   typeof(T),
                   (type, columnName) =>
                       type.GetProperties( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).FirstOrDefault(prop =>
                           prop.GetCustomAttributes(true)
                               .OfType<A>()
                               .Any(attr => attr.Name == columnName)
                           )
                   ),
                new DefaultTypeMap(typeof(T))
            })
    {
        //
    }
}

How to properly create composite primary keys - MYSQL

Suppose you have already created a table now you can use this query to make composite primary key

alter table employee add primary key(emp_id,emp_name);

How do I declare and assign a variable on a single line in SQL

Here goes:

DECLARE @var nvarchar(max) = 'Man''s best friend';

You will note that the ' is escaped by doubling it to ''.

Since the string delimiter is ' and not ", there is no need to escape ":

DECLARE @var nvarchar(max) = '"My Name is Luca" is a great song';

The second example in the MSDN page on DECLARE shows the correct syntax.

How to calculate the sentence similarity using word2vec model of gensim with python

If not using Word2Vec we have other model to find it using BERT for embed. Below are reference link https://github.com/UKPLab/sentence-transformers

pip install -U sentence-transformers

from sentence_transformers import SentenceTransformer
import scipy.spatial

embedder = SentenceTransformer('bert-base-nli-mean-tokens')

# Corpus with example sentences
corpus = ['A man is eating a food.',
          'A man is eating a piece of bread.',
          'The girl is carrying a baby.',
          'A man is riding a horse.',
          'A woman is playing violin.',
          'Two men pushed carts through the woods.',
          'A man is riding a white horse on an enclosed ground.',
          'A monkey is playing drums.',
          'A cheetah is running behind its prey.'
          ]
corpus_embeddings = embedder.encode(corpus)

# Query sentences:
queries = ['A man is eating pasta.', 'Someone in a gorilla costume is playing a set of drums.', 'A cheetah chases prey on across a field.']
query_embeddings = embedder.encode(queries)

# Find the closest 5 sentences of the corpus for each query sentence based on cosine similarity
closest_n = 5
for query, query_embedding in zip(queries, query_embeddings):
    distances = scipy.spatial.distance.cdist([query_embedding], corpus_embeddings, "cosine")[0]

    results = zip(range(len(distances)), distances)
    results = sorted(results, key=lambda x: x[1])

    print("\n\n======================\n\n")
    print("Query:", query)
    print("\nTop 5 most similar sentences in corpus:")

    for idx, distance in results[0:closest_n]:
        print(corpus[idx].strip(), "(Score: %.4f)" % (1-distance))

Other Link to follow https://github.com/hanxiao/bert-as-service

How do I remove packages installed with Python's easy_install?

To list installed Python packages, you can use yolk -l. You'll need to use easy_install yolk first though.

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

In case of Request to a REST Service:

You need to allow the CORS (cross origin sharing of resources) on the endpoint of your REST Service with Spring annotation:

@CrossOrigin(origins = "http://localhost:8080")

Very good tutorial: https://spring.io/guides/gs/rest-service-cors/

How to $http Synchronous call with AngularJS

Since sync XHR is being deprecated, it's best not to rely on that. If you need to do a sync POST request, you can use the following helpers inside of a service to simulate a form post.

It works by creating a form with hidden inputs which is posted to the specified URL.

//Helper to create a hidden input
function createInput(name, value) {
  return angular
    .element('<input/>')
    .attr('type', 'hidden')
    .attr('name', name)
    .val(value);
}

//Post data
function post(url, data, params) {

    //Ensure data and params are an object
    data = data || {};
    params = params || {};

    //Serialize params
    const serialized = $httpParamSerializer(params);
    const query = serialized ? `?${serialized}` : '';

    //Create form
    const $form = angular
        .element('<form/>')
        .attr('action', `${url}${query}`)
        .attr('enctype', 'application/x-www-form-urlencoded')
        .attr('method', 'post');

    //Create hidden input data
    for (const key in data) {
        if (data.hasOwnProperty(key)) {
            const value = data[key];
            if (Array.isArray(value)) {
                for (const val of value) {
                    const $input = createInput(`${key}[]`, val);
                    $form.append($input);
                }
            }
            else {
                const $input = createInput(key, value);
                $form.append($input);
            }
        }
    }

    //Append form to body and submit
    angular.element(document).find('body').append($form);
    $form[0].submit();
    $form.remove();
}

Modify as required for your needs.

How to set default text for a Tkinter Entry widget

Use Entry.insert. For example:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

Or use textvariable option:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

What is the difference between procedural programming and functional programming?

A functional programming is identical to procedural programming in which global variables are not being used.

Programmatically change the src of an img tag

With the snippet you provided (and without making assumptions about the parents of the element) you could get a reference to the image with

document.querySelector('img[name="edit-save"]');

and change the src with

document.querySelector('img[name="edit-save"]').src = "..."

so you could achieve the desired effect with

var img = document.querySelector('img[name="edit-save"]');
img.onclick = function() {
    this.src = "..." // this is the reference to the image itself
};

otherwise, as other suggested, if you're in control of the code, it's better to assign an id to the image a get a reference with getElementById (since it's the fastest method to retrieve an element)

What is the LDF file in SQL Server?

LDF holds the transaction log. If you set your backups correctly - it will be small. It it grows - you have a very common problem of setting database recovery mode to FULL and then forgetting to backup the transaction log (LDF file). Let me explain how to fix it.

  1. If your business can afford to lose a little data between backups, just set the database recovery mode to SIMPLE, then forget about LDF - it will be small. This is the recommended solution for most of the cases.
  2. If you have to be able to restore to the exact point in time - use FULL recovery mode. In this case you have to take regular Transaction Log backups. The simplest way to do it is to use a tool like SqlBackupAndFTP (disclosure - I am a developer). The log file will be truncated at this time and would not grow beyond certain limits.

Some would suggest to use SHRINKFILE to trim you log. Note that this is OK only as an exception. If you do it regularly, it defeats the purpose of FULL recovery model: first you go into trouble of saving every single change in the log, then you just dump it. Set recovery mode to SIMPLE instead.

Installing Apple's Network Link Conditioner Tool

For Xcode 8 you gotta download a package named Additional Tools for Xcode 8

For other versions (8.1, 8.2) get the package here

Double click and open the dmg and go to Hardware directory. Double click on Network Link Conditioner.prefPane.

enter image description here

Click on install

enter image description here

Now Network Link Conditioner will be available in System Preferences.

For versions older than Xcode 8, the package to be downloaded is called Hardware IO Tools for Xcode. Get it from this page

VMware Workstation and Device/Credential Guard are not compatible

Device/Credential Guard is a Hyper-V based Virtual Machine/Virtual Secure Mode that hosts a secure kernel to make Windows 10 much more secure.

enter image description here

...the VSM instance is segregated from the normal operating system functions and is protected by attempts to read information in that mode. The protections are hardware assisted, since the hypervisor is requesting the hardware treat those memory pages differently. This is the same way to two virtual machines on the same host cannot interact with each other; their memory is independent and hardware regulated to ensure each VM can only access it’s own data.

From here, we now have a protected mode where we can run security sensitive operations. At the time of writing, we support three capabilities that can reside here: the Local Security Authority (LSA), and Code Integrity control functions in the form of Kernel Mode Code Integrity (KMCI) and the hypervisor code integrity control itself, which is called Hypervisor Code Integrity (HVCI).

enter image description here

When these capabilities are handled by Trustlets in VSM, the Host OS simply communicates with them through standard channels and capabilities inside of the OS. While this Trustlet-specific communication is allowed, having malicious code or users in the Host OS attempt to read or manipulate the data in VSM will be significantly harder than on a system without this configured, providing the security benefit.

Running LSA in VSM, causes the LSA process itself (LSASS) to remain in the Host OS, and a special, additional instance of LSA (called LSAIso – which stands for LSA Isolated) is created. This is to allow all of the standard calls to LSA to still succeed, offering excellent legacy and backwards compatibility, even for services or capabilities that require direct communication with LSA. In this respect, you can think of the remaining LSA instance in the Host OS as a ‘proxy’ or ‘stub’ instance that simply communicates with the isolated version in prescribed ways.


And Hyper-V and VMware didn't work the same time until 2020, when VMware used Hyper-V Platform to co-exist with Hyper-V starting with Version 15.5.5.

How does VMware Workstation work before version 15.5.5?

VMware Workstation traditionally has used a Virtual Machine Monitor (VMM) which operates in privileged mode requiring direct access to the CPU as well as access to the CPU’s built in virtualization support (Intel’s VT-x and AMD’s AMD-V). When a Windows host enables Virtualization Based Security (“VBS“) features, Windows adds a hypervisor layer based on Hyper-V between the hardware and Windows. Any attempt to run VMware’s traditional VMM fails because being inside Hyper-V the VMM no longer has access to the hardware’s virtualization support.

Introducing User Level Monitor

To fix this Hyper-V/Host VBS compatibility issue, VMware’s platform team re-architected VMware’s Hypervisor to use Microsoft’s WHP APIs. This means changing our VMM to run at user level instead of in privileged mode, as well modifying it to use the WHP APIs to manage the execution of a guest instead of using the underlying hardware directly.

What does this mean to you?

VMware Workstation/Player can now run when Hyper-V is enabled. You no longer have to choose between running VMware Workstation and Windows features like WSL, Device Guard and Credential Guard. When Hyper-V is enabled, ULM mode will automatically be used so you can run VMware Workstation normally. If you don’t use Hyper-V at all, VMware Workstation is smart enough to detect this and the VMM will be used.

System Requirements

To run Workstation/Player using the Windows Hypervisor APIs, the minimum required Windows 10 version is Windows 10 20H1 build 19041.264. VMware Workstation/Player minimum version is 15.5.5.

To avoid the error, update your Windows 10 to Version 2004/Build 19041 (Mai 2020 Update) and use at least VMware 15.5.5.

How to rollback a specific migration?

To rollback the last migration you can do:

rake db:rollback

If you want to rollback a specific migration with a version you should do:

rake db:migrate:down VERSION=YOUR_MIGRATION_VERSION

If the migration file you want to rollback was called db/migrate/20141201122027_create_some_table.rb, then the VERSION for that migration is 20141201122027, which is the timestamp of when that migration was created, and the command to roll back that migration would be:

rake db:migrate:down VERSION=20141201122027

How do you stylize a font in Swift?

Add Custom Font in Swift

  1. Drag and drop your font in your project.
  2. Double check that it is added in Copy Bundle Resource. (Build Phase -> Copy Bundle Resource).
  3. In your plist file add "Font Provided by application" and add your fonts with full name.
  4. Now use your font like: myLabel.font = UIFont (name: "GILLSANSCE-ROMAN", size: 20)

Presto SQL - Converting a date string to date format

date_format requires first argument as timestamp so not the best way to convert a string. Use date_parse instead.

Also, use %c for non zero-padded month, %e for non zero-padded day of the month and %Y for four digit year.

SELECT date_parse('7/22/2016 6:05:04 PM', '%c/%e/%Y %r')

Declaring abstract method in TypeScript

No, no, no! Please do not try to make your own 'abstract' classes and methods when the language does not support that feature; the same goes for any language feature you wish a given language supported. There is no correct way to implement abstract methods in TypeScript. Just structure your code with naming conventions such that certain classes are never directly instantiated, but without explicitly enforcing this prohibition.

Also, the example above is only going to provide this enforcement at run time, NOT at compile time, as you would expect in Java/C#.

jQuery Ajax error handling, show custom exception messages

Controller:

public class ClientErrorHandler : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        var response = filterContext.RequestContext.HttpContext.Response;
        response.Write(filterContext.Exception.Message);
        response.ContentType = MediaTypeNames.Text.Plain;
        filterContext.ExceptionHandled = true;
    }
}

[ClientErrorHandler]
public class SomeController : Controller
{
    [HttpPost]
    public ActionResult SomeAction()
    {
        throw new Exception("Error message");
    }
}

View script:

$.ajax({
    type: "post", url: "/SomeController/SomeAction",
    success: function (data, text) {
        //...
    },
    error: function (request, status, error) {
        alert(request.responseText);
    }
});

Enabling SSL with XAMPP

You can also configure your SSL in xampp/apache/conf/extra/httpd-vhost.conf like this:

<VirtualHost *:443>
    DocumentRoot C:/xampp/htdocs/yourProject
    ServerName yourProject.whatever
    SSLEngine on
    SSLCertificateFile "conf/ssl.crt/server.crt"
    SSLCertificateKeyFile "conf/ssl.key/server.key"
</VirtualHost>

I guess, it's better not change it in the httpd-ssl.conf if you have more than one project and you need SSL on more than one of them

How do I count unique items in field in Access query?

A quick trick to use for me is using the find duplicates query SQL and changing 1 to 0 in Having expression. Like this:

SELECT COUNT([UniqueField]) AS DistinctCNT FROM
(
  SELECT First([FieldName]) AS [UniqueField]
  FROM TableName
  GROUP BY [FieldName]
  HAVING (((Count([FieldName]))>0))
);

Hope this helps, not the best way I am sure, and Access should have had this built in.

Convert Python ElementTree to string

How do I convert ElementTree.Element to a String?

For Python 3:

xml_str = ElementTree.tostring(xml, encoding='unicode')

For Python 2:

xml_str = ElementTree.tostring(xml, encoding='utf-8')

The following is compatible with both Python 2 & 3, but only works for Latin characters:

xml_str = ElementTree.tostring(xml).decode()

Example usage

from xml.etree import ElementTree

xml = ElementTree.Element("Person", Name="John")
xml_str = ElementTree.tostring(xml).decode()
print(xml_str)

Output:

<Person Name="John" />

Explanation

Despite what the name implies, ElementTree.tostring() returns a bytestring by default in Python 2 & 3. This is an issue in Python 3, which uses Unicode for strings.

In Python 2 you could use the str type for both text and binary data. Unfortunately this confluence of two different concepts could lead to brittle code which sometimes worked for either kind of data, sometimes not. [...]

To make the distinction between text and binary data clearer and more pronounced, [Python 3] made text and binary data distinct types that cannot blindly be mixed together.

Source: Porting Python 2 Code to Python 3

If we know what version of Python is being used, we can specify the encoding as unicode or utf-8. Otherwise, if we need compatibility with both Python 2 & 3, we can use decode() to convert into the correct type.

For reference, I've included a comparison of .tostring() results between Python 2 and Python 3.

ElementTree.tostring(xml)
# Python 3: b'<Person Name="John" />'
# Python 2: <Person Name="John" />

ElementTree.tostring(xml, encoding='unicode')
# Python 3: <Person Name="John" />
# Python 2: LookupError: unknown encoding: unicode

ElementTree.tostring(xml, encoding='utf-8')
# Python 3: b'<Person Name="John" />'
# Python 2: <Person Name="John" />

ElementTree.tostring(xml).decode()
# Python 3: <Person Name="John" />
# Python 2: <Person Name="John" />

Thanks to Martijn Peters for pointing out that the str datatype changed between Python 2 and 3.


Why not use str()?

In most scenarios, using str() would be the "cannonical" way to convert an object to a string. Unfortunately, using this with Element returns the object's location in memory as a hexstring, rather than a string representation of the object's data.

from xml.etree import ElementTree

xml = ElementTree.Element("Person", Name="John")
print(str(xml))  # <Element 'Person' at 0x00497A80>

Leave only two decimal places after the dot

If you want to take just two numbers after comma you can use the Math Class that give you the round function for example :

float value = 92.197354542F;
value = (float)System.Math.Round(value,2);         // value = 92.2;

Hope this Help
Cheers

How to disable JavaScript in Chrome Developer Tools?

Full and fast instructions for Chrome browsers (Opera incl.)

The first way

  1. If Developer Tools aren't open then press F12 key on keyboard to show the Developer Tools. In Opera browser you have to use key combination Ctrl + Shift + i on keyboard to open it.
  2. To show the settings just press F1 key on keyboard. The Developer Tools window must be focused when you are doing it. Or if you want to open the settings with the mouse then you have to click on ? button in the top right corner of the Developer Tools, then click Settings in the menu.

Then you have to scroll down the settings window to bottom and then you will see the checkbox for disabling JavaScript like follows:

disable JavaScript in chrome developer tools

Just click on this checkbox and push esc key on keyboard for hide the settings. If you want to enable it then you have to do the same way again.

The second way

  1. If Developer Tools aren't open then open it like in the first way is described.
  2. Press the key combination Ctrl + Shift + P (for Windows or Linux) or Cmd (?) + Shift + P (for Mac) to open the Command Menu. Be sure that the focus is on the DevTools window.
  3. Type there "Disable JavaScript" and then press Enter or click it with the mouse. If you want to turn back the enanled JS then open the Command Menu again and type there "Enable JavaScript" and then press Enter or click it with the mouse. You could also write just only "JavaScript" or "Java" there and then choose it with the mouse.

disable JavaScript in chrome developer tools

If all this does not work

For some reason it is possible that it does not work. I this case open a new empty site in "Incognito Mode" and do all this there.

The quickest way

In Chrome Web Store or on Opera Addon site you can find and install extensions which do it per one click. Just search "Javascript Switcher":

error running apache after xampp install

Try those methods, it should work:

  • quit/exit Skype (make sure it's not running) because it reserves localhost:80
  • disable Anti-virus (Try first to disable skype and running again, if it didn't work do this step)
  • Right click on xampp control panel and run as administrator

How to delete an SMS from the inbox in Android programmatically?

Use one of this method to select the last received SMS and delete it, here in this case i am getting the top most sms and going to delete using thread and id value of sms,

try {
    Uri uri = Uri.parse("content://sms/inbox");
    Cursor c = v.getContext().getContentResolver().query(uri, null, null, null, null);
    int i = c.getCount();

    if (c.moveToFirst()) {
    }
} catch (CursorIndexOutOfBoundsException ee) {
    Toast.makeText(v.getContext(), "Error :" + ee.getMessage(), Toast.LENGTH_LONG).show();
}

Change Input to Upper Case

Javascript string objects have a toLocaleUpperCase() function that makes the conversion itself easy.

Here's an example of live capitalisation:

$(function() {
    $('input').keyup(function() {
        this.value = this.value.toLocaleUpperCase();
    });
});

Unfortunately, this resets the textbox contents completely, so the user's caret position (if not "the end of the textbox") is lost.

You can hack this back in, though, with some browser-switching magic:

// Thanks http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/
function getCaretPosition(ctrl) {
    var CaretPos = 0;    // IE Support
    if (document.selection) {
        ctrl.focus();
        var Sel = document.selection.createRange();
        Sel.moveStart('character', -ctrl.value.length);
        CaretPos = Sel.text.length;
    }
    // Firefox support
    else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
        CaretPos = ctrl.selectionStart;
    }

    return CaretPos;
}

function setCaretPosition(ctrl, pos) {
    if (ctrl.setSelectionRange) {
        ctrl.focus();
        ctrl.setSelectionRange(pos,pos);
    }
    else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}


// The real work

$(function() {
    $('input').keyup(function() {
        // Remember original caret position
        var caretPosition = getCaretPosition(this);

        // Uppercase-ize contents
        this.value = this.value.toLocaleUpperCase();

        // Reset caret position
        // (we ignore selection length, as typing deselects anyway)
        setCaretPosition(this, caretPosition);
    });
});

Ultimately, it might be easiest to fake it. Set the style text-transform: uppercase on the textbox so that it appears uppercase to the user, then in your Javascript apply the text transformation once whenever the user's caret focus leaves the textbox entirely:

HTML:

<input type="text" name="keywords" class="uppercase" />

CSS:

input.uppercase { text-transform: uppercase; }

Javascript:

$(function() {
    $('input').focusout(function() {
        // Uppercase-ize contents
        this.value = this.value.toLocaleUpperCase();
    });
});

Hope this helps.

how to read xml file from url using php

you can get the data from the XML by using "simplexml_load_file" Function. Please refer this link

http://php.net/manual/en/function.simplexml-load-file.php

$url = "http://maps.google.com/maps/api/directions/xml?origin=Quentin+Road+Brooklyn%2C+New+York%2C+11234+United+States&destination=550+Madison+Avenue+New+York%2C+New+York%2C+10001+United+States&sensor=false";
$xml = simplexml_load_file($url);
print_r($xml);

How do I prompt for Yes/No/Cancel input in a Linux shell script?

read -p "Are you alright? (y/n) " RESP
if [ "$RESP" = "y" ]; then
  echo "Glad to hear it"
else
  echo "You need more bash programming"
fi

Is there a better jQuery solution to this.form.submit();?

You can always JQuery-ize your form.submit, but it may just call the same thing:

$("form").submit(); // probably able to affect multiple forms (good or bad)

// or you can address it by ID
$("#yourFormId").submit();

You can also attach functions to the submit event, but that is a different concept.

Insert data into a view (SQL Server)

What about naming your column?

INSERT INTO dbo.rLicenses (name) VALUES ('test')

It's been years since I tried updating via a view so YMMV as HLGEM mentioned.

I would consider an "INSTEAD OF" trigger on the view to allow a simple INSERT dbo.Licenses (ie the table) in the trigger

How to convert MySQL time to UNIX timestamp using PHP?

From one of my other posts, getting a unixtimestamp:

$unixTimestamp = time();

Converting to mysql datetime format:

$mysqlTimestamp = date("Y-m-d H:i:s", $unixTimestamp);

Getting some mysql timestamp:

$mysqlTimestamp = '2013-01-10 12:13:37';

Converting it to a unixtimestamp:

$unixTimestamp = strtotime('2010-05-17 19:13:37');

...comparing it with one or a range of times, to see if the user entered a realistic time:

if($unixTimestamp > strtotime("1999-12-15") && $unixTimestamp < strtotime("2025-12-15"))
{...}

Unix timestamps are safer too. You can do the following to check if a url passed variable is valid, before checking (for example) the previous range check:

if(ctype_digit($_GET["UpdateTimestamp"]))
{...}

Find which version of package is installed with pip

To do this using Python code:

Using importlib.metadata.version

Python =3.8

import importlib.metadata
importlib.metadata.version('beautifulsoup4')
'4.9.1'

Python =3.7

(using importlib_metadata.version)

!pip install importlib-metadata

import importlib_metadata
importlib_metadata.version('beautifulsoup4')
'4.9.1'

Using pkg_resources.Distribution

import pkg_resources
pkg_resources.get_distribution('beautifulsoup4').version
'4.9.1'
pkg_resources.get_distribution('beautifulsoup4').parsed_version
<Version('4.9.1')>

Credited to comments by sinoroc and mirekphd.

Why can't I declare static methods in an interface?

Illegal combination of modifiers : static and abstract

If a member of a class is declared as static, it can be used with its class name which is confined to that class, without creating an object.

If a member of a class is declared as abstract, you need to declare the class as abstract and you need to provide the implementation of the abstract member in its inherited class (Sub-Class).

You need to provide an implementation to the abstract member of a class in sub-class where you are going to change the behaviour of static method, also declared as abstract which is a confined to the base class, which is not correct

Creating a script for a Telnet session?

I like the example given by Active State using python. Here is the full link. I added the simple log in part from the link but you can get the gist of what you could do.

import telnetlib

prdLogBox='142.178.1.3'
uid = 'uid'
pwd = 'yourpassword'

tn = telnetlib.Telnet(prdLogBox)
tn.read_until("login: ")
tn.write(uid + "\n")
tn.read_until("Password:")
tn.write(pwd + "\n")
tn.write("exit\n")
tn.close()

Python subprocess/Popen with a modified environment

With Python 3.5 you could do it this way:

import os
import subprocess

my_env = {**os.environ, 'PATH': '/usr/sbin:/sbin:' + os.environ['PATH']}

subprocess.Popen(my_command, env=my_env)

Here we end up with a copy of os.environ and overridden PATH value.

It was made possible by PEP 448 (Additional Unpacking Generalizations).

Another example. If you have a default environment (i.e. os.environ), and a dict you want to override defaults with, you can express it like this:

my_env = {**os.environ, **dict_with_env_variables}

default web page width - 1024px or 980px?

even there is no right or wrong answer for this question , but I personally prefer 960px width . since all modern monitors support at least 1024 × 768 pixel resolution. 960 is divisible by 2, 3, 4, 5, 6, 8, 10, 12, 15, 16, 20, 24, 30, 32, 40, 48, 60, 64, 80, 96, 120, 160, 192, 240, 320 and 480. This makes it a highly flexible base number to work with.

see this article that shows most popular screens resolutions 2013-2014 in US and UK : http://www.hobo-web.co.uk/best-screen-size/

Get and Set a Single Cookie with Node.js HTTP Server

If you don't care what's in the cookie and you just want to use it, try this clean approach using request (a popular node module):

var request = require('request');
var j = request.jar();
var request = request.defaults({jar:j});
request('http://www.google.com', function () {
  request('http://images.google.com', function (error, response, body){
     // this request will will have the cookie which first request received
     // do stuff
  });
});

Java - Abstract class to contain variables?

Sure.. Why not?
Abstract base classes are just a convenience to house behavior and data common to 2 or more classes in a single place for efficiency of storage and maintenance. Its an implementation detail.
Take care however that you are not using an abstract base class where you should be using an interface. Refer to Interface vs Base class

Python: 'ModuleNotFoundError' when trying to import module from imported package

For me when I created a file and saved it as python file, I was getting this error during importing. I had to create a filename with the type ".py" , like filename.py and then save it as a python file. post trying to import the file worked for me.

How do I ignore files in Subversion?

svn status will tell you which files are not in SVN, as well as what's changed.

Look at the SVN properties for the ignore property.

For all things SVN, the Red Book is required reading.

How to set a transparent background of JPanel?

In my particular case it was easier to do this:

 panel.setOpaque(true);
 panel.setBackground(new Color(0,0,0,0,)): // any color with alpha 0 (in this case the color is black

How to read text file in JavaScript

Javascript doesn't have access to the user's filesystem for security reasons. FileReader is only for files manually selected by the user.

setting min date in jquery datepicker

The problem is that the default option of "yearRange" is 10 years.

So 2012 - 10 = 2002.

So change the yearRange to c-20:c or just 1999 (yearRange: '1999:c'), and use that in combination with restrict dates (mindate, maxdate).

For more info: http://jqueryui.com/demos/datepicker/#option-yearRange


See example: http://jsfiddle.net/kGjdL/

And your code with the addition:

$(function () {
    $('#datepicker').datepicker({
        dateFormat: 'yy-mm-dd',
        showButtonPanel: true,
        changeMonth: true,
        changeYear: true,
        showOn: "button",
        buttonImage: "images/calendar.gif",
        buttonImageOnly: true,
        minDate: new Date(1999, 10 - 1, 25),
        maxDate: '+30Y',
        yearRange: '1999:c',
        inline: true
    });
});

append new row to old csv file python

Based in the answer of @G M and paying attention to the @John La Rooy's warning, I was able to append a new row opening the file in 'a'mode.

Even in windows, in order to avoid the newline problem, you must declare it as newline=''.

Now you can open the file in 'a'mode (without the b).

import csv

with open(r'names.csv', 'a', newline='') as csvfile:
    fieldnames = ['This','aNew']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writerow({'This':'is', 'aNew':'Row'})

I didn't try with the regular writer (without the Dict), but I think that it'll be ok too.

mysql update query with sub query

For the impatient:

UPDATE target AS t
INNER JOIN (
  SELECT s.id, COUNT(*) AS count
  FROM source_grouped AS s
  -- WHERE s.custom_condition IS (true)
  GROUP BY s.id
) AS aggregate ON aggregate.id = t.id
SET t.count = aggregate.count

That's @mellamokb's answer, as above, reduced to the max.

Java: Instanceof and Generics

Technically you shouldn't have to, that's the point of generics, so you can do compile-type checking:

public int indexOf(E arg0) {
   ...
}

but then the @Override may be a problem if you have a class hierarchy. Otherwise see Yishai's answer.