Programs & Examples On #Localnotification

A Cordova/PhoneGap plugin to create local notifications on iOS devices using hybrid apps

Will iOS launch my app into the background if it was force-quit by the user?

Actually if you need to test background fetch you need to enable one option in scheme:

enabling bg fetch

Another way how you can test it: simulate bg fetch

Here is full information about this new feature: http://www.objc.io/issue-5/multitasking.html

iOS application: how to clear notifications?

Update for iOS 10 (Swift 3)

In order to clear all local notifications in iOS 10 apps, you should use the following code:

import UserNotifications

...

if #available(iOS 10.0, *) {
    let center = UNUserNotificationCenter.current()
    center.removeAllPendingNotificationRequests() // To remove all pending notifications which are not delivered yet but scheduled.
    center.removeAllDeliveredNotifications() // To remove all delivered notifications
} else {
    UIApplication.shared.cancelAllLocalNotifications()
}

This code handles the clearing of local notifications for iOS 10.x and all preceding versions of iOS. You will need to import UserNotifications for the iOS 10.x code.

How to write a test which expects an Error to be thrown in Jasmine?

For anyone who still might be facing this issue, for me the posted solution didn't work and it kept on throwing this error: Error: Expected function to throw an exception. I later realised that the function which I was expecting to throw an error was an async function and was expecting promise to be rejected and then throw error and that's what I was doing in my code:

throw new Error('REQUEST ID NOT FOUND');

and thats what I did in my test and it worked:

it('Test should throw error if request not found', willResolve(() => {
         const promise = service.getRequestStatus('request-id');
                return expectToReject(promise).then((err) => {
                    expect(err.message).toEqual('REQUEST NOT FOUND');
                });
            }));

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

I know that people recommend staying away from rt.exec(String), but this works, and I don't know how to change it into the array version.

rt.exec("cmd.exe /c cd \""+new_dir+"\" & start cmd.exe /k \"java -flag -flag -cp terminal-based-program.jar\"");

Calculating the angle between the line defined by two points

Had a need for similar functionality myself, so after much hair pulling I came up with the function below

/**
 * Fetches angle relative to screen centre point
 * where 3 O'Clock is 0 and 12 O'Clock is 270 degrees
 * 
 * @param screenPoint
 * @return angle in degress from 0-360.
 */
public double getAngle(Point screenPoint) {
    double dx = screenPoint.getX() - mCentreX;
    // Minus to correct for coord re-mapping
    double dy = -(screenPoint.getY() - mCentreY);

    double inRads = Math.atan2(dy, dx);

    // We need to map to coord system when 0 degree is at 3 O'clock, 270 at 12 O'clock
    if (inRads < 0)
        inRads = Math.abs(inRads);
    else
        inRads = 2 * Math.PI - inRads;

    return Math.toDegrees(inRads);
}

How do I use Comparator to define a custom sort order?

I had to do something similar to Sean and ilalex's answer.
But I had too many options to explicitly define the sort order for and only needed to float certain entries to the front of the list ... in the specified (non-natural) order.
Hopefully this is helpful to someone else.

public class CarComparator implements Comparator<Car> {

    //sort these items in this order to the front of the list 
    private static List<String> ORDER = Arrays.asList("dd", "aa", "cc", "bb");

    public int compare(final Car o1, final Car o2) {
        int result = 0;
        int o1Index = ORDER.indexOf(o1.getName());
        int o2Index = ORDER.indexOf(o2.getName());
        //if neither are found in the order list, then do natural sort
        //if only one is found in the order list, float it above the other
        //if both are found in the order list, then do the index compare
        if (o1Index < 0 && o2Index < 0) result = o1.getName().compareTo(o2.getName());
        else if (o1Index < 0) result = 1;
        else if (o2Index < 0) result = -1;
        else result = o1Index - o2Index;
        return result;
    }

//Testing output: dd,aa,aa,cc,bb,bb,bb,a,aaa,ac,ac,ba,bd,ca,cb,cb,cd,da,db,dc,zz
}

How to mock a final class with mockito

Actually there is one way, which I use for spying. It would work for you only if two preconditions are satisfied:

  1. You use some kind of DI to inject an instance of final class
  2. Final class implements an interface

Please recall Item 16 from Effective Java. You may create a wrapper (not final) and forward all call to the instance of final class:

public final class RainOnTrees implement IRainOnTrees {
    @Override public void startRain() { // some code here }
}

public class RainOnTreesWrapper implement IRainOnTrees {
    private IRainOnTrees delegate;
    public RainOnTreesWrapper(IRainOnTrees delegate) {this.delegate = delegate;}
    @Override public void startRain() { delegate.startRain(); }
}

Now not only can you mock your final class but also spy on it:

public class Seasons{
    RainOnTrees rain;
    public Seasons(IRainOnTrees rain) { this.rain = rain; };
    public void findSeasonAndRain(){
        rain.startRain();
   }
}

IRainOnTrees rain = spy(new RainOnTreesWrapper(new RainOnTrees()) // or mock(IRainOnTrees.class)
doNothing().when(rain).startRain();
new Seasons(rain).findSeasonAndRain();

Value does not fall within the expected range

This might be due to the fact that you are trying to add a ListBoxItem with a same name to the page.

If you want to refresh the content of the listbox with the newly retrieved values you will have to first manually remove the content of the listbox other wise your loop will try to create lb_1 again and add it to the same list.

Look at here for a similar problem that occured Silverlight: Value does not fall within the expected range exception

Cheers,

How to view the Folder and Files in GAC?

I'm a day late and a dollar short on this one. If you want to view the folder structure of the GAC in Windows Explorer, you can do this by using the registry:

  1. Launch regedit.
  2. Navigate to HKLM\Software\Microsoft\Fusion
  3. Add a DWORD called DisableCacheViewer and set the value to 1.

For a temporary view, you can substitute a drive for the folder path, which strips away the special directory properties.

  1. Launch a Command Prompt at your account's privilege level.
  2. Type SUBST Z: C:\Windows\assembly
    • Z can be any free drive letter.
  3. Open My Computer and look in the new substitute directory.
  4. To remove the virtual drive from Command Prompt, type SUBST Z: /D

As for why you'd want to do something like this, I've used this trick to compare GAC'd DLLs between different machines to make sure they're truly the same.

'MOD' is not a recognized built-in function name

It can be done using % operator. i.e. SELECT 50 % 5

In Python, how do I read the exif data for an image?

Here's the one that may be little easier to read. Hope this is helpful.

from PIL import Image
from PIL import ExifTags

exifData = {}
img = Image.open(picture.jpg)
exifDataRaw = img._getexif()
for tag, value in exifDataRaw.items():
    decodedTag = ExifTags.TAGS.get(tag, tag)
    exifData[decodedTag] = value

How to avoid soft keyboard pushing up my layout?

In my case, the reason the buttons got pushed up was because the view above them was a ScrollView, and it got collapsed with the buttons pushed up above the keyboard no matter what value of android:windowSoftInputMode I was setting.

I was able to avoid my bottom row of buttons getting pushed up by the soft keyboard by setting

android:isScrollContainer="false" 

on the ScrollView that sits above the buttons.

INNER JOIN in UPDATE sql for DB2

The reference documentation for the UPDATE statement on DB2 LUW 9.7 gives the following example:

   UPDATE (SELECT EMPNO, SALARY, COMM,
     AVG(SALARY) OVER (PARTITION BY WORKDEPT),
     AVG(COMM) OVER (PARTITION BY WORKDEPT)
     FROM EMPLOYEE E) AS E(EMPNO, SALARY, COMM, AVGSAL, AVGCOMM)
   SET (SALARY, COMM) = (AVGSAL, AVGCOMM)
   WHERE EMPNO = '000120'

The parentheses after UPDATE can contain a full-select, meaning any valid SELECT statement can go there.

Based on that, I would suggest the following:

UPDATE (
  SELECT
    f1.firstfield,
    f2.anotherfield,
    f2.something
  FROM file1 f1
  WHERE f1.firstfield like 'BLAH%' 
  INNER JOIN file2 f2
  ON substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
)
AS my_files(firstfield, anotherfield, something)
SET
  firstfield = ( 'BIT OF TEXT' || something )

Edit: Ian is right. My first instinct was to try subselects instead:

UPDATE file1 f1
SET f1.firstfield = ( 'BIT OF TEXT' || (
  SELECT f2.something
  FROM file2 f2
  WHERE substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
))
WHERE f1.firstfield LIKE 'BLAH%' 
AND substr(f1.firstfield,10,20) IN (
  SELECT substr(f2.anotherfield,1,10)
  FROM file2 f2
)

But I'm not sure if the concatenation would work. It also assumes that there's a 1:1 mapping between the substrings. If there are multiple rows that match, it wouldn't work.

Align div right in Bootstrap 3

The class pull-right is still there in Bootstrap 3 See the 'helper classes' here

pull-right is defined by

.pull-right {
  float: right !important;
}

without more info on styles and content, it's difficult to say.

It definitely pulls right in this JSBIN when the page is wider than 990px - which is when the col-md styling kicks in, Bootstrap 3 being mobile first and all.

Bootstrap 4

Note that for Bootstrap 4 .pull-right has been replaced with .float-right https://www.geeksforgeeks.org/pull-left-and-pull-right-classes-in-bootstrap-4/#:~:text=pull%2Dright%20classes%20have%20been,based%20on%20the%20Bootstrap%20Grid.

Python: How to get stdout after running os.system?

These answers didn't work for me. I had to use the following:

import subprocess
p = subprocess.Popen(["pwd"], stdout=subprocess.PIPE)
out = p.stdout.read()
print out

Or as a function (using shell=True was required for me on Python 2.6.7 and check_output was not added until 2.7, making it unusable here):

def system_call(command):
    p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True)
    return p.stdout.read()

What exactly does Perl's "bless" do?

For example, if you can be confident that any Bug object is going to be a blessed hash, you can (finally!) fill in the missing code in the Bug::print_me method:

 package Bug;
 sub print_me
 {
     my ($self) = @_;
     print "ID: $self->{id}\n";
     print "$self->{descr}\n";
     print "(Note: problem is fatal)\n" if $self->{type} eq "fatal";
 }

Now, whenever the print_me method is called via a reference to any hash that's been blessed into the Bug class, the $self variable extracts the reference that was passed as the first argument and then the print statements access the various entries of the blessed hash.

How to change TIMEZONE for a java.util.Calendar/Date

In Java, Dates are internally represented in UTC milliseconds since the epoch (so timezones are not taken into account, that's why you get the same results, as getTime() gives you the mentioned milliseconds).
In your solution:

Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();

long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);

you just add the offset from GMT to the specified timezone ("Asia/Calcutta" in your example) in milliseconds, so this should work fine.

Another possible solution would be to utilise the static fields of the Calendar class:

//instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cSchedStartCal.get(Calendar.HOUR_OF_DAY);

Refer to stackoverflow.com/questions/7695859/ for a more in-depth explanation.

mkdir's "-p" option

PATH: Answered long ago, however, it maybe more helpful to think of -p as "Path" (easier to remember), as in this causes mkdir to create every part of the path that isn't already there.

mkdir -p /usr/bin/comm/diff/er/fence

if /usr/bin/comm already exists, it acts like: mkdir /usr/bin/comm/diff mkdir /usr/bin/comm/diff/er mkdir /usr/bin/comm/diff/er/fence

As you can see, it saves you a bit of typing, and thinking, since you don't have to figure out what's already there and what isn't.

How to debug a bash script?

Use eclipse with the plugins shelled & basheclipse.

https://sourceforge.net/projects/shelled/?source=directory https://sourceforge.net/projects/basheclipse/?source=directory

For shelled: Download the zip and import it into eclipse via help -> install new software : local archive For basheclipse: Copy the jars into dropins directory of eclipse

Follow the steps provides https://sourceforge.net/projects/basheclipse/files/?source=navbar

enter image description here

I wrote a tutorial with many screenshots at http://dietrichschroff.blogspot.de/2017/07/bash-enabling-eclipse-for-bash.html

Android: Access child views from a ListView

This code is easier to use:

 View rowView = listView.getChildAt(viewIndex);//The item number in the List View
    if(rowView != null)
        {
           // Your code here
        }

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

How to emulate a do-while loop in Python?

If you're in a scenario where you are looping while a resource is unavaliable or something similar that throws an exception, you could use something like

import time

while True:
    try:
       f = open('some/path', 'r')
    except IOError:
       print('File could not be read. Retrying in 5 seconds')   
       time.sleep(5)
    else:
       break

Viewing root access files/folders of android on windows

Obviously, you'll need a rooted android device. Then set up an FTP server and transfer the files.

Gradients on UIView and UILabels On iPhone

Mirko Froehlich's answer worked for me, except when i wanted to use custom colors. The trick is to specify UI color with Hue, saturation and brightness instead of RGB.

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = myView.bounds;
UIColor *startColour = [UIColor colorWithHue:.580555 saturation:0.31 brightness:0.90 alpha:1.0];
UIColor *endColour = [UIColor colorWithHue:.58333 saturation:0.50 brightness:0.62 alpha:1.0];
gradient.colors = [NSArray arrayWithObjects:(id)[startColour CGColor], (id)[endColour CGColor], nil];
[myView.layer insertSublayer:gradient atIndex:0];

To get the Hue, Saturation and Brightness of a color, use the in built xcode color picker and go to the HSB tab. Hue is measured in degrees in this view, so divide the value by 360 to get the value you will want to enter in code.

Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern

var response = taskwithresponse.Result;
          var jsonString = response.ReadAsAsync<List<Job>>().Result;

Set line height in Html <p> to make the html looks like a office word when <p> has different font sizes

I found that in my code when I used a ration or percentage for line-height line-height;1.5;

My page would scale in such a way that lower case font and upper case font would take up different page heights (I.E. All caps took more room than all lower). Normally I think this looks better, but I had to go to a fixed height line-height:24px; so that I could predict exactly how many pixels each page would take with a given number of lines.

Fully custom validation error message with Rails

Try this.

class User < ActiveRecord::Base
  validate do |user|
    user.errors.add_to_base("Country can't be blank") if user.country_iso.blank?
  end
end

I found this here.

Update for Rails 3 to 6:

validate do |user|
  user.errors.add(:base, "Country can't be blank") if user.country_iso.blank?
end

Here is another way to do it. What you do is define a human_attribute_name method on the model class. The method is passed the column name as a string and returns the string to use in validation messages.

class User < ActiveRecord::Base

  HUMANIZED_ATTRIBUTES = {
    :email => "E-mail address"
  }

  def self.human_attribute_name(attr)
    HUMANIZED_ATTRIBUTES[attr.to_sym] || super
  end

end

The above code is from here

How to get data out of a Node.js http get request

I think it's too late to answer this question but I faced the same problem recently my use case was to call the paginated JSON API and get all the data from each pagination and append it to a single array.

const https = require('https');
const apiUrl = "https://example.com/api/movies/search/?Title=";
let finaldata = [];
let someCallBack = function(data){
  finaldata.push(...data);
  console.log(finaldata);
};
const getData = function (substr, pageNo=1, someCallBack) {

  let actualUrl = apiUrl + `${substr}&page=${pageNo}`;
  let mydata = []
  https.get(actualUrl, (resp) => {
    let data = '';
    resp.on('data', (chunk) => {
        data += chunk;
    });
    resp.on('end', async () => {
        if (JSON.parse(data).total_pages!==null){
          pageNo+=1;
          somCallBack(JSON.parse(data).data);
          await getData(substr, pageNo, someCallBack);
        }
    });
  }).on("error", (err) => {
      console.log("Error: " + err.message);
  });
}

getData("spiderman", pageNo=1, someCallBack);

Like @ackuser mentioned we can use other module but In my use case I had to use the node https. Hoping this will help others.

HTML set image on browser tab

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

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

Change some value inside the List<T>

You could use ForEach, but you have to convert the IEnumerable<T> to a List<T> first.

list.Where(w => w.Name == "height").ToList().ForEach(s => s.Value = 30);

adb is not recognized as internal or external command on windows

If you go to your android-sdk/tools folder I think you'll find a message :

The adb tool has moved to platform-tools/

If you don't see this directory in your SDK, launch the SDK and AVD Manager (execute the android tool) and install "Android SDK Platform-tools"

Please also update your PATH environment variable to include the platform-tools/ directory, so you can execute adb from any location.

So you should also add C:/android-sdk/platform-tools to you environment path. Also after you modify the PATH variable make sure that you start a new CommandPrompt window.

What should every programmer know about security?

Every programmer should know how to write exploit code.

Without knowing how systems are exploited you are accidentally stopping vulnerabilities. Knowing how to patch code is absolutely meaningless unless you know how to test your patches. Security isn't just a bunch of thought experiments, you must be scientific and test your experiments.

Use :hover to modify the css of another class?

There are two approaches you can take, to have a hovered element affect (E) another element (F):

  1. F is a child-element of E, or
  2. F is a later-sibling (or sibling's descendant) element of E (in that E appears in the mark-up/DOM before F):

To illustrate the first of these options (F as a descendant/child of E):

.item:hover .wrapper {
    color: #fff;
    background-color: #000;
}?

To demonstrate the second option, F being a sibling element of E:

.item:hover ~ .wrapper {
    color: #fff;
    background-color: #000;
}?

In this example, if .wrapper was an immediate sibling of .item (with no other elements between the two) you could also use .item:hover + .wrapper.

JS Fiddle demonstration.

References:

Variables declared outside function

Unlike languages that employ 'true' lexical scoping, Python opts to have specific 'namespaces' for variables, whether it be global, nonlocal, or local. It could be argued that making developers consciously code with such namespaces in mind is more explicit, thus more understandable. I would argue that such complexities make the language more unwieldy, but I guess it's all down to personal preference.

Here are some examples regarding global:-

>>> global_var = 5
>>> def fn():
...     print(global_var)
... 
>>> fn()
5
>>> def fn_2():
...     global_var += 2
...     print(global_var)
... 
>>> fn_2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in fn_2
UnboundLocalError: local variable 'global_var' referenced before assignment
>>> def fn_3():
...     global global_var
...     global_var += 2
...     print(global_var)
... 
>>> fn_3()
7

The same patterns can be applied to nonlocal variables too, but this keyword is only available to the latter Python versions.

In case you're wondering, nonlocal is used where a variable isn't global, but isn't within the function definition it's being used. For example, a def within a def, which is a common occurrence partially due to a lack of multi-statement lambdas. There's a hack to bypass the lack of this feature in the earlier Pythons though, I vaguely remember it involving the use of a single-element list...

Note that writing to variables is where these keywords are needed. Just reading from them isn't ambiguous, thus not needed. Unless you have inner defs using the same variable names as the outer ones, which just should just be avoided to be honest.

Finding out the name of the original repository you cloned from in Git

This is quick Bash command, that you're probably searching for, will print only a basename of the remote repository:

Where you fetch from:

basename $(git remote show -n origin | grep Fetch | cut -d: -f2-)

Alternatively where you push to:

basename $(git remote show -n origin | grep Push | cut -d: -f2-)

Especially the -n option makes the command much quicker.

Java 8 lambdas, Function.identity() or t->t

As of the current JRE implementation, Function.identity() will always return the same instance while each occurrence of identifier -> identifier will not only create its own instance but even have a distinct implementation class. For more details, see here.

The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x, equivalent to return identifier;) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.

So using Function.identity() instead of x -> x might save some memory but that shouldn’t drive your decision if you really think that x -> x is more readable than Function.identity().

You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function instance while debugging. In contrast, when encountering the instance returned by Function.identity() during debugging an operation, you won’t know who has called that method and passed the instance to the operation.

LaTeX table positioning

What happens if the text plus tables plus text doesn't fit onto a single page? By trying to force the typesetting in this way, you are very likely to end up with pages that run too short; i.e., because a table cannot by default break over a page it will be pushed to the next, and leave a gap on the page before. You'll notice that you never see this in a published book.

The floating behaviour is a Good Thing! I recommend using [htbp] as the default setting for all tables and figures until your document is complete; only then should think about fine-tuning their precise placement.

P.S. Read the FAQ; most other answers here are partial combinations of advice given there.

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

If you want to read large files, you should read them bit by bit instead of reading them at once.
It’s simple math: If you read a 1 MB large file at once, than at least 1 MB of memory is needed at the same time to hold the data.

So you should read them bit by bit using fopen & fread.

converting list to json format - quick and easy way

I've done something like before using the JavaScript serialization class:

using System.Web.Script.Serialization;

And:

JavaScriptSerializer jss = new JavaScriptSerializer();

string output = jss.Serialize(ListOfMyObject);
Response.Write(output);
Response.Flush();
Response.End();

In javascript, how do you search an array for a substring match

I've created a simple to use library (ss-search) which is designed to handle objects, but could also work in your case:

search(windowArray.map(x => ({ key: x }), ["key"], "SEARCH_TEXT").map(x => x.key)

The advantage of using this search function is that it will normalize the text before executing the search to return more accurate results.

Need a good hex editor for Linux

Bless is a high quality, full featured hex editor.

It is written in mono/Gtk# and its primary platform is GNU/Linux. However it should be able to run without problems on every platform that mono and Gtk# run.

Bless currently provides the following features:

  • Efficient editing of large data files and block devices.
  • Multilevel undo - redo operations.
  • Customizable data views.
  • Fast data rendering on screen.
  • Multiple tabs.
  • Fast find and replace operations.
  • A data conversion table.
  • Advanced copy/paste capabilities.
  • Highlighting of selection pattern matches in the file.
  • Plugin based architecture.
  • Export of data to text and html (others with plugins).
  • Bitwise operations on data.
  • A comprehensive user manual.

wxHexEditor is another Free Hex Editor, built because there is no good hex editor for Linux system, specially for big files.

  • It uses 64 bit file descriptors (supports files or devices up to 2^64 bytes , means some exabytes but tested only 1 PetaByte file (yet). ).
  • It does NOT copy whole file to your RAM. That make it FAST and can open files (which sizes are Multi Giga < Tera < Peta < Exabytes)
  • Could open your devices on Linux, Windows or MacOSX.
  • Memory Usage : Currently ~10 MegaBytes while opened multiple > ~8GB files.
  • Could operate thru XOR encryption.
  • Written with C++/wxWidgets GUI libs and can be used with other OSes such as Mac OS, Windows as native application.
  • You can copy/edit your Disks, HDD Sectors with it.( Usefull for rescue files/partitions by hand. )
  • You can delete/insert bytes to file, more than once, without creating temp file.

DHEX is a more than just another hex editor: It includes a diff mode, which can be used to easily and conveniently compare two binary files. Since it is based on ncurses and is themeable, it can run on any number of systems and scenarios. With its utilization of search logs, it is possible to track changes in different iterations of files easily. Wikipedia article

You can sort on Linux to find some more here: http://en.wikipedia.org/wiki/Comparison_of_hex_editors

Docker: Copying files from Docker container to host

If you just want to pull a file from an image (instead of a running container) you can do this:

docker run --rm <image> cat <source> > <local_dest>

This will bring up the container, write the new file, then remove the container. One drawback, however, is that the file permissions and modified date will not be preserved.

When do I need to use AtomicBoolean in Java?

When multiple threads need to check and change the boolean. For example:

if (!initialized) {
   initialize();
   initialized = true;
}

This is not thread-safe. You can fix it by using AtomicBoolean:

if (atomicInitialized.compareAndSet(false, true)) {
    initialize();
}

Can a shell script set environment variables of the calling shell?

It's "kind of" possible through using gdb and setenv(3), although I have a hard time recommending actually doing this. (Additionally, i.e. the most recent ubuntu won't actually let you do this without telling the kernel to be more permissive about ptrace, and the same may go for other distros as well).

$ cat setfoo
#! /bin/bash

gdb /proc/${PPID}/exe ${PPID} <<END >/dev/null
call setenv("foo", "bar", 0)
END
$ echo $foo

$ ./setfoo
$ echo $foo
bar

How can I use an ES6 import in Node.js?

I just wanted to use the import and export in JavaScript files.

Everyone says it's not possible. But, as of May 2018, it's possible to use above in plain Node.js, without any modules like Babel, etc.

Here is a simple way to do it.

Create the below files, run, and see the output for yourself.

Also don't forget to see Explanation below.

File myfile.mjs

function myFunc() {
    console.log("Hello from myFunc")
}

export default myFunc;

File index.mjs

import myFunc from "./myfile.mjs"  // Simply using "./myfile" may not work in all resolvers

myFunc();

Run

node  --experimental-modules  index.mjs

Output

(node:12020) ExperimentalWarning: The ESM module loader is experimental.

Hello from myFunc

Explanation:

  1. Since it is experimental modules, .js files are named .mjs files
  2. While running you will add --experimental-modules to the node index.mjs
  3. While running with experimental modules in the output you will see: "(node:12020) ExperimentalWarning: The ESM module loader is experimental. "
  4. I have the current release of Node.js, so if I run node --version, it gives me "v10.3.0", though the LTE/stable/recommended version is 8.11.2 LTS.
  5. Someday in the future, you could use .js instead of .mjs, as the features become stable instead of Experimental.
  6. More on experimental features, see: https://nodejs.org/api/esm.html

Format an Excel column (or cell) as Text in C#?

I know this question is aged, still, I would like to contribute.

Applying Range.NumberFormat = "@" just partially solve the problem:

  • Yes, if you place the focus on a cell of the range, you will read text in the format menu
  • Yes, it align the data to the left
  • But if you use the type formula to check the type of the value in the cell, it will return 1 meaning number

Applying the apostroph behave better. It sets the format to text, it align data to left and if you check the format of the value in the cell using the type formula, it will return 2 meaning text

How to expand textarea width to 100% of parent (or how to expand any HTML element to 100% of parent width)?

I would do something like this:

HTML:

<div class="wrapper">
    <div class="side">sidebar here</div>
    <div class="main">
        <textarea class="taclass"></textarea>
    </div>
</div><!--/ wrapper -->

CSS:

.wrapper{
    display: block;
    width: 100%;
    overflow: hidden;
}
.side{
    float:left;
    width:20%;
}
.main{
    float:right;
    width:80%;
}
.taclass{
    display:block;
    width:100%;
    padding:2%;
    -webkit-box-sizing: border-box;
       -moz-box-sizing: border-box;
            box-sizing: border-box;
}

PHP Regex to check date is in YYYY-MM-DD format

Function to validate generic date format:

function validateDate($date, $format = 'Y-m-d') {
  $d = DateTime::createFromFormat($format, $date);
  return $d && $d->format($format) == $date;
}

Example of execution:

var_dump(validateDate('2021-02-28')); // true
var_dump(validateDate('2021-02-29')); // false

difference between throw and throw new Exception()

Your second example will reset the exception's stack trace. The first most accurately preserves the origins of the exception. Also you've unwrapped the original type which is key in knowing what actually went wrong... If the second is required for functionality - e.g. To add extended info or re-wrap with special type such as a custom 'HandleableException' then just be sure that the InnerException property is set too!

How to round up a number in Javascript?

/**
 * @param num The number to round
 * @param precision The number of decimal places to preserve
 */
function roundUp(num, precision) {
  precision = Math.pow(10, precision)
  return Math.ceil(num * precision) / precision
}

roundUp(192.168, 1) //=> 192.2

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

I've had this happen on VS after I changed the file's line endings. Changing them back to Windows CR LF fixed the issue.

How to paste yanked text into the Vim command line

For pasting something from the system clipboard into the Vim command line ("command mode"), use Ctrl+R followed by +. For me, at least on Ubuntu, Shift+Ins is not working.

PS: I am not sure why Ctrl+R followed by *, which is theoretically the same as Ctrl+R followed by + doesn't seem to work always. I searched and discovered the + version and it seems to work always, at least on my box.

What is "pom" packaging in maven?

To simply answer your question when you do a mvn:install, maven will create a packaged artifact based on (packaging attribute in pom.xml), After you run your maven install you can find the file with .package extension

  • In target directory of the project workspace
  • Also where your maven 2 local repository is search for (.m2/respository) on your box, Your artifact is listed in .m2 repository under (groupId/artifactId/artifactId-version.packaging) directory
  • If you look under the directory you will find packaged extension file and also pom extension (pom extension is basically the pom.xml used to generate this package)
  • If your maven project is multi-module each module will two files as described above except for the top level project that will only have a pom

Split string with multiple delimiters in Python

Luckily, Python has this built-in :)

import re
re.split('; |, ',str)

Update:
Following your comment:

>>> a='Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n',a)
['Beautiful', 'is', 'better', 'than', 'ugly']

React setState not updating state

just add componentDidUpdate(){} method in your code, and it will work. you can check the life cycle of react native here:

https://images.app.goo.gl/BVRAi4ea2P4LchqJ8

What is the 'override' keyword in C++ used for?

The override keyword serves two purposes:

  1. It shows the reader of the code that "this is a virtual method, that is overriding a virtual method of the base class."
  2. The compiler also knows that it's an override, so it can "check" that you are not altering/adding new methods that you think are overrides.

To explain the latter:

class base
{
  public:
    virtual int foo(float x) = 0; 
};


class derived: public base
{
   public:
     int foo(float x) override { ... } // OK
}

class derived2: public base
{
   public:
     int foo(int x) override { ... } // ERROR
};

In derived2 the compiler will issue an error for "changing the type". Without override, at most the compiler would give a warning for "you are hiding virtual method by same name".

How do you Programmatically Download a Webpage in Java

On a Unix/Linux box you could just run 'wget' but this is not really an option if you're writing a cross-platform client. Of course this assumes that you don't really want to do much with the data you download between the point of downloading it and it hitting the disk.

How to get filename without extension from file path in Ruby

Note that double quotes strings escape \'s.

'C:\projects\blah.dll'.split('\\').last

Get div's offsetTop positions in React

I do realize that the author asks question in relation to a class-based component, however I think it's worth mentioning that as of React 16.8.0 (February 6, 2019) you can take advantage of hooks in function-based components.

Example code:

import { useRef } from 'react'

function Component() {
  const inputRef = useRef()

  return (
    <input ref={inputRef} />
    <div
      onScroll={() => {
        const { offsetTop } = inputRef.current
        ...
      }}
    >
  )
}

How can I get the console logs from the iOS Simulator?

tailing /var/log/system.log didn't work for me. I found my logs by using Console.app. They were in

~/Library/Logs/iOS Simulator/{version}/system.log

Current time in microseconds in java

No, Java doesn't have that ability.

It does have System.nanoTime(), but that just gives an offset from some previously known time. So whilst you can't take the absolute number from this, you can use it to measure nanosecond (or higher) precision.

Note that the JavaDoc says that whilst this provides nanosecond precision, that doesn't mean nanosecond accuracy. So take some suitably large modulus of the return value.

Get width in pixels from element with style set with %?

You want to get the computed width. Try: .offsetWidth

(I.e: this.offsetWidth='50px' or var w=this.offsetWidth)

You might also like this answer on SO.

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

jQuery event handlers always execute in order they were bound - any way around this?

You can do a custom namespace of events.

$('span').bind('click.doStuff1',function(){doStuff1();});
$('span').bind('click.doStuff2',function(){doStuff2();});

Then, when you need to trigger them you can choose the order.

$('span').trigger('click.doStuff1').trigger('click.doStuff2');

or

$('span').trigger('click.doStuff2').trigger('click.doStuff1');

Also, just triggering click SHOULD trigger both in the order they were bound... so you can still do

$('span').trigger('click'); 

Get domain name

If you want specific users to have access to all or part of the WMI object space, you need to permission them as shown here. Note that you have to be running on as an admin to perform this setting.

Load properties file in JAR?

For the record, this is documented in How do I add resources to my JAR? (illustrated for unit tests but the same applies for a "regular" resource):

To add resources to the classpath for your unit tests, you follow the same pattern as you do for adding resources to the JAR except the directory you place resources in is ${basedir}/src/test/resources. At this point you would have a project directory structure that would look like the following:

my-app
|-- pom.xml
`-- src
    |-- main
    |   |-- java
    |   |   `-- com
    |   |       `-- mycompany
    |   |           `-- app
    |   |               `-- App.java
    |   `-- resources
    |       `-- META-INF
    |           |-- application.properties
    `-- test
        |-- java
        |   `-- com
        |       `-- mycompany
        |           `-- app
        |               `-- AppTest.java
        `-- resources
            `-- test.properties

In a unit test you could use a simple snippet of code like the following to access the resource required for testing:

...

// Retrieve resource
InputStream is = getClass().getResourceAsStream("/test.properties" );

// Do something with the resource

...

Disable arrow key scrolling in users browser

For maintainability, I would attach the "blocking" handler on the element itself (in your case, the canvas).

theCanvas.onkeydown = function (e) {
    if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
        e.view.event.preventDefault();
    }
}

Why not simply do window.event.preventDefault()? MDN states:

window.event is a proprietary Microsoft Internet Explorer property which is only available while a DOM event handler is being called. Its value is the Event object currently being handled.

Further readings:

Example of a strong and weak entity types

./Database/DataModels/RelationalDataModel/WeakEntity

It probably can be written in two factors:

  • DEPENDENCE: Depends on the existence of an identifying entity set (total, one-to-many relationship).
  • IDENTIFICATION: Does not have a primary key. It has a partial key (or discriminator). It needs to use the primary key of another table for identification.

If we would think of a database holding questions and answers, then the questions would be the strong entity and the answers would be the weak entity. So, Question (id, text) and Answer (number, question_id, text) would be our tables. But why is the Answer's table a weak entity?

  • Dependence to the question table. Every answer is connected to one question (assumption) and so it cannot be on its own. That is why we have people who ask one question and answer it themselves so that they can help other people and get some extra likings.

  • Identification from the primary key of the question. One would not be able to identify an answer (assuming that its id is a number identifier) because a question might be answered by answers whose identifier might exist in other questions too. Primary key of the answer table: (number, question_id).

How to convert a string to utf-8 in Python

If I understand you correctly, you have a utf-8 encoded byte-string in your code.

Converting a byte-string to a unicode string is known as decoding (unicode -> byte-string is encoding).

You do that by using the unicode function or the decode method. Either:

unicodestr = unicode(bytestr, encoding)
unicodestr = unicode(bytestr, "utf-8")

Or:

unicodestr = bytestr.decode(encoding)
unicodestr = bytestr.decode("utf-8")

py2exe - generate single executable file

You should create an installer, as mentioned before. Even though it is also possible to let py2exe bundle everything into a single executable, by setting bundle_files option to 1 and the zipfile keyword argument to None, I don't recommend this for PyGTK applications.

That's because of GTK+ tries to load its data files (locals, themes, etc.) from the directory it was loaded from. So you have to make sure that the directory of your executable contains also the libraries used by GTK+ and the directories lib, share and etc from your installation of GTK+. Otherwise you will get problems running your application on a machine where GTK+ is not installed system-wide.

For more details read my guide to py2exe for PyGTK applications. It also explains how to bundle everything, but GTK+.

Difference between "enqueue" and "dequeue"

Some of the basic data structures in programming languages such as C and C++ are stacks and queues.

The stack data structure follows the "First In Last Out" policy (FILO) where the first element inserted or "pushed" into a stack is the last element that is removed or "popped" from the stack.

Similarly, a queue data structure follows a "First In First Out" policy (as in the case of a normal queue when we stand in line at the counter), where the first element is pushed into the queue or "Enqueued" and the same element when it has to be removed from the queue is "Dequeued".

This is quite similar to push and pop in a stack, but the terms enqueue and dequeue avoid confusion as to whether the data structure in use is a stack or a queue.

Class coders has a simple program to demonstrate the enqueue and dequeue process. You could check it out for reference.

http://classcoders.blogspot.in/2012/01/enque-and-deque-in-c.html

How do you create a dictionary in Java?

This creates dictionary of text (string):

Map<String, String> dictionary = new HashMap<String, String>();

you then use it as a:

dictionary.put("key", "value");
String value = dictionary.get("key");

Works but gives an error you need to keep the constructor class same as the declaration class. I know it inherits from the parent class but, unfortunately it gives an error on runtime.

Map<String, String> dictionary = new Map<String, String>();

This works properly.

How do I check if a string contains another string in Objective-C?

Oneliner (Smaller amount of code. DRY, as you have only one NSLog):

NSString *string = @"hello bla bla";
NSLog(@"String %@", ([string rangeOfString:@"bla"].location == NSNotFound) ? @"not found" : @"cotains bla"); 

trying to align html button at the center of the my page

try this it is quite simple and give you cant make changes to your .css file this should work

<p align="center">
<button type="button" style="background-color:yellow;margin-left:auto;margin-right:auto;display:block;margin-top:22%;margin-bottom:0%"> mybuttonname</button>
</p>

Why is a "GRANT USAGE" created the first time I grant a user privileges?

I was trying to find the meaning of GRANT USAGE on *.* TO and found here. I can clarify that GRANT USAGE on *.* TO user IDENTIFIED BY PASSWORD password will be granted when you create the user with the following command (CREATE):

CREATE USER 'user'@'localhost' IDENTIFIED BY 'password'; 

When you grant privilege with GRANT, new privilege s will be added on top of it.

MySQL string replace

You can simply use replace() function,

with where clause-

update tabelName set columnName=REPLACE(columnName,'from','to') where condition;

without where clause-

update tabelName set columnName=REPLACE(columnName,'from','to');

Note: The above query if for update records directly in table, if you want on select query and the data should not be affected in table then can use the following query-

select REPLACE(columnName,'from','to') as updateRecord;

java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

A common misunderstanding among starters is that they think that the call of a forward(), sendRedirect(), or sendError() would magically exit and "jump" out of the method block, hereby ignoring the remnant of the code. For example:

protected void doXxx() {
    if (someCondition) {
        sendRedirect();
    }
    forward(); // This is STILL invoked when someCondition is true!
}

This is thus actually not true. They do certainly not behave differently than any other Java methods (expect of System#exit() of course). When the someCondition in above example is true and you're thus calling forward() after sendRedirect() or sendError() on the same request/response, then the chance is big that you will get the exception:

java.lang.IllegalStateException: Cannot forward after response has been committed

If the if statement calls a forward() and you're afterwards calling sendRedirect() or sendError(), then below exception will be thrown:

java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

To fix this, you need either to add a return; statement afterwards

protected void doXxx() {
    if (someCondition) {
        sendRedirect();
        return;
    }
    forward();
}

... or to introduce an else block.

protected void doXxx() {
    if (someCondition) {
        sendRedirect();
    } else {
        forward();
    }
}

To naildown the root cause in your code, just search for any line which calls a forward(), sendRedirect() or sendError() without exiting the method block or skipping the remnant of the code. This can be inside the same servlet before the particular code line, but also in any servlet or filter which was been called before the particular servlet.

In case of sendError(), if your sole purpose is to set the response status, use setStatus() instead.


Another probable cause is that the servlet writes to the response while a forward() will be called, or has been called in the very same method.

protected void doXxx() {
    out.write("some string");
    // ... 
    forward(); // Fail!
}

The response buffer size defaults in most server to 2KB, so if you write more than 2KB to it, then it will be committed and forward() will fail the same way:

java.lang.IllegalStateException: Cannot forward after response has been committed

Solution is obvious, just don't write to the response in the servlet. That's the responsibility of the JSP. You just set a request attribute like so request.setAttribute("data", "some string") and then print it in JSP like so ${data}. See also our Servlets wiki page to learn how to use Servlets the right way.


Another probable cause is that the servlet writes a file download to the response after which e.g. a forward() is called.

protected void doXxx() {
    out.write(bytes);
    // ... 
    forward(); // Fail!
}

This is technically not possible. You need to remove the forward() call. The enduser will stay on the currently opened page. If you actually intend to change the page after a file download, then you need to move the file download logic to page load of the target page.


Yet another probable cause is that the forward(), sendRedirect() or sendError() methods are invoked via Java code embedded in a JSP file in form of old fashioned way <% scriptlets %>, a practice which was officially discouraged since 2001. For example:

<!DOCTYPE html>
<html lang="en">
    <head>
        ... 
    </head>
    <body>
        ...

        <% sendRedirect(); %>
        
        ...
    </body>
</html>

The problem here is that JSP internally immediately writes template text (i.e. HTML code) via out.write("<!DOCTYPE html> ... etc ...") as soon as it's encountered. This is thus essentially the same problem as explained in previous section.

Solution is obvious, just don't write Java code in a JSP file. That's the responsibility of a normal Java class such as a Servlet or a Filter. See also our Servlets wiki page to learn how to use Servlets the right way.


See also:


Unrelated to your concrete problem, your JDBC code is leaking resources. Fix that as well. For hints, see also How often should Connection, Statement and ResultSet be closed in JDBC?

How do I calculate the date in JavaScript three months prior to today?

A "one liner" (on many line for easy read)) to be put directly into a variable:

var oneMonthAgo = new Date(
    new Date().getFullYear(),
    new Date().getMonth() - 1, 
    new Date().getDate()
);

Oracle date "Between" Query

Following query also can be used:

select * 
  from t23
 where trunc(start_date) between trunc(to_date('01/15/2010','mm/dd/yyyy')) and trunc(to_date('01/17/2010','mm/dd/yyyy'))

How can I use Html.Action?

first, create a class to hold your parameters:

public class PkRk {
    public int pk { get; set; }
    public int rk { get; set; }
}

then, use the Html.Action passing the parameters:

Html.Action("PkRkAction", new { pkrk = new PkRk { pk=400, rk=500} })

and use in Controller:

public ActionResult PkRkAction(PkRk pkrk) {
    return PartialView(pkrk);
}

jquery multiple checkboxes array

var checkedString = $('input:checkbox:checked.name').map(function() { return this.value; }).get().join();

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

  1. replace all single quotes with double quotes
  2. replace 'u"' from your strings to '"' ... so basically convert internal unicodes to strings before loading the string into json
>> strs = "{u'key':u'val'}"
>> strs = strs.replace("'",'"')
>> json.loads(strs.replace('u"','"'))

Uploading a file in Rails

Update 2018

While everything written below still holds true, Rails 5.2 now includes active_storage, which allows stuff like uploading directly to S3 (or other cloud storage services), image transformations, etc. You should check out the rails guide and decide for yourself what fits your needs.


While there are plenty of gems that solve file uploading pretty nicely (see https://www.ruby-toolbox.com/categories/rails_file_uploads for a list), rails has built-in helpers which make it easy to roll your own solution.

Use the file_field-form helper in your form, and rails handles the uploading for you:

<%= form_for @person do |f| %>
  <%= f.file_field :picture %>
<% end %>

You will have access in the controller to the uploaded file as follows:

uploaded_io = params[:person][:picture]
File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'wb') do |file|
  file.write(uploaded_io.read)
end

It depends on the complexity of what you want to achieve, but this is totally sufficient for easy file uploading/downloading tasks. This example is taken from the rails guides, you can go there for further information: http://guides.rubyonrails.org/form_helpers.html#uploading-files

.crx file install in chrome

Opening the debug console in Chrome, or even looking at the html source file (after it is loaded in the browser), make sure that all the paths there are valid (i.e. when you follow a link you get to it's content, and not an error). When something is not valid, fix the path (e.g. get rid of the server specific part and make sure you only refer to files that are part of your extension through paths like /js/jquery-123-min.js).

MongoDB vs Firebase

Apples and oranges. Firebase is a Backend-as-a-Service containing identity management, realtime data views and a document database. It runs in the cloud.

MongoDB on the other hand is a full fledged database with a rich query language. In principle it runs on your own machine, but there are cloud providers.

If you are looking for the database component only MongoDB is much more mature and feature-rich.

How to set a fixed width column with CSS flexbox

You should use the flex or flex-basis property rather than width. Read more on MDN.

.flexbox .red {
  flex: 0 0 25em;
}

The flex CSS property is a shorthand property specifying the ability of a flex item to alter its dimensions to fill available space. It contains:

flex-grow: 0;     /* do not grow   - initial value: 0 */
flex-shrink: 0;   /* do not shrink - initial value: 1 */
flex-basis: 25em; /* width/height  - initial value: auto */

A simple demo shows how to set the first column to 50px fixed width.

_x000D_
_x000D_
.flexbox {_x000D_
  display: flex;_x000D_
}_x000D_
.red {_x000D_
  background: red;_x000D_
  flex: 0 0 50px;_x000D_
}_x000D_
.green {_x000D_
  background: green;_x000D_
  flex: 1;_x000D_
}_x000D_
.blue {_x000D_
  background: blue;_x000D_
  flex: 1;_x000D_
}
_x000D_
<div class="flexbox">_x000D_
  <div class="red">1</div>_x000D_
  <div class="green">2</div>_x000D_
  <div class="blue">3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


See the updated codepen based on your code.

Confirm button before running deleting routine from website

You can do it with an confirm() message using Javascript.

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

This is specific for each site. So if you type that once, you will only get through that site and all other sites will need a similar type-through.

It is also remembered for that site and you have to click on the padlock to reset it (so you can type it again):

enter image description here

Needless to say use of this "feature" is a bad idea and is unsafe - hence the name.

You should find out why the site is showing the error and/or stop using it until they fix it. HSTS specifically adds protections for bad certs to prevent you clicking through them. The fact it's needed suggests there is something wrong with the https connection - like the site or your connection to it has been hacked.

The chrome developers also do change this periodically. They changed it recently from badidea to thisisunsafe so everyone using badidea, suddenly stopped being able to use it. You should not depend on it. As Steffen pointed out in the comments below, it is available in the code should it change again though they now base64 encode it to make it more obscure. The last time they changed they put this comment in the commit:

Rotate the interstitial bypass keyword

The security interstitial bypass keyword hasn't changed in two years and awareness of the bypass has been increased in blogs and social media. Rotate the keyword to help prevent misuse.

I think the message from the Chrome team is clear - you should not use it. It would not surprise me if they removed it completely in future.

If you are using this when using a self-signed certificate for local testing then why not just add your self-signed certificate certificate to your computer's certificate store so you get a green padlock and do not have to type this? Note Chrome insists on a SAN field in certificates now so if just using the old subject field then even adding it to the certificate store will not result in a green padlock.

If you leave the certificate untrusted then certain things do not work. Caching for example is completely ignored for untrusted certificates. As is HTTP/2 Push.

HTTPS is here to stay and we need to get used to using it properly - and not bypassing the warnings with a hack that is liable to change and doesn't work the same as a full HTTPS solution.

Why is a ConcurrentModificationException thrown and how to debug it

I ran into this exception when try to remove x last items from list. myList.subList(lastIndex, myList.size()).clear(); was the only solution that worked for me.

How can I execute PHP code from the command line?

You can use:

 echo '<?php if(function_exists("my_func")) echo "function exists"; ' | php

The short tag "< ?=" can be helpful too:

 echo '<?= function_exists("foo") ? "yes" : "no";' | php
 echo '<?= 8+7+9 ;' | php

The closing tag "?>" is optional, but don't forget the final ";"!

Is there possibility of sum of ArrayList without looping

You can use GNU Trove library:

TIntList tt = new TIntArrayList();
tt.add(1);
tt.add(2);
tt.add(3);
int sum = tt.sum();

Convert JSON array to an HTML table in jQuery

For very advanced JSON objects to HTML tables you can try My jQuery Solution that is based on this closed thread.

var myList=[{"name": "abc","age": 50},{"name": {"1": "piet","2": "jan","3": "klaas"},"age": "25","hobby": "watching tv"},{"name": "xyz","hobby": "programming","subtable": [{"a": "a","b": "b"},{"a": "a","b": "b"}]}];

// Builds the HTML Table out of myList json data from Ivy restful service.
 function buildHtmlTable() {
      addTable(myList, $("#excelDataTable"));
 }

function addTable(list, appendObj) {
    var columns = addAllColumnHeaders(list, appendObj);

    for (var i = 0; i < list.length; i++) {
        var row$ = $('<tr/>');
        for (var colIndex = 0; colIndex < columns.length; colIndex++) {
            var cellValue = list[i][columns[colIndex]];

            if (cellValue == null) {
                cellValue = "";
            }

            if (cellValue.constructor === Array)
            {
                $a = $('<td/>');
                row$.append($a);
                addTable(cellValue, $a);

            } else if (cellValue.constructor === Object)
            {

                var array = $.map(cellValue, function (value, index) {
                    return [value];
                });

                $a = $('<td/>');
                row$.append($a);
                addObject(array, $a);

            } else {
                row$.append($('<td/>').html(cellValue));
            }
        }
        appendObj.append(row$);
    }
}


function addObject(list, appendObj) {
    for (var i = 0; i < list.length; i++) {
        var row$ = $('<tr/>');

        var cellValue = list[i];

        if (cellValue == null) {
            cellValue = "";
        }

        if (cellValue.constructor === Array)
        {
            $a = $('<td/>');
            row$.append($a);
            addTable(cellValue, $a);

        } else if (cellValue.constructor === Object)
        {

            var array = $.map(cellValue, function (value, index) {
                return [value];
            });

            $a = $('<td/>');
            row$.append($a);
            addObject(array, $a);

        } else {
            row$.append($('<td/>').html(cellValue));
        }
        appendObj.append(row$);
    }
}

// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(list, appendObj)
{
    var columnSet = [];
    var headerTr$ = $('<tr/>');

    for (var i = 0; i < list.length; i++) {
        var rowHash = list[i];
        for (var key in rowHash) {
            if ($.inArray(key, columnSet) == -1) {
                columnSet.push(key);
                headerTr$.append($('<th/>').html(key));
            }
        }
    }
    appendObj.append(headerTr$);

    return columnSet;
}

How to make a vertical SeekBar in Android?

This worked for me, just put it into any layout you want to.

<FrameLayout
    android:layout_width="32dp"
    android:layout_height="192dp">

    <SeekBar
        android:layout_width="192dp"
        android:layout_height="32dp"
        android:layout_gravity="center"
        android:rotation="270" />

</FrameLayout>

How to frame two for loops in list comprehension python

In comprehension, the nested lists iteration should follow the same order than the equivalent imbricated for loops.

To understand, we will take a simple example from NLP. You want to create a list of all words from a list of sentences where each sentence is a list of words.

>>> list_of_sentences = [['The','cat','chases', 'the', 'mouse','.'],['The','dog','barks','.']]
>>> all_words = [word for sentence in list_of_sentences for word in sentence]
>>> all_words
['The', 'cat', 'chases', 'the', 'mouse', '.', 'The', 'dog', 'barks', '.']

To remove the repeated words, you can use a set {} instead of a list []

>>> all_unique_words = list({word for sentence in list_of_sentences for word in sentence}]
>>> all_unique_words
['.', 'dog', 'the', 'chase', 'barks', 'mouse', 'The', 'cat']

or apply list(set(all_words))

>>> all_unique_words = list(set(all_words))
['.', 'dog', 'the', 'chases', 'barks', 'mouse', 'The', 'cat']

reactjs - how to set inline style of backgroundcolor?

https://facebook.github.io/react/tips/inline-styles.html

You don't need the quotes.

<a style={{backgroundColor: bgColors.Yellow}}>yellow</a>

MetadataException when using Entity Framework Entity Connection

I had the same problem with three projects in one solution and all of the suggestions didn't work until I made a reference in the reference file of the web site project to the project where the edmx file sits.

How to parse string into date?

CONVERT(datetime, '24.04.2012', 104)

Should do the trick. See here for more info: CAST and CONVERT (Transact-SQL)

Difference between a theta join, equijoin and natural join

Theta Join: When you make a query for join using any operator,(e.g., =, <, >, >= etc.), then that join query comes under Theta join.

Equi Join: When you make a query for join using equality operator only, then that join query comes under Equi join.

Example:

> SELECT * FROM Emp JOIN Dept ON Emp.DeptID = Dept.DeptID;
> SELECT * FROM Emp INNER JOIN Dept USING(DeptID)
This will show:
 _________________________________________________
| Emp.Name | Emp.DeptID | Dept.Name | Dept.DeptID |
|          |            |           |             |

Note: Equi join is also a theta join!

Natural Join: a type of Equi Join which occurs implicitly by comparing all the same names columns in both tables.

Note: here, the join result has only one column for each pair of same named columns.

Example

 SELECT * FROM Emp NATURAL JOIN Dept
This will show:
 _______________________________
| DeptID | Emp.Name | Dept.Name |
|        |          |           |

The import android.support cannot be resolved

I followed the instructions above by Gene in Android Studio 1.5.1 but it added this to my build.gradle file:

compile 'platforms:android:android-support-v4:23.1.1'

so I changed it to:

compile 'com.android.support:support-v4:23.1.1'

And it started working.

Subset and ggplot2

Are you looking for the following plot:

library(ggplot2) 
l<-df[df$ID %in% c("P1","P3"),]
myplot<-ggplot(l)+geom_line(aes(Value1, Value2, group=ID, colour=ID))

enter image description here

jQuery UI Dialog with ASP.NET button postback

This was the clearest solution for me

var dlg2 = $('#dialog2').dialog({
        position: "center",
        autoOpen: false,
        width: 600,
        buttons: {
            "Ok": function() {
                $(this).dialog("close");
            },
            "Cancel": function() {
                $(this).dialog("close");
            }
        }
    });

dlg2.parent().appendTo('form:first');
$('#dialog_link2').click(function(){
    dlg2.dialog('open');

All the content inside the dlg2 will be available to insert in your database. Don't forget to change the dialog variable to match yours.

What's the difference between %s and %d in Python string formatting?

They are format specifiers. They are used when you want to include the value of your Python expressions into strings, with a specific format enforced.

See Dive into Python for a relatively detailed introduction.

How to create nested directories using Mkdir in Golang?

This way you don't have to use any magic numbers:

os.MkdirAll(newPath, os.ModePerm)

Also, rather than using + to create paths, you can use:

import "path/filepath"
path := filepath.Join(someRootPath, someSubPath)

The above uses the correct separators automatically on each platform for you.

Remove all line breaks from a long string of text

How do you enter line breaks with raw_input? But, once you have a string with some characters in it you want to get rid of, just replace them.

>>> mystr = raw_input('please enter string: ')
please enter string: hello world, how do i enter line breaks?
>>> # pressing enter didn't work...
...
>>> mystr
'hello world, how do i enter line breaks?'
>>> mystr.replace(' ', '')
'helloworld,howdoienterlinebreaks?'
>>>

In the example above, I replaced all spaces. The string '\n' represents newlines. And \r represents carriage returns (if you're on windows, you might be getting these and a second replace will handle them for you!).

basically:

# you probably want to use a space ' ' to replace `\n`
mystring = mystring.replace('\n', ' ').replace('\r', '')

Note also, that it is a bad idea to call your variable string, as this shadows the module string. Another name I'd avoid but would love to use sometimes: file. For the same reason.

SSH to Vagrant box in Windows?

Either

  1. In your cmd console type the following:

    set PATH=%PATH%;C:\Program Files (x86)\Git\bin
    

OR

  1. Permanently set the path in your system's environment variables:

    C:\Program Files (x86)\Git\bin;
    

How to reset settings in Visual Studio Code?

Heads up, if clearing the settings doesn't fix your issue you may need to uninstall the extensions as well.

Remove an entire column from a data.frame in R

There are several options for removing one or more columns with dplyr::select() and some helper functions. The helper functions can be useful because some do not require naming all the specific columns to be dropped. Note that to drop columns using select() you need to use a leading - to negate the column names.

Using the dplyr::starwars sample data for some variety in column names:

library(dplyr)

starwars %>% 
  select(-height) %>%                  # a specific column name
  select(-one_of('mass', 'films')) %>% # any columns named in one_of()
  select(-(name:hair_color)) %>%       # the range of columns from 'name' to 'hair_color'
  select(-contains('color')) %>%       # any column name that contains 'color'
  select(-starts_with('bi')) %>%       # any column name that starts with 'bi'
  select(-ends_with('er')) %>%         # any column name that ends with 'er'
  select(-matches('^v.+s$')) %>%       # any column name matching the regex pattern
  select_if(~!is.list(.)) %>%          # not by column name but by data type
  head(2)

# A tibble: 2 x 2
homeworld species
  <chr>     <chr>  
1 Tatooine  Human  
2 Tatooine  Droid 

You can also drop by column number:

starwars %>% 
  select(-2, -(4:10)) # column 2 and columns 4 through 10

Java JDBC connection status

Your best chance is to just perform a simple query against one table, e.g.:

select 1 from SOME_TABLE;

Oh, I just saw there is a new method available since 1.6:

java.sql.Connection.isValid(int timeoutSeconds):

Returns true if the connection has not been closed and is still valid. The driver shall submit a query on the connection or use some other mechanism that positively verifies the connection is still valid when this method is called. The query submitted by the driver to validate the connection shall be executed in the context of the current transaction.

Import a custom class in Java

If all of your classes are in the same package, you shouldn't need to import them.

Simply instantiate the object like so:

CustomObject myObject = new CustomObject();

How to change the href for a hyperlink using jQuery

Use the attr method on your lookup. You can switch out any attribute with a new value.

$("a.mylink").attr("href", "http://cupcream.com");

HttpServlet cannot be resolved to a type .... is this a bug in eclipse?

I faced the same problem in eclipse with tomcat7 with the error javax.servlet cannot be resolved. If I select the server in targeted runtime mode and build project again, the error get's resolved.

How to wait for a number of threads to complete?

If you make a list of the threads, you can loop through them and .join() against each, and your loop will finish when all the threads have. I haven't tried it though.

http://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#join()

How to run an awk commands in Windows?

Actually, I do like mark instruction but little differently. I've added C:\Program Files (x86)\GnuWin32\bin\ to the Path variable, and try to run it with type awk using cmd.

Hope it works.

JQuery Number Formatting

I wrote a JavaScript analogue of a PHP function number_format on a base of Abe Miessler addCommas function. Could be usefull.

number_format = function (number, decimals, dec_point, thousands_sep) {
        number = number.toFixed(decimals);

        var nstr = number.toString();
        nstr += '';
        x = nstr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? dec_point + x[1] : '';
        var rgx = /(\d+)(\d{3})/;

        while (rgx.test(x1))
            x1 = x1.replace(rgx, '$1' + thousands_sep + '$2');

        return x1 + x2;
    }

For example:

var some_number = number_format(42661.55556, 2, ',', ' '); //gives 42 661,56

How can I split a JavaScript string by white space or comma?

When I want to take into account extra characters like your commas (in my case each token may be entered with quotes), I'd do a string.replace() to change the other delimiters to blanks and then split on whitespace.

Can Twitter Bootstrap alerts fade in as well as out?

I got this way to close fading my Alert after 3 seconds. Hope it will be useful.

    setTimeout(function(){
    $('.alert').fadeTo("slow", 0.1, function(){
        $('.alert').alert('close')
    });     
    }, 3000)

How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3?

Anyone looking for this functionality past 2018: it's much cleaner to do this with just CSS using position: sticky.

position: sticky doesn't work with some table elements (thead/tr) in Chrome. You can move sticky to tds/ths of tr you need to be sticky. Like this:

thead tr:nth-child(1) th {
  background: white;
  position: sticky;
  top: 0;
  z-index: 10;
}

How do I make calls to a REST API using C#?

Here are a few different ways of calling an external API in C# (updated 2019).

.NET's built-in ways:

  • WebRequest& WebClient - verbose APIs & Microsoft's documentation is not very easy to follow
  • HttpClient - .NET's newest kid on the block & much simpler to use than above.

Free, open-source NuGet Packages, which frankly have a much better developer experience than .NET's built in clients:

  • ServiceStack.Text (1,000 GitHub stars, 7 million NuGet downloads) (*) - fast, light and resilient.
  • RestSharp (6,000 GitHub stars, 23 million NuGet downloads) (*) - simple REST and HTTP API Client
  • Flurl (1,700 GitHub stars, 3 million NuGet downloads) (*)- a fluent, portable, testable HTTP client library

All the above packages provide a great developer experience (i.e., concise, easy API) and are well maintained.

(*) as at August 2019

Example: Getting a Todo item from a Fake Rest API using ServiceStack.Text. The other libraries have very similar syntax.

class Program
{
    static void Main(string[] args)
    {
        // Fake rest API
        string url = "https://jsonplaceholder.typicode.com/todos/1";

        // GET data from API & map to POCO
        var todo =  url.GetJsonFromUrl().FromJson<Todo>();

        // Print the result to screen
        todo.PrintDump();
    }

    public class Todo
    {
        public int UserId { get; set; }
        public int Id { get; set; }
        public string Title { get; set; }
        public bool Completed { get; set; }
    }

}

Running the above example in a .NET Core Console app, produces the following output.

Enter image description here

Install these packages using NuGet

Install-Package ServiceStack.Text, or

Install-Package RestSharp, or

Install-Package Flurl.Http

Java: using switch statement with enum under subclass

Java infers automatically the type of the elements in case, so the labels must be unqualified.

int i;
switch(i) {
   case 5: // <- integer is expected
}
MyEnum e;
switch (e) {
   case VALUE_A: // <- an element of the enumeration is expected
}

Address validation using Google Maps API

A great blog describing 14 address finders: https://www.conversion-uplift.co.uk/free-address-lookup-tools/

Many address autocomplete services, including Google's Places API, appears to offer international address support but it has limited accuracy.

For example, New Zealand address and geolocation data are free to download from Land Information New Zealand (LINZ). When a user search for an address such as 76 Francis St Hauraki from Google or Address Doctor, a positive match is returned. The land parcel was matched but not the postal/delivery address, which is either 76A or 76B. The problem is amplified with apartments and units on a single land parcel.

For 100% accuracy, use a country-specific address finder instead such as https://www.addy.co.nz for NZ address autocomplete.

Rounding to two decimal places in Python 2.7?

print "financial return of outcome 1 = $%.2f" % (out1)

How to randomize Excel rows

Use Excel Online (Google Sheets).. And install Power Tools for Google Sheets.. Then in Google Sheets go to Addons tab and start Power Tools. Then choose Randomize from Power Tools menu. Select Shuffle. Then select choices of your test in excel sheet. Then select Cells in each row and click Shuffle from Power Tools menu. This will shuffle each row's selected cells independently from one another.

How to fix "'System.AggregateException' occurred in mscorlib.dll"

The accepted answer will work if you can easily reproduce the issue. However, as a matter of best practice, you should be catching any exceptions (and logging) that are executed within a task. Otherwise, your application will crash if anything unexpected occurs within the task.

Task.Factory.StartNew(x=>
   throw new Exception("I didn't account for this");
)

However, if we do this, at least the application does not crash.

Task.Factory.StartNew(x=>
   try {
      throw new Exception("I didn't account for this");
   }
   catch(Exception ex) {
      //Log ex
   }
)

What is the difference between Python and IPython?

IPython is basically the "recommended" Python shell, which provides extra features. There is no language called IPython.

How to tell if a file is git tracked (by shell exit code)?

I don't know of any git command that gives a "bad" exit code, but it seems like an easy way to do it would be to use a git command that gives no output for a file that isn't tracked, such as git-log or git-ls-files. That way you don't really have to do any parsing, you can run it through another simple utility like grep to see if there was any output.

For example,

git-ls-files test_file.c | grep .

will exit with a zero code if the file is tracked, but a exit code of one if the file is not tracked.

What is a reasonable code coverage % for unit tests (and why)?

We were targeting >80% till few days back, But after we used a lot of Generated code, We do not care for %age, but rather make reviewer take a call on the coverage required.

How to go from one page to another page using javascript?

hope this would help:

window.location.href = '/url_after_domain';

How to set all elements of an array to zero or any same value?

You could use memset, if you sure about the length.

memset(ptr, 0x00, length)

Visual Studio SignTool.exe Not Found

If you do not care about sign your program when you publish, just right click your project then choose Properties --> Signing --> un-check Sign the ClickOnce manifest . I had the same issue when building my program on another machine which did not have ClickOne.

How to print a dictionary's key?

Or you can do it that manner:

for key in my_dict:
     print key, my_dict[key]

How can I split a text file using PowerShell?

There's also this quick (and somewhat dirty) one-liner:

$linecount=0; $i=0; Get-Content .\BIG_LOG_FILE.txt | %{ Add-Content OUT$i.log "$_"; $linecount++; if ($linecount -eq 3000) {$I++; $linecount=0 } }

You can tweak the number of first lines per batch by changing the hard-coded 3000 value.

How do I test if a variable is a number in Bash?

I tried ultrasawblade's recipe as it seemed the most practical to me, and couldn't make it work. In the end i devised another way though, based as others in parameter substitution, this time with regex replacement:

[[ "${var//*([[:digit:]])}" ]]; && echo "$var is not numeric" || echo "$var is numeric"

It removes every :digit: class character in $var and checks if we are left with an empty string, meaning that the original was only numbers.

What i like about this one is its small footprint and flexibility. In this form it only works for non-delimited, base 10 integers, though surely you can use pattern matching to suit it to other needs.

What's the difference between SortedList and SortedDictionary?

Here is a tabular view if it helps...

From a performance perspective:

+------------------+---------+----------+--------+----------+----------+---------+
| Collection       | Indexed | Keyed    | Value  | Addition |  Removal | Memory  |
|                  | lookup  | lookup   | lookup |          |          |         |
+------------------+---------+----------+--------+----------+----------+---------+
| SortedList       | O(1)    | O(log n) | O(n)   | O(n)*    | O(n)     | Lesser  |
| SortedDictionary | O(n)**  | O(log n) | O(n)   | O(log n) | O(log n) | Greater |
+------------------+---------+----------+--------+----------+----------+---------+

  * Insertion is O(log n) for data that are already in sort order, so that each 
    element is added to the end of the list. If a resize is required, that element
    takes O(n) time, but inserting n elements is still amortized O(n log n).
    list.
** Available through enumeration, e.g. Enumerable.ElementAt.

From an implementation perspective:

+------------+---------------+----------+------------+------------+------------------+
| Underlying | Lookup        | Ordering | Contiguous | Data       | Exposes Key &    |
| structure  | strategy      |          | storage    | access     | Value collection |
+------------+---------------+----------+------------+------------+------------------+
| 2 arrays   | Binary search | Sorted   | Yes        | Key, Index | Yes              |
| BST        | Binary search | Sorted   | No         | Key        | Yes              |
+------------+---------------+----------+------------+------------+------------------+

To roughly paraphrase, if you require raw performance SortedDictionary could be a better choice. If you require lesser memory overhead and indexed retrieval SortedList fits better. See this question for more on when to use which.

You can read more here, here, here, here and here.

Use a.empty, a.bool(), a.item(), a.any() or a.all()

solution is easy:

replace

 mask = (50  < df['heart rate'] < 101 &
            140 < df['systolic blood pressure'] < 160 &
            90  < df['dyastolic blood pressure'] < 100 &
            35  < df['temperature'] < 39 &
            11  < df['respiratory rate'] < 19 &
            95  < df['pulse oximetry'] < 100
            , "excellent", "critical")

by

mask = ((50  < df['heart rate'] < 101) &
        (140 < df['systolic blood pressure'] < 160) &
        (90  < df['dyastolic blood pressure'] < 100) &
        (35  < df['temperature'] < 39) &
        (11  < df['respiratory rate'] < 19) &
        (95  < df['pulse oximetry'] < 100)
        , "excellent", "critical")

Boxplot show the value of mean

The Magrittr way

I know there is an accepted answer already, but I wanted to show one cool way to do it in single command with the help of magrittr package.

PlantGrowth %$% # open dataset and make colnames accessible with '$'
split(weight,group) %T>% # split by group and side-pipe it into boxplot
boxplot %>% # plot
lapply(mean) %>% # data from split can still be used thanks to side-pipe '%T>%'
unlist %T>% # convert to atomic and side-pipe it to points
points(pch=18)  %>% # add points for means to the boxplot
text(x=.+0.06,labels=.) # use the values to print text

This code will produce a boxplot with means printed as points and values: boxplot with means

I split the command on multiple lines so I can comment on what each part does, but it can also be entered as a oneliner. You can learn more about this in my gist.

git add, commit and push commands in one?

This Result - Try this: Simple script one command for git add, git commit and git push

Open your CMD on Windows and paste this answer

git commit -m "your message" . && git push origin master

This example my picture screenshot : https://i.stack.imgur.com/2IZDe.jpg

Missing .map resource?

jQuery recently started using source maps.

For example, let's look at the minified jQuery 2.0.3 file's first few lines.

/*! jQuery v2.0.3 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery.min.map
*/

Excerpt from Introduction to JavaScript Source Maps:

Have you ever found yourself wishing you could keep your client-side code readable and more importantly debuggable even after you've combined and minified it, without impacting performance? Well now you can through the magic of source maps.

Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location. Developer tools (currently WebKit nightly builds, Google Chrome, or Firefox 23+) can parse the source map automatically and make it appear as though you're running unminified and uncombined files.

emphasis mine

It's incredibly useful, and will only download if the user opens dev tools.

Solution

Remove the source mapping line, or do nothing. It isn't really a problem.


Side note: your server should return 404, not 500. It could point to a security problem if this happens in production.

What is the best or most commonly used JMX Console / Client

I would prefer using JConsole for application monitoring, and it does have graphical view. If you’re using JDK 5.0 or above then it’s the best. Please refer to this using jconsole page for more details.

I have been primarily using it for GC tuning and finding bottlenecks.

How do I display todays date on SSRS report?

In the text box that contains the header, you can use an expression to get the date. Try something like

    ="Report Generation Date: " & Today()

right click in the text box in the layout view. At the bottom of the list you'll see the expression option. There you will be able to enter the code. This option will allow you to avoid adding a second textbox.

Recording video feed from an IP camera over a network

about 3 years ago i needed cctv. I found zoneminder, tried to edit it to my liking, but found i was fixing it more than editing it.

Not to mention mp4 recording feature isn't actually part of the master branch (which is kind of lol, since its a cctv program and its already been about 3 years or more since it was suggested). Its literally just adapting the ffmpeg command lol.

So i found the solution!

If you want something done right, do it yourself.

I present to you Shinobi! Shinobi : The Open Source CCTV Platform

enter image description here

Rounding a double value to x number of decimal places in swift

In Swift 5.3 and Xcode 12:

let pi: Double = 3.14159265358979
String(format:"%.2f", pi)

Example:

enter image description here

PS.: It still the same since Swift 2.0 and Xcode 7.2

What's the PowerShell syntax for multiple values in a switch statement?

A slight modification to derekerdmann's post to meet the original request using regex's alternation operator "|"(pipe).

It's also slightly easier for regex newbies to understand and read.

Note that while using regex, if you don't put the start of string character "^"(caret/circumflex) and/or end of string character "$"(dollar) then you may get unexpected/unintuitive behavior (like matching "yesterday" or "why").

Putting grouping characters "()"(parentheses) around the options reduces the need to put start and end of string characters for each option. Without them, you'll get possibly unexpected behavior if you're not savvy with regex. Of course, if you're not processing user input, but rather some set of known strings, it will be more readable without grouping and start and end of string characters.

switch -regex ($someString) #many have noted ToLower() here is redundant
{
        #processing user input
    "^(y|yes|indubitably)$" { "You entered Yes." }

        # not processing user input
    "y|yes|indubitably" { "Yes was the selected string" } 
    default { "You entered No." } 
}

Release generating .pdb files, why?

PDB can be generated for Release as well as for Debug. This is set at (in VS2010 but in VS2005 must be similar):

Project ? Properties ? Build ? Advanced ? Debug Info

Just change it to None.

How to enable assembly bind failure logging (Fusion) in .NET

Add the following values to

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion
Add:
DWORD ForceLog set value to 1
DWORD LogFailures set value to 1
DWORD LogResourceBinds set value to 1
DWORD EnableLog set value to 1
String LogPath set value to folder for logs (e.g. C:\FusionLog\)

Make sure you include the backslash after the folder name and that the Folder exists.

You need to restart the program that you're running to force it to read those registry settings.

By the way, don't forget to turn off fusion logging when not needed.

enter image description here

How can I convert string to datetime with format specification in JavaScript?

//Here pdate is the string date time
var date1=GetDate(pdate);
    function GetDate(a){
        var dateString = a.substr(6);
        var currentTime = new Date(parseInt(dateString ));
        var month =("0"+ (currentTime.getMonth() + 1)).slice(-2);
        var day =("0"+ currentTime.getDate()).slice(-2);
        var year = currentTime.getFullYear();
        var date = day + "/" + month + "/" + year;
        return date;
    }

How are iloc and loc different?

.loc and .iloc are used for indexing, i.e., to pull out portions of data. In essence, the difference is that .loc allows label-based indexing, while .iloc allows position-based indexing.

If you get confused by .loc and .iloc, keep in mind that .iloc is based on the index (starting with i) position, while .loc is based on the label (starting with l).

.loc

.loc is supposed to be based on the index labels and not the positions, so it is analogous to Python dictionary-based indexing. However, it can accept boolean arrays, slices, and a list of labels (none of which work with a Python dictionary).

iloc

.iloc does the lookup based on index position, i.e., pandas behaves similarly to a Python list. pandas will raise an IndexError if there is no index at that location.

Examples

The following examples are presented to illustrate the differences between .iloc and .loc. Let's consider the following series:

>>> s = pd.Series([11, 9], index=["1990", "1993"], name="Magic Numbers")
>>> s
1990    11
1993     9
Name: Magic Numbers , dtype: int64

.iloc Examples

>>> s.iloc[0]
11
>>> s.iloc[-1]
9
>>> s.iloc[4]
Traceback (most recent call last):
    ...
IndexError: single positional indexer is out-of-bounds
>>> s.iloc[0:3] # slice
1990 11
1993  9
Name: Magic Numbers , dtype: int64
>>> s.iloc[[0,1]] # list
1990 11
1993  9
Name: Magic Numbers , dtype: int64

.loc Examples

>>> s.loc['1990']
11
>>> s.loc['1970']
Traceback (most recent call last):
    ...
KeyError: ’the label [1970] is not in the [index]’
>>> mask = s > 9
>>> s.loc[mask]
1990 11
Name: Magic Numbers , dtype: int64
>>> s.loc['1990':] # slice
1990    11
1993     9
Name: Magic Numbers, dtype: int64

Because s has string index values, .loc will fail when indexing with an integer:

>>> s.loc[0]
Traceback (most recent call last):
    ...
KeyError: 0

Maven parent pom vs modules pom

There is one little catch with the third approach. Since aggregate POMs (myproject/pom.xml) usually don't have parent at all, they do not share configuration. That means all those aggregate POMs will have only default repositories.

That is not a problem if you only use plugins from Central, however, this will fail if you run plugin using the plugin:goal format from your internal repository. For example, you can have foo-maven-plugin with the groupId of org.example providing goal generate-foo. If you try to run it from the project root using command like mvn org.example:foo-maven-plugin:generate-foo, it will fail to run on the aggregate modules (see compatibility note).

Several solutions are possible:

  1. Deploy plugin to the Maven Central (not always possible).
  2. Specify repository section in all of your aggregate POMs (breaks DRY principle).
  3. Have this internal repository configured in the settings.xml (either in local settings at ~/.m2/settings.xml or in the global settings at /conf/settings.xml). Will make build fail without those settings.xml (could be OK for large in-house projects that are never supposed to be built outside of the company).
  4. Use the parent with repositories settings in your aggregate POMs (could be too many parent POMs?).

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

Another reason could be an outdated version of JDK. I was using jdk version 1.8.0_60, simply updating to the latest version solved the certificate issue.

This certificate has an invalid issuer Apple Push Services

This is not actually a development issue. It happens due to expiration of the Apple Worldwide Developer Relations Intermediate Certificate issued by Apple Worldwide Developer Relations Certificate Authority. WWDRCA issues the certificate to sign your software for Apple devices, allowing our systems to confirm that your software is delivered to users as intended and has not been modified.

To resolve this issue, you have to follow the below steps:

  1. Open Keychain Access
  2. Go to View -> Show Expired Certificates

Enter image description here

  1. Go to System in Keychain Enter image description here

  2. Here you find that "Apple Worldwide Developer Relations Certificate Authority" is marked as expired. So delete it. Also check under Login Tab and delete expired WWDRCA.

  3. Download new WWDR Intermediate Certificate from here(The renewed Apple Worldwide Developer Relations Certification Intermediate Certificate will expire on February 7, 2023).

  4. Install it by double clicking on it.

If you still face any issue with your iOS apps, Mac apps, Safari extensions, Apple Wallet and Safari push notifications, then please follow this link of expiration.

The Apple Worldwide Developer Relations Certification Intermediate Certificate expires soon and we've issued a renewed certificate that must be included when signing all new Apple Wallet Passes, push packages for Safari Push Notifications, and Safari Extensions starting February 14, 2016.

While most developers and users will not be affected by the certificate change, we recommend that all developers download and install the renewed certificate on their development systems and servers as a best practice. All apps will remain available on the App Store for iOS, Mac, and Apple TV.

How to convert a string variable containing time to time_t type in c++?

You can use strptime(3) to parse the time, and then mktime(3) to convert it to a time_t:

const char *time_details = "16:35:12";
struct tm tm;
strptime(time_details, "%H:%M:%S", &tm);
time_t t = mktime(&tm);  // t is now your desired time_t

Perform a Shapiro-Wilk Normality Test

You are applying shapiro.test() to a data.frame instead of the column. Try the following:

shapiro.test(heisenberg$HWWIchg)

Http Servlet request lose params from POST body after read it once

Spring has built-in support for this with an AbstractRequestLoggingFilter:

@Bean
public Filter loggingFilter(){
    final AbstractRequestLoggingFilter filter = new AbstractRequestLoggingFilter() {
        @Override
        protected void beforeRequest(final HttpServletRequest request, final String message) {

        }

        @Override
        protected void afterRequest(final HttpServletRequest request, final String message) {

        }
    };

    filter.setIncludePayload(true);
    filter.setIncludeQueryString(false);
    filter.setMaxPayloadLength(1000000);

    return filter;
}

Unfortunately you still won't be able to read the payload directly off the request, but the String message parameter will include the payload so you can grab it from there as follows:

String body = message.substring(message.indexOf("{"), message.lastIndexOf("]"));

Docker how to change repository name or rename image?

docker image tag server:latest myname/server:latest

or

docker image tag d583c3ac45fd myname/server:latest

Tags are just human-readable aliases for the full image name (d583c3ac45fd...).

So you can have as many of them associated with the same image as you like. If you don't like the old name you can remove it after you've retagged it:

docker rmi server

That will just remove the alias/tag. Since d583c3ac45fd has other names, the actual image won't be deleted.

How to work with progress indicator in flutter?

I took the following approach, which uses a simple modal progress indicator widget that wraps whatever you want to make modal during an async call.

The example in the package also addresses how to handle form validation while making async calls to validate the form (see flutter/issues/9688 for details of this problem). For example, without leaving the form, this async form validation method can be used to validate a new user name against existing names in a database while signing up.

https://pub.dartlang.org/packages/modal_progress_hud

Here is the demo of the example provided with the package (with source code):

async form validation with modal progress indicator

Example could be adapted to other modal progress indicator behaviour (like different animations, additional text in modal, etc..).

How can I know when an EditText loses focus?

Kotlin way

editText.setOnFocusChangeListener { _, hasFocus ->
    if (!hasFocus) {  }
}

Passing 'this' to an onclick event

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript.

How does the "this" keyword work?

How do I install a pip package globally instead of locally?

Why don't you try sudo with the H flag? This should do the trick.

sudo -H pip install flake8

A regular sudo pip install flake8 will try to use your own home directory. The -H instructs it to use the system's home directory. More info at https://stackoverflow.com/a/43623102/

Is there any way to set environment variables in Visual Studio Code?

I run vscode from my command line by navigating to the folder with the code and running

code .

If you do that all your bash/zsh variables are passed into vs code. You can update your .bashrc/.zshrc file or just do

export KEY=value

before opening it.

How to add a local repo and treat it as a remote repo

I am posting this answer to provide a script with explanations that covers three different scenarios of creating a local repo that has a local remote. You can run the entire script and it will create the test repos in your home folder (tested on windows git bash). The explanations are inside the script for easier saving to your personal notes, its very readable from, e.g. Visual Studio Code.

I would also like to thank Jack for linking to this answer where adelphus has good, detailed, hands on explanations on the topic.

This is my first post here so please advise what should be improved.

## SETUP LOCAL GIT REPO WITH A LOCAL REMOTE
# the main elements:
# - remote repo must be initialized with --bare parameter
# - local repo must be initialized
# - local repo must have at least one commit that properly initializes a branch(root of the commit tree)
# - local repo needs to have a remote
# - local repo branch must have an upstream branch on the remote

{ # the brackets are optional, they allow to copy paste into terminal and run entire thing without interruptions, run without them to see which cmd outputs what

cd ~
rm -rf ~/test_git_local_repo/

## Option A - clean slate - you have nothing yet

mkdir -p ~/test_git_local_repo/option_a ; cd ~/test_git_local_repo/option_a
git init --bare local_remote.git # first setup the local remote
git clone local_remote.git local_repo # creates a local repo in dir local_repo
cd ~/test_git_local_repo/option_a/local_repo
git remote -v show origin # see that git clone has configured the tracking
touch README.md ; git add . ; git commit -m "initial commit on master" # properly init master
git push origin master # now have a fully functional setup, -u not needed, git clone does this for you

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branches and their respective remote upstream branches with the initial commit
git remote -v show origin # see all branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote

## Option B - you already have a local git repo and you want to connect it to a local remote

mkdir -p ~/test_git_local_repo/option_b ; cd ~/test_git_local_repo/option_b
git init --bare local_remote.git # first setup the local remote

# simulate a pre-existing git local repo you want to connect with the local remote
mkdir local_repo ; cd local_repo
git init # if not yet a git repo
touch README.md ; git add . ; git commit -m "initial commit on master" # properly init master
git checkout -b develop ; touch fileB ; git add . ; git commit -m "add fileB on develop" # create develop and fake change

# connect with local remote
cd ~/test_git_local_repo/option_b/local_repo
git remote add origin ~/test_git_local_repo/option_b/local_remote.git
git remote -v show origin # at this point you can see that there is no the tracking configured (unlike with git clone), so you need to push with -u
git push -u origin master # -u to set upstream
git push -u origin develop # -u to set upstream; need to run this for every other branch you already have in the project

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branch(es) and its remote upstream with the initial commit
git remote -v show origin # see all remote branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote

## Option C - you already have a directory with some files and you want it to be a git repo with a local remote

mkdir -p ~/test_git_local_repo/option_c ; cd ~/test_git_local_repo/option_c
git init --bare local_remote.git # first setup the local remote

# simulate a pre-existing directory with some files
mkdir local_repo ; cd local_repo ; touch README.md fileB

# make a pre-existing directory a git repo and connect it with local remote
cd ~/test_git_local_repo/option_c/local_repo
git init
git add . ; git commit -m "inital commit on master" # properly init master
git remote add origin ~/test_git_local_repo/option_c/local_remote.git
git remote -v show origin # see there is no the tracking configured (unlike with git clone), so you need to push with -u
git push -u origin master # -u to set upstream

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branch and its remote upstream with the initial commit
git remote -v show origin # see all remote branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote
}

Identify if a string is a number

With c# 7 it you can inline the out variable:

if(int.TryParse(str, out int v))
{
}

Android - how to replace part of a string by another string?

It is working, but it wont modify the caller object, but returning a new String.
So you just need to assign it to a new String variable, or to itself:

string = string.replace("to", "xyz");

or

String newString = string.replace("to", "xyz");

API Docs

public String replace (CharSequence target, CharSequence replacement) 

Since: API Level 1

Copies this string replacing occurrences of the specified target sequence with another sequence. The string is processed from the beginning to the end.

Parameters

  • target the sequence to replace.
  • replacement the replacement sequence.

Returns the resulting string.
Throws NullPointerException if target or replacement is null.

Best way to find if an item is in a JavaScript array?

As of ECMAScript 2016 you can use includes()

arr.includes(obj);

If you want to support IE or other older browsers:

function include(arr,obj) {
    return (arr.indexOf(obj) != -1);
}

EDIT: This will not work on IE6, 7 or 8 though. The best workaround is to define it yourself if it's not present:

  1. Mozilla's (ECMA-262) version:

       if (!Array.prototype.indexOf)
       {
    
            Array.prototype.indexOf = function(searchElement /*, fromIndex */)
    
         {
    
    
         "use strict";
    
         if (this === void 0 || this === null)
           throw new TypeError();
    
         var t = Object(this);
         var len = t.length >>> 0;
         if (len === 0)
           return -1;
    
         var n = 0;
         if (arguments.length > 0)
         {
           n = Number(arguments[1]);
           if (n !== n)
             n = 0;
           else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
             n = (n > 0 || -1) * Math.floor(Math.abs(n));
         }
    
         if (n >= len)
           return -1;
    
         var k = n >= 0
               ? n
               : Math.max(len - Math.abs(n), 0);
    
         for (; k < len; k++)
         {
           if (k in t && t[k] === searchElement)
             return k;
         }
         return -1;
       };
    
     }
    
  2. Daniel James's version:

     if (!Array.prototype.indexOf) {
       Array.prototype.indexOf = function (obj, fromIndex) {
         if (fromIndex == null) {
             fromIndex = 0;
         } else if (fromIndex < 0) {
             fromIndex = Math.max(0, this.length + fromIndex);
         }
         for (var i = fromIndex, j = this.length; i < j; i++) {
             if (this[i] === obj)
                 return i;
         }
         return -1;
       };
     }
    
  3. roosteronacid's version:

     Array.prototype.hasObject = (
       !Array.indexOf ? function (o)
       {
         var l = this.length + 1;
         while (l -= 1)
         {
             if (this[l - 1] === o)
             {
                 return true;
             }
         }
         return false;
       } : function (o)
       {
         return (this.indexOf(o) !== -1);
       }
     );
    

How do I call a function twice or more times consecutively?

I would:

for _ in range(3):
    do()

The _ is convention for a variable whose value you don't care about.

You might also see some people write:

[do() for _ in range(3)]

however that is slightly more expensive because it creates a list containing the return values of each invocation of do() (even if it's None), and then throws away the resulting list. I wouldn't suggest using this unless you are using the list of return values.

Reading from stdin

You can do something like this to read 10 bytes:

char buffer[10];
read(STDIN_FILENO, buffer, 10);

remember read() doesn't add '\0' to terminate to make it string (just gives raw buffer).

To read 1 byte at a time:

char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
 //do stuff
}

and don't forget to #include <unistd.h>, STDIN_FILENO defined as macro in this file.

There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:

Integer value   Name
       0        Standard input (stdin)
       1        Standard output (stdout)
       2        Standard error (stderr)

So instead STDIN_FILENO you can use 0.

Edit:
In Linux System you can find this using following command:

$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define   STDIN_FILENO    0   /* Standard input.  */

Notice the comment /* Standard input. */

How to select all instances of a variable and edit variable name in Sublime

This worked for me. Put your cursor at the beginning of the word you want to replace, then

CtrlK, CtrlD, CtrlD ...

That should select as many instances of the word as you like, then you can just type the replacement.

How to Get the HTTP Post data in C#?

In my case because I assigned the post data to the header, this is how I get it:

protected void Page_Load(object sender, EventArgs e){
    ...
    postValue = Request.Headers["Key"];

This is how I attached the value and key to the POST:

var request = new NSMutableUrlRequest(url){
    HttpMethod = "POST", 
    Headers = NSDictionary.FromObjectAndKey(FromObject(value), FromObject("key"))
};
webView.LoadRequest(request);

Reading Properties file in Java

I see that the question is an old one. If anyone stumbles upon this in the future, I think this is one simple way of doing it. Keep the properties file in your project folder.

        FileReader reader = new FileReader("Config.properties");

        Properties prop = new Properties();
        prop.load(reader);

JSON Parse File Path

Loading local JSON file

Use something like this

$.getJSON("../../data/file.json", function(json) {
    console.log(json); // this will show the info in firebug console 
    alert(json);
});

How can I replace every occurrence of a String in a file with PowerShell?

A bit old and different, as I needed to change a certain line in all instances of a particular file name.

Also, Set-Content was not returning consistent results, so I had to resort to Out-File.

Code below:


$FileName =''
$OldLine = ''
$NewLine = ''
$Drives = Get-PSDrive -PSProvider FileSystem
foreach ($Drive in $Drives) {
    Push-Location $Drive.Root
        Get-ChildItem -Filter "$FileName" -Recurse | ForEach { 
            (Get-Content $_.FullName).Replace($OldLine, $NewLine) | Out-File $_.FullName
        }
    Pop-Location
}

This is what worked best for me on this PowerShell version:

Major.Minor.Build.Revision

5.1.16299.98

How to see my Eclipse version?

Go to Help -> About Eclipse Sdk

enter image description here

enter image description here

Make 2 functions run at the same time

I think what you are trying to convey can be achieved through multiprocessing. However if you want to do it through threads you can do this. This might help

from threading import Thread
import time

def func1():
    print 'Working'
    time.sleep(2)

def func2():
    print 'Working'
    time.sleep(2)

th = Thread(target=func1)
th.start()
th1=Thread(target=func2)
th1.start()

replace special characters in a string python

You can replace the special characters with the desired characters as follows,

import string
specialCharacterText = "H#y #@w @re &*)?"
inCharSet = "!@#$%^&*()[]{};:,./<>?\|`~-=_+\""
outCharSet = "                               " #corresponding characters in inCharSet to be replaced
splCharReplaceList = string.maketrans(inCharSet, outCharSet)
splCharFreeString = specialCharacterText.translate(splCharReplaceList)

Didn't Java once have a Pair class?

There are lots of implementation around here, but all the time something is missing , the Override of equal and hash method.

here is a more complete version of this class:

/**
 * Container to ease passing around a tuple of two objects. This object provides a sensible
 * implementation of equals(), returning true if equals() is true on each of the contained
 * objects.
 */
public class Pair<F, S> {
    public final F first;
    public final S second;

    /**
     * Constructor for a Pair.
     *
     * @param first the first object in the Pair
     * @param second the second object in the pair
     */
    public Pair(F first, S second) {
        this.first = first;
        this.second = second;
    }

    /**
     * Checks the two objects for equality by delegating to their respective
     * {@link Object#equals(Object)} methods.
     *
     * @param o the {@link Pair} to which this one is to be checked for equality
     * @return true if the underlying objects of the Pair are both considered
     *         equal
     */
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Pair)) {
            return false;
        }
        Pair<?, ?> p = (Pair<?, ?>) o;
        return Objects.equals(p.first, first) && Objects.equals(p.second, second);
    }

    /**
     * Compute a hash code using the hash codes of the underlying objects
     *
     * @return a hashcode of the Pair
     */
    @Override
    public int hashCode() {
        return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
    }

    /**
     * Convenience method for creating an appropriately typed pair.
     * @param a the first object in the Pair
     * @param b the second object in the pair
     * @return a Pair that is templatized with the types of a and b
     */
    public static <A, B> Pair <A, B> create(A a, B b) {
        return new Pair<A, B>(a, b);
    }
}

Simple CSS Animation Loop – Fading In & Out "Loading" Text

As King King said, you must add the browser specific prefix. This should cover most browsers:

_x000D_
_x000D_
@keyframes flickerAnimation {_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-o-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-moz-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-webkit-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
.animate-flicker {_x000D_
   -webkit-animation: flickerAnimation 1s infinite;_x000D_
   -moz-animation: flickerAnimation 1s infinite;_x000D_
   -o-animation: flickerAnimation 1s infinite;_x000D_
    animation: flickerAnimation 1s infinite;_x000D_
}
_x000D_
<div class="animate-flicker">Loading...</div>
_x000D_
_x000D_
_x000D_

What is the maximum length of a URL in different browsers?

Just remove or comment the following lines

public void ConfigureServices(IServiceCollection services) { /Identity/ services.AddDbContext(options => options.UseSqlServer(Configuration["ConnectionStrings:IdentityConnection"])); services.AddIdentity<AppUser, IdentityRole>().AddEntityFrameworkStores().AddDefaultTokenProviders(); /End/

        /*Identity Login Url */
        services.ConfigureApplicationCookie(opts => opts.LoginPath = "/Login");

        services.AddMvc();
        //Authorization
        //services.AddMvc(config =>
        //{
        //    var policy = new AuthorizationPolicyBuilder()
        //                    .RequireAuthenticatedUser()
        //                    .Build();
        //    config.Filters.Add(new AuthorizeFilter(policy));
        //});
    }

How to Store Historical Data

You could just partition the tables no?

"Partitioned Table and Index Strategies Using SQL Server 2008 When a database table grows in size to the hundreds of gigabytes or more, it can become more difficult to load new data, remove old data, and maintain indexes. Just the sheer size of the table causes such operations to take much longer. Even the data that must be loaded or removed can be very sizable, making INSERT and DELETE operations on the table impractical. The Microsoft SQL Server 2008 database software provides table partitioning to make such operations more manageable."

Getting CheckBoxList Item values

Try to use this.

        for (int i = 0; i < chBoxListTables.Items.Count; i++)
        {
            if (chBoxListTables.Items[i].Selected)
            {
                string str = chBoxListTables.Items[i].Text;
                MessageBox.Show(str);

                var itemValue = chBoxListTables.Items[i].Value;
            }
        }

The "V" should be in CAPS in Value.

Here is another code example used in WinForm app and runs properly.

        var chBoxList= new CheckedListBox();
        chBoxList.Items.Add(new ListItem("One", "1"));
        chBoxList.Items.Add(new ListItem("Two", "2"));
        chBoxList.SetItemChecked(1, true);

        var checkedItems = chBoxList.CheckedItems;
        var chkText = ((ListItem)checkedItems[0]).Text;
        var chkValue = ((ListItem)checkedItems[0]).Value;
        MessageBox.Show(chkText);
        MessageBox.Show(chkValue);

How to set the background image of a html 5 canvas to .png image

As shown in this example, you can apply a background to a canvas element through CSS and this background will not be considered part the image, e.g. when fetching the contents through toDataURL().

Here are the contents of the example, for Stack Overflow posterity:

<!DOCTYPE HTML>
<html><head>
  <meta charset="utf-8">
  <title>Canvas Background through CSS</title>
  <style type="text/css" media="screen">
    canvas, img { display:block; margin:1em auto; border:1px solid black; }
    canvas { background:url(lotsalasers.jpg) }
  </style>
</head><body>
<canvas width="800" height="300"></canvas>
<img>
<script type="text/javascript" charset="utf-8">
  var can = document.getElementsByTagName('canvas')[0];
  var ctx = can.getContext('2d');
  ctx.strokeStyle = '#f00';
  ctx.lineWidth   = 6;
  ctx.lineJoin    = 'round';
  ctx.strokeRect(140,60,40,40);
  var img = document.getElementsByTagName('img')[0];
  img.src = can.toDataURL();
</script>
</body></html>

How do I change the formatting of numbers on an axis with ggplot?

I'm late to the game here but in-case others want an easy solution, I created a set of functions which can be called like:

 ggplot + scale_x_continuous(labels = human_gbp)

which give you human readable numbers for x or y axes (or any number in general really).

You can find the functions here: Github Repo Just copy the functions in to your script so you can call them.

How to programmatically connect a client to a WCF service?

You'll have to use the ChannelFactory class.

Here's an example:

var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint))
{
    IMyService client = null;

    try
    {
        client = myChannelFactory.CreateChannel();
        client.MyServiceOperation();
        ((ICommunicationObject)client).Close();
        myChannelFactory.Close();
    }
    catch
    {
        (client as ICommunicationObject)?.Abort();
    }
}

Related resources:

How to write a file with C in Linux?

First of all, the code you wrote isn't portable, even if you get it to work. Why use OS-specific functions when there is a perfectly platform-independent way of doing it? Here's a version that uses just a single header file and is portable to any platform that implements the C standard library.

#include <stdio.h>

int main(int argc, char **argv)
{
    FILE* sourceFile;
    FILE* destFile;
    char buf[50];
    int numBytes;

    if(argc!=3)
    {
        printf("Usage: fcopy source destination\n");
        return 1;
    }

    sourceFile = fopen(argv[1], "rb");
    destFile = fopen(argv[2], "wb");

    if(sourceFile==NULL)
    {
        printf("Could not open source file\n");
        return 2;
    }
    if(destFile==NULL)
    {
        printf("Could not open destination file\n");
        return 3;
    }

    while(numBytes=fread(buf, 1, 50, sourceFile))
    {
        fwrite(buf, 1, numBytes, destFile);
    }

    fclose(sourceFile);
    fclose(destFile);

    return 0;
}

EDIT: The glibc reference has this to say:

In general, you should stick with using streams rather than file descriptors, unless there is some specific operation you want to do that can only be done on a file descriptor. If you are a beginning programmer and aren't sure what functions to use, we suggest that you concentrate on the formatted input functions (see Formatted Input) and formatted output functions (see Formatted Output).

If you are concerned about portability of your programs to systems other than GNU, you should also be aware that file descriptors are not as portable as streams. You can expect any system running ISO C to support streams, but non-GNU systems may not support file descriptors at all, or may only implement a subset of the GNU functions that operate on file descriptors. Most of the file descriptor functions in the GNU library are included in the POSIX.1 standard, however.

php random x digit number

the simplest way i can think of is using rand function with str_pad

<?php
echo str_pad(rand(0,999), 5, "0", STR_PAD_LEFT);
?>

In above example , it will generate random number in range 0 to 999.

And having 5 digits.

Uploading Laravel Project onto Web Server

Had this problem too and found out that the easiest way is to point your domain to the public folder and leave everything else the way they are.

PLEASE ENSURE TO USE THE RIGHT VERSION OF PHP. Save yourself some stress :)

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

XMLHttpRequest status 0 (responseText is empty)

The cause of your problems is that you are trying to do a cross-domain call and it fails.

If you're doing localhost development you can make cross-domain calls - I do it all the time.

For Firefox, you have to enable it in your config settings

signed.applets.codebase_principal_support = true

Then add something like this to your XHR open code:

  if (isLocalHost()){
    if (typeof(netscape) != 'undefined' && typeof(netscape.security) != 'undefined'){
      netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
    }
  }

For IE, if I remember right, all you have to do is enable the browser's Security setting under "Miscellaneous → Access data sources across domains" to get it to work with ActiveX XHRs.

IE8 and above also added cross-domain capabilities to the native XmlHttpRequest objects, but I haven't played with those yet.

Delete all local git branches

Make sure you do this first

git fetch

Once you have all remote branches information, use the following command to remove every single branch except master

 git branch -a | grep -v "master" | grep remotes | sed 's/remotes\/origin\///g' | xargs git push origin --delete

Retrieve CPU usage and memory usage of a single process on Linux?

ps axo pid,etime,%cpu,%mem,cmd | grep 'processname' | grep -v grep

PID - Process ID

etime - Process Running/Live Duration

%cpu - CPU usage

%mem - Memory usage

cmd - Command

Replace processname with whatever process you want to track, mysql nginx php-fpm etc ...

How do I convert from BLOB to TEXT in MySQL?

SELECCT TO_BASE64(blobfield)  
FROM the Table

worked for me.

The CAST(blobfield AS CHAR(10000) CHARACTER SET utf8) and CAST(blobfield AS CHAR(10000) CHARACTER SET utf16) did not show me the text value I wanted to get.

Why is "throws Exception" necessary when calling a function?

The throws Exception declaration is an automated way of keeping track of methods that might throw an exception for anticipated but unavoidable reasons. The declaration is typically specific about the type or types of exceptions that may be thrown such as throws IOException or throws IOException, MyException.

We all have or will eventually write code that stops unexpectedly and reports an exception due to something we did not anticipate before running the program, like division by zero or index out of bounds. Since the errors were not expected by the method, they could not be "caught" and handled with a try catch clause. Any unsuspecting users of the method would also not know of this possibility and their programs would also stop.

When the programmer knows certain types of errors may occur but would like to handle these exceptions outside of the method, the method can "throw" one or more types of exceptions to the calling method instead of handling them. If the programmer did not declare that the method (might) throw an exception (or if Java did not have the ability to declare it), the compiler could not know and it would be up to the future user of the method to know about, catch and handle any exceptions the method might throw. Since programs can have many layers of methods written by many different programs, it becomes difficult (impossible) to keep track of which methods might throw exceptions.

Even though Java has the ability to declare exceptions, you can still write a new method with unhandled and undeclared exceptions, and Java will compile it and you can run it and hope for the best. What Java won't let you do is compile your new method if it uses a method that has been declared as throwing exception(s), unless you either handle the declared exception(s) in your method or declare your method as throwing the same exception(s) or if there are multiple exceptions, you can handle some and throw the rest.

When a programmer declares that the method throws a specific type of exception, it is just an automated way of warning other programmers using the method that an exception is possible. The programmer can then decide to handled the exception or pass on the warning by declaring the calling method as also throwing the same exception. Since the compiler has been warned the exception is possible in this new method, it can automatically check if future callers of the new method handle the exception or declare it and enforcing one or the other to happen.

The nice thing about this type of solution is that when the compiler reports Error: Unhandled exception type java.io.IOException it gives the file and line number of the method that was declared to throw the exception. You can then choose to simply pass the buck and declare your method also "throws IOException". This can be done all the way up to main method where it would then cause the program to stop and report the exception to the user. However, it is better to catch the exception and deal with it in a nice way such as explaining to the user what has happened and how to fix it. When a method does catch and handle the exception, it no longer has to declare the exception. The buck stops there so to speak.

Get list of a class' instance methods

You can get a more detailed list (e.g. structured by defining class) with gems like debugging or looksee.

how to loop through rows columns in excel VBA Macro

This one is similar to @Wilhelm's solution. The loop automates based on a range created by evaluating the populated date column. This was slapped together based strictly on the conversation here and screenshots.

Please note: This assumes that the headers will always be on the same row (row 8). Changing the first row of data (moving the header up/down) will cause the range automation to break unless you edit the range block to take in the header row dynamically. Other assumptions include that VOL and CAPACITY formula column headers are named "Vol" and "Cap" respectively.

Sub Loop3()

Dim dtCnt As Long
Dim rng As Range
Dim frmlas() As String

Application.ScreenUpdating = False

'The following code block sets up the formula output range
dtCnt = Sheets("Loop").Range("A1048576").End(xlUp).Row              'lowest date column populated
endHead = Sheets("Loop").Range("XFD8").End(xlToLeft).Column         'right most header populated
Set rng = Sheets("Loop").Range(Cells(9, 2), Cells(dtCnt, endHead))  'assigns range for automation

ReDim frmlas(1)      'array assigned to formula strings
    'VOL column formula
frmlas(0) = "VOL FORMULA"
    'CAPACITY column formula
frmlas(1) = "CAP FORMULA"

For i = 1 To rng.Columns.count
If rng(0, i).Value = "Vol" Then         'checks for volume formula column
    For j = 1 To rng.Rows.count
        rng(j, i).Formula= frmlas(0)    'inserts volume formula
    Next j
ElseIf rng(0, i).Value = "Cap" Then     'checks for capacity formula column
    For j = 1 To rng.Rows.count
        rng(j, i).Formula = frmlas(1)   'inserts capacity formula
    Next j
End If
Next i

Application.ScreenUpdating = True

End Sub

How can I give access to a private GitHub repository?

Two steps:
1. Login and click "Invite someone" in the right column under "People". Enter and select persons github id.
2. It will then give you the option to "Invite Username to some teams" at which point you simply check off which teams you want to add them to then click "Send Invitation"

Alternatively:
1. Get the persons github id (not their email)
2. Navigate to the repository you would like to add the user to
3. Click "Settings" in the right column (not the gearbox settings along the top)
4. Click Collaborators long the left column
5. Select the repository name
6. Where it reads "Invite or add users to team" add the persons github id
7. An invitation will then be e-mailed.

Please let me know how this worked for you!

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

Building up on Paul Burke's answer I faced many problems resolving external SD card's URI path as most of the suggested "built-in" functions return paths which do not get resolved to files.

However, this is my approach of his // TODO handle non-primary volumes.

String resolvedPath = "";
File[] possibleExtSdComposites = context.getExternalFilesDirs(null);
for (File f : possibleExtSdComposites) {
    // Reset final path
    resolvedPath = "";

    // Construct list of folders
    ArrayList<String> extSdSplit = new ArrayList<>(Arrays.asList(f.getPath().split("/")));

    // Look for folder "<your_application_id>"
    int idx = extSdSplit.indexOf(BuildConfig.APPLICATION_ID);

    // ASSUMPTION: Expected to be found at depth 2 (in this case ExtSdCard's root is /storage/0000-0000/) - e.g. /storage/0000-0000/Android/data/<your_application_id>/files
    ArrayList<String> hierarchyList = new ArrayList<>(extSdSplit.subList(0, idx - 2));

    // Construct list containing full possible path to the file
    hierarchyList.add(tail);
    String possibleFilePath = TextUtils.join("/", hierarchyList);

    // If file is found --> success
    if (idx != -1 && new File(possibleFilePath).exists()) {
        resolvedPath = possibleFilePath;
        break;
    }
}

if (!resolvedPath.equals("")) {
    return resolvedPath;
} else {
    return null;
}

Note it depends on hierarchy which might be different on every phone manufacturer - I have not tested them all (it worked well so far on Xperia Z3 API 23 and Samsung Galaxy A3 API 23).

Please confirm if it does not perform well elsewhere.

How to grep recursively, but only in files with certain extensions?

Should write "-exec grep " for each "-o -name "

find . -name '*.h' -exec grep -Hn "CP_Image" {} \; -o -name '*.cpp' -exec grep -Hn "CP_Image" {} \;

Or group them by ( )

find . \( -name '*.h' -o -name '*.cpp' \) -exec grep -Hn "CP_Image" {} \;

option '-Hn' show the file name and line.

How do I exit the results of 'git diff' in Git Bash on windows?

Using WIN + Q worked for me. Just q alone gave me "command not found" and eventually it jumped back into the git diff insanity.

SonarQube not picking up Unit Test Coverage

The presence of argLine configurations in either of surefire and jacoco plugins stops the jacoco report generation. The argLine should be defined in properties

<properties>
  <argLine>your jvm options here</argLine>
</properties>

Vertical line using XML drawable

You can use a shape but instead of a line make it rectangle.

android:shape="rectangle">
<stroke
    android:width="5dp"
    android:color="#ff000000"
    android:dashGap="10px"
    android:dashWidth="30px" />

and In your layout use this...

<ImageView
    android:layout_width="7dp"
    android:layout_height="match_parent"
    android:src="@drawable/dashline"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layerType="software"/>

You might have to play with the width, depending on the size of the dashes, to get it into a single line.

Hope this helps Cheers

No Access-Control-Allow-Origin header is present on the requested resource

Solution:
Instead of using setHeader method I have used addHeader.

response.addHeader("Access-Control-Allow-Origin", "*");

* in above line will allow access to all domains, For allowing access to specific domain only:

response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");

For issues related to IE<=9, Please see here.

Simplest way to display current month and year like "Aug 2016" in PHP?

Full version:

<? echo date('F Y'); ?>

Short version:

<? echo date('M Y'); ?>

Here is a good reference for the different date options.

update

To show the previous month we would have to introduce the mktime() function and make use of the optional timestamp parameter for the date() function. Like this:

echo date('F Y', mktime(0, 0, 0, date('m')-1, 1, date('Y')));

This will also work (it's typically used to get the last day of the previous month):

echo date('F Y', mktime(0, 0, 0, date('m'), 0, date('Y')));

Hope that helps.