Programs & Examples On #Jtag

JTAG is a common interface used for programming and debugging microprocessors and other types of embedded devices.

Spring - applicationContext.xml cannot be opened because it does not exist

You actually need to understand the ApplicationContext. It is an interface and it will have different implementations based on configuration.

As you are using new ClassPathXmlApplicationContext("applicationContext.xml"); , kindly pay attention to initial right hand-side , it says ClassPathXmlApplicationContext , so the XML must be present in the class path. So drag your applicationContext.xml wherever it is to the src folder.

Gist: new ClassPathXmlApplicationContext as the name [ClassPathXml]will look for the xml file in the src folder of your project, so drag your xml file there only.

? ClassPathXmlApplicationContext—Loads a context definition from an XML file located in the classpath, treating context definition files as classpath resources.

? FileSystemXmlApplicationContext—Loads a context definition from an XML file in the file system.

? XmlWebApplicationContext—Loads context definitions from an XML file contained within a web application.

Giving graphs a subtitle in matplotlib

Just use TeX ! This works :

title(r"""\Huge{Big title !} \newline \tiny{Small subtitle !}""")

EDIT: To enable TeX processing, you need to add the "usetex = True" line to matplotlib parameters:

fig_size = [12.,7.5]
params = {'axes.labelsize': 8,
      'text.fontsize':   6,
      'legend.fontsize': 7,
      'xtick.labelsize': 6,
      'ytick.labelsize': 6,
      'text.usetex': True,       # <-- There 
      'figure.figsize': fig_size,
      }
rcParams.update(params)

I guess you also need a working TeX distribution on your computer. All details are given at this page:

http://matplotlib.org/users/usetex.html

Received fatal alert: handshake_failure through SSLHandshakeException

This issue is occurring because of the java version. I was using 1.8.0.231 JDK and getting this error. I have degraded my java version from 1.8.0.231 to 1.8.0.171, Now It is working fine.

Func delegate with no return type

All of the Func delegates take at least one parameter

That's not true. They all take at least one type argument, but that argument determines the return type.

So Func<T> accepts no parameters and returns a value. Use Action or Action<T> when you don't want to return a value.

How to query all the GraphQL type fields without writing a long query?

I faced this same issue when I needed to load location data that I had serialized into the database from the google places API. Generally I would want the whole thing so it works with maps but I didn't want to have to specify all of the fields every time.

I was working in Ruby so I can't give you the PHP implementation but the principle should be the same.

I defined a custom scalar type called JSON which just returns a literal JSON object.

The ruby implementation was like so (using graphql-ruby)

module Graph
  module Types
    JsonType = GraphQL::ScalarType.define do
      name "JSON"
      coerce_input -> (x) { x }
      coerce_result -> (x) { x }
    end
  end
end

Then I used it for our objects like so

field :location, Types::JsonType

I would use this very sparingly though, using it only where you know you always need the whole JSON object (as I did in my case). Otherwise it is defeating the object of GraphQL more generally speaking.

Storing data into list with class

How do you expect List<EmailData>.Add to know how to turn three strings into an instance of EmailData? You're expecting too much of the Framework. There is no overload of List<T>.Add that takes in three string parameters. In fact, the only overload of List<T>.Add takes in a T. Therefore, you have to create an instance of EmailData and pass that to List<T>.Add. That is what the above code does.

Try:

lstemail.Add(new EmailData {
    FirstName = "JOhn", 
    LastName = "Smith",
    Location = "Los Angeles"
});

This uses the C# object initialization syntax. Alternatively, you can add a constructor to your class

public EmailData(string firstName, string lastName, string location) {
    this.FirstName = firstName;
    this.LastName = lastName;
    this.Location = location;
}

Then:

lstemail.Add(new EmailData("JOhn", "Smith", "Los Angeles"));

What is ANSI format?

ASCII just defines a 7 bit code page with 128 symbols. ANSI extends this to 8 bit and there are several different code pages for the symbols 128 to 255.

The naming ANSI is not correct because it is actually the ISO/IEC 8859 norm that defines this code pages. See ISO/IEC 8859 for reference. There are 16 code pages ISO/IEC 8859-1 to ISO/IEC 8859-16.

Windows-1252 is again based on ISO/IEC 8859-1 with some modification mainly in the range of the C1 control set in the range 128 to 159. Wikipedia states that Windows-1252 is also refered as ISO-8859-1 with a second hyphen between ISO and 8859. (Unbelievable! Who does something like that?!?)

How do you find all subclasses of a given class in Java?

The reason you see a difference between your implementation and Eclipse is because you scan each time, while Eclipse (and other tools) scan only once (during project load most of the times) and create an index. Next time you ask for the data it doesn't scan again, but look at the index.

What exactly does += do in python?

Remember when you used to sum, for example 2 & 3, in your old calculator and every time you hit the = you see 3 added to the total, the += does similar job. Example:

>>> orange = 2
>>> orange += 3
>>> print(orange)
5
>>> orange +=3
>>> print(orange)
8

Check if array is empty or null

User JQuery is EmptyObject to check whether array is contains elements or not.

var testArray=[1,2,3,4,5];
var testArray1=[];
console.log(jQuery.isEmptyObject(testArray)); //false
console.log(jQuery.isEmptyObject(testArray1)); //true

Generate random numbers with a given (numerical) distribution

Here is a more effective way of doing this:

Just call the following function with your 'weights' array (assuming the indices as the corresponding items) and the no. of samples needed. This function can be easily modified to handle ordered pair.

Returns indexes (or items) sampled/picked (with replacement) using their respective probabilities:

def resample(weights, n):
    beta = 0

    # Caveat: Assign max weight to max*2 for best results
    max_w = max(weights)*2

    # Pick an item uniformly at random, to start with
    current_item = random.randint(0,n-1)
    result = []

    for i in range(n):
        beta += random.uniform(0,max_w)

        while weights[current_item] < beta:
            beta -= weights[current_item]
            current_item = (current_item + 1) % n   # cyclic
        else:
            result.append(current_item)
    return result

A short note on the concept used in the while loop. We reduce the current item's weight from cumulative beta, which is a cumulative value constructed uniformly at random, and increment current index in order to find the item, the weight of which matches the value of beta.

Resize font-size according to div size

I was looking for the same funcionality and found this answer. However, I wanted to give you guys a quick update. It's CSS3's vmin unit.

p, li
{
  font-size: 1.2vmin;
}

vmin means 'whichever is smaller between the 1% of the ViewPort's height and the 1% of the ViewPort's width'.

More info on SitePoint

Adding elements to object

This is an old question, anyway today the best practice is by using Object.defineProperty

const object1 = {};

Object.defineProperty(object1, 'property1', {
  value: 42,
  writable: false
});

object1.property1 = 77;
// throws an error in strict mode

console.log(object1.property1);
// expected output: 42

Get first and last day of month using threeten, LocalDate

You can try this to avoid indicating custom date and if there is need to display start and end dates of current month:

    LocalDate start = LocalDate.now().minusDays(LocalDate.now().getDayOfMonth()-1);
    LocalDate end = LocalDate.now().minusDays(LocalDate.now().getDayOfMonth()).plusMonths(1);
    System.out.println("Start of month: " + start);
    System.out.println("End of month: " + end);

Result:

>     Start of month: 2019-12-01
>     End of month: 2019-12-30

Compare two objects with .equals() and == operator

When we use == , the Reference of object is compared not the actual objects. We need to override equals method to compare Java Objects.

Some additional information C++ has operator over loading & Java does not provide operator over loading. Also other possibilities in java are implement Compare Interface .which defines a compareTo method.

Comparator interface is also used compare two objects

What is N-Tier architecture?

When we talk of Tiers, we generally talk of Physical Processes (having different memory space).

Thus, in case, Layers of an application are deployed in different processes, those different processes will be different tiers.

E.g, In a 3-tier application, business tier talks to Mainframes (separate process) and talks to Reporting Service (separate process), then that application would be 5 tier.

Hence, the generic name is n-tier.

How to disable keypad popup when on edittext?

     edittext.setShowSoftInputOnFocus(false);

Now you can use any custom keyboard you like.

What is the difference between readonly="true" & readonly="readonly"?

readonly="true" is invalid HTML5, readonly="readonly" is valid.

HTML5 spec:

http://www.w3.org/TR/html5/forms.html#attr-input-readonly :

The readonly attribute is a boolean attribute

http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

Conclusion:

The following are valid, equivalent and true:

<input type="text" readonly />
<input type="text" readonly="" />
<input type="text" readonly="readonly" />
<input type="text" readonly="ReAdOnLy" />

The following are invalid:

<input type="text" readonly="0" />
<input type="text" readonly="1" />
<input type="text" readonly="false" />
<input type="text" readonly="true" />

The absence of the attribute is the only valid syntax for false:

<input type="text"/>

Recommendation

If you care about writing valid XHTML, use readonly="readonly", since <input readonly> is invalid and other alternatives are less readable. Else, just use <input readonly> as it is shorter.

Why does z-index not work?

If you set position to other value than static but your element's z-index still doesn't seem to work, it may be that some parent element has z-index set.

The stacking contexts have hierarchy, and each stacking context is considered in the stacking order of the parent's stacking context.

So with following html

_x000D_
_x000D_
div { border: 2px solid #000; width: 100px; height: 30px; margin: 10px; position: relative; background-color: #FFF; }_x000D_
#el3 { background-color: #F0F; width: 100px; height: 60px; top: -50px; }
_x000D_
<div id="el1" style="z-index: 5"></div>_x000D_
<div id="el2" style="z-index: 3">_x000D_
  <div id="el3" style="z-index: 8"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

no matter how big the z-index of el3 will be set, it will always be under el1 because it's parent has lower stacking context. You can imagine stacking order as levels where stacking order of el3 is actually 3.8 which is lower than 5.

If you want to check stacking contexts of parent elements, you can use this:

var el = document.getElementById("#yourElement"); // or use $0 in chrome;
do {
    var styles = window.getComputedStyle(el);
    console.log(styles.zIndex, el);
} while(el.parentElement && (el = el.parentElement));

There is a great article about stacking contexts on MDN

Whats the CSS to make something go to the next line in the page?

There are two options that I can think of, but without more details, I can't be sure which is the better:

#elementId {
    display: block;
}

This will force the element to a 'new line' if it's not on the same line as a floated element.

#elementId {
     clear: both;
}

This will force the element to clear the floats, and move to a 'new line.'

In the case of the element being on the same line as another that has position of fixed or absolute nothing will, so far as I know, force a 'new line,' as those elements are removed from the document's normal flow.

Java regex capturing groups indexes

For The Rest Of Us

Here is a simple and clear example of how this works

Regex: ([a-zA-Z0-9]+)([\s]+)([a-zA-Z ]+)([\s]+)([0-9]+)

String: "!* UserName10 John Smith 01123 *!"

group(0): UserName10 John Smith 01123
group(1): UserName10
group(2):  
group(3): John Smith
group(4):  
group(5): 01123

As you can see, I have created FIVE groups which are each enclosed in parentheses.

I included the !* and *! on either side to make it clearer. Note that none of those characters are in the RegEx and therefore will not be produced in the results. Group(0) merely gives you the entire matched string (all of my search criteria in one single line). Group 1 stops right before the first space because the space character was not included in the search criteria. Groups 2 and 4 are simply the white space, which in this case is literally a space character, but could also be a tab or a line feed etc. Group 3 includes the space because I put it in the search criteria ... etc.

Hope this makes sense.

How to stash my previous commit?

An alternative solution uses the stash:

Before:

~/dev/gitpro $git stash list

~/dev/gitpro $git log --oneline -3

* 7049dd5 (HEAD -> master) c111
* 3f1fa3d c222
* 0a0f6c4 c333
  1. git reset head~1 <--- head shifted one back to c222; working still contains c111 changes
  2. git stash push -m "commit 111" <--- staging/working (containing c111 changes) stashed; staging/working rolled back to revised head (containing c222 changes)
  3. git reset head~1 <--- head shifted one back to c333; working still contains c222 changes
  4. git stash push -m "commit 222" <--- staging/working (containing c222 changes) stashed; staging/working rolled back to revised head (containing c333 changes)
  5. git stash pop stash@{1} <--- oldest stash entry with c111 changes removed & applied to staging/working
  6. git commit -am "commit 111" <-- new commit with c111's changes becomes new head

note you cannot run 'git stash pop' without specifying the stash@{1} entry. The stash is a LIFO stack -- not FIFO -- so that would incorrectly pop the stash@{0} entry with c222's changes (instead of stash@{1} with c111's changes).

note if there are conflicting chunks between commits 111 and 222, then you'll be forced to resolve them when attempting to pop. (This would be the case if you went with an alternative rebase solution as well.)

After:

~/dev/gitpro $git stash list

stash@{0}: On master: c222

~/dev/gitpro $git log -2 --oneline

* edbd9e8 (HEAD -> master) c111
* 0a0f6c4 c333

Using Camera in the Android emulator

Just in case you just need to show a picture in response to a camera request, there is image-to-camera.

Just download, build, install, copy an image of your choice to the device, and you can select it via the app, which is an alternative to the built-in camera.

Specifing width of a flexbox flex item: width or basis?

The bottom statement is equivalent to:

.half {
   flex-grow: 0;
   flex-shrink: 0;
   flex-basis: 50%;
}

Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.

Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.

I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)

Calling a JavaScript function named in a variable

If it´s in the global scope it´s better to use:

function foo()
{
    alert('foo');
}

var a = 'foo';
window[a]();

than eval(). Because eval() is evaaaaaal.

Exactly like Nosredna said 40 seconds before me that is >.<

Python xml ElementTree from a string source?

You can parse the text as a string, which creates an Element, and create an ElementTree using that Element.

import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.fromstring(xmlstring))

I just came across this issue and the documentation, while complete, is not very straightforward on the difference in usage between the parse() and fromstring() methods.

With Twitter Bootstrap, how can I customize the h1 text color of one page and leave the other pages to be default?

in bootstrap 3 here are the classes to change the text color:

<p class="text-muted">...</p> //grey
<p class="text-primary">...</p> //light blue
<p class="text-success">...</p> //green
<p class="text-info">...</p> //blue
<p class="text-warning">...</p> //orangish,yellow
<p class="text-danger">...</p> //red

Documentation under Helper classes - Contextual colors.

Convert seconds to Hour:Minute:Second

The gmtdate() function didn't work for me as I was tracking hours worked on a project and if it's over 24 hours, you get amount left over after 24 hours is subtracted. In other words 37 hours becomes 13 hours. (all as stated above by Glavic - thanks for your examples!) This one worked well:

Convert seconds to format by 'foot' no limit :
$seconds = 8525;
$H = floor($seconds / 3600);
$i = ($seconds / 60) % 60;
$s = $seconds % 60;
echo sprintf("%02d:%02d:%02d", $H, $i, $s);
# 02:22:05

How to configure WAMP (localhost) to send email using Gmail?

Gmail servers use SMTP Authentication under SSL or TLS. I think that there is no way to use the mail() function under that circumstances, so you might want to check these alternatives:

They all support SMTP auth under SSL.

You'll need to enable the php_openssl extension in your php.ini.

Additional Resources:

How to mention C:\Program Files in batchfile

While createting the bat file, you can easly avoid the space. If you want to mentioned "program files "folder in batch file.

Do following steps:

1. Type c: then press enter

2. cd program files

3. cd "choose your own folder name"

then continue as you wish.

This way you can create batch file and you can mention program files folder.

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
  StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

send bold & italic text on telegram bot with html

For JS:

First, if you haven't installed telegram bot just install with the command

npm i messaging-api-telegram

Now, initialize its client with

const client = new TelegramClient({
    accessToken: process.env.<TELEGRAM_ACCESS_TOKEN>
});

Then, to send message use sendMessage() async function like below -

    const resp = await client.sendMessage(chatId, msg, {
        disableWebPagePreview: false,
        disableNotification: false,
        parseMode: "HTML"
    });

Here parse mode by default would be plain text but with parseOptions parseMode we can do 1. "HTML" and "MARKDOWN" to let use send messages in stylish way. Also get your access token of bot from telegram page and chatId or group chat Id from same.

How to open the command prompt and insert commands using Java?

You have to set all \" (quotes) carefully. The parameter \k is used to leave the command prompt open after the execution.

1) to combine 2 commands use (for example pause and ipconfig)

Runtime.getRuntime()
  .exec("cmd /c start cmd.exe /k \"pause && ipconfig\"", null, selectedFile.getParentFile());

2) to show the content of a file use (MORE is a command line viewer on Windows)

File selectedFile = new File(pathToFile):
Runtime.getRuntime()
  .exec("cmd /c start cmd.exe /k \"MORE \"" + selectedFile.getName() + "\"\"", null, selectedFile.getParentFile());

One nesting quote \" is for the command and the file name, the second quote \" is for the filename itself, for spaces etc. in the name particularly.

How to Execute SQL Script File in Java?

If you use Spring you can use DataSourceInitializer:

@Bean
public DataSourceInitializer dataSourceInitializer(@Qualifier("dataSource") final DataSource dataSource) {
    ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
    resourceDatabasePopulator.addScript(new ClassPathResource("/data.sql"));
    DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
    dataSourceInitializer.setDataSource(dataSource);
    dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);
    return dataSourceInitializer;
}

Used to set up a database during initialization and clean up a database during destruction.

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/datasource/init/DataSourceInitializer.html

What is the purpose of "pip install --user ..."?

Without Virtual Environments

pip <command> --user changes the scope of the current pip command to work on the current user account's local python package install location, rather than the system-wide package install location, which is the default.

This only really matters on a multi-user machine. Anything installed to the system location will be visible to all users, so installing to the user location will keep that package installation separate from other users (they will not see it, and would have to install it themselves separately to use it). Because there can be version conflicts, installing a package with dependencies needed by other packages can cause problems, so it's best not to push all packages a given user uses to the system install location.

  • If it is a single-user machine, there is little or no difference to installing to the --user location. It will be installed to a different folder, that may or may not need to be added to the path, depending on the package and how it's used (many packages install command-line tools that must be on the path to run from a shell).
  • If it is a multi-user machine, --user is preferred to using root/sudo or requiring administrator installation and affecting the Python environment of every user, except in cases of general packages that the administrator wants to make available to all users by default.
    • Note: Per comments, on most Unix/Linux installs it has been pointed out that system installs should use the general package manager, such as apt, rather than pip.

With Virtual Environments

The --user option in an active venv/virtualenv environment will install to the local user python location (same as without a virtual environment).

Packages are installed to the virtual environment by default, but if you use --user it will force it to install outside the virtual environments, in the users python script directory (in Windows, this currently is c:\users\<username>\appdata\roaming\python\python37\scripts for me with Python 3.7).

However, you won't be able to access a system or user install from within virtual environment (even if you used --user while in a virtual environment).

If you install a virtual environment with the --system-site-packages argument, you will have access to the system script folder for python. I believe this included the user python script folder as well, but I'm unsure. However, there may be unintended consequences for this and it is not the intended way to use virtual environments.


Location of the Python System and Local User Install Folders

You can find the location of the user install folder for python with python -m site --user-base. I'm finding conflicting information in Q&A's, the documentation and actually using this command on my PC as to what the defaults are, but they are underneath the user home directory (~ shortcut in *nix, and c:\users\<username> typically for Windows).


Other Details

The --user option is not a valid for every command. For example pip uninstall will find and uninstall packages wherever they were installed (in the user folder, virtual environment folder, etc.) and the --user option is not valid.

Things installed with pip install --user will be installed in a local location that will only be seen by the current user account, and will not require root access (on *nix) or administrator access (on Windows).

The --user option modifies all pip commands that accept it to see/operate on the user install folder, so if you use pip list --user it will only show you packages installed with pip install --user.

Concatenating multiple text files into a single file in Bash

You can do like this: cat [directory_path]/**/*.[h,m] > test.txt

if you use {} to include the extension of the files you want to find, there is a sequencing problem.

ERROR 2003 (HY000): Can't connect to MySQL server (111)

Not sure as cant see it in steps you mentioned.

Please try FLUSH PRIVILEGES [Reloads the privileges from the grant tables in the mysql database]:

flush privileges;

You need to execute it after GRANT

Hope this help!

Change a HTML5 input's placeholder color with CSS

I don't remember where I've found this code snippet on the Internet (it wasn't written by me, don't remember where I've found it, nor who wrote it).

$('[placeholder]').focus(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
            input.val('');
            input.removeClass('placeholder');
        }
    }).blur(function() {
        var input = $(this);
        if (input.val() == '' || input.val() == input.attr('placeholder')) {
            input.addClass('placeholder');
            input.val(input.attr('placeholder'));
        }
    }).blur();
    $('[placeholder]').parents('form').submit(function() {
        $(this).find('[placeholder]').each(function() {
            var input = $(this);
            if (input.val() == input.attr('placeholder')) {
                input.val('');
            }
        })
    });

Just load this JavaScript code and then edit your placeholder with CSS by calling this rule:

form .placeholder {
   color: #222;
   font-size: 25px;
   /* etc. */
}

Delete all files of specific type (extension) recursively down a directory using a batch file

If you are trying to delete certain .extensions in the C: drive use this cmd:

del /s c:\*.blaawbg

I had a customer that got a encryption virus and i needed to find all junk files and delete them.

C# Version Of SQL LIKE

As aready proposed in this answer and this other answer Microsoft.VisualBasic.CompilerServices.Operators.LikeString could be a good option for simple tasks, when a RegExp is overkill. Syntax is different from RegExp and SQL LIKE operator, but it's really simple to learn (mainly because it's also very limited).

Assembly Microsoft.VisualBasic must be added as a reference to the project to use this method.

For more information see Operators.LikeString Method and for a description of the syntax see Like Operator (Visual Basic).

It can be used as an extension method to String class:

/// <summary>
/// Visual Basic like operator. Performs simple, case insensitive, string pattern matching.
/// </summary>
/// <param name="thisString"></param>
/// <param name="pattern"> ? = Any single character. * = Zero or more characters. # = Any single digit (0–9)</param>
/// <returns>true if the string matches the pattern</returns>
public static bool Like(this string thisString, string pattern)
    => Microsoft.VisualBasic.CompilerServices.Operators
        .LikeString(thisString, pattern, Microsoft.VisualBasic.CompareMethod.Text);

How do I undo a checkout in git?

Try this first:

git checkout master

(If you're on a different branch than master, use the branch name there instead.)

If that doesn't work, try...

For a single file:

git checkout HEAD /path/to/file

For the entire repository working copy:

git reset --hard HEAD

And if that doesn't work, then you can look in the reflog to find your old head SHA and reset to that:

git reflog
git reset --hard <sha from reflog>

HEAD is a name that always points to the latest commit in your current branch.

How do you clear your Visual Studio cache on Windows Vista?

The accepted answer gave two locations:

here

C:\Documents and Settings\Administrator\Local Settings\Temp\VWDWebCache

and possibly here

C:\Documents and Settings\Administrator\Local Settings\Application Data\Microsoft\WebsiteCache

Did you try those?

Edited to add

On my Windows Vista machine, it's located in

%Temp%\VWDWebCache

and in

%LocalAppData%\Microsoft\WebsiteCache

From your additional information (regarding team edition) this comes from Clear Client TFS Cache:

Clear Client TFS Cache

Visual Studio and Team Explorer provide a caching mechanism which can get out of sync. If I have multiple instances of a single TFS which can be connected to from a single Visual Studio client, that client can become confused.

To solve it..

For Windows Vista delete contents of this folder

%LocalAppData%\Microsoft\Team Foundation\1.0\Cache

Get record counts for all tables in MySQL database

One more option: for non InnoDB it uses data from information_schema.TABLES (as it's faster), for InnoDB - select count(*) to get the accurate count. Also it ignores views.

SET @table_schema = DATABASE();
-- or SET @table_schema = 'my_db_name';

SET GROUP_CONCAT_MAX_LEN=131072;
SET @selects = NULL;

SELECT GROUP_CONCAT(
        'SELECT "', table_name,'" as TABLE_NAME, COUNT(*) as TABLE_ROWS FROM `', table_name, '`'
        SEPARATOR '\nUNION\n') INTO @selects
  FROM information_schema.TABLES
  WHERE TABLE_SCHEMA = @table_schema
        AND ENGINE = 'InnoDB'
        AND TABLE_TYPE = "BASE TABLE";

SELECT CONCAT_WS('\nUNION\n',
  CONCAT('SELECT TABLE_NAME, TABLE_ROWS FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND ENGINE <> "InnoDB" AND TABLE_TYPE = "BASE TABLE"'),
  @selects) INTO @selects;

PREPARE stmt FROM @selects;
EXECUTE stmt USING @table_schema;
DEALLOCATE PREPARE stmt;

If your database has a lot of big InnoDB tables counting all rows can take more time.

UNIX export command

export is a built-in command of the bash shell and other Bourne shell variants. It is used to mark a shell variable for export to child processes.

Difference between readFile() and readFileSync()

fs.readFile takes a call back which calls response.send as you have shown - good. If you simply replace that with fs.readFileSync, you need to be aware it does not take a callback so your callback which calls response.send will never get called and therefore the response will never end and it will timeout.

You need to show your readFileSync code if you're not simply replacing readFile with readFileSync.

Also, just so you're aware, you should never call readFileSync in a node express/webserver since it will tie up the single thread loop while I/O is performed. You want the node loop to process other requests until the I/O completes and your callback handling code can run.

Importing a csv into mysql via command line

I know this says command line, but just a tidbit of something quick to try that might work, if you've got MySQL workbench and the csv isn't too large, you can simply

  • SELECT * FROM table
  • Copy entire CSV
  • Paste csv into the query results section of Workbench
  • Hope for the best

I say hope for the best because this is MySQL Workbench. You never know when it's going to explode


If you want to do this on a remote server, you would do

mysql -h<server|ip> -u<username> -p --local-infile bark -e "LOAD DATA LOCAL INFILE '<filename.csv>'  INTO TABLE <table>  FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'"

Note, I didn't put a password after -p as putting one on the command line is considered bad practice

Subtract two variables in Bash

Use Python:

#!/bin/bash
# home/victoria/test.sh

START=$(date +"%s")                                     ## seconds since Epoch
for i in $(seq 1 10)
do
  sleep 1.5
  END=$(date +"%s")                                     ## integer
  TIME=$((END - START))                                 ## integer
  AVG_TIME=$(python -c "print(float($TIME/$i))")        ## int to float
  printf 'i: %i | elapsed time: %0.1f sec | avg. time: %0.3f\n' $i $TIME $AVG_TIME
  ((i++))                                               ## increment $i
done

Output

$ ./test.sh 
i: 1 | elapsed time: 1.0 sec | avg. time: 1.000
i: 2 | elapsed time: 3.0 sec | avg. time: 1.500
i: 3 | elapsed time: 5.0 sec | avg. time: 1.667
i: 4 | elapsed time: 6.0 sec | avg. time: 1.500
i: 5 | elapsed time: 8.0 sec | avg. time: 1.600
i: 6 | elapsed time: 9.0 sec | avg. time: 1.500
i: 7 | elapsed time: 11.0 sec | avg. time: 1.571
i: 8 | elapsed time: 12.0 sec | avg. time: 1.500
i: 9 | elapsed time: 14.0 sec | avg. time: 1.556
i: 10 | elapsed time: 15.0 sec | avg. time: 1.500
$

When should I use uuid.uuid1() vs. uuid.uuid4() in python?

My team just ran into trouble using UUID1 for a database upgrade script where we generated ~120k UUIDs within a couple of minutes. The UUID collision led to violation of a primary key constraint.

We've upgraded 100s of servers but on our Amazon EC2 instances we ran into this issue a few times. I suspect poor clock resolution and switching to UUID4 solved it for us.

is inaccessible due to its protection level

Dan, it's just you're accessing the protected field instead of properties.

See for example this line in your Main(...):

myClub.distance = Console.ReadLine();

myClub.distance is the protected field, while you wanted to set the property mydistance.

I'm just giving you some hint, I'm not going to correct your code, since this is homework! ;)

Console output in a Qt GUI app?

I also played with this, discovering that redirecting output worked, but I never saw output to the console window, which is present for every windows application. This is my solution so far, until I find a Qt replacement for ShowWindow and GetConsoleWindow.

Run this from a command prompt without parameters - get the window. Run from command prompt with parameters (eg. cmd aaa bbb ccc) - you get the text output on the command prompt window - just as you would expect for any Windows console app.

Please excuse the lame example - it represents about 30 minutes of tinkering.

#include "mainwindow.h"
#include <QTextStream>
#include <QCoreApplication>
#include <QApplication>
#include <QWidget>
#include <windows.h>

QT_USE_NAMESPACE

int main(int argc, char *argv[])
{
    if (argc > 1)   {
        // User has specified command-line arguments
        QCoreApplication a(argc, argv);
        QTextStream  out(stdout);
        int     i;

        ShowWindow (GetConsoleWindow(),SW_NORMAL);
        for (i=1; i<argc; i++)
             out << i << ':' << argv [i] << endl;
        out << endl << "Hello, World" << endl;
        out << "Application Directory Path:" << a.applicationDirPath() << endl;
        out << "Application File Path:" << a.applicationFilePath() << endl;
        MessageBox (0,(LPCWSTR)"Continue?",(LPCWSTR)"Silly Question",MB_YESNO);
        return 0;
    } else  {
        QApplication a(argc, argv);
        MainWindow w;

        w.setWindowTitle("Simple example");
        w.show();
        return a.exec();
    }
}

How to run Spring Boot web application in Eclipse itself?

You can also use the "Spring Boot App" run configuration. For that you'll need to install the Spring Tool Suite plug-in for Eclipse (STS).

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

You should probably stop using launch images in iOS 8 and use a storyboard or nib/xib.

  • In Xcode 6, open the File menu and choose New ? File... ? iOS ? User Interface ? Launch Screen.

  • Then open the settings for your project by clicking on it.

  • In the General tab, in the section called App Icons and Launch Images, set the Launch Screen File to the files you just created (this will set UILaunchStoryboardName in info.plist).

Note that for the time being the simulator will only show a black screen, so you need to test on a real device.

Adding a Launch Screen xib file to your project:

Adding a new Launch Screen xib file

Configuring your project to use the Launch Screen xib file instead of the Asset Catalog:

Configure project to use Launch Screen xob

Any way to write a Windows .bat file to kill processes?

Please find the below logic where it works on the condition.

If we simply call taskkill /im applicationname.exe, it will kill only if this process is running. If this process is not running, it will throw an error.

So as to check before takskill is called, a check can be done to make sure execute taskkill will be executed only if the process is running, so that it won't throw error.

tasklist /fi "imagename eq applicationname.exe" |find ":" > nul

if errorlevel 1 taskkill /f /im "applicationname.exe"

Populate dropdown select with array using jQuery

function validateForm(){
    var success = true;
    resetErrorMessages();
    var myArray = [];
    $(".linkedServiceDonationPurpose").each(function(){
        myArray.push($(this).val())
    });

    $(".linkedServiceDonationPurpose").each(function(){
    for ( var i = 0; i < myArray.length; i = i + 1 ) {
        for ( var j = i+1; j < myArray.length; j = j + 1 )
            if(myArray[i] == myArray[j] &&  $(this).val() == myArray[j]){
                $(this).next( "div" ).html('Duplicate item selected');
                success=false;
           }
        } 
    });
    if (success) {
        return true;
    } else {
        return false;
    }
    function resetErrorMessages() {
        $(".error").each(function(){
            $(this).html('');
        });``
    }
}

JPA: JOIN in JPQL

Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName 

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")
    .setParameter("groupName", groupName)
    .getSingleResult(); 
String fname = (String) temp[0];
String lname = (String) temp[1];

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... } 

How do I position one image on top of another in HTML?

It may be a little late but for this you can do:

enter image description here

HTML

<!-- html -->
<div class="images-wrapper">
  <img src="images/1" alt="image 1" />
  <img src="images/2" alt="image 2" />
  <img src="images/3" alt="image 3" />
  <img src="images/4" alt="image 4" />
</div>

SASS

// In _extra.scss
$maxImagesNumber: 5;

.images-wrapper {
  img {
    position: absolute;
    padding: 5px;
    border: solid black 1px;
  }

  @for $i from $maxImagesNumber through 1 {
    :nth-child(#{ $i }) {
      z-index: #{ $maxImagesNumber - ($i - 1) };
      left: #{ ($i - 1) * 30 }px;
    }
  }
}

background-size in shorthand background property (CSS3)

You will have to use vendor prefixes to support different browsers and therefore can't use it in shorthand.

body { 
        background: url(images/bg.jpg) no-repeat center center fixed; 
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
}

Representational state transfer (REST) and Simple Object Access Protocol (SOAP)

SOAP - Simple Object Access Protocol is a protocol!

REST - REpresentational State Transfer is an architectural style!

SOAP is an XML protocol used to transfer messages, typically over HTTP

REST and SOAP are arguably not mutually exclusive. A RESTful architecture might use HTTP or SOAP or some other communication protocol. REST is optimized for the web and thus HTTP is a perfect choice. HTTP is also the only protocol discussed in Roy Fielding's paper.

Although REST and SOAP are clearly very different, the question does illuminate the fact that REST and HTTP are often used in tandem. This is primarily due to the simplicity of HTTP and its very natural mapping to RESTful principles.

Fundamental REST Principles

Client-Server Communication

Client-server architectures have a very distinct separation of concerns. All applications built in the RESTful style must also be client-server in princple.

Stateless

Each each client request to the server requires that its state be fully represented. The server must be able to completely understand the client request without using any server context or server session state. It follows that all state must be kept on the client. We will discuss stateless representation in more detail later.

Cacheable

Cache constraints may be used, thus enabling response data to to be marked as cacheable or not-cachable. Any data marked as cacheable may be reused as the response to the same subsequent request.

Uniform Interface

All components must interact through a single uniform interface. Because all component interaction occurs via this interface, interaction with different services is very simple. The interface is the same! This also means that implementation changes can be made in isolation. Such changes, will not affect fundamental component interaction because the uniform interface is always unchanged. One disadvantage is that you are stuck with the interface. If an optimization could be provided to a specific service by changing the interface, you are out of luck as REST prohibits this. On the bright side, however, REST is optimized for the web, hence incredible popularity of REST over HTTP!

The above concepts represent defining characteristics of REST and differentiate the REST architecture from other architectures like web services. It is useful to note that a REST service is a web service, but a web service is not necessarily a REST service.

See this blog post on REST Design Principals for more details on REST and the above stated bullets.

"No resource identifier found for attribute 'showAsAction' in package 'android'"

From answer that was removed due to being written in Spanish:

All of the above fixes may not work in android studio. If you are using ANDROID STUDIO please use the following fix.

Use

xmlns: compat = "http://schemas.android.com/tools"

on the menu label instead of

xmlns: compat = "http://schemas.android.com/apk/res-auto"

Selecting empty text input using jQuery

$(":text[value='']").doStuff();

?

By the way, your call of:

$('input[id=cmdSubmit]')...

can be greatly simplified and speeded up with:

$('#cmdSubmit')...

Why won't my PHP app send a 404 error?

If you want the server’s default error page to be displayed, you have to handle this in the server.

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

For me changing the Jenkins version helped.

  <parent>
    <groupId>org.jenkins-ci.plugins</groupId>
    <artifactId>plugin</artifactId>
    <version>1.642.4</version><!-- which version of Jenkins is this plugin built against? -->
  </parent>

Authenticating against Active Directory with Java on Linux

If all you want to do is authenticate against AD using Kerberos, then a simple http://spnego.sourceforge.net/HelloKDC.java program should do it.

Take a look at the project's "pre-flight" documentation which talks about the HelloKDC.java program.

How to get multiple selected values from select box in JSP?

Since I don't find a simple answer just adding more this will be JSP page. save this content to a jsp file once you run you can see the values of the selected displayed.

Update: save the file as test.jsp and run it on any web/app server

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<%@ page import="java.lang.*" %>
<%@ page import="java.io.*" %>
<% String[] a = request.getParameterValues("multiple");
if(a!=null)
{
for(int i=0;i<a.length;i++){
//out.println(Integer.parseInt(a[i])); //If integer
out.println(a[i]);
}}
%>
<html>
<body>
<form action="test.jsp" method="get">
<select name="multiple" multiple="multiple"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>
<input type="submit">
</form>
</body>
</html>

How to create a file in memory for user to download, but not through server?

All of the above example works just fine in chrome and IE, but fail in Firefox. Please do consider appending an anchor to the body and removing it after click.

var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob(['Test,Text'], {type: 'text/csv'}));
a.download = 'test.csv';

// Append anchor to body.
document.body.appendChild(a);
a.click();

// Remove anchor from body
document.body.removeChild(a);

Perfect 100% width of parent container for a Bootstrap input?

If you're using C# ASP.NET MVC's default template you may find that site.css overrides some of Bootstraps styles. If you want to use Bootstrap, as I did, having M$ override this (without your knowledge) can be a source of great frustration! Feel free to remove any of the unwanted styles...

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

What is Node.js?

I think the advantages are:

  1. Web development in a dynamic language (JavaScript) on a VM that is incredibly fast (V8). It is much faster than Ruby, Python, or Perl.

  2. Ability to handle thousands of concurrent connections with minimal overhead on a single process.

  3. JavaScript is perfect for event loops with first class function objects and closures. People already know how to use it this way having used it in the browser to respond to user initiated events.

  4. A lot of people already know JavaScript, even people who do not claim to be programmers. It is arguably the most popular programming language.

  5. Using JavaScript on a web server as well as the browser reduces the impedance mismatch between the two programming environments which can communicate data structures via JSON that work the same on both sides of the equation. Duplicate form validation code can be shared between server and client, etc.

MySQL create stored procedure syntax with delimiter

Here is the sample MYSQL Stored Procedure with delimiter and how to call..

DELIMITER $$

DROP PROCEDURE IF EXISTS `sp_user_login` $$
CREATE DEFINER=`root`@`%` PROCEDURE `sp_user_login`(
  IN loc_username VARCHAR(255),
  IN loc_password VARCHAR(255)
)
BEGIN

  SELECT user_id,
         user_name,
         user_emailid,
         user_profileimage,
         last_update
    FROM tbl_user
   WHERE user_name = loc_username
     AND password = loc_password
     AND status = 1;

END $$

DELIMITER ;

and call by, mysql_connection specification and

$loginCheck="call sp_user_login('".$username."','".$password."');";

it will return the result from the procedure.

What is the difference between MacVim and regular Vim?

The one reason I have which made switching to MacVim worth it: Yank uses the system clipboard.

I can finally copy paste between MacVim on my terminal and the rest of my applications.

Hide element by class in pure Javascript

Array.filter( document.getElementsByClassName('appBanner'), function(elem){ elem.style.visibility = 'hidden'; });

Forked @http://jsfiddle.net/QVJXD/

Enum "Inheritance"

You can perform inheritance in enum, however it's limited to following types only . int, uint, byte, sbyte, short, ushort, long, ulong

E.g.

public enum Car:int{
Toyota,
Benz,
}

MS Access VBA: Sending an email through Outlook

Add a reference to the Outlook object model in the Visual Basic editor. Then you can use the code below to send an email using outlook.

Sub sendOutlookEmail()
Dim oApp As Outlook.Application
Dim oMail As MailItem
Set oApp = CreateObject("Outlook.application")

Set oMail = oApp.CreateItem(olMailItem)
oMail.Body = "Body of the email"
oMail.Subject = "Test Subject"
oMail.To = "[email protected]"
oMail.Send
Set oMail = Nothing
Set oApp = Nothing


End Sub

Spring boot - configure EntityManager

With Spring Boot its not necessary to have any config file like persistence.xml. You can configure with annotations Just configure your DB config for JPA in the

application.properties

spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@DB...
spring.datasource.username=username
spring.datasource.password=pass

spring.jpa.database-platform=org.hibernate.dialect....
spring.jpa.show-sql=true

Then you can use CrudRepository provided by Spring where you have standard CRUD transaction methods. There you can also implement your own SQL's like JPQL.

@Transactional
public interface ObjectRepository extends CrudRepository<Object, Long> {
...
}

And if you still need to use the Entity Manager you can create another class.

public class ObjectRepositoryImpl implements ObjectCustomMethods{

    @PersistenceContext
    private EntityManager em;

}

This should be in your pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.5.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.11.Final</version>
    </dependency>
</dependencies>

Radio button validation in javascript

You could do something like this

var option=document.getElementsByName('Gender');

if (!(option[0].checked || option[1].checked)) {
    alert("Please Select Your Gender");
    return false;
}

Is it not possible to define multiple constructors in Python?

If your signatures differ only in the number of arguments, using default arguments is the right way to do it. If you want to be able to pass in different kinds of argument, I would try to avoid the isinstance-based approach mentioned in another answer, and instead use keyword arguments.

If using just keyword arguments becomes unwieldy, you can combine it with classmethods (the bzrlib code likes this approach). This is just a silly example, but I hope you get the idea:

class C(object):

    def __init__(self, fd):
        # Assume fd is a file-like object.
        self.fd = fd

    @classmethod
    def fromfilename(cls, name):
        return cls(open(name, 'rb'))

# Now you can do:
c = C(fd)
# or:
c = C.fromfilename('a filename')

Notice all those classmethods still go through the same __init__, but using classmethods can be much more convenient than having to remember what combinations of keyword arguments to __init__ work.

isinstance is best avoided because Python's duck typing makes it hard to figure out what kind of object was actually passed in. For example: if you want to take either a filename or a file-like object you cannot use isinstance(arg, file), because there are many file-like objects that do not subclass file (like the ones returned from urllib, or StringIO, or...). It's usually a better idea to just have the caller tell you explicitly what kind of object was meant, by using different keyword arguments.

select into in mysql

Use the CREATE TABLE SELECT syntax.

http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html

CREATE TABLE new_tbl SELECT * FROM orig_tbl;

How to read a list of files from a folder using PHP?

<html>
<head>
<title>Names</title>
</head>
<body style="background-color:powderblue;">

<form method='post' action='alex.php'>
 <input type='text' name='name'>
<input type='submit' value='name'>
</form>
Enter Name:
<?php

  if($_POST)
  {
  $Name = $_POST['name'];
  $count = 0;
  $fh=fopen("alex.txt",'a+') or die("failed to create");
  while(!feof($fh))
  {
    $line = chop(fgets($fh));
    if($line==$Name && $line!="")
    $count=1;
  }
  if($count==0 && $Name!="")
  {
    fwrite($fh, "\r\n$Name"); 
 }
  else if($count!=0 && $line!="") 
  { 
    echo '<font color="red">'.$Name.', the name you entered is already in the list.</font><br><br>';
  }
  $count=0;
  fseek($fh, 0);
  while(!feof($fh))
  {
    $a = chop(fgets($fh));
    echo $a.'<br>';
    $count++;
  }
  if($count<=1)
  echo '<br>There are no names in the list<br>';
  fclose($fh);
  }
?>
</body>
</html>

What are the benefits to marking a field as `readonly` in C#?

Be careful with private readonly arrays. If these are exposed a client as an object (you might do this for COM interop as I did) the client can manipulate array values. Use the Clone() method when returning an array as an object.

How can I produce an effect similar to the iOS 7 blur view?

This is a solution that you can see in the vidios of the WWDC. You have to do a Gaussian Blur, so the first thing you have to do is to add a new .m and .h file with the code i'm writing here, then you have to make and screen shoot, use the desired effect and add it to your view, then your UITable UIView or what ever has to be transparent, you can play with applyBlurWithRadius, to archive the desired effect, this call works with any UIImage.

At the end the blured image will be the background and the rest of the controls above has to be transparent.

For this to work you have to add the next libraries:

Acelerate.framework,UIKit.framework,CoreGraphics.framework

I hope you like it.

Happy coding.

    //Screen capture.
    UIGraphicsBeginImageContext(self.view.bounds.size);

    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(c, 0, 0);
    [self.view.layer renderInContext:c];

    UIImage* viewImage = UIGraphicsGetImageFromCurrentImageContext();
    viewImage = [viewImage applyLightEffect];

    UIGraphicsEndImageContext();

    //.h FILE
    #import <UIKit/UIKit.h>

    @interface UIImage (ImageEffects)

   - (UIImage *)applyLightEffect;
   - (UIImage *)applyExtraLightEffect;
   - (UIImage *)applyDarkEffect;
   - (UIImage *)applyTintEffectWithColor:(UIColor *)tintColor;

   - (UIImage *)applyBlurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage;

   @end

    //.m FILE
    #import "cGaussianEffect.h"
    #import <Accelerate/Accelerate.h>
    #import <float.h>


     @implementation UIImage (ImageEffects)


    - (UIImage *)applyLightEffect
    {
        UIColor *tintColor = [UIColor colorWithWhite:1.0 alpha:0.3];
        return [self applyBlurWithRadius:1 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
    }


    - (UIImage *)applyExtraLightEffect
    {
        UIColor *tintColor = [UIColor colorWithWhite:0.97 alpha:0.82];
        return [self applyBlurWithRadius:1 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
    }


    - (UIImage *)applyDarkEffect
    {
        UIColor *tintColor = [UIColor colorWithWhite:0.11 alpha:0.73];
        return [self applyBlurWithRadius:1 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
    }


    - (UIImage *)applyTintEffectWithColor:(UIColor *)tintColor
    {
        const CGFloat EffectColorAlpha = 0.6;
        UIColor *effectColor = tintColor;
        int componentCount = CGColorGetNumberOfComponents(tintColor.CGColor);
        if (componentCount == 2) {
            CGFloat b;
            if ([tintColor getWhite:&b alpha:NULL]) {
                effectColor = [UIColor colorWithWhite:b alpha:EffectColorAlpha];
            }
        }
        else {
            CGFloat r, g, b;
            if ([tintColor getRed:&r green:&g blue:&b alpha:NULL]) {
                effectColor = [UIColor colorWithRed:r green:g blue:b alpha:EffectColorAlpha];
            }
        }
        return [self applyBlurWithRadius:10 tintColor:effectColor saturationDeltaFactor:-1.0 maskImage:nil];
    }


    - (UIImage *)applyBlurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage
    {
        if (self.size.width < 1 || self.size.height < 1) {
            NSLog (@"*** error: invalid size: (%.2f x %.2f). Both dimensions must be >= 1: %@", self.size.width, self.size.height, self);
            return nil;
        }
        if (!self.CGImage) {
            NSLog (@"*** error: image must be backed by a CGImage: %@", self);
            return nil;
        }
        if (maskImage && !maskImage.CGImage) {
            NSLog (@"*** error: maskImage must be backed by a CGImage: %@", maskImage);
            return nil;
        }

        CGRect imageRect = { CGPointZero, self.size };
        UIImage *effectImage = self;

        BOOL hasBlur = blurRadius > __FLT_EPSILON__;
        BOOL hasSaturationChange = fabs(saturationDeltaFactor - 1.) > __FLT_EPSILON__;
        if (hasBlur || hasSaturationChange) {
            UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
            CGContextRef effectInContext = UIGraphicsGetCurrentContext();
            CGContextScaleCTM(effectInContext, 1.0, -1.0);
            CGContextTranslateCTM(effectInContext, 0, -self.size.height);
            CGContextDrawImage(effectInContext, imageRect, self.CGImage);

            vImage_Buffer effectInBuffer;
            effectInBuffer.data     = CGBitmapContextGetData(effectInContext);
            effectInBuffer.width    = CGBitmapContextGetWidth(effectInContext);
            effectInBuffer.height   = CGBitmapContextGetHeight(effectInContext);
            effectInBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectInContext);

            UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
            CGContextRef effectOutContext = UIGraphicsGetCurrentContext();
            vImage_Buffer effectOutBuffer;
            effectOutBuffer.data     = CGBitmapContextGetData(effectOutContext);
            effectOutBuffer.width    = CGBitmapContextGetWidth(effectOutContext);
            effectOutBuffer.height   = CGBitmapContextGetHeight(effectOutContext);
            effectOutBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectOutContext);

            if (hasBlur) {
                CGFloat inputRadius = blurRadius * [[UIScreen mainScreen] scale];
                NSUInteger radius = floor(inputRadius * 3. * sqrt(2 * M_PI) / 4 + 0.5);
                if (radius % 2 != 1) {
                    radius += 1;
                }
                vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
                vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
                vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
            }
            BOOL effectImageBuffersAreSwapped = NO;
            if (hasSaturationChange) {
                CGFloat s = saturationDeltaFactor;
                CGFloat floatingPointSaturationMatrix[] = {
                    0.0722 + 0.9278 * s,  0.0722 - 0.0722 * s,  0.0722 - 0.0722 * s,  0,
                    0.7152 - 0.7152 * s,  0.7152 + 0.2848 * s,  0.7152 - 0.7152 * s,  0,
                    0.2126 - 0.2126 * s,  0.2126 - 0.2126 * s,  0.2126 + 0.7873 * s,  0,
                                  0,                    0,                    0,  1,
                };
                const int32_t divisor = 256;
                NSUInteger matrixSize = sizeof(floatingPointSaturationMatrix)/sizeof(floatingPointSaturationMatrix[0]);
                int16_t saturationMatrix[matrixSize];
                for (NSUInteger i = 0; i < matrixSize; ++i) {
                    saturationMatrix[i] = (int16_t)roundf(floatingPointSaturationMatrix[i] * divisor);
                }
                if (hasBlur) {
                    vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
                    effectImageBuffersAreSwapped = YES;
                }
                else {
                    vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
                }
            }
            if (!effectImageBuffersAreSwapped)
                effectImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();

            if (effectImageBuffersAreSwapped)
                effectImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }

        UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
        CGContextRef outputContext = UIGraphicsGetCurrentContext();
        CGContextScaleCTM(outputContext, 1.0, -1.0);
        CGContextTranslateCTM(outputContext, 0, -self.size.height);

        CGContextDrawImage(outputContext, imageRect, self.CGImage);

        if (hasBlur) {
            CGContextSaveGState(outputContext);
            if (maskImage) {
                CGContextClipToMask(outputContext, imageRect, maskImage.CGImage);
            }
            CGContextDrawImage(outputContext, imageRect, effectImage.CGImage);
            CGContextRestoreGState(outputContext);
        }

        if (tintColor) {
            CGContextSaveGState(outputContext);
            CGContextSetFillColorWithColor(outputContext, tintColor.CGColor);
            CGContextFillRect(outputContext, imageRect);
            CGContextRestoreGState(outputContext);
        }

        UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        return outputImage;
    }

Enable remote connections for SQL Server Express 2012

I had to add a firewall inbound port rule to open UDP port 1434. This is the one Sql Server Browser listens on.

Writing to a TextBox from another thread?

Here is the what I have done to avoid CrossThreadException and writing to the textbox from another thread.

Here is my Button.Click function- I want to generate a random number of threads and then get their IDs by calling the getID() method and the TextBox value while being in that worker thread.

private void btnAppend_Click(object sender, EventArgs e) 
{
    Random n = new Random();

    for (int i = 0; i < n.Next(1,5); i++)
    {
        label2.Text = "UI Id" + ((Thread.CurrentThread.ManagedThreadId).ToString());
        Thread t = new Thread(getId);
        t.Start();
    }
}

Here is getId (workerThread) code:

public void getId()
{
    int id = Thread.CurrentThread.ManagedThreadId;
    //Note that, I have collected threadId just before calling this.Invoke
    //method else it would be same as of UI thread inside the below code block 
    this.Invoke((MethodInvoker)delegate ()
    {
        inpTxt.Text += "My id is" +"--"+id+Environment.NewLine; 
    });
}

How can I get a first element from a sorted list?

If you just want to get the minimum of a list, instead of sorting it and then getting the first element (O(N log N)), you can use do it in linear time using min:

<T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll)

That looks gnarly at first, but looking at your previous questions, you have a List<String>. In short: min works on it.

For the long answer: all that super and extends stuff in the generic type constraints is what Josh Bloch calls the PECS principle (usually presented next to a picture of Arnold -- I'M NOT KIDDING!)

Producer Extends, Consumer Super

It essentially makes generics more powerful, since the constraints are more flexible while still preserving type safety (see: what is the difference between ‘super’ and ‘extends’ in Java Generics)

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Git is a version control system; think of it as a series of snapshots (commits) of your code. You see a path of these snapshots, in which order they where created. You can make branches to experiment and come back to snapshots you took.

    GitHub, is a web-page on which you can publish your Git repositories and collaborate with other people.

  2. Is Git saving every repository locally (in the user's machine) and in GitHub?

    No, it's only local. You can decide to push (publish) some branches on GitHub.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    Yes, Git runs local if you don't use GitHub. An alternative to using GitHub could be running Git on files hosted on Dropbox, but GitHub is a more streamlined service as it was made especially for Git.

  4. How does Git compare to a backup system such as Time Machine?

    It's a different thing, Git lets you track changes and your development process. If you use Git with GitHub, it becomes effectively a backup. However usually you would not push all the time to GitHub, at which point you do not have a full backup if things go wrong. I use git in a folder that is synchronized with Dropbox.

  5. Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?

    Yes, committing and pushing are both manual.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    • If you encounter an error between commits you can use the command git diff to see the differences between the current code and the last working commit, helping you to locate your error.

    • You can also just go back to the last working commit.

    • If you want to try a change, but are not sure that it will work. You create a branch to test you code change. If it works fine, you merge it to the main branch. If it does not you just throw the branch away and go back to the main branch.

    • You did some debugging. Before you commit you always look at the changes from the last commit. You see your debug print statement that you forgot to delete.

Make sure you check gitimmersion.com.

mysql error 1364 Field doesn't have a default values

Run mysql console:

mysql -u your_username -p

, select database:

USE your_database;

and run (also from mysql console):

SET GLOBAL sql_mode='';

That will turn off strict mode and mysql won't complain any more.

To make things clear: your database definition says "this field must have default value defined", and by doing steps from above you say to MySql "neah, just ignore it". So if you just want to do some quick fix locally this solution is ok. But generally you should investigate in your database definition and check if field really needs default value and if so set it. And if default value is not needed this requirement should be removed to have clean situation.

Converting HTML to PDF using PHP?

If you wish to create a pdf from php, pdflib will help you (as some others suggested).

Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.

So, the options I know are:

DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.

HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.

Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:

wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.

htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.

Generate random colors (RGB)

import random
rgb_full="(" + str(random.randint(1,256))  + "," + str(random.randint(1,256))  + "," + str(random.randint(1,256))  + ")"

How to reset (clear) form through JavaScript?

You could use the following:

$('[element]').trigger('reset')

Get size of folder or file

  • Works for Android and Java
  • Works for both folders and files
  • Checks for null pointer everywhere where needed
  • Ignores symbolic link aka shortcuts
  • Production ready!

Source code:

   public long fileSize(File root) {
        if(root == null){
            return 0;
        }
        if(root.isFile()){
            return root.length();
        }
        try {
            if(isSymlink(root)){
                return 0;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }

        long length = 0;
        File[] files = root.listFiles();
        if(files == null){
            return 0;
        }
        for (File file : files) {
            length += fileSize(file);
        }

        return length;
    }

    private static boolean isSymlink(File file) throws IOException {
        File canon;
        if (file.getParent() == null) {
            canon = file;
        } else {
            File canonDir = file.getParentFile().getCanonicalFile();
            canon = new File(canonDir, file.getName());
        }
        return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
    }

How to sort mongodb with pymongo

Say, you want to sort by 'created_on' field, then you can do like this,

.sort('{}'.format('created_on'), 1 if sort_type == 'asc' else -1)

Convert hex color value ( #ffffff ) to integer value

I have the same problem that I found some color in form of #AAAAAA and I want to conver that into a form that android could make use of. I found that you can just use 0xFFAAAAAA so that android could automatically tell the color. Notice the first FF is telling alpha value. Hope it helps

Multiple variables in a 'with' statement?

Note that if you split the variables into lines, you must use backslashes to wrap the newlines.

with A() as a, \
     B() as b, \
     C() as c:
    doSomething(a,b,c)

Parentheses don't work, since Python creates a tuple instead.

with (A(),
      B(),
      C()):
    doSomething(a,b,c)

Since tuples lack a __enter__ attribute, you get an error (undescriptive and does not identify class type):

AttributeError: __enter__

If you try to use as within parentheses, Python catches the mistake at parse time:

with (A() as a,
      B() as b,
      C() as c):
    doSomething(a,b,c)
SyntaxError: invalid syntax

When will this be fixed?

This issue is tracked in https://bugs.python.org/issue12782.

Recently, Python announced in PEP 617 that they'll be replacing the current parser with a new one. Because Python's current parser is LL(1), it cannot distinguish between "multiple context managers" with (A(), B()): and "tuple of values" with (A(), B())[0]:.

The new parser can properly parse "multiple context managers" surrounded by tuples. The new parser will be enabled in 3.9, but this syntax will still be rejected until the old parser is removed in Python 3.10.

What port number does SOAP use?

SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.

One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.

so exclusively open SOAP Port in Firewalls

Array versus List<T>: When to use which?

It completely depends on the contexts in which the data structure is needed. For example, if you are creating items to be used by other functions or services using List is the perfect way to accomplish it.

Now if you have a list of items and you just want to display them, say on a web page array is the container you need to use.

How to know a Pod's own IP address from inside a container in the Pod?

The container's IP address should be properly configured inside of its network namespace, so any of the standard linux tools can get it. For example, try ifconfig, ip addr show, hostname -I, etc. from an attached shell within one of your containers to test it out.

How to install the Six module in Python2.7

here's what six is:

pip search six
six                       - Python 2 and 3 compatibility utilities

to install:

pip install six

though if you did install python-dateutil from pip six should have been set as a dependency.

N.B.: to install pip run easy_install pip from command line.

Integrating MySQL with Python in Windows

This may read like your grandpa givin advice, but all answers here did not mention the best way: go nd install ActivePython instead of python.org windows binaries. I was really wondering for a long time why Python development on windows was such a pita - until I installed activestate python. I am not affiliated with them. It is just the plain truth. Write it on every wall: Python development on Windows = ActiveState! you then just pypm install mysql-python and everything works smoothly. no compile orgy. no strange errors. no terror. Just start coding and doing real work after five minutes. This is the only way to go on windows. Really.

Specified cast is not valid.. how to resolve this

If you are expecting double, decimal, float, integer why not use the one which accomodates all namely decimal (128 bits are enough for most numbers you are looking at).

instead of (double)value use decimal.Parse(value.ToString()) or Convert.ToDecimal(value)

How to create a sub array from another array in Java?

You can use

JDK > 1.5

Arrays.copyOfRange(Object[] src, int from, int to)

Javadoc

JDK <= 1.5

System.arraycopy(Object[] src, int srcStartIndex, Object[] dest, int dstStartIndex, int lengthOfCopiedIndices); 

Javadoc

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

VS Code - Search for text in all files in a directory

This action is not bound to a key by default, to bind it do this:

  1. File > Preferences > Keyboard Shortcuts (Ctrl+K, Ctrl+S)
  2. Search for "find folder"
  3. Press the + icon on the left of "filesExplorer.findInFolder" search result
  4. Enter your desired key combination

Add error bars to show standard deviation on a plot in R

You can use segments to add the bars in base graphics. Here epsilon controls the line across the top and bottom of the line.

plot (x, y, ylim=c(0, 6))
epsilon = 0.02
for(i in 1:5) {
    up = y[i] + sd[i]
    low = y[i] - sd[i]
    segments(x[i],low , x[i], up)
    segments(x[i]-epsilon, up , x[i]+epsilon, up)
    segments(x[i]-epsilon, low , x[i]+epsilon, low)
}

As @thelatemail points out, I should really have used vectorised function calls:

segments(x, y-sd,x, y+sd)
epsilon = 0.02
segments(x-epsilon,y-sd,x+epsilon,y-sd)
segments(x-epsilon,y+sd,x+epsilon,y+sd)

enter image description here

How do C++ class members get initialized if I don't do it explicitly?

If it is on the stack, the contents of uninitialized members that don't have their own constructor will be random and undefined. Even if it is global, it would be a bad idea to rely on them being zeroed out. Whether it is on the stack or not, if a member has its own constructor, that will get called to initialize it.

So, if you have string* pname, the pointer will contain random junk. but for string name, the default constructor for string will be called, giving you an empty string. For your reference type variables, I'm not sure, but it'll probably be a reference to some random chunk of memory.

jQuery-UI datepicker default date

You can try with the code that is below.

It will make the default date become the date you are looking for.

$('#birthdate').datepicker("setDate", new Date(1985,01,01) );

Left/Right float button inside div

You can use justify-content: space-between in .test like so:

_x000D_
_x000D_
.test {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  width: 20rem;_x000D_
  border: .1rem red solid;_x000D_
}
_x000D_
<div class="test">_x000D_
  <button>test</button>_x000D_
  <button>test</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_


For those who want to use Bootstrap 4 can use justify-content-between:

_x000D_
_x000D_
div {_x000D_
  width: 20rem;_x000D_
  border: .1rem red solid;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="d-flex justify-content-between">_x000D_
  <button>test</button>_x000D_
  <button>test</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Java: how do I get a class literal from a generic type?

Due to the exposed fact that Class literals doesn't have generic type information, I think you should assume that it will be impossible to get rid of all the warnings. In a way, using Class<Something> is the same as using a collection without specifying the generic type. The best I could come out with was:

private <C extends A<C>> List<C> getList(Class<C> cls) {
    List<C> res = new ArrayList<C>();
    // "snip"... some stuff happening in here, using cls
    return res;
}

public <C extends A<C>> List<A<C>> getList() {
    return getList(A.class);
}

Remove android default action bar

I've noticed that if you set the theme in the AndroidManifest, it seems to get rid of that short time where you can see the action bar. So, try adding this to your manifest:

<android:theme="@android:style/Theme.NoTitleBar">

Just add it to your application tag to apply it app-wide.

Set Matplotlib colorbar size to match graph

This combination (and values near to these) seems to "magically" work for me to keep the colorbar scaled to the plot, no matter what size the display.

plt.colorbar(im,fraction=0.046, pad=0.04)

It also does not require sharing the axis which can get the plot out of square.

What is the best way to manage a user's session in React?

There is a React module called react-client-session that makes storing client side session data very easy. The git repo is here.

This is implemented in a similar way as the closure approach in my other answer, however it also supports persistence using 3 different persistence stores. The default store is memory(not persistent).

  1. Cookie
  2. localStorage
  3. sessionStorage

After installing, just set the desired store type where you mount the root component ...

import ReactSession from 'react-client-session';

ReactSession.setStoreType("localStorage");

... and set/get key value pairs from anywhere in your app:

import ReactSession from 'react-client-session';

ReactSession.set("username", "Bob");
ReactSession.get("username");  // Returns "Bob"

Code for download video from Youtube on Java, Android

Ref : Youtube Video Download (Android/Java)

private static final HashMap<String, Meta> typeMap = new HashMap<String, Meta>();

initTypeMap(); call first

class Meta {
    public String num;
    public String type;
    public String ext;

    Meta(String num, String ext, String type) {
        this.num = num;
        this.ext = ext;
        this.type = type;
    }
}

class Video {
    public String ext = "";
    public String type = "";
    public String url = "";

    Video(String ext, String type, String url) {
        this.ext = ext;
        this.type = type;
        this.url = url;
    }
}

public ArrayList<Video> getStreamingUrisFromYouTubePage(String ytUrl)
        throws IOException {
    if (ytUrl == null) {
        return null;
    }

    // Remove any query params in query string after the watch?v=<vid> in
    // e.g.
    // http://www.youtube.com/watch?v=0RUPACpf8Vs&feature=youtube_gdata_player
    int andIdx = ytUrl.indexOf('&');
    if (andIdx >= 0) {
        ytUrl = ytUrl.substring(0, andIdx);
    }

    // Get the HTML response
    /* String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1)";*/
   /* HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
            userAgent);
    HttpGet request = new HttpGet(ytUrl);
    HttpResponse response = client.execute(request);*/
    String html = "";
    HttpsURLConnection c = (HttpsURLConnection) new URL(ytUrl).openConnection();
    c.setRequestMethod("GET");
    c.setDoOutput(true);
    c.connect();
    InputStream in = c.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder str = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        str.append(line.replace("\\u0026", "&"));
    }
    in.close();
    html = str.toString();

    // Parse the HTML response and extract the streaming URIs
    if (html.contains("verify-age-thumb")) {
        Log.e("Downloader", "YouTube is asking for age verification. We can't handle that sorry.");
        return null;
    }

    if (html.contains("das_captcha")) {
        Log.e("Downloader", "Captcha found, please try with different IP address.");
        return null;
    }

    Pattern p = Pattern.compile("stream_map\":\"(.*?)?\"");
    // Pattern p = Pattern.compile("/stream_map=(.[^&]*?)\"/");
    Matcher m = p.matcher(html);
    List<String> matches = new ArrayList<String>();
    while (m.find()) {
        matches.add(m.group());
    }

    if (matches.size() != 1) {
        Log.e("Downloader", "Found zero or too many stream maps.");
        return null;
    }

    String urls[] = matches.get(0).split(",");
    HashMap<String, String> foundArray = new HashMap<String, String>();
    for (String ppUrl : urls) {
        String url = URLDecoder.decode(ppUrl, "UTF-8");
        Log.e("URL","URL : "+url);

        Pattern p1 = Pattern.compile("itag=([0-9]+?)[&]");
        Matcher m1 = p1.matcher(url);
        String itag = null;
        if (m1.find()) {
            itag = m1.group(1);
        }

        Pattern p2 = Pattern.compile("signature=(.*?)[&]");
        Matcher m2 = p2.matcher(url);
        String sig = null;
        if (m2.find()) {
            sig = m2.group(1);
        } else {
            Pattern p23 = Pattern.compile("signature&s=(.*?)[&]");
            Matcher m23 = p23.matcher(url);
            if (m23.find()) {
                sig = m23.group(1);
            }
        }

        Pattern p3 = Pattern.compile("url=(.*?)[&]");
        Matcher m3 = p3.matcher(ppUrl);
        String um = null;
        if (m3.find()) {
            um = m3.group(1);
        }

        if (itag != null && sig != null && um != null) {
            Log.e("foundArray","Adding Value");
            foundArray.put(itag, URLDecoder.decode(um, "UTF-8") + "&"
                    + "signature=" + sig);
        }
    }
    Log.e("foundArray","Size : "+foundArray.size());
    if (foundArray.size() == 0) {
        Log.e("Downloader", "Couldn't find any URLs and corresponding signatures");
        return null;
    }


    ArrayList<Video> videos = new ArrayList<Video>();

    for (String format : typeMap.keySet()) {
        Meta meta = typeMap.get(format);

        if (foundArray.containsKey(format)) {
            Video newVideo = new Video(meta.ext, meta.type,
                    foundArray.get(format));
            videos.add(newVideo);
            Log.d("Downloader", "YouTube Video streaming details: ext:" + newVideo.ext
                    + ", type:" + newVideo.type + ", url:" + newVideo.url);
        }
    }

    return videos;
}

private class YouTubePageStreamUriGetter extends AsyncTask<String, String, ArrayList<Video>> {
    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = ProgressDialog.show(webViewActivity.this, "",
                "Connecting to YouTube...", true);
    }

    @Override
    protected ArrayList<Video> doInBackground(String... params) {
        ArrayList<Video> fVideos = new ArrayList<>();
        String url = params[0];
        try {
            ArrayList<Video> videos = getStreamingUrisFromYouTubePage(url);
            /*                Log.e("Downloader","Size of Video : "+videos.size());*/
            if (videos != null && !videos.isEmpty()) {
                for (Video video : videos)
                {
                    Log.e("Downloader", "ext : " + video.ext);
                    if (video.ext.toLowerCase().contains("mp4") || video.ext.toLowerCase().contains("3gp") || video.ext.toLowerCase().contains("flv") || video.ext.toLowerCase().contains("webm")) {
                        ext = video.ext.toLowerCase();
                        fVideos.add(new Video(video.ext,video.type,video.url));
                    }
                }


                return fVideos;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Downloader", "Couldn't get YouTube streaming URL", e);
        }
        Log.e("Downloader", "Couldn't get stream URI for " + url);
        return null;
    }

    @Override
    protected void onPostExecute(ArrayList<Video> streamingUrl) {
        super.onPostExecute(streamingUrl);
        progressDialog.dismiss();
        if (streamingUrl != null) {
            if (!streamingUrl.isEmpty()) {
                //Log.e("Steaming Url", "Value : " + streamingUrl);

                for (int i = 0; i < streamingUrl.size(); i++) {
                    Video fX = streamingUrl.get(i);
                    Log.e("Founded Video", "URL : " + fX.url);
                    Log.e("Founded Video", "TYPE : " + fX.type);
                    Log.e("Founded Video", "EXT : " + fX.ext);
                }
                //new ProgressBack().execute(new String[]{streamingUrl, filename + "." + ext});
            }
        }
    }
}
public void initTypeMap()
{
    typeMap.put("13", new Meta("13", "3GP", "Low Quality - 176x144"));
    typeMap.put("17", new Meta("17", "3GP", "Medium Quality - 176x144"));
    typeMap.put("36", new Meta("36", "3GP", "High Quality - 320x240"));
    typeMap.put("5", new Meta("5", "FLV", "Low Quality - 400x226"));
    typeMap.put("6", new Meta("6", "FLV", "Medium Quality - 640x360"));
    typeMap.put("34", new Meta("34", "FLV", "Medium Quality - 640x360"));
    typeMap.put("35", new Meta("35", "FLV", "High Quality - 854x480"));
    typeMap.put("43", new Meta("43", "WEBM", "Low Quality - 640x360"));
    typeMap.put("44", new Meta("44", "WEBM", "Medium Quality - 854x480"));
    typeMap.put("45", new Meta("45", "WEBM", "High Quality - 1280x720"));
    typeMap.put("18", new Meta("18", "MP4", "Medium Quality - 480x360"));
    typeMap.put("22", new Meta("22", "MP4", "High Quality - 1280x720"));
    typeMap.put("37", new Meta("37", "MP4", "High Quality - 1920x1080"));
    typeMap.put("33", new Meta("38", "MP4", "High Quality - 4096x230"));
}

Edit 2:

Some time This Code Not worked proper

Same-origin policy

https://en.wikipedia.org/wiki/Same-origin_policy

https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

problem of Same-origin policy. Essentially, you cannot download this file from www.youtube.com because they are different domains. A workaround of this problem is [CORS][1]. 

Ref : https://superuser.com/questions/773719/how-do-all-of-these-save-video-from-youtube-services-work/773998#773998

url_encoded_fmt_stream_map // traditional: contains video and audio stream
adaptive_fmts              // DASH: contains video or audio stream

Each of these is a comma separated array of what I would call "stream objects". Each "stream object" will contain values like this

url  // direct HTTP link to a video
itag // code specifying the quality
s    // signature, security measure to counter downloading

Each URL will be encoded so you will need to decode them. Now the tricky part.

YouTube has at least 3 security levels for their videos

unsecured // as expected, you can download these with just the unencoded URL
s         // see below
RTMPE     // uses "rtmpe://" protocol, no known method for these

The RTMPE videos are typically used on official full length movies, and are protected with SWF Verification Type 2. This has been around since 2011 and has yet to be reverse engineered.

The type "s" videos are the most difficult that can actually be downloaded. You will typcially see these on VEVO videos and the like. They start with a signature such as

AA5D05FA7771AD4868BA4C977C3DEAAC620DE020E.0F421820F42978A1F8EAFCDAC4EF507DB5 Then the signature is scrambled with a function like this

function mo(a) {
  a = a.split("");
  a = lo.rw(a, 1);
  a = lo.rw(a, 32);
  a = lo.IC(a, 1);
  a = lo.wS(a, 77);
  a = lo.IC(a, 3);
  a = lo.wS(a, 77);
  a = lo.IC(a, 3);
  a = lo.wS(a, 44);
  return a.join("")
}

This function is dynamic, it typically changes every day. To make it more difficult the function is hosted at a URL such as

http://s.ytimg.com/yts/jsbin/html5player-en_US-vflycBCEX.js

this introduces the problem of Same-origin policy. Essentially, you cannot download this file from www.youtube.com because they are different domains. A workaround of this problem is CORS. With CORS, s.ytimg.com could add this header

Access-Control-Allow-Origin: http://www.youtube.com

and it would allow the JavaScript to download from www.youtube.com. Of course they do not do this. A workaround for this workaround is to use a CORS proxy. This is a proxy that responds with the following header to all requests

Access-Control-Allow-Origin: *

So, now that you have proxied your JS file, and used the function to scramble the signature, you can use that in the querystring to download a video.

How do I enable NuGet Package Restore in Visual Studio?

Helped me through Tools >>> Nuget Package Manager >>> General then tick option Allow Nuget to download missing package and Automatically check for missing packages during build in visual studio.

enter image description here

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"defer</script>

Add Defer to the end of your Script tag, it worked for me (;

Everything needs to be loaded in the correct order (:

Bad operand type for unary +: 'str'

You say that if int(splitLine[0]) > int(lastUnix): is causing the trouble, but you don't actually show anything which suggests that. I think this line is the problem instead:

print 'Pulled', + stock

Do you see why this line could cause that error message? You want either

>>> stock = "AAAA"
>>> print 'Pulled', stock
Pulled AAAA

or

>>> print 'Pulled ' + stock
Pulled AAAA

not

>>> print 'Pulled', + stock
PulledTraceback (most recent call last):
  File "<ipython-input-5-7c26bb268609>", line 1, in <module>
    print 'Pulled', + stock
TypeError: bad operand type for unary +: 'str'

You're asking Python to apply the + symbol to a string like +23 makes a positive 23, and she's objecting.

Distinct() with lambda?

You can use InlineComparer

public class InlineComparer<T> : IEqualityComparer<T>
{
    //private readonly Func<T, T, bool> equalsMethod;
    //private readonly Func<T, int> getHashCodeMethod;
    public Func<T, T, bool> EqualsMethod { get; private set; }
    public Func<T, int> GetHashCodeMethod { get; private set; }

    public InlineComparer(Func<T, T, bool> equals, Func<T, int> hashCode)
    {
        if (equals == null) throw new ArgumentNullException("equals", "Equals parameter is required for all InlineComparer instances");
        EqualsMethod = equals;
        GetHashCodeMethod = hashCode;
    }

    public bool Equals(T x, T y)
    {
        return EqualsMethod(x, y);
    }

    public int GetHashCode(T obj)
    {
        if (GetHashCodeMethod == null) return obj.GetHashCode();
        return GetHashCodeMethod(obj);
    }
}

Usage sample:

  var comparer = new InlineComparer<DetalleLog>((i1, i2) => i1.PeticionEV == i2.PeticionEV && i1.Etiqueta == i2.Etiqueta, i => i.PeticionEV.GetHashCode() + i.Etiqueta.GetHashCode());
  var peticionesEV = listaLogs.Distinct(comparer).ToList();
  Assert.IsNotNull(peticionesEV);
  Assert.AreNotEqual(0, peticionesEV.Count);

Source: https://stackoverflow.com/a/5969691/206730
Using IEqualityComparer for Union
Can I specify my explicit type comparator inline?

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

You may need to config the CORS at Spring Boot side. Please add below class in your Project.

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class WebConfig implements Filter,WebMvcConfigurer {



    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
      HttpServletResponse response = (HttpServletResponse) res;
      HttpServletRequest request = (HttpServletRequest) req;
      System.out.println("WebConfig; "+request.getRequestURI());
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
      response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,observe");
      response.setHeader("Access-Control-Max-Age", "3600");
      response.setHeader("Access-Control-Allow-Credentials", "true");
      response.setHeader("Access-Control-Expose-Headers", "Authorization");
      response.addHeader("Access-Control-Expose-Headers", "responseType");
      response.addHeader("Access-Control-Expose-Headers", "observe");
      System.out.println("Request Method: "+request.getMethod());
      if (!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
          try {
              chain.doFilter(req, res);
          } catch(Exception e) {
              e.printStackTrace();
          }
      } else {
          System.out.println("Pre-flight");
          response.setHeader("Access-Control-Allow-Origin", "*");
          response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT");
          response.setHeader("Access-Control-Max-Age", "3600");
          response.setHeader("Access-Control-Allow-Headers", "Access-Control-Expose-Headers"+"Authorization, content-type," +
          "USERID"+"ROLE"+
                  "access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with,responseType,observe");
          response.setStatus(HttpServletResponse.SC_OK);
      }

    }

}

UPDATE:

To append Token to each request you can create one Interceptor as below.

import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = window.localStorage.getItem('tokenKey'); // you probably want to store it in localStorage or something


    if (!token) {
      return next.handle(req);
    }

    const req1 = req.clone({
      headers: req.headers.set('Authorization', `${token}`),
    });

    return next.handle(req1);
  }

}

Example

Call a function from another file?

First of all you do not need a .py.

If you have a file a.py and inside you have some functions:

def b():
  # Something
  return 1

def c():
  # Something
  return 2

And you want to import them in z.py you have to write

from a import b, c

How to know function return type and argument types?

I attended a coursera course, there was lesson in which, we were taught about design recipe.

Below docstring format I found preety useful.

def area(base, height):
    '''(number, number ) -> number    #**TypeContract**
    Return the area of a tring with dimensions base   #**Description**
    and height

    >>>area(10,5)          #**Example **
    25.0
    >>area(2.5,3)
    3.75
    '''
    return (base * height) /2 

I think if docstrings are written in this way, it might help a lot to developers.

Link to video [Do watch the video] : https://www.youtube.com/watch?v=QAPg6Vb_LgI

Rotation of 3D vector?

Here is an elegant method using quaternions that are blazingly fast; I can calculate 10 million rotations per second with appropriately vectorised numpy arrays. It relies on the quaternion extension to numpy found here.

Quaternion Theory: A quaternion is a number with one real and 3 imaginary dimensions usually written as q = w + xi + yj + zk where 'i', 'j', 'k' are imaginary dimensions. Just as a unit complex number 'c' can represent all 2d rotations by c=exp(i * theta), a unit quaternion 'q' can represent all 3d rotations by q=exp(p), where 'p' is a pure imaginary quaternion set by your axis and angle.

We start by converting your axis and angle to a quaternion whose imaginary dimensions are given by your axis of rotation, and whose magnitude is given by half the angle of rotation in radians. The 4 element vectors (w, x, y, z) are constructed as follows:

import numpy as np
import quaternion as quat

v = [3,5,0]
axis = [4,4,1]
theta = 1.2 #radian

vector = np.array([0.] + v)
rot_axis = np.array([0.] + axis)
axis_angle = (theta*0.5) * rot_axis/np.linalg.norm(rot_axis)

First, a numpy array of 4 elements is constructed with the real component w=0 for both the vector to be rotated vector and the rotation axis rot_axis. The axis angle representation is then constructed by normalizing then multiplying by half the desired angle theta. See here for why half the angle is required.

Now create the quaternions v and qlog using the library, and get the unit rotation quaternion q by taking the exponential.

vec = quat.quaternion(*v)
qlog = quat.quaternion(*axis_angle)
q = np.exp(qlog)

Finally, the rotation of the vector is calculated by the following operation.

v_prime = q * vec * np.conjugate(q)

print(v_prime) # quaternion(0.0, 2.7491163, 4.7718093, 1.9162971)

Now just discard the real element and you have your rotated vector!

v_prime_vec = v_prime.imag # [2.74911638 4.77180932 1.91629719] as a numpy array

Note that this method is particularly efficient if you have to rotate a vector through many sequential rotations, as the quaternion product can just be calculated as q = q1 * q2 * q3 * q4 * ... * qn and then the vector is only rotated by 'q' at the very end using v' = q * v * conj(q).

This method gives you a seamless transformation between axis angle <---> 3d rotation operator simply by exp and log functions (yes log(q) just returns the axis-angle representation!). For further clarification of how quaternion multiplication etc. work, see here

how to fix Cannot call sendRedirect() after the response has been committed?

The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.

It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.

JAVA 7 OFFICIAL LINK

ADDITIONAL INFO

Pull all images from a specified directory and then display them

You can display all image from a folder using simple php script. Suppose folder name “images” and put some image in this folder and then use any text editor and paste this code and run this script. This is php code

    <?php
     $files = glob("images/*.*");
     for ($i=0; $i<count($files); $i++)
      {
        $image = $files[$i];
        $supported_file = array(
                'gif',
                'jpg',
                'jpeg',
                'png'
         );

         $ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
         if (in_array($ext, $supported_file)) {
            echo basename($image)."<br />"; // show only image name if you want to show full path then use this code // echo $image."<br />";
             echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
            } else {
                continue;
            }
          }
       ?>

if you do not check image type then use this code

<?php
$files = glob("images/*.*");
for ($i = 0; $i < count($files); $i++) {
    $image = $files[$i];
    echo basename($image) . "<br />"; // show only image name if you want to show full path then use this code // echo $image."<br />";
    echo '<img src="' . $image . '" alt="Random image" />' . "<br /><br />";

}
?>

How to make flexbox items the same size?

The accepted answer by Adam (flex: 1 1 0) works perfectly for flexbox containers whose width is either fixed, or determined by an ancestor. Situations where you want the children to fit the container.

However, you may have a situation where you want the container to fit the children, with the children equally sized based on the largest child. You can make a flexbox container fit its children by either:

  • setting position: absolute and not setting width or right, or
  • place it inside a wrapper with display: inline-block

For such flexbox containers, the accepted answer does NOT work, the children are not sized equally. I presume that this is a limitation of flexbox, since it behaves the same in Chrome, Firefox and Safari.

The solution is to use a grid instead of a flexbox.

Demo: https://codepen.io/brettdonald/pen/oRpORG

<p>Normal scenario — flexbox where the children adjust to fit the container — and the children are made equal size by setting {flex: 1 1 0}</p>

<div id="div0">
  <div>
    Flexbox
  </div>
  <div>
    Width determined by viewport
  </div>
  <div>
    All child elements are equal size with {flex: 1 1 0}
  </div>
</div>

<p>Now we want to have the container fit the children, but still have the children all equally sized, based on the largest child. We can see that {flex: 1 1 0} has no effect.</p>

<div class="wrap-inline-block">
<div id="div1">
  <div>
    Flexbox
  </div>
  <div>
    Inside inline-block
  </div>
  <div>
    We want all children to be the size of this text
  </div>
</div>
</div>

<div id="div2">
  <div>
    Flexbox
  </div>
  <div>
    Absolutely positioned
  </div>
  <div>
    We want all children to be the size of this text
  </div>
</div>

<br><br><br><br><br><br>
<p>So let's try a grid instead. Aha! That's what we want!</p>

<div class="wrap-inline-block">
<div id="div3">
  <div>
    Grid
  </div>
  <div>
    Inside inline-block
  </div>
  <div>
    We want all children to be the size of this text
  </div>
</div>
</div>

<div id="div4">
  <div>
    Grid
  </div>
  <div>
    Absolutely positioned
  </div>
  <div>
    We want all children to be the size of this text
  </div>
</div>
body {
  margin: 1em;
}

.wrap-inline-block {
  display: inline-block;
}

#div0, #div1, #div2, #div3, #div4 {
  border: 1px solid #888;
  padding: 0.5em;
  text-align: center;
  white-space: nowrap;
}

#div2, #div4 {
  position: absolute;
  left: 1em;
}

#div0>*, #div1>*, #div2>*, #div3>*, #div4>* {
  margin: 0.5em;
  color: white;
  background-color: navy;
  padding: 0.5em;
}

#div0, #div1, #div2 {
  display: flex;
}

#div0>*, #div1>*, #div2>* {
  flex: 1 1 0;
}

#div0 {
  margin-bottom: 1em;
}

#div2 {
  top: 15.5em;
}

#div3, #div4 {
  display: grid;
  grid-template-columns: repeat(3,1fr);
}

#div4 {
  top: 28.5em;
}

Is there a limit on number of tcp/ip connections between machines on linux?

When looking for the max performance you run into a lot of issue and potential bottlenecks. Running a simple hello world test is not necessarily going to find them all.

Possible limitations include:

  • Kernel socket limitations: look in /proc/sys/net for lots of kernel tuning..
  • process limits: check out ulimit as others have stated here
  • as your application grows in complexity, it may not have enough CPU power to keep up with the number of connections coming in. Use top to see if your CPU is maxed
  • number of threads? I'm not experienced with threading, but this may come into play in conjunction with the previous items.

What do I do when my program crashes with exception 0xc0000005 at address 0?

Exception code 0xc0000005 is an Access Violation. An AV at fault offset 0x00000000 means that something in your service's code is accessing a nil pointer. You will just have to debug the service while it is running to find out what it is accessing. If you cannot run it inside a debugger, then at least install a third-party exception logger framework, such as EurekaLog or MadExcept, to find out what your service was doing at the time of the AV.

Adding attributes to an XML node

If you serialize the object that you have, you can do something like this by using "System.Xml.Serialization.XmlAttributeAttribute" on every property that you want to be specified as an attribute in your model, which in my opinion is a lot easier:

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class UserNode
{
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string userName { get; set; }

    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string passWord { get; set; }

    public int Age { get; set; }
    public string Name { get; set; }         
 }

 public class LoginNode 
 {
    public UserNode id { get; set; }
 }

Then you just serialize to XML an instance of LoginNode called "Login", and that's it!

Here you have a few examples to serialize and object to XML, but I would suggest to create an extension method in order to be reusable for other objects.

How to import a JSON file in ECMAScript 6?

A simple workaround:

config.js

export default
{
  // my json here...
}

then...

import config from '../config.js'

does not allow import of existing .json files, but does a job.

numpy max vs amax vs maximum

For completeness, in Numpy there are four maximum related functions. They fall into two different categories:

  • np.amax/np.max, np.nanmax: for single array order statistics
  • and np.maximum, np.fmax: for element-wise comparison of two arrays

I. For single array order statistics

NaNs propagator np.amax/np.max and its NaN ignorant counterpart np.nanmax.

  • np.max is just an alias of np.amax, so they are considered as one function.

    >>> np.max.__name__
    'amax'
    >>> np.max is np.amax
    True
    
  • np.max propagates NaNs while np.nanmax ignores NaNs.

    >>> np.max([np.nan, 3.14, -1])
    nan
    >>> np.nanmax([np.nan, 3.14, -1])
    3.14
    

II. For element-wise comparison of two arrays

NaNs propagator np.maximum and its NaNs ignorant counterpart np.fmax.

  • Both functions require two arrays as the first two positional args to compare with.

    # x1 and x2 must be the same shape or can be broadcast
    np.maximum(x1, x2, /, ...);
    np.fmax(x1, x2, /, ...)
    
  • np.maximum propagates NaNs while np.fmax ignores NaNs.

    >>> np.maximum([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
    array([ nan,  nan, 2.72])
    >>> np.fmax([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
    array([-inf, 3.14, 2.72])
    
  • The element-wise functions are np.ufunc(Universal Function), which means they have some special properties that normal Numpy function don't have.

    >>> type(np.maximum)
    <class 'numpy.ufunc'>
    >>> type(np.fmax)
    <class 'numpy.ufunc'>
    >>> #---------------#
    >>> type(np.max)
    <class 'function'>
    >>> type(np.nanmax)
    <class 'function'>
    

And finally, the same rules apply to the four minimum related functions:

  • np.amin/np.min, np.nanmin;
  • and np.minimum, np.fmin.

How to get "wc -l" to print just the number of lines without file name?

Best way would be first of all find all files in directory then use AWK NR (Number of Records Variable)

below is the command :

find <directory path>  -type f | awk  'END{print NR}'

example : - find /tmp/ -type f | awk 'END{print NR}'

ESRI : Failed to parse source map

Check if you're using some Chrome extension (Night mode or something else). Disable that and see if the 'inject' gone.

How to get filename without extension from file path in Ruby

In case the extension is not known (it needs the / separator):

irb(main):024:0> f = 'C:\foobar\blah.txt'.gsub("\\","/")
=> "C:/foobar/blah.txt"
irb(main):027:0> File.basename(f,File.extname(f))
=> "blah"

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

Quick summary, you can do either:

  1. Include the JavaFX modules via --module-path and --add-modules like in José's answer.

    OR

  2. Once you have JavaFX libraries added to your project (either manually or via maven/gradle import), add the module-info.java file similar to the one specified in this answer. (Note that this solution makes your app modular, so if you use other libraries, you will also need to add statements to require their modules inside the module-info.java file).


This answer is a supplement to Jose's answer.

The situation is this:

  1. You are using a recent Java version, e.g. 13.
  2. You have a JavaFX application as a Maven project.
  3. In your Maven project you have the JavaFX plugin configured and JavaFX dependencies setup as per Jose's answer.
  4. You go to the source code of your main class which extends Application, you right-click on it and try to run it.
  5. You get an IllegalAccessError involving an "unnamed module" when trying to launch the app.

Excerpt for a stack trace generating an IllegalAccessError when trying to run a JavaFX app from Intellij Idea:

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.lang.IllegalAccessError: class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x45069d0e) cannot access class com.sun.javafx.util.Utils (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.util to unnamed module @0x45069d0e
    at com.sun.javafx.fxml.FXMLLoaderHelper.<clinit>(FXMLLoaderHelper.java:38)
    at javafx.fxml.FXMLLoader.<clinit>(FXMLLoader.java:2056)
    at org.jewelsea.demo.javafx.springboot.Main.start(Main.java:13)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
Exception running application org.jewelsea.demo.javafx.springboot.Main

OK, now you are kind of stuck and have no clue what is going on.

What has actually happened is this:

  1. Maven has successfully downloaded the JavaFX dependencies for your application, so you don't need to separately download the dependencies or install a JavaFX SDK or module distribution or anything like that.
  2. Idea has successfully imported the modules as dependencies to your project, so everything compiles OK and all of the code completion and everything works fine.

So it seems everything should be OK. BUT, when you run your application, the code in the JavaFX modules is failing when trying to use reflection to instantiate instances of your application class (when you invoke launch) and your FXML controller classes (when you load FXML). Without some help, this use of reflection can fail in some cases, generating the obscure IllegalAccessError. This is due to a Java module system security feature which does not allow code from other modules to use reflection on your classes unless you explicitly allow it (and the JavaFX application launcher and FXMLLoader both require reflection in their current implementation in order for them to function correctly).

This is where some of the other answers to this question, which reference module-info.java, come into the picture.

So let's take a crash course in Java modules:

The key part is this:

4.9. Opens

If we need to allow reflection of private types, but we don't want all of our code exposed, we can use the opens directive to expose specific packages.

But remember, this will open the package up to the entire world, so make sure that is what you want:

module my.module { opens com.my.package; }

So, perhaps you don't want to open your package to the entire world, then you can do:

4.10. Opens … To

Okay, so reflection is great sometimes, but we still want as much security as we can get from encapsulation. We can selectively open our packages to a pre-approved list of modules, in this case, using the opens…to directive:

module my.module { opens com.my.package to moduleOne, moduleTwo, etc.; }

So, you end up creating a src/main/java/module-info.java class which looks like this:

module org.jewelsea.demo.javafx.springboot {
    requires javafx.fxml;
    requires javafx.controls;
    requires javafx.graphics;
    opens org.jewelsea.demo.javafx.springboot to javafx.graphics,javafx.fxml;
}

Where, org.jewelsea.demo.javafx.springboot is the name of the package which contains the JavaFX Application class and JavaFX Controller classes (replace this with the appropriate package name for your application). This tells the Java runtime that it is OK for classes in the javafx.graphics and javafx.fxml to invoke reflection on the classes in your org.jewelsea.demo.javafx.springboot package. Once this is done, and the application is compiled and re-run things will work fine and the IllegalAccessError generated by JavaFX's use of reflection will no longer occur.

But what if you don't want to create a module-info.java file

If instead of using the the Run button in the top toolbar of IDE to run your application class directly, you instead:

  1. Went to the Maven window in the side of the IDE.
  2. Chose the javafx maven plugin target javafx.run.
  3. Right-clicked on that and chose either Run Maven Build or Debug....

Then the app will run without the module-info.java file. I guess this is because the maven plugin is smart enough to dynamically include some kind of settings which allows the app to be reflected on by the JavaFX classes even without a module-info.java file, though I don't know how this is accomplished.

To get that setting transferred to the Run button in the top toolbar, right-click on the javafx.run Maven target and choose the option to Create Run/Debug Configuration for the target. Then you can just choose Run from the top toolbar to execute the Maven target.

How do I convert from stringstream to string in C++?

std::stringstream::str() is the method you are looking for.

With std::stringstream:

template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
    std::stringstream ss;
    ss << NumericValue;
    return ss.str();
}

std::stringstream is a more generic tool. You can use the more specialized class std::ostringstream for this specific job.

template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
    std::ostringstream oss;
    oss << NumericValue;
    return oss.str();
}

If you are working with std::wstring type of strings, you must prefer std::wstringstream or std::wostringstream instead.

template <class T>
std::wstring YourClass::NumericToString(const T & NumericValue)
{
    std::wostringstream woss;
    woss << NumericValue;
    return woss.str();
}

if you want the character type of your string could be run-time selectable, you should also make it a template variable.

template <class CharType, class NumType>
std::basic_string<CharType> YourClass::NumericToString(const NumType & NumericValue)
{
    std::basic_ostringstream<CharType> oss;
    oss << NumericValue;
    return oss.str();
}

For all the methods above, you must include the following two header files.

#include <string>
#include <sstream>

Note that, the argument NumericValue in the examples above can also be passed as std::string or std::wstring to be used with the std::ostringstream and std::wostringstream instances respectively. It is not necessary for the NumericValue to be a numeric value.

Jenkins / Hudson environment variables

I kept running into this problem, but now I just add:

source /etc/profile

As the first step in my build process. Now all my subsequent rules are loaded for Jenkins to operate smoothly.

HTTP GET in VB.NET

Public Function getLoginresponce(ByVal email As String, ByVal password As String) As String
    Dim requestUrl As String = "your api"
    Dim request As HttpWebRequest = TryCast(WebRequest.Create(requestUrl), HttpWebRequest)
    Dim response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
    Dim dataStream As Stream = response.GetResponseStream()
    Dim reader As New StreamReader(dataStream)
    Dim responseFromServer As String = reader.ReadToEnd()
    Dim result = responseFromServer
    reader.Close()
    response.Close()
    Return result
End Function

Getting HTML elements by their attribute names

I think you want to take a look at jQuery since that Javascript library provides a lot of functionality you might want to use in this kind of cases. In your case you could write (or find one on the internet) a hasAttribute method, like so (not tested):

$.fn.hasAttribute = function(tagName, attrName){
  var result = [];
  $.each($(tagName), function(index, value) { 
     var attr = $(this).attr(attrName); 
     if (typeof attr !== 'undefined' && attr !== false)
        result.push($(this));
  });
  return result;
}

Mock MVC - Add Request Parameter to test

@ModelAttribute is a Spring mapping of request parameters to a particular object type. so your parameters might look like userClient.username and userClient.firstName, etc. as MockMvc imitates a request from a browser, you'll need to pass in the parameters that Spring would use from a form to actually build the UserClient object.

(i think of ModelAttribute is kind of helper to construct an object from a bunch of fields that are going to come in from a form, but you may want to do some reading to get a better definition)

Winforms issue - Error creating window handle

I got same error in my application.I am loading many controls in single page.In button click event i am clearing the controls.clearing the controls doesnot release the controls from memory.So dispose the controls from memory. I just commented controls.clear() method and include few lines of code to dispose the controls. Something like this

for each ctl as control in controlcollection

ctl.dispose()

Next

Move the most recent commit(s) to a new branch with Git

Yet another way to do this, using just 2 commands. Also keeps your current working tree intact.

git checkout -b newbranch # switch to a new branch
git branch -f master HEAD~3 # make master point to some older commit

Old version - before I learned about git branch -f

git checkout -b newbranch # switch to a new branch
git push . +HEAD~3:master # make master point to some older commit 

Being able to push to . is a nice trick to know.

JAX-WS and BASIC authentication, when user names and passwords are in a database

BindingProvider.USERNAME_PROPERTY and BindingProvider.PASSWORD_PROPERTY are matching HTTP Basic Authentication mechanism that enable authentication process at the HTTP level and not at the application nor servlet level.

Basically, only the HTTP server will know the username and the password (and eventually application according to HTTP/application server specification, such with Apache/PHP). With Tomcat/Java, add a login config BASIC in your web.xml and appropriate security-constraint/security-roles (roles that will be later associated to users/groups of real users).

<login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>YourRealm</realm-name>
</login-config>

Then, connect the realm at the HTTP server (or application server) level with the appropriate user repository. For tomcat you may look at JAASRealm, JDBCRealm or DataSourceRealm that may suit your needs.

http://tomcat.apache.org/tomcat-6.0-doc/realm-howto.html

How to clean old dependencies from maven repositories?

I came up with a utility and hosted on GitHub to clean old versions of libraries in the local Maven repository. The utility, on its default execution removes all older versions of artifacts leaving only the latest ones. Optionally, it can remove all snapshots, sources, javadocs, and also groups or artifacts can be forced / excluded in this process. This cross platform also supports date based removal based on last access / download dates.

https://github.com/techpavan/mvn-repo-cleaner

jQuery Loop through each div

$('div.target').each(function() {
   /* Measure the width of each image. */
   var test = $(this).find('.scrolling img').width();

   /* Find out how many images there are. */
   var testimg = $(this).find('.scrolling img').length;

   /* Do the maths. */
   var final = (test* testimg)*1.2;

   /* Apply the maths to the CSS. */
   $(this).find('scrolling').width(final); 
});

Here you loop through all your div's with class target and you do the calculations. Within this loop you can simply use $(this) to indicate the currently selected <div> tag.

Getting Python error "from: can't read /var/mail/Bio"

Put this at the top of your .py file (for python 2.x)

#!/usr/bin/env python 

or for python 3.x

#!/usr/bin/env python3

This should look up the python environment, without it, it will execute the code as if it were not python code, but straight to the CLI. If you need to specify a manual location of python environment put

#!/#path/#to/#python

Add an object to an Array of a custom class

The array declaration should be:

Car[] garage = new Car[100];

You can also just assign directly:

garage[1] = new Car("Blue");

How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

In the %run magic documentation you can find:

-i run the file in IPython’s namespace instead of an empty one. This is useful if you are experimenting with code written in a text editor which depends on variables defined interactively.

Therefore, supplying -i does the trick:

%run -i 'script.py'

The "correct" way to do it

Maybe the command above is just what you need, but with all the attention this question gets, I decided to add a few more cents to it for those who don't know how a more pythonic way would look like.
The solution above is a little hacky, and makes the code in the other file confusing (Where does this x variable come from? and what is the f function?).

I'd like to show you how to do it without actually having to execute the other file over and over again.
Just turn it into a module with its own functions and classes and then import it from your Jupyter notebook or console. This also has the advantage of making it easily reusable and jupyters contextassistant can help you with autocompletion or show you the docstring if you wrote one.
If you're constantly editing the other file, then autoreload comes to your help.

Your example would look like this:
script.py

import matplotlib.pyplot as plt

def myplot(f, x):
    """
    :param f: function to plot
    :type f: callable
    :param x: values for x
    :type x: list or ndarray

    Plots the function f(x).
    """
    # yes, you can pass functions around as if
    # they were ordinary variables (they are)
    plt.plot(x, f(x))
    plt.xlabel("Eje $x$",fontsize=16)
    plt.ylabel("$f(x)$",fontsize=16)
    plt.title("Funcion $f(x)$")

Jupyter console

In [1]: import numpy as np

In [2]: %load_ext autoreload

In [3]: %autoreload 1

In [4]: %aimport script

In [5]: def f(x):
      :     return np.exp(-x ** 2)
      :
      :

In [6]: x = np.linspace(-1, 3, 100)

In [7]: script.myplot(f, x)

In [8]: ?script.myplot
Signature: script.myplot(f, x)
Docstring:
:param f: function to plot
:type f: callable
:param x: x values
:type x: list or ndarray
File:      [...]\script.py
Type:      function

Using sed and grep/egrep to search and replace

Use this command:

egrep -lRZ "\.jpg|\.png|\.gif" . \
    | xargs -0 -l sed -i -e 's/\.jpg\|\.gif\|\.png/.bmp/g'
  • egrep: find matching lines using extended regular expressions

    • -l: only list matching filenames

    • -R: search recursively through all given directories

    • -Z: use \0 as record separator

    • "\.jpg|\.png|\.gif": match one of the strings ".jpg", ".gif" or ".png"

    • .: start the search in the current directory

  • xargs: execute a command with the stdin as argument

    • -0: use \0 as record separator. This is important to match the -Z of egrep and to avoid being fooled by spaces and newlines in input filenames.

    • -l: use one line per command as parameter

  • sed: the stream editor

    • -i: replace the input file with the output without making a backup

    • -e: use the following argument as expression

    • 's/\.jpg\|\.gif\|\.png/.bmp/g': replace all occurrences of the strings ".jpg", ".gif" or ".png" with ".bmp"

Downloading an entire S3 bucket?

You may simple get it with s3cmd command:

s3cmd get --recursive --continue s3://test-bucket local-directory/

With Spring can I make an optional path variable?

If you are using Spring 4.1 and Java 8 you can use java.util.Optional which is supported in @RequestParam, @PathVariable, @RequestHeader and @MatrixVariable in Spring MVC -

@RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET)
public @ResponseBody TestBean typedTestBean(
    @PathVariable Optional<String> type,
    @RequestParam("track") String track) {      
    if (type.isPresent()) {
        //type.get() will return type value
        //corresponds to path "/json/{type}"
    } else {
        //corresponds to path "/json"
    }       
}

How do I disable text selection with CSS or JavaScript?

I'm not sure if you can turn it off, but you can change the colors of it :)

myDiv::selection,
myDiv::-moz-selection,
myDiv::-webkit-selection {
    background:#000;
    color:#fff;
}

Then just match the colors to your "darky" design and see what happens :)

How do I convert strings in a Pandas data frame to a 'date' data type?

Use astype

In [31]: df
Out[31]: 
   a        time
0  1  2013-01-01
1  2  2013-01-02
2  3  2013-01-03

In [32]: df['time'] = df['time'].astype('datetime64[ns]')

In [33]: df
Out[33]: 
   a                time
0  1 2013-01-01 00:00:00
1  2 2013-01-02 00:00:00
2  3 2013-01-03 00:00:00

iptables v1.4.14: can't initialize iptables table `nat': Table does not exist (do you need to insmod?)

On OpenSUSE 15.3 systemd log reported this error (insmod suggestion was unhelpful).

Feb 18 08:36:38 vagrant-openSUSE-Leap dockerd[20635]: iptables v1.6.2: can't initialize iptables table `nat': Table does not exist (do you need to insmod?)

REBOOT fixed the problem

Spark Kill Running Application

First use:

yarn application -list

Note down the application id Then to kill use:

yarn application -kill application_id

Checkbox for nullable boolean

All the answers above came with it's own issues. Easiest/cleanest way IMO is to create a helper

MVC5 Razor

App_Code/Helpers.cshtml

@helper CheckBoxFor(WebViewPage page, string propertyName, bool? value, string htmlAttributes = null)
{
    if (value == null)
    {
        <div class="checkbox-nullable">
            <input type="checkbox" @page.Html.Raw(htmlAttributes)>
        </div>
    }
    else if (value == true)
    {
        <input type="checkbox" value="true" @page.Html.Raw(htmlAttributes) checked>
    }
    else
    {
        <input type="checkbox" value="false" @page.Html.Raw(htmlAttributes)>
    }
}

Usage

@Helpers.CheckBoxFor(this, "IsPaymentRecordOk", Model.IsPaymentRecordOk)

In my scenario, a nullable checkbox means that a staff member had not yet asked the question to the client, so it's wrapped in a .checkbox-nullable so that you may style appropriately and help the end-user identify that it is neither true nor false

CSS

.checkbox-nullable {
    border: 1px solid red;
    padding: 3px;
    display: inline-block;
}

Add space between HTML elements only using CSS

span:not(:last-child) {
    margin-right: 10px;
}

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

Since late 2012, it is usually under /usr/share/tomcat7.

Prior to that, it was usually found under /opt/tomcat7.

Using BufferedReader to read Text File

private void readFile() throws Exception {
      AsynchronousFileChannel input=AsynchronousFileChannel.open(Paths.get("E:/dicom_server_storage/abc.txt"),StandardOpenOption.READ);
      ByteBuffer buffer=ByteBuffer.allocate(1024);
      input.read(buffer,0,null,new CompletionHandler<Integer,Void>(){
        @Override public void completed(    Integer result,    Void attachment){
          System.out.println("Done reading the file.");
        }
        @Override public void failed(    Throwable exc,    Void attachment){
          System.err.println("An error occured:" + exc.getMessage());
        }
      }
    );
      System.out.println("This thread keeps on running");
      Thread.sleep(100);
    }

Obtain smallest value from array in Javascript?

I think I have an easy-to-understand solution for this, using only the basics of javaScript.

function myFunction() {
            var i = 0;
            var smallestNumber = justPrices[0];
            for(i = 0; i < justPrices.length; i++) {
                if(justPrices[i] < smallestNumber) {
                    smallestNumber = justPrices[i];
                }
            }
            return smallestNumber;
        }

The variable smallestNumber is set to the first element of justPrices, and the for loop loops through the array (I'm just assuming that you know how a for loop works; if not, look it up). If an element of the array is smaller than the current smallestNumber (which at first is the first element), it will replace it's value. When the whole array has gone through the loop, smallestNumber will contain the smallest number in the array.

How can I get client information such as OS and browser

The browser sends this information in the HTTP header. See the snoop example of Tomcat for some code (source, online demo).

Note that this information is not reliable. Browser can and do lie about who they are and what OS they run on.

Uploading an Excel sheet and importing the data into SQL Server database

    public async Task<HttpResponseMessage> PostFormDataAsync()    //async is used for defining an asynchronous method
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }
        var fileLocation = "";
        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(root);  //Helps in HTML file uploads to write data to File Stream
        try
        {
            // Read the form data.
        await Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                Trace.WriteLine(file.Headers.ContentDisposition.FileName); //Gets the file name
                var filePath = file.Headers.ContentDisposition.FileName.Substring(1, file.Headers.ContentDisposition.FileName.Length - 2); //File name without the path
                File.Copy(file.LocalFileName, file.LocalFileName + filePath); //Save a copy for reading it
                fileLocation = file.LocalFileName + filePath; //Complete file location
            }
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, recordStatus);
            return response;
}
catch (System.Exception e)
    {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
    }
}
public void ReadFromExcel()
{
try
        {
            DataTable sheet1 = new DataTable();
            OleDbConnectionStringBuilder csbuilder = new OleDbConnectionStringBuilder();
            csbuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
            csbuilder.DataSource = fileLocation;
            csbuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES");
            string selectSql = @"SELECT * FROM [Sheet1$]";
            using (OleDbConnection connection = new OleDbConnection(csbuilder.ConnectionString))
            using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectSql, connection))
            {
                connection.Open();
                adapter.Fill(sheet1);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }          
}

How to find index position of an element in a list when contains returns true

benefit.indexOf(map4)

It either returns an index or -1 if the items is not found.

I strongly recommend wrapping the map in some object and use generics if possible.

Default Xmxsize in Java 8 (max heap size)

It varies on implementation and version, but usually it depends on the VM used (e.g. client or server, see -client and -server parameters) and on your system memory.

Often for client the default value is 1/4th of your physical memory or 1GB (whichever is smaller).

Also Java configuration options (command line parameters) can be "outsourced" to environment variables including the -Xmx, which can change the default (meaning specify a new default). Specifically the JAVA_TOOL_OPTIONS environment variable is checked by all Java tools and used if exists (more details here and here).

You can run the following command to see default values:

java -XX:+PrintFlagsFinal -version

It gives you a loooong list, -Xmx is in MaxHeapSize, -Xms is in InitialHeapSize. Filter your output (e.g. |grep on linux) or save it in a file so you can search in it.

How can I get the current stack trace in Java?

In Java 9 there is a new way:

public static void showTrace() {

  List<StackFrame> frames =
    StackWalker.getInstance( Option.RETAIN_CLASS_REFERENCE )
               .walk( stream  -> stream.collect( Collectors.toList() ) );

  for ( StackFrame stackFrame : frames )
    System.out.println( stackFrame );
}

How to empty (clear) the logcat buffer in Android

For anyone coming to this question wondering how to do this in Eclipse, You can remove the displayed text from the logCat using the button provided (often has a red X on the icon)

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

STEP 1: Include the following in OnConfiguring()

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddJsonFile("appsettings.json")
            .Build();
        optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
    }

STEP 2: Create appsettings.json:

  {
    "ConnectionStrings": {       
      "DefaultConnection": "Server=YOURSERVERNAME; Database=YOURDATABASENAME; Trusted_Connection=True; MultipleActiveResultSets=true"        
    } 
  }

STEP 3: Hard copy appsettings.json to the correct directory

  Hard copy appsettings.json.config to the directory specified in the AppDomain.CurrentDomain.BaseDirectory directory. 
  Use your debugger to find out which directory that is.        

Assumption: you have already included package Microsoft.Extensions.Configuration.Json (get it from Nuget) in your project.

Safely turning a JSON string into an object

Summary:

Javascript (both browser and NodeJS) have a built in JSON object. On this Object are 2 convenient methods for dealing with JSON. They are the following:

  1. JSON.parse() Takes JSON as argument, returns JS object
  2. JSON.stringify() Takes JS object as argument returns JSON object

Other applications:

Besides for very conveniently dealing with JSON they have can be used for other means. The combination of both JSON methods allows us to make very easy make deep clones of arrays or objects. For example:

_x000D_
_x000D_
let arr1 = [1, 2, [3 ,4]];_x000D_
let newArr = arr1.slice();_x000D_
_x000D_
arr1[2][0] = 'changed'; _x000D_
console.log(newArr); // not a deep clone_x000D_
_x000D_
let arr2 = [1, 2, [3 ,4]];_x000D_
let newArrDeepclone = JSON.parse(JSON.stringify(arr2));_x000D_
_x000D_
arr2[2][0] = 'changed'; _x000D_
console.log(newArrDeepclone); // A deep clone, values unchanged
_x000D_
_x000D_
_x000D_

Android Endless List

One solution is to implement an OnScrollListener and make changes (like adding items, etc.) to the ListAdapter at a convenient state in its onScroll method.

The following ListActivity shows a list of integers, starting with 40, adding items when the user scrolls to the end of the list.

public class Test extends ListActivity implements OnScrollListener {

    Aleph0 adapter = new Aleph0();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setListAdapter(adapter); 
        getListView().setOnScrollListener(this);
    }

    public void onScroll(AbsListView view,
        int firstVisible, int visibleCount, int totalCount) {

        boolean loadMore = /* maybe add a padding */
            firstVisible + visibleCount >= totalCount;

        if(loadMore) {
            adapter.count += visibleCount; // or any other amount
            adapter.notifyDataSetChanged();
        }
    }

    public void onScrollStateChanged(AbsListView v, int s) { }    

    class Aleph0 extends BaseAdapter {
        int count = 40; /* starting amount */

        public int getCount() { return count; }
        public Object getItem(int pos) { return pos; }
        public long getItemId(int pos) { return pos; }

        public View getView(int pos, View v, ViewGroup p) {
                TextView view = new TextView(Test.this);
                view.setText("entry " + pos);
                return view;
        }
    }
}

You should obviously use separate threads for long running actions (like loading web-data) and might want to indicate progress in the last list item (like the market or gmail apps do).

Get current batchfile directory

Within your .bat file:

set mypath=%cd%

You can now use the variable %mypath% to reference the file path to the .bat file. To verify the path is correct:

@echo %mypath%

For example, a file called DIR.bat with the following contents

set mypath=%cd%
@echo %mypath%
Pause

run from the directory g:\test\bat will echo that path in the DOS command window.

CSS How to set div height 100% minus nPx

I haven't seen anything like this posted yet, but I thought I'd put it out there.

<div class="main">
<header>Header</header>
<div class="content">Content</div>

Then CSS:

body, html {
    height: 100%;
    margin: 0;
    padding: 0;
}

.main {
    height: 100%;
    padding-top: 50px;
    box-sizing: border-box;
}

header {
    height: 50px;
    margin-top: -50px;
    width: 100%;
    background-color: #5078a5;
}

.content {
    height: 100%;
    background-color: #999999;
}

Here is a working jsfiddle

Note: I have no idea what the browser compatability is for this. I was just playing around with alternate solutions and this seemed to work well.

Bootstrap collapse animation not smooth

Do not set a height on the .collapse tag. It affects the animation, if the height is overridden with css; it will not animate correctly.

How to make the overflow CSS property work with hidden as value

In addition to provided answers:

it seems like parent element (the one with overflow:hidden) must not be display:inline. Changing to display:inline-block worked for me.

_x000D_
_x000D_
.outer {_x000D_
  position: relative;_x000D_
  border: 1px dotted black;_x000D_
  padding: 5px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
.inner {_x000D_
  position: absolute;_x000D_
  left: 50%;_x000D_
  margin-left: -20px;_x000D_
  top: 70%;_x000D_
  width: 40px;_x000D_
  height: 80px;_x000D_
  background: yellow;_x000D_
}
_x000D_
<span class="outer">_x000D_
  Some text_x000D_
  <span class="inner"></span>_x000D_
</span>_x000D_
<span class="outer" style="display:inline-block;">_x000D_
  Some text_x000D_
  <span class="inner"></span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

Error: Configuration with name 'default' not found in Android Studio

This is probably a rare case, but for me a library that was included in the settings.gradle was not there.

E.g. I had: include ':libraries:Android-RateThisApp:library' in my settings.gradle

but the folder Android-RateThisApp was empty. As soon as I checked out this submodule the gradle sync succeed.

How can change width of dropdown list?

This worked for me:

ul.dropdown-menu > li {
    max-width: 144px;
}

in Chromium and Firefox.

Detect if page has finished loading

var pageLoaded=0;

$(document).ready(function(){
   pageLoaded=1;
});

Using jquery: https://learn.jquery.com/using-jquery-core/document-ready/

JavaScript/jQuery - How to check if a string contain specific words

If you are looking for exact words and don't want it to match things like "nightmare" (which is probably what you need), you can use a regex:

/\bare\b/gi

\b = word boundary
g = global
i = case insensitive (if needed)

If you just want to find the characters "are", then use indexOf.

If you want to match arbitrary words, you have to programatically construct a RegExp (regular expression) object itself based on the word string and use test.

ERROR! MySQL manager or server PID file could not be found! QNAP

I was able to solve this on OS X by shutting down the existing mysql.server that was running:

mysql.server stop

The starting:

mysql.server start

From there I could run mysql.server restart without throwing the ERROR.

When do you use Java's @Override annotation and why?

The annotation @Override is used for helping to check whether the developer what to override the correct method in the parent class or interface. When the name of super's methods changing, the compiler can notify that case, which is only for keep consistency with the super and the subclass.

BTW, if we didn't announce the annotation @Override in the subclass, but we do override some methods of the super, then the function can work as that one with the @Override. But this method can not notify the developer when the super's method was changed. Because it did not know the developer's purpose -- override super's method or define a new method?

So when we want to override that method to make use of the Polymorphism, we have better to add @Override above the method.

Creating a SearchView that looks like the material design guidelines

It is actually quite easy to do this, if you are using android.support.v7 library.

Step - 1

Declare a menu item

<item android:id="@+id/action_search"
    android:title="Search"
    android:icon="@drawable/abc_ic_search_api_mtrl_alpha"
    app:showAsAction="ifRoom|collapseActionView"
    app:actionViewClass="android.support.v7.widget.SearchView" />

Step - 2

Extend AppCompatActivity and in the onCreateOptionsMenu setup the SearchView.

import android.support.v7.widget.SearchView;

...

public class YourActivity extends AppCompatActivity {

    ...

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_home, menu);
        // Retrieve the SearchView and plug it into SearchManager
        final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
        SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        return true;
    }

    ... 

}

Result

enter image description here

enter image description here

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

How to check if an array value exists?

Assuming you are using a simple array

. i.e.

$MyArray = array("red","blue","green");

You can use this function

function val_in_arr($val,$arr){
  foreach($arr as $arr_val){
    if($arr_val == $val){
      return true;
    }
  }
  return false;
}

Usage:

val_in_arr("red",$MyArray); //returns true
val_in_arr("brown",$MyArray); //returns false

How to generate UML diagrams (especially sequence diagrams) from Java code?

EDIT: If you're a designer then Papyrus is your best choice it's very advanced and full of features, but if you just want to sketch out some UML diagrams and easy installation then ObjectAid is pretty cool and it doesn't require any plugins I just installed it over Eclipse-Java EE and works great !.


UPDATE Oct 11th, 2013

My original post was in June 2012 a lot of things have changed many tools has grown and others didn't. Since I'm going back to do some modeling and also getting some replies to the post I decided to install papyrus again and will investigate other possible UML modeling solutions again. UML generation (with synchronization feature) is really important not to software designer but to the average developer.

I wish papyrus had straightforward way to Reverse Engineer classes into UML class diagram and It would be super cool if that reverse engineering had a synchronization feature, but unfortunately papyrus project is full of features and I think developers there have already much at hand since also many actions you do over papyrus might not give you any response and just nothing happens but that's out of this question scope anyway.

The Answer (Oct 11th, 2013)

Tools

  1. Download Papyrus
  2. Go to Help -> Install New Software...
  3. In the Work with: drop-down, select --All Available Sites--
  4. In the filter, type in Papyrus
  5. After installation finishes restart Eclipse
  6. Repeat steps 1-3 and this time, install Modisco

Steps

  1. In your java project (assume it's called MyProject) create a folder e.g UML
  2. Right click over the project name -> Discovery -> Discoverer -> Discover Java and inventory model from java project, a file called MyProject_kdm.xmi will be generated. enter image description here
  3. Right click project name file --> new --> papyrus model -> and call it MyProject.
  4. Move the three generated files MyProject.di , MyProject.notation, MyProject.uml to the UML folder
  5. Right click on MyProject_kdm.xmi -> Discovery -> Discoverer -> Discover UML model from KDM code again you'll get a property dialog set the serialization prop to TRUE to generate a file named MyProject.uml enter image description here

  6. Move generated MyProject.uml which was generated at root, to UML folder, Eclipse will ask you If you wanted to replace it click yes. What we did in here was that we replaced an empty model with a generated one.

  7. ALT+W -> show view -> papyrus -> model explorer

  8. In that view, you'll find your classes like in the picture enter image description here

  9. In the view Right click root model -> New diagram enter image description here

  10. Then start grabbing classes to the diagram from the view

Some features

  • To show the class elements (variables, functions etc) Right click on any class -> Filters -> show/hide contents Voila !!

  • You can have default friendly color settings from Window -> pereferences -> papyrus -> class diagram

  • one very important setting is Arrange when you drop the classes they get a cramped right click on any empty space at a class diagram and click Arrange All

  • Arrows in the model explorer view can be grabbed to the diagram to show generalization, realization etc

  • After all of that your settings will show diagrams like enter image description here

  • Synchronization isn't available as far as I know you'll need to manually import any new classes.

That's all, And don't buy commercial products unless you really need it, papyrus is actually great and sophisticated instead donate or something.

Disclaimer: I've no relation to the papyrus people, in fact, I didn't like papyrus at first until I did lots of research and experienced it with some patience. And will get back to this post again when I try other free tools.

How does setTimeout work in Node.JS?

The semantics of setTimeout are roughly the same as in a web browser: the timeout arg is a minimum number of ms to wait before executing, not a guarantee. Furthermore, passing 0, a non-number, or a negative number, will cause it to wait a minimum number of ms. In Node, this is 1ms, but in browsers it can be as much as 50ms.

The reason for this is that there is no preemption of JavaScript by JavaScript. Consider this example:

setTimeout(function () {
  console.log('boo')
}, 100)
var end = Date.now() + 5000
while (Date.now() < end) ;
console.log('imma let you finish but blocking the event loop is the best bug of all TIME')

The flow here is:

  1. schedule the timeout for 100ms.
  2. busywait for 5000ms.
  3. return to the event loop. check for pending timers and execute.

If this was not the case, then you could have one bit of JavaScript "interrupt" another. We'd have to set up mutexes and semaphors and such, to prevent code like this from being extremely hard to reason about:

var a = 100;
setTimeout(function () {
  a = 0;
}, 0);
var b = a; // 100 or 0?

The single-threadedness of Node's JavaScript execution makes it much simpler to work with than most other styles of concurrency. Of course, the trade-off is that it's possible for a badly-behaved part of the program to block the whole thing with an infinite loop.

Is this a better demon to battle than the complexity of preemption? That depends.

How to update and order by using ms sql

UPDATE messages SET 
 status=10 
WHERE ID in (SELECT TOP (10) Id FROM Table WHERE status=0 ORDER BY priority DESC);

What killed my process and why?

In an lsf environment (interactive or otherwise) if the application exceeds memory utilization beyond some preset threshold by the admins on the queue or the resource request in submit to the queue the processes will be killed so other users don't fall victim to a potential run away. It doesn't always send an email when it does so, depending on how its set up.

One solution in this case is to find a queue with larger resources or define larger resource requirements in the submission.

You may also want to review man ulimit

Although I don't remember ulimit resulting in Killed its been a while since I needed that.

What is a handle in C++?

In C++/CLI, a handle is a pointer to an object located on the GC heap. Creating an object on the (unmanaged) C++ heap is achieved using new and the result of a new expression is a "normal" pointer. A managed object is allocated on the GC (managed) heap with a gcnew expression. The result will be a handle. You can't do pointer arithmetic on handles. You don't free handles. The GC will take care of them. Also, the GC is free to relocate objects on the managed heap and update the handles to point to the new locations while the program is running.

WooCommerce: Finding the products in database

I would recommend using WordPress custom fields to store eligible postcodes for each product. add_post_meta() and update_post_meta are what you're looking for. It's not recommended to alter the default WordPress table structure. All postmetas are inserted in wp_postmeta table. You can find the corresponding products within wp_posts table.

Getting Serial Port Information

EDIT: Sorry, I zipped past your question too quick. I realize now that you're looking for a list with the port name + port description. I've updated the code accordingly...

Using System.Management, you can query for all the ports, and all the information for each port (just like Device Manager...)

Sample code (make sure to add reference to System.Management):

using System;
using System.Management;
using System.Collections.Generic;
using System.Linq;
using System.IO.Ports;        

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var searcher = new ManagementObjectSearcher
                ("SELECT * FROM WIN32_SerialPort"))
            {
                string[] portnames = SerialPort.GetPortNames();
                var ports = searcher.Get().Cast<ManagementBaseObject>().ToList();
                var tList = (from n in portnames
                            join p in ports on n equals p["DeviceID"].ToString()
                            select n + " - " + p["Caption"]).ToList();

                tList.ForEach(Console.WriteLine);
            }

            // pause program execution to review results...
            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
    }
}

More info here: http://msdn.microsoft.com/en-us/library/aa394582%28VS.85%29.aspx

React JS get current date

OPTION 1: if you want to make a common utility function then you can use this

export function getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

and use it by just importing it as

import {getCurrentDate} from './utils'
console.log(getCurrentDate())

OPTION 2: or define and use in a class directly

getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

How do you round a floating point number in Perl?

cat table |
  perl -ne '/\d+\s+(\d+)\s+(\S+)/ && print "".**int**(log($1)/log(2))."\t$2\n";' 

LogCat message: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included

As for me I've solved this problem by next way - as developer.android.com says, after adding google-play-services_lib you should add <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> in your manifest, but on the new SDK you'll always get an error:

Error: No resource found that matches the given name (at 'value' with value '@integer/ google_play_services_version').

To solve that error many people advise to use a raw value, 4030500, instead of @integer/google_play_services_version, but it is correct ONLY for Google services revision 13.

If you use any older version or version for Froyo (like me) you should put another value in it. To know what value you should put just open a Google Play services manifest and copy-paste a version_code value. For Froyo services, it is 3265130. After adding this I've stopped getting this error, and I've began to receive coordinates in my application at last.

What is the difference between new/delete and malloc/free?

1.new syntex is simpler than malloc()

2.new/delete is a operator where malloc()/free() is a function.

3.new/delete execute faster than malloc()/free() because new assemly code directly pasted by the compiler.

4.we can change new/delete meaning in program with the help of operator overlading.

How to stop BackgroundWorker correctly

I agree with guys. But sometimes you have to add more things.

IE

1) Add this worker.WorkerSupportsCancellation = true;

2) Add to you class some method to do the following things

public void KillMe()
{
   worker.CancelAsync();
   worker.Dispose();
   worker = null;
   GC.Collect();
}

So before close your application your have to call this method.

3) Probably you can Dispose, null all variables and timers which are inside of the BackgroundWorker.

How does one generate a random number in Apple's Swift language?

var randomNumber = Int(arc4random_uniform(UInt32(5)))

Here 5 will make sure that the random number is generated through zero to four. You can set the value accordingly.

Eclipse internal error while initializing Java tooling

I was facing the same issue in eclipse so I am telling you the same step that I did you just need to go eclipse installed folder where you will find the file named eclipse.ini in my case the location was

C:\Users\comp\eclipse\jee-2018-12\eclipse

you can find your location.

in that location, open eclipse.ini in text mode and there you will find some below text
-Xms256m -Xmx1024m

change it to

-Xms512m -Xmx1024m

I hope that will help you 100% as checked in my System ;-)

Executing Shell Scripts from the OS X Dock?

You could create a Automator workflow with a single step - "Run Shell Script"

Then File > Save As, and change the File Format to "Application". When you open the application, it will run the Shell Script step, executing the command, exiting after it completes.

The benefit to this is it's really simple to do, and you can very easily get user input (say, selecting a bunch of files), then pass it to the input of the shell script (either to stdin, or as arguments).

(Automator is in your /Applications folder!)

Example workflow

href around input type submit

<a href="1.html"><input type="text" class="button_active" value="1"></a>
<a href="2.html"><input type="text" class="button" value="2"></a>
<a href="3.html"><input type="text" class="button" value="3"></a>

Try that. Unless you truly need to stick with the type as submit, then what I provided should work. If you are going to stick with submit, then everything mentioned above is correct, it makes no sense.

How to switch to new window in Selenium for Python?

window_handles should give you the references to all open windows.

this is what the docu has to say about switching windows.

Count number of matches of a regex in Javascript

(('a a a').match(/b/g) || []).length; // 0
(('a a a').match(/a/g) || []).length; // 3

Based on https://stackoverflow.com/a/48195124/16777 but fixed to actually work in zero-results case.

How to use mongoimport to import csv

Robert Stewart have already answered for how to import with mongoimport.

I am suggesting easy way to import CSV elegantly with 3T MongoChef Tool (3.2+ version). Might help someone in future.

  1. You just need to select collection
  2. Select file to import
  3. You can also unselect data which is going to import. Also many options are there.
  4. Collection imported

See how to import video

Making a Simple Ajax call to controller in asp.net mvc

Add "JsonValueProviderFactory" in global.asax :

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}

How to check if a variable is set in Bash?

if [[ ${!xx[@]} ]] ; then echo xx is defined; fi

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

Only issue with the solution provided by Greg is that it does not account for number greater than 100 with the "teen" numbers ending. For example, 111 should be 111th, not 111st. This is my solution:

/**
 * Return ordinal suffix (e.g. 'st', 'nd', 'rd', or 'th') for a given number
 * 
 * @param value
 *           a number
 * @return Ordinal suffix for the given number
 */
public static String getOrdinalSuffix( int value )
{
    int hunRem = value % 100;
    int tenRem = value % 10;

    if ( hunRem - tenRem == 10 )
    {
        return "th";
    }
    switch ( tenRem )
    {
    case 1:
        return "st";
    case 2:
        return "nd";
    case 3:
        return "rd";
    default:
        return "th";
    }
}