Programs & Examples On #Ring

Ring is a Clojure web applications library written by Mark McGranaghan. It was inspired by Python's WSGI and Ruby's Rack. By abstracting the details of HTTP into a simple, unified API, Ring allows web applications to be constructed of modular components that can be shared among a variety of applications, web servers, and web frameworks.

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

How to implement a simple scenario the OO way

You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.

Method Call Chaining; returning a pointer vs a reference?

The difference between pointers and references is quite simple: a pointer can be null, a reference can not.

Examine your API, if it makes sense for null to be able to be returned, possibly to indicate an error, use a pointer, otherwise use a reference. If you do use a pointer, you should add checks to see if it's null (and such checks may slow down your code).

Here it looks like references are more appropriate.

How do I get some variable from another class in Java?

I am trying to get int x equal to 5 (as seen in the setNum() method) but when it prints it gives me 0.

To run the code in setNum you have to call it. If you don't call it, the default value is 0.

How to correctly write async method?

You are calling DoDownloadAsync() but you don't wait it. So your program going to the next line. But there is another problem, Async methods should return Task or Task<T>, if you return nothing and you want your method will be run asyncronously you should define your method like this:

private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } 

And in Main method you can't await for DoDownloadAsync, because you can't use await keyword in non-async function, and you can't make Main async. So consider this:

var result = DoDownloadAsync();  Debug.WriteLine("DoDownload done"); result.Wait(); 

How to split a string in two and store it in a field

I would suggest the following:

String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName); 

String index out of range: 4

You are using the wrong iteration counter, replace inp.charAt(i) with inp.charAt(j).

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Empty brackets '[]' appearing when using .where

A good bet is to utilize Rails' Arel SQL manager, which explicitly supports case-insensitive ActiveRecord queries:

t = Guide.arel_table Guide.where(t[:title].matches('%attack')) 

Here's an interesting blog post regarding the portability of case-insensitive queries using Arel. It's worth a read to understand the implications of utilizing Arel across databases.

Xml Parsing in C#

First add an Enrty and Category class:

public class Entry {     public string Id { get; set; }     public string Title { get; set; }     public string Updated { get; set; }     public string Summary { get; set; }     public string GPoint { get; set; }     public string GElev { get; set; }     public List<string> Categories { get; set; } }  public class Category {     public string Label { get; set; }     public string Term { get; set; } } 

Then use LINQ to XML

XDocument xDoc = XDocument.Load("path");          List<Entry> entries = (from x in xDoc.Descendants("entry")             select new Entry()             {                 Id = (string) x.Element("id"),                 Title = (string)x.Element("title"),                 Updated = (string)x.Element("updated"),                 Summary = (string)x.Element("summary"),                 GPoint = (string)x.Element("georss:point"),                 GElev = (string)x.Element("georss:elev"),                 Categories = (from c in x.Elements("category")                                   select new Category                                   {                                       Label = (string)c.Attribute("label"),                                       Term = (string)c.Attribute("term")                                   }).ToList();             }).ToList(); 

Instantiating a generic type

You basically have two choices:

1.Require an instance:

public Navigation(T t) {     this("", "", t); } 

2.Require a class instance:

public Navigation(Class<T> c) {     this("", "", c.newInstance()); } 

You could use a factory pattern, but ultimately you'll face this same issue, but just push it elsewhere in the code.

When to create variables (memory management)

I've heard that you must set a variable to 'null' once you're done using it so the garbage collector can get to it (if it's a field var).

This is very rarely a good idea. You only need to do this if the variable is a reference to an object which is going to live much longer than the object it refers to.

Say you have an instance of Class A and it has a reference to an instance of Class B. Class B is very large and you don't need it for very long (a pretty rare situation) You might null out the reference to class B to allow it to be collected.

A better way to handle objects which don't live very long is to hold them in local variables. These are naturally cleaned up when they drop out of scope.

If I were to have a variable that I won't be referring to agaon, would removing the reference vars I'm using (and just using the numbers when needed) save memory?

You don't free the memory for a primitive until the object which contains it is cleaned up by the GC.

Would that take more space than just plugging '5' into the println method?

The JIT is smart enough to turn fields which don't change into constants.

Been looking into memory management, so please let me know, along with any other advice you have to offer about managing memory

Use a memory profiler instead of chasing down 4 bytes of memory. Something like 4 million bytes might be worth chasing if you have a smart phone. If you have a PC, I wouldn't both with 4 million bytes.

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

java doesn't run if structure inside of onclick listener

both your conditions are the same:

if(s < f) {     calc = f - s;     n = s; }else if(f > s){     calc =  s - f;     n = f;  } 

so

if(s < f)   

and

}else if(f > s){ 

are the same

change to

}else if(f < s){ 

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

Removing "http://" from a string

preg_replace('/^[^:\/?]+:\/\//','',$url); 

some results:

input: http://php.net/preg_replace output: php.net/preg_replace  input: https://www.php.net/preg_replace output: www.php.net/preg_replace  input: ftp://www.php.net/preg_replace output: www.php.net/preg_replace  input: https://php.net/preg_replace?url=http://whatever.com output: php.net/preg_replace?url=http://whatever.com  input: php.net/preg_replace?url=http://whatever.com output: php.net/preg_replace?url=http://whatever.com  input: php.net?site=http://whatever.com output: php.net?site=http://whatever.com 

is it possible to add colors to python output?

If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.

Here an example:

print ('This is \x1b[31mred\x1b[0m.') 

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

Cannot retrieve string(s) from preferences (settings)

All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if to bind them all together in the way I believe you intend.

Two Page Login with Spring Security 3.2.x

There should be three pages here:

  1. Initial login page with a form that asks for your username, but not your password.
  2. You didn't mention this one, but I'd check whether the client computer is recognized, and if not, then challenge the user with either a CAPTCHA or else a security question. Otherwise the phishing site can simply use the tendered username to query the real site for the security image, which defeats the purpose of having a security image. (A security question is probably better here since with a CAPTCHA the attacker could have humans sitting there answering the CAPTCHAs to get at the security images. Depends how paranoid you want to be.)
  3. A page after that that displays the security image and asks for the password.

I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.

I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.

You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST submission on step 1 (and 2 if applicable).

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

Got a NumberFormatException while trying to parse a text file for objects

The problem might be your split() call. Try just split(" ") without the square brackets.

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

Querying date field in MongoDB with Mongoose

{ "date" : "1000000" } in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }

It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback) and if that works, you have a typing issue.

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

FragmentActivity to Fragment

first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

        <FrameLayout             android:id="@+id/content_frame"             android:layout_width="match_parent"             android:layout_height="match_parent"  >         </FrameLayout> 

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

protected void ButtonPP_Click(object sender, EventArgs e) {     if (radioBtnACO.SelectedIndex < 0)     {         string csname1 = "PopupScript";          var cstext1 = new StringBuilder();         cstext1.Append("alert('Please Select Criteria!')");          ScriptManager.RegisterStartupScript(this, GetType(), csname1,             cstext1.ToString(), true);     } } 

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

Are these methods thread safe?

The only problem with threads is accessing the same object from different threads without synchronization.

If each function only uses parameters for reading and local variables, they don't need any synchronization to be thread-safe.

make UITableViewCell selectable only while editing

Have you tried setting the selection properties of your tableView like this:

tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES; 

If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath in your UITableView delegate. The documentation states:

Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected. 

You can have this method return nil in cases where you don't want the selection to happen.

Comparing two joda DateTime instances

DateTime inherits its equals method from AbstractInstant. It is implemented as such

public boolean equals(Object readableInstant) {     // must be to fulfil ReadableInstant contract     if (this == readableInstant) {         return true;     }     if (readableInstant instanceof ReadableInstant == false) {         return false;     }     ReadableInstant otherInstant = (ReadableInstant) readableInstant;     return         getMillis() == otherInstant.getMillis() &&         FieldUtils.equals(getChronology(), otherInstant.getChronology()); } 

Notice the last line comparing chronology. It's possible your instances' chronologies are different.

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app

Simply update react-scripts to the latest version.

yarn add react-scripts@latest

OR IF USING NPM

npm install react-scripts@latest

TS1086: An accessor cannot be declared in ambient context

In my case downgrading @angular/animations worked, if you can afford to do that, run the command

npm i @angular/[email protected]

Or use another version that might work for you from the Versions tab here: https://www.npmjs.com/package/@angular/animations

IntelliJ: Error:java: error: release version 5 not supported

I've done most things you are proposing with Java compiler and bytecode and solved the problem in the past. It's been almost 1 month since I ran my Java code (and back then everything was fixed), but now the problem appeared again. Don't know why, pretty annoyed though!

This time the solution was: Right click to project name -> Open module settings F4 -> Language level ...and there you can define the language level your project/pc is.

No maven/pom configuration worked for me both in the past and now and I've already set the Java compiler and bytecode at 12.

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

Here is I solved:

Open the extension settings:

enter image description here

And search for the variable you want to change, and unchecked/checked it

enter image description here

The variables you should consider are:

intelephense.diagnostics.undefinedTypes 
intelephense.diagnostics.undefinedFunctions         
intelephense.diagnostics.undefinedConstants         
intelephense.diagnostics.undefinedClassConstants 
intelephense.diagnostics.undefinedMethods 
intelephense.diagnostics.undefinedProperties 
intelephense.diagnostics.undefinedVariables

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

For my situation this error was caused by having circular references in json sent from the server when using an ORM for parent/child relationships. So the quick and easy solution was

JsonConvert.SerializeObject(myObject, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore })

The better solution is to create DTOs that do not contain the references on both sides (parent/child).

Server Discovery And Monitoring engine is deprecated

It is important to run your mongod command and keep the server running. If not, you will still be seeing this error.

I attach you my code:

_x000D_
_x000D_
const mongodb = require('mongodb')
const MongoClient = mongodb.MongoClient

const connectionURL = 'mongodb://127.0.0.1:27017'
const databaseName = 'task-manager'

MongoClient.connect(connectionURL, {useNewUrlParser: true, useUnifiedTopology: true}, (error, client) => {
    if(error) {
        return console.log('Error connecting to the server.')
    }

    console.log('Succesfully connected.')
})
_x000D_
_x000D_
_x000D_

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

With out typescript error

    const formData = new FormData();
    Object.keys(newCategory).map((k,i)=>{  
        var d =Object.values(newCategory)[i];
        formData.append(k,d) 
    })

Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }

For those who Google:

No index signature with a parameter of type 'string' was found on type...

most likely your error should read like:

Did you mean to use a more specific type such as keyof Number instead of string?

I solved a similar typing issue with code like this:

const stringBasedKey = `SomeCustomString${someVar}` as keyof typeof YourTypeHere;

This issue helped me to learn the real meaning of the error.

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

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

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

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

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



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

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

    }

}

UPDATE:

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

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

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

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


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

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

    return next.handle(req1);
  }

}

Example

Why am I getting Unknown error in line 1 of pom.xml?

You must to upgrade the m2e connector. It's a known bug, but there is a solution:

  1. Into Eclipse click "Help" > "Install new Software..."

  2. Appears a window. In the "Install" window:

    2a. Into the input box "Work with", enter next site location and press Enter https://download.eclipse.org/m2e-wtp/releases/1.4/

    2b. Appears a lot of information into "Name" input Box. Select all the items

    2c. Click "Next" Button.

Finish the installation and restart Eclipse.

How to fix ReferenceError: primordials is not defined in node

I faced the same issue. What I tried and worked for me:

  1. Check the version of NODE and GULP (combination of node v12 and gulp less than v4 doesn't work)

  2. I downgrade NPM version by:

    • sudo NPM install -g n
    • sudo n 10.16.0

It worked fine, then just follow instruction of your console.

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

The answer of @cheez sometime doesn't work and recursively call the function again and again. To solve this problem you should copy the function deeply. You can do this by using the function partial, so the final code is:

import numpy as np
from functools import partial

# save np.load
np_load_old = partial(np.load)

# modify the default parameters of np.load
np.load = lambda *a,**k: np_load_old(*a, allow_pickle=True, **k)

# call load_data with allow_pickle implicitly set to true
(train_data, train_labels), (test_data, test_labels) = 
imdb.load_data(num_words=10000)

# restore np.load for future normal usage
np.load = np_load_old

What is the incentive for curl to release the library for free?

I'm Daniel Stenberg.

I made curl

I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.

I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.

Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.

Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.

Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.

At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.

Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.

Why do I still work on curl?

Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?

  1. I can't speak for my fellow project team members. We all participate in this for our own reasons.
  2. I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
  3. There are still bugs to fix and features to add!
  4. curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
  5. curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
  6. I would not do it differently if I could back and do it again.

Am I proud of what we've done?

Yes. So insanely much.

But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.

We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.

Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.

For real?

Yeah. For real.

Do I ever get tired? Is it ever done?

Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.

But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.

curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.

Module not found: Error: Can't resolve 'core-js/es6'

Sure, I had a similar issue and a simple

npm uninstall @babel/polyfill --save &&
npm install @babel/polyfill --save

did the trick for me.

However, usage of @babel/polyfill is deprecated (according to this comment) so only try this if you think you have older packages installed or if all else fails.

How to set value to form control in Reactive Forms in Angular

Setting or Updating of Reactive Forms Form Control values can be done using both patchValue and setValue. However, it might be better to use patchValue in some instances.

patchValue does not require all controls to be specified within the parameters in order to update/set the value of your Form Controls. On the other hand, setValue requires all Form Control values to be filled in, and it will return an error if any of your controls are not specified within the parameter.

In this scenario, we will want to use patchValue, since we are only updating user and questioning:

this.qService.editQue([params["id"]]).subscribe(res => {
  this.question = res;
  this.editqueForm.patchValue({
    user: this.question.user,
    questioning: this.question.questioning
  });
});

EDIT: If you feel like doing some of ES6's Object Destructuring, you may be interested to do this instead

const { user, questioning } = this.question;

this.editqueForm.patchValue({
  user,
  questioning
});

Ta-dah!

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

I also have the same problem, and the solution is I didn't bind the event in my onClick. so when it renders for the first time and the data is more, which ends up calling the state setter again, which triggers React to call your function again and so on.

export default function Component(props) {

function clickEvent (event, variable){
    console.log(variable);
}

return (
    <div>
        <IconButton
            key="close"
            aria-label="Close"
            color="inherit"
            onClick={e => clickEvent(e, 10)} // or you can call like this:onClick={() => clickEvent(10)} 
        >
    </div>
)
}

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65

If you don't have cocoa pods installed you need to:

sudo gem install cocoapods

Then run:

cd /ios
pod install

delete the build folder in ios folder of your react native project

run:

react-native run-ios

if error persists:

  • delete build folder again
  • open the /ios folder in Xcode
  • navigate File -> Project Settings -> Build System -> change (Shared workspace settings and Per-User workspace settings): Build System -> Legacy Build System

session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

I have almost the same problems like this, the problems is come inside the pipeline when running my selenium test that need chromedriver package to running the e2e test.

My error build pipeline

The problems is just because in the pipeline (in my case) is having the chrome version 73, and my chromedriver package is installed on version 74.

Finally there are two simple solutions:

  1. Downgrade your chrome
  2. Downgrade your chromedriver package version. in my case, cause i running inside the pipeline i need to install chromedriver before running the selenium test like displayed below.

    - script: npm install [email protected] --chromedriver-force-download displayName: 'Install Chrome'

How can I solve the error 'TS2532: Object is possibly 'undefined'?

For others facing a similar problem to mine, where you know a particular object property cannot be null, you can use the non-null assertion operator (!) after the item in question. This was my code:

  const naciStatus = dataToSend.naci?.statusNACI;
  if (typeof naciStatus != "undefined") {
    switch (naciStatus) {
      case "AP":
        dataToSend.naci.certificateStatus = "FALSE";
        break;
      case "AS":
      case "WR":
        dataToSend.naci.certificateStatus = "TRUE";
        break;
      default:
        dataToSend.naci.certificateStatus = "";
    }
  }

And because dataToSend.naci cannot be undefined in the switch statement, the code can be updated to include exclamation marks as follows:

  const naciStatus = dataToSend.naci?.statusNACI;
  if (typeof naciStatus != "undefined") {
    switch (naciStatus) {
      case "AP":
        dataToSend.naci!.certificateStatus = "FALSE";
        break;
      case "AS":
      case "WR":
        dataToSend.naci!.certificateStatus = "TRUE";
        break;
      default:
        dataToSend.naci!.certificateStatus = "";
    }
  }

Typescript: Type 'string | undefined' is not assignable to type 'string'

You could make use of Typescript's optional chaining. Example:

const name = person?.name;

If the property name exists on the person object you would get its value but if not it would automatically return undefined.

You could make use of this resource for a better understanding.

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html

Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

You must specify which type the response is

  this.productService.getProducts().subscribe(res => {
          this.productsArray = res;
        });

Try this

  this.productService.getProducts().subscribe((res: Product[]) => {
          this.productsArray = res;
        });

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?

Just add this at start: image = cv2.imread(image)

Can't perform a React state update on an unmounted component

Based on @ford04 answer, here is the same encapsulated in a method :

import React, { FC, useState, useEffect, DependencyList } from 'react';

export function useEffectAsync( effectAsyncFun : ( isMounted: () => boolean ) => unknown, deps?: DependencyList ) {
    useEffect( () => {
        let isMounted = true;
        const _unused = effectAsyncFun( () => isMounted );
        return () => { isMounted = false; };
    }, deps );
} 

Usage:

const MyComponent : FC<{}> = (props) => {
    const [ asyncProp , setAsyncProp ] = useState( '' ) ;
    useEffectAsync( async ( isMounted ) =>
    {
        const someAsyncProp = await ... ;
        if ( isMounted() )
             setAsyncProp( someAsyncProp ) ;
    });
    return <div> ... ;
} ;

Can I set state inside a useEffect hook

useEffect can hook on a certain prop or state. so, the thing you need to do to avoid infinite loop hook is binding some variable or state to effect

For Example:

useEffect(myeffectCallback, [])

above effect will fire only once the component has rendered. this is similar to componentDidMount lifecycle

const [something, setSomething] = withState(0)
const [myState, setMyState] = withState(0)
useEffect(() => {
  setSomething(0)
}, myState)

above effect will fire only my state has changed this is similar to componentDidUpdate except not every changing state will fire it.

You can read more detail though this link

FlutterError: Unable to load asset

I also had this problem. I think there is a bug in the way Flutter caches images. My guess is that when you first attempted to load pizza0.png, it wasn't available, and Flutter has cached this failed result. Then, even after adding the correct image, Flutter still assumes it isn't available.

This is all guess-work, based on the fact that I had the same problem, and calling this once on app start fixed the problem for me:

imageCache.clear();

This clears the image cache, meaning that Flutter will then attempt to load the images fresh rather than search the cache.

PS I've also found that you need to call this whenever you change any existing images, for the same reason - Flutter will load the old cached version. The alternative is to rename the image.

Pandas Merging 101

This post will go through the following topics:

  • how to correctly generalize to multiple DataFrames (and why merge has shortcomings here)
  • merging on unique keys
  • merging on non-unqiue keys

BACK TO TOP



Generalizing to multiple DataFrames

Oftentimes, the situation arises when multiple DataFrames are to be merged together. Naively, this can be done by chaining merge calls:

df1.merge(df2, ...).merge(df3, ...)

However, this quickly gets out of hand for many DataFrames. Furthermore, it may be necessary to generalise for an unknown number of DataFrames.

Here I introduce pd.concat for multi-way joins on unique keys, and DataFrame.join for multi-way joins on non-unique keys. First, the setup.

# Setup.
np.random.seed(0)
A = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'valueA': np.random.randn(4)})    
B = pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'valueB': np.random.randn(4)})
C = pd.DataFrame({'key': ['D', 'E', 'J', 'C'], 'valueC': np.ones(4)})
dfs = [A, B, C] 

# Note, the "key" column values are unique, so the index is unique.
A2 = A.set_index('key')
B2 = B.set_index('key')
C2 = C.set_index('key')

dfs2 = [A2, B2, C2]

Multiway merge on unique keys

If your keys (here, the key could either be a column or an index) are unique, then you can use pd.concat. Note that pd.concat joins DataFrames on the index.

# merge on `key` column, you'll need to set the index before concatenating
pd.concat([
    df.set_index('key') for df in dfs], axis=1, join='inner'
).reset_index()

  key    valueA    valueB  valueC
0   D  2.240893 -0.977278     1.0

# merge on `key` index
pd.concat(dfs2, axis=1, sort=False, join='inner')

       valueA    valueB  valueC
key                            
D    2.240893 -0.977278     1.0

Omit join='inner' for a FULL OUTER JOIN. Note that you cannot specify LEFT or RIGHT OUTER joins (if you need these, use join, described below).


Multiway merge on keys with duplicates

concat is fast, but has its shortcomings. It cannot handle duplicates.

A3 = pd.DataFrame({'key': ['A', 'B', 'C', 'D', 'D'], 'valueA': np.random.randn(5)})
pd.concat([df.set_index('key') for df in [A3, B, C]], axis=1, join='inner')
ValueError: Shape of passed values is (3, 4), indices imply (3, 2)

In this situation, we can use join since it can handle non-unique keys (note that join joins DataFrames on their index; it calls merge under the hood and does a LEFT OUTER JOIN unless otherwise specified).

# join on `key` column, set as the index first
# For inner join. For left join, omit the "how" argument.
A.set_index('key').join(
    [df.set_index('key') for df in (B, C)], how='inner').reset_index()

  key    valueA    valueB  valueC
0   D  2.240893 -0.977278     1.0

# join on `key` index
A3.set_index('key').join([B2, C2], how='inner')

       valueA    valueB  valueC
key                            
D    1.454274 -0.977278     1.0
D    0.761038 -0.977278     1.0


Continue Reading

Jump to other topics in Pandas Merging 101 to continue learning:

* you are here

Why is 2 * (i * i) faster than 2 * i * i in Java?

(Editor's note: this answer is contradicted by evidence from looking at the asm, as shown by another answer. This was a guess backed up by some experiments, but it turned out not to be correct.)


When the multiplication is 2 * (i * i), the JVM is able to factor out the multiplication by 2 from the loop, resulting in this equivalent but more efficient code:

int n = 0;
for (int i = 0; i < 1000000000; i++) {
    n += i * i;
}
n *= 2;

but when the multiplication is (2 * i) * i, the JVM doesn't optimize it since the multiplication by a constant is no longer right before the n += addition.

Here are a few reasons why I think this is the case:

  • Adding an if (n == 0) n = 1 statement at the start of the loop results in both versions being as efficient, since factoring out the multiplication no longer guarantees that the result will be the same
  • The optimized version (by factoring out the multiplication by 2) is exactly as fast as the 2 * (i * i) version

Here is the test code that I used to draw these conclusions:

public static void main(String[] args) {
    long fastVersion = 0;
    long slowVersion = 0;
    long optimizedVersion = 0;
    long modifiedFastVersion = 0;
    long modifiedSlowVersion = 0;

    for (int i = 0; i < 10; i++) {
        fastVersion += fastVersion();
        slowVersion += slowVersion();
        optimizedVersion += optimizedVersion();
        modifiedFastVersion += modifiedFastVersion();
        modifiedSlowVersion += modifiedSlowVersion();
    }

    System.out.println("Fast version: " + (double) fastVersion / 1000000000 + " s");
    System.out.println("Slow version: " + (double) slowVersion / 1000000000 + " s");
    System.out.println("Optimized version: " + (double) optimizedVersion / 1000000000 + " s");
    System.out.println("Modified fast version: " + (double) modifiedFastVersion / 1000000000 + " s");
    System.out.println("Modified slow version: " + (double) modifiedSlowVersion / 1000000000 + " s");
}

private static long fastVersion() {
    long startTime = System.nanoTime();
    int n = 0;
    for (int i = 0; i < 1000000000; i++) {
        n += 2 * (i * i);
    }
    return System.nanoTime() - startTime;
}

private static long slowVersion() {
    long startTime = System.nanoTime();
    int n = 0;
    for (int i = 0; i < 1000000000; i++) {
        n += 2 * i * i;
    }
    return System.nanoTime() - startTime;
}

private static long optimizedVersion() {
    long startTime = System.nanoTime();
    int n = 0;
    for (int i = 0; i < 1000000000; i++) {
        n += i * i;
    }
    n *= 2;
    return System.nanoTime() - startTime;
}

private static long modifiedFastVersion() {
    long startTime = System.nanoTime();
    int n = 0;
    for (int i = 0; i < 1000000000; i++) {
        if (n == 0) n = 1;
        n += 2 * (i * i);
    }
    return System.nanoTime() - startTime;
}

private static long modifiedSlowVersion() {
    long startTime = System.nanoTime();
    int n = 0;
    for (int i = 0; i < 1000000000; i++) {
        if (n == 0) n = 1;
        n += 2 * i * i;
    }
    return System.nanoTime() - startTime;
}

And here are the results:

Fast version: 5.7274411 s
Slow version: 7.6190804 s
Optimized version: 5.1348007 s
Modified fast version: 7.1492705 s
Modified slow version: 7.2952668 s

How can I force component to re-render with hooks in React?

One line solution:

const useForceUpdate = () => useState()[1];

useState returns a pair of values: the current state and a function that updates it - state and setter, here we are using only the setter in order to force re-render.

What is the meaning of "Failed building wheel for X" in pip install?

Try this:

sudo apt-get install libpcap-dev libpq-dev

It has worked for me when I have installed these two.

See the link here for more information

Flutter: RenderBox was not laid out

Reason for the error:

Column tries to expands in vertical axis, and so does the ListView, hence you need to constrain the height of ListView.


Solutions

  1. Use either Expanded or Flexible if you want to allow ListView to take up entire left space in Column.

    Column(
      children: <Widget>[
        Expanded(
          child: ListView(...),
        )
      ],
    )
    

  1. Use SizedBox if you want to restrict the size of ListView to a certain height.

    Column(
      children: <Widget>[
        SizedBox(
          height: 200, // constrain height
          child: ListView(),
        )
      ],
    )
    

  1. Use shrinkWrap, if your ListView isn't too big.

    Column(
      children: <Widget>[
        ListView(
          shrinkWrap: true, // use it
        )
      ],
    )
    

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

Here a temporary workaround, If you are using room just upgrade to 1.1.0 or higher

implementation "android.arch.persistence.room:runtime:1.1.0"

it removes this warning for me.

What is "not assignable to parameter of type never" error in typescript?

I was able to get past this by using the Array keyword instead of empty brackets:

const enhancers: Array<any> = [];

Use:

if (typeof devToolsExtension === 'function') {
  enhancers.push(devToolsExtension())
}

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

I have got the same error as :

error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/

As, said by @Agaline, i download the outside wheel from this Christoph Gohlke.

If your is Python 3.7 then try to PyAudio-0.2.11-cp37-cp37m-win_amd64.whl and use command as, go to the download directroy and:

pip install PyAudio-0.2.11-cp37-cp37m-win_amd64.whl and it works.

GoogleMaps API KEY for testing

There seems no way to have google maps api key free without credit card. To test the functionality of google map you can use it while leaving the api key field "EMPTY". It will show a message saying "For Development Purpose Only". And that way you can test google map functionality without putting billing information for google map api key.

<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap" async defer></script>

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

var userPasswordString = new Buffer(baseAuth, 'base64').toString('ascii');

Change this line from your code to this -

var userPasswordString = Buffer.from(baseAuth, 'base64').toString('ascii');

or in my case, I gave the encoding in reverse order

var userPasswordString = Buffer.from(baseAuth, 'utf-8').toString('base64');

Starting ssh-agent on Windows 10 fails: "unable to start ssh-agent service, error :1058"

Yeah, as others have suggested, this error seems to mean that ssh-agent is installed but its service (on windows) hasn't been started.

You can check this by running in Windows PowerShell:

> Get-Service ssh-agent

And then check the output of status is not running.

Status   Name               DisplayName
------   ----               -----------
Stopped  ssh-agent          OpenSSH Authentication Agent

Then check that the service has been disabled by running

> Get-Service ssh-agent | Select StartType

StartType
---------
Disabled

I suggest setting the service to start manually. This means that as soon as you run ssh-agent, it'll start the service. You can do this through the Services GUI or you can run the command in admin mode:

 > Get-Service -Name ssh-agent | Set-Service -StartupType Manual

Alternatively, you can set it through the GUI if you prefer.

services.msc showing the properties of the OpenSSH Agent

Flutter - The method was called on null

The reason for this error occurs is that you are using the CryptoListPresenter _presenter without initializing.

I found that CryptoListPresenter _presenter would have to be initialized to fix because _presenter.loadCurrencies() is passing through a null variable at the time of instantiation;

there are two ways to initialize

  1. Can be initialized during an declaration, like this

    CryptoListPresenter _presenter = CryptoListPresenter();
    
  2. In the second, initializing(with assigning some value) it when initState is called, which the framework will call this method once for each state object.

    @override
    void initState() {
      _presenter = CryptoListPresenter(...);
    }
    

How to convert string to boolean in typescript Angular 4

In your scenario, converting a string to a boolean can be done via something like someString === 'true' (as was already answered).

However, let me try to address your main issue: dealing with the local storage.

The local storage only supports strings as values; a good way of using it would thus be to always serialise your data as a string before storing it in the storage, and reversing the process when fetching it.

A possibly decent format for serialising your data in is JSON, since it is very easy to deal with in JavaScript.

The following functions could thus be used to interact with local storage, provided that your data can be serialised into JSON.

function setItemInStorage(key, item) {
  localStorage.setItem(key, JSON.stringify(item));
}

function getItemFromStorage(key) {
  return JSON.parse(localStorage.getItem(key));
}

Your example could then be rewritten as:

setItemInStorage('CheckOutPageReload', [this.btnLoginNumOne, this.btnLoginEdit]);

And:

if (getItemFromStorage('CheckOutPageReload')) {
  const pageLoadParams = getItemFromStorage('CheckOutPageReload');
  this.btnLoginNumOne = pageLoadParams[0];
  this.btnLoginEdit = pageLoadParams[1];
}

What is the Record type in typescript?

A Record lets you create a new type from a Union. The values in the Union are used as attributes of the new type.

For example, say I have a Union like this:

type CatNames = "miffy" | "boris" | "mordred";

Now I want to create an object that contains information about all the cats, I can create a new type using the values in the CatName Union as keys.

type CatList = Record<CatNames, {age: number}>

If I want to satisfy this CatList, I must create an object like this:

const cats:CatList = {
  miffy: { age:99 },
  boris: { age:16 },
  mordred: { age:600 }
}

You get very strong type safety:

  • If I forget a cat, I get an error.
  • If I add a cat that's not allowed, I get an error.
  • If I later change CatNames, I get an error. This is especially useful because CatNames is likely imported from another file, and likely used in many places.

Real-world React example.

I used this recently to create a Status component. The component would receive a status prop, and then render an icon. I've simplified the code quite a lot here for illustrative purposes

I had a union like this:

type Statuses = "failed" | "complete";

I used this to create an object like this:

const icons: Record<
  Statuses,
  { iconType: IconTypes; iconColor: IconColors }
> = {
  failed: {
    iconType: "warning",
    iconColor: "red"
  },
  complete: {
    iconType: "check",
    iconColor: "green"
  };

I could then render by destructuring an element from the object into props, like so:

const Status = ({status}) => <Icon {...icons[status]} />

If the Statuses union is later extended or changed, I know my Status component will fail to compile and I'll get an error that I can fix immediately. This allows me to add additional error states to the app.

Note that the actual app had dozens of error states that were referenced in multiple places, so this type safety was extremely useful.

Flutter plugin not installed error;. When running flutter doctor

For those who still have this error even if they have tried the solutions mentioned before, try this it works on windows 10/ macOS and linux (run in the command line):

  1. flutter channel dev
  2. flutter upgrade
  3. flutter config --android-studio-dir="C:\Program Files\Android\Android Studio"

Android Material and appcompat Manifest merger failed

Reason of Fail

You are using material library which is part of AndroidX. If you are not aware of AndroidX, please go through this answer.

One app should use either AndroidX or old Android Support libraries. That's why you faced this issue.

For example -

In your gradle, you are using

  • com.android.support:appcompat-v7 (Part of old --Android Support Library--)
  • com.google.android.material:material (Part of AndroidX) (AndroidX build artifact of com.android.support:design)

Solution

So the solution is to use either AndroidX or old Support Library. I recommend to use AndroidX, because Android will not update support libraries after version 28.0.0. See release notes of Support Library.

Just migrate to AndroidX.Here is my detailed answer to migrate to AndroidX. I am putting here the needful steps from that answer.

Before you migrate, it is strongly recommended to backup your project.

Existing project

  • Android Studio > Refactor Menu > Migrate to AndroidX...
  • It will analysis and will open Refractor window in bottom. Accept changes to be done.

image

New project

Put these flags in your gradle.properties

android.enableJetifier=true
android.useAndroidX=true

Check @Library mappings for equal AndroidX package.

Check @Official page of Migrate to AndroidX

What is Jetifier?

Under which circumstances textAlign property works in Flutter?

textAlign property only works when there is a more space left for the Text's content. Below are 2 examples which shows when textAlign has impact and when not.


No impact

For instance, in this example, it won't have any impact because there is no extra space for the content of the Text.

Text(
  "Hello",
  textAlign: TextAlign.end, // no impact
),

enter image description here


Has impact

If you wrap it in a Container and provide extra width such that it has more extra space.

Container(
  width: 200,
  color: Colors.orange,
  child: Text(
    "Hello",
    textAlign: TextAlign.end, // has impact
  ),
)

enter image description here

Xcode couldn't find any provisioning profiles matching

You can get this issue if Apple update their terms. Simply log into your dev account and accept any updated terms and you should be good (you will need to goto Xcode -> project->signing and capabilities and retry the certificate check. This should get you going if terms are the issue.

How to resolve TypeError: can only concatenate str (not "int") to str

Use this:

print("Program for calculating sum")
numbers=[1, 2, 3, 4, 5, 6, 7, 8]
sum=0
for number in numbers:
    sum += number
print("Total Sum is: %d" %sum )

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

This one worked for me, for MySQL: (Application properties)

spring.datasource.url=jdbc:mysql://localhost:3306/db?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&
useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=admin
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true

FirebaseInstanceIdService is deprecated

And this:

FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken()

suppose to be solution of deprecated:

FirebaseInstanceId.getInstance().getToken()

EDIT

FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken() can produce exception if the task is not yet completed, so the method witch Nilesh Rathod described (with .addOnSuccessListener) is correct way to do it.

Kotlin:

FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener(this) { instanceIdResult ->
        val newToken = instanceIdResult.token
        Log.e("newToken", newToken)
    }

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

Remove this line from your code:

console.info(JSON.parse(scatterSeries));

Setting values of input fields with Angular 6

You should use the following:

       <td><input id="priceInput-{{orderLine.id}}" type="number" [(ngModel)]="orderLine.price"></td>

You will need to add the FormsModule to your app.module in the inputs section as follows:

import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  ..

The use of the brackets around the ngModel are as follows:

  • The [] show that it is taking an input from your TS file. This input should be a public member variable. A one way binding from TS to HTML.

  • The () show that it is taking output from your HTML file to a variable in the TS file. A one way binding from HTML to TS.

  • The [()] are both (e.g. a two way binding)

See here for more information: https://angular.io/guide/template-syntax

I would also suggest replacing id="priceInput-{{orderLine.id}}" with something like this [id]="getElementId(orderLine)" where getElementId(orderLine) returns the element Id in the TS file and can be used anywere you need to reference the element (to avoid simple bugs like calling it priceInput1 in one place and priceInput-1 in another. (if you still need to access the input by it's Id somewhere else)

Handling back button in Android Navigation Component

I written in main activity like this,

override fun onSupportNavigateUp(): Boolean {
        return findNavController(R.id.my_nav_host_fragment).navigateUp(appBarConfiguration)
    }   

Pytesseract : "TesseractNotFound Error: tesseract is not installed or it's not in your path", how do I fix this?

For Windows users only:

Install tesseract using:

pip install tesseract

and then add this line to your code, mind the "\"

pytesseract.pytesseract.tesseract_cmd = "C:\Program Files (x86)\Tesseract-OCR\\tesseract.exe" 

How to add image in Flutter

To use image in Flutter. Do these steps.

1. Create a Directory inside assets folder named images. As shown in figure belowenter image description here

2. Put your desired images to images folder.

3. Open pubpsec.yaml file . And add declare your images.Like:--enter image description here

4. Use this images in your code as.

  Card(
            elevation: 10,
              child: Container(
              decoration: BoxDecoration(
                color: Colors.orangeAccent,
              image: DecorationImage(
              image: AssetImage("assets/images/dropbox.png"),
          fit: BoxFit.fitWidth,
          alignment: Alignment.topCenter,
          ),
          ),
          child: Text("$index",style: TextStyle(color: Colors.red,fontSize: 16,fontFamily:'LangerReguler')),
                alignment: Alignment.center,
          ),
          );

Using Environment Variables with Vue.js

In vue-cli version 3:

There are the three options for .env files: Either you can use .env or:

  • .env.test
  • .env.development
  • .env.production

You can use custom .env variables by using the prefix regex as /^/ instead of /^VUE_APP_/ in /node_modules/@vue/cli-service/lib/util/resolveClientEnv.js:prefixRE

This is certainly not recommended for the sake of developing an open source app in different modes like test, development, and production of .env files. Because every time you npm install .. , it will be overridden.

Angular 6: How to set response type as text while making http call

You should not use those headers, the headers determine what kind of type you are sending, and you are clearly sending an object, which means, JSON.

Instead you should set the option responseType to text:

addToCart(productId: number, quantity: number): Observable<any> {
  const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');

  return this.http.post(
    'http://localhost:8080/order/addtocart', 
    { dealerId: 13, createdBy: "-1", productId, quantity }, 
    { headers, responseType: 'text'}
  ).pipe(catchError(this.errorHandlerService.handleError));
}

How do I resolve a TesseractNotFoundError?

Just run these command if you are using linux,

sudo apt update
sudo apt install tesseract-ocr
sudo apt install libtesseract-dev

then run this,

python -m pip install tesseract tesseract-ocr pytesseract

Dart/Flutter : Converting timestamp

Assuming the field in timestamp firestore is called timestamp, in dart you could call the toDate() method on the returned map.

// Map from firestore
// Using flutterfire package hence the returned data()
Map<String, dynamic> data = documentSnapshot.data();
DateTime _timestamp = data['timestamp'].toDate();

Difference between npx and npm?

Introducing npx: an npm package runner

NPM - Manages packages but doesn't make life easy executing any.
NPX - A tool for executing Node packages.

NPX comes bundled with NPM version 5.2+

NPM by itself does not simply run any package. it doesn't run any package in a matter of fact. If you want to run a package using NPM, you must specify that package in your package.json file.

When executables are installed via NPM packages, NPM links to them:

  1. local installs have "links" created at ./node_modules/.bin/ directory.
  2. global installs have "links" created from the global bin/ directory (e.g. /usr/local/bin) on Linux or at %AppData%/npm on Windows.

Documentation you should read


NPM:

One might install a package locally on a certain project:

npm install some-package

Now let's say you want NodeJS to execute that package from the command line:

$ some-package

The above will fail. Only globally installed packages can be executed by typing their name only.

To fix this, and have it run, you must type the local path:

$ ./node_modules/.bin/some-package

You can technically run a locally installed package by editing your packages.json file and adding that package in the scripts section:

{
  "name": "whatever",
  "version": "1.0.0",
  "scripts": {
    "some-package": "some-package"
  }
}

Then run the script using npm run-script (or npm run):

npm run some-package

NPX:

npx will check whether <command> exists in $PATH, or in the local project binaries, and execute it. So, for the above example, if you wish to execute the locally-installed package some-package all you need to do is type:

npx some-package

Another major advantage of npx is the ability to execute a package which wasn't previously installed:

$ npx create-react-app my-app

The above example will generate a react app boilerplate within the path the command had run in, and ensures that you always use the latest version of a generator or build tool without having to upgrade each time you’re about to use it.


Use-Case Example:

npx command may be helpful in the script section of a package.json file, when it is unwanted to define a dependency which might not be commonly used or any other reason:

"scripts": {
    "start": "npx [email protected]",
    "serve": "npx http-server"
}

Call with: npm run serve


Related questions:

  1. How to use package installed locally in node_modules?
  2. NPM: how to source ./node_modules/.bin folder?
  3. How do you run a js file using npm scripts?

java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion

Update: This is no longer a bug or a workaround, it is required if your app targets API Level 28 (Android 9.0) or above and uses the Google Maps SDK for Android 16.0.0 or below (or if your app uses the Apache HTTP Legacy library). It is now included in the official docs. The public issue has been closed as intended behavior.

This is a bug on the Google Play Services side, until it's fixed, you should be able to workaround by adding this to your AndroidManifest.xml inside the <application> tag:

<uses-library android:name="org.apache.http.legacy" android:required="false" />

Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true

As noted the 3.1.0-beta4 release of the driver got "released into the wild" a little early by the looks of things. The release is part of work in progress to support newer features in the MongoDB 4.0 upcoming release and make some other API changes.

One such change triggering the current warning is the useNewUrlParser option, due to some changes around how passing the connection URI actually works. More on that later.

Until things "settle down", it would probably be advisable to "pin" at least to the minor version for 3.0.x releases:

  "dependencies": {
    "mongodb": "~3.0.8"
  }

That should stop the 3.1.x branch being installed on "fresh" installations to node modules. If you already did install a "latest" release which is the "beta" version, then you should clean up your packages ( and package-lock.json ) and make sure you bump that down to a 3.0.x series release.

As for actually using the "new" connection URI options, the main restriction is to actually include the port on the connection string:

const { MongoClient } = require("mongodb");
const uri = 'mongodb://localhost:27017';  // mongodb://localhost - will fail

(async function() {
  try {

    const client = await MongoClient.connect(uri,{ useNewUrlParser: true });
    // ... anything

    client.close();
  } catch(e) {
    console.error(e)
  }

})()

That's a more "strict" rule in the new code. The main point being that the current code is essentially part of the "node-native-driver" ( npm mongodb ) repository code, and the "new code" actually imports from the mongodb-core library which "underpins" the "public" node driver.

The point of the "option" being added is to "ease" the transition by adding the option to new code so the newer parser ( actually based around url ) is being used in code adding the option and clearing the deprecation warning, and therefore verifying that your connection strings passed in actually comply with what the new parser is expecting.

In future releases the 'legacy' parser would be removed and then the new parser will simply be what is used even without the option. But by that time, it is expected that all existing code had ample opportunity to test their existing connection strings against what the new parser is expecting.

So if you want to start using new driver features as they are released, then use the available beta and subsequent releases and ideally make sure you are providing a connection string which is valid for the new parser by enabling the useNewUrlParser option in MongoClient.connect().

If you don't actually need access to features related to preview of the MongoDB 4.0 release, then pin the version to a 3.0.x series as noted earlier. This will work as documented and "pinning" this ensures that 3.1.x releases are not "updated" over the expected dependency until you actually want to install a stable version.

Iterating through a list to render multiple widgets in Flutter?

The Dart language has aspects of functional programming, so what you want can be written concisely as:

List<String> list = ['one', 'two', 'three', 'four'];
List<Widget> widgets = list.map((name) => new Text(name)).toList();

Read this as "take each name in list and map it to a Text and form them back into a List".

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

You are having issue with newly MySQL version that came with "caching_sha2_password" plugin, follow the below command to get it resolved.

DROP USER 'your_user_name'@'%';
CREATE USER 'your_user_name'@'%' IDENTIFIED WITH mysql_native_password BY 'your_user_password';
GRANT ALL PRIVILEGES ON your_db_name.* TO 'your_user_name'@'%' identified by 'your_user_password';

Or you can just use the below command to keep your privileges as it is:

ALTER USER your_user_name IDENTIFIED WITH mysql_native_password;

Connection Java-MySql : Public Key Retrieval is not allowed

This solution worked for MacOS Sierra, and running MySQL version 8.0.11. Please make sure driver you have added in your build path - "add external jar" should match up with SQL version.

String url = "jdbc:mysql://localhost:3306/syscharacterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true";

How to set the width of a RaisedButton in Flutter?

You need to use an Expanded Widget. But, if your button is on a column, the Expanded Widget fills the rest of the column. So, you need to enclose the Expanded Widget within a row.

Row(children: <Widget>[
Expanded(
  flex: 1,
  child: RaisedButton(
    child: Text("Your Text"),
      onPressed: _submitForm,
    ),
  ),),])

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

Apart from the possible solutions in other answers, it is also possible that somehow Maven dependency corruption has occurred on your machine. I was facing the same error on trying to run my (Web) Spring boot application, and it got resolved by running the following -

mvn dependency:purge-local-repository -DreResolve=true

followed by

mvn package

I came onto this solution looking into another issue where Eclipse wouldn't let me run the main application class from the IDE, due to a different error, similar to one on this SO thread -> The type org.springframework.context.ConfigurableApplicationContext cannot be resolved. It is indirectly referenced from required .class files

Http post and get request in angular 6

You can do a post/get using a library which allows you to use HttpClient with strongly-typed callbacks.

The data and the error are available directly via these callbacks.

The library is called angular-extended-http-client.

angular-extended-http-client library on GitHub

angular-extended-http-client library on NPM

Very easy to use.

Traditional approach

In the traditional approach you return Observable<HttpResponse<T>> from Service API. This is tied to HttpResponse.

With this approach you have to use .subscribe(x => ...) in the rest of your code.

This creates a tight coupling between the http layer and the rest of your code.

Strongly-typed callback approach

You only deal with your Models in these strongly-typed callbacks.

Hence, The rest of your code only knows about your Models.

Sample usage

The strongly-typed callbacks are

Success:

  • IObservable<T>
  • IObservableHttpResponse
  • IObservableHttpCustomResponse<T>

Failure:

  • IObservableError<TError>
  • IObservableHttpError
  • IObservableHttpCustomError<TError>

Add package to your project and in your app module

import { HttpClientExtModule } from 'angular-extended-http-client';

and in the @NgModule imports

  imports: [
    .
    .
    .
    HttpClientExtModule
  ],

Your Models


export class SearchModel {
    code: string;
}

//Normal response returned by the API.
export class RacingResponse {
    result: RacingItem[];
}

//Custom exception thrown by the API.
export class APIException {
    className: string;
}

Your Service

In your Service, you just create params with these callback types.

Then, pass them on to the HttpClientExt's get method.

import { Injectable, Inject } from '@angular/core'
import { SearchModel, RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.

@Injectable()
export class RacingService {

    //Inject HttpClientExt component.
    constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {

    }

    //Declare params of type IObservable<T> and IObservableError<TError>.
    //These are the success and failure callbacks.
    //The success callback will return the response objects returned by the underlying HttpClient call.
    //The failure callback will return the error objects returned by the underlying HttpClient call.
    searchRaceInfo(model: SearchModel, success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
        let url = this.config.apiEndpoint;

        this.client.post<SearchModel, RacingResponse>(url, model, 
                                                      ResponseType.IObservable, success, 
                                                      ErrorType.IObservableError, failure);
    }
}

Your Component

In your Component, your Service is injected and the searchRaceInfo API called as shown below.

  search() {    


    this.service.searchRaceInfo(this.searchModel, response => this.result = response.result,
                                                  error => this.errorMsg = error.className);

  }

Both, response and error returned in the callbacks are strongly typed. Eg. response is type RacingResponse and error is APIException.

How do I use hexadecimal color strings in Flutter?

How to use Hex Color Code #b74093 in Flutter

Simply remove the # sign from hex color code and ad 0xff with color code inside Color class

#b74093 will become Color(0xffb74093) in Flutter

#B74093 will become Color(0xFFB74093) in Flutter

the ff or FF in Color(0xFFB74093) defines the opacity

Hexa Colors Example with all opacity types on Dartpad

enter image description here

Set focus on <input> element

In Angular, within HTML itself, you can set focus to input on click of a button.

<button (click)="myInput.focus()">Click Me</button>

<input #myInput></input>

Dart: mapping a list (list.map)

I try this same method, but with a different list with more values in the function map. My problem was to forget a return statement. This is very important :)

 bottom: new TabBar(
      controller: _controller,
      isScrollable: true,
      tabs:
        moviesTitles.map((title) { return Tab(text: title)}).toList()
      ,
    ),

You must add a reference to assembly 'netstandard, Version=2.0.0.0

After upgrading from 4.6.1 framework to 4.7.2 we started getting this error:

"The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'." and ultimately the solution was to add the "netstandard" assembly reference mentioned above:

<compilation debug="true" targetFramework="4.7.1" >
    <assemblies>
      <add assembly="netstandard, Version=2.0.0.0, Culture=neutral, 
            PublicKeyToken=cc7b13ffcd2ddd51"/>
    </assemblies>
  </compilation>

Upgrading React version and it's dependencies by reading package.json

Use this command to update react npm install --save [email protected] Don't forget to change 16.12.0 to the latest version or the version you need to setup.

How do I convert 2018-04-10T04:00:00.000Z string to DateTime?

Using Date pattern yyyy-MM-dd'T'HH:mm:ss.SSS'Z' and Java 8 you could do

String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date);

Update: For pre 26 use Joda time

String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
LocalDate date = org.joda.time.LocalDate.parse(string, formatter);

In app/build.gradle file, add like this-

dependencies {    
    compile 'joda-time:joda-time:2.9.4'
}

Extract Google Drive zip from Google colab notebook

Try this:

!unpack file.zip

If its now working or file is 7z try below

!apt-get install p7zip-full
!p7zip -d file_name.tar.7z
!tar -xvf file_name.tar

Or

!pip install pyunpack
!pip install patool

from pyunpack import Archive
Archive(‘file_name.tar.7z’).extractall(‘path/to/’)
!tar -xvf file_name.tar

Angular 5 ngHide ngShow [hidden] not working

Try this

 <input class="txt" type="password" [(ngModel)]="input_pw" [hidden]="isHidden">

Convert string to boolean in C#

You must use some of the C # conversion systems:

string to boolean: True to true

string str = "True";
bool mybool = System.Convert.ToBoolean(str);

boolean to string: true to True

bool mybool = true;
string str = System.Convert.ToString(mybool);

//or

string str = mybool.ToString();

bool.Parse expects one parameter which in this case is str, even .

Convert.ToBoolean expects one parameter.

bool.TryParse expects two parameters, one entry (str) and one out (result).

If TryParse is true, then the conversion was correct, otherwise an error occurred

string str = "True";
bool MyBool = bool.Parse(str);

//Or

string str = "True";
if(bool.TryParse(str, out bool result))
{
   //Correct conversion
}
else
{
     //Incorrect, an error has occurred
}

Error occurred during initialization of boot layer FindException: Module not found

The reason behind this is that meanwhile creating your own class, you had also accepted to create a default class as prescribed by your IDE and after writing your code in your own class, you are getting such an error. In order to eliminate this, go to the PROJECT folder ? src ? Default package. Keep only one class (in which you had written code) and delete others.

After that, run your program and it will definitely run without any error.

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

your dependency based on data is trying to find their respective entities which one has not been created, comments the dependencies based on data and runs the app again.

<!-- <dependency> -->
        <!-- <groupId>org.springframework.boot</groupId> -->
        <!-- <artifactId>spring-boot-starter-data-jpa</artifactId> -->
        <!-- </dependency> -->

Converting a POSTMAN request to Curl

enter image description here

You can see the button "Code" in the attached screenshot, press it and you can get your code in many different languages including PHP cURL

enter image description here

How do I disable a Button in Flutter?

I like to use flutter_mobx for this and work on the state.

Next I use an observer:

Container(child: Observer(builder: (_) {
  var method;
  if (!controller.isDisabledButton) method = controller.methodController;
  return RaiseButton(child: Text('Test') onPressed: method);
}));

On the Controller:

@observable
bool isDisabledButton = true;

Then inside the control you can manipulate this variable as you want.

Refs.: Flutter mobx

Spring Data JPA findOne() change to Optional how to use this?

Indeed, in the latest version of Spring Data, findOne returns an optional. If you want to retrieve the object from the Optional, you can simply use get() on the Optional. First of all though, a repository should return the optional to a service, which then handles the case in which the optional is empty. afterwards, the service should return the object to the controller.

How to implement drop down list in flutter?

Use StatefulWidget and setState to update dropdown.

  String _dropDownValue;

  @override
  Widget build(BuildContext context) {
    return DropdownButton(
      hint: _dropDownValue == null
          ? Text('Dropdown')
          : Text(
              _dropDownValue,
              style: TextStyle(color: Colors.blue),
            ),
      isExpanded: true,
      iconSize: 30.0,
      style: TextStyle(color: Colors.blue),
      items: ['One', 'Two', 'Three'].map(
        (val) {
          return DropdownMenuItem<String>(
            value: val,
            child: Text(val),
          );
        },
      ).toList(),
      onChanged: (val) {
        setState(
          () {
            _dropDownValue = val;
          },
        );
      },
    );
  }

initial state of dropdown:

Initial State

Open dropdown and select value:

Select Value

Reflect selected value to dropdown:

Value selected

Checking for duplicate strings in JavaScript array

_x000D_
_x000D_
function hasDuplicates(arr) {
    var counts = [];

    for (var i = 0; i <= arr.length; i++) {
        if (counts[arr[i]] === undefined) {
            counts[arr[i]] = 1;
        } else {
            return true;
        }
    }
    return false;
}

// [...]

var arr = [1, 1, 2, 3, 4];

if (hasDuplicates(arr)) {
  alert('Error: you have duplicates values !')
}
_x000D_
_x000D_
_x000D_

Simple Javascript (if you don't know ES6)

function hasDuplicates(arr) {
    var counts = [];

    for (var i = 0; i <= arr.length; i++) {
        if (counts[arr[i]] === undefined) {
            counts[arr[i]] = 1;
        } else {
            return true;
        }
    }
    return false;
}

// [...]

var arr = [1, 1, 2, 3, 4];

if (hasDuplicates(arr)) {
  alert('Error: you have duplicates values !')
}

How to remove whitespace from a string in typescript?

Trim just removes the trailing and leading whitespace. Use .replace(/ /g, "") if there are just spaces to be replaced.

this.maintabinfo = this.inner_view_data.replace(/ /g, "").toLowerCase();

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

As android latest update doesn't support 'compile' keyword use 'implementation' in place inside your module build.gradle file.

And check thoroughly in build.gradle for dependancy with + sign like this.

implementation 'com.android.support:support-v4:28.+'

If there are any dependencies like this, just update them with a specific version. After that:

  1. Sync gradle.
  2. Clean your project.
  3. Rebuild the project.

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

Configure Two DataSources in Spring Boot 2.0.* or above

If you need to configure multiple data sources, you have to mark one of the DataSource instances as @Primary, because various auto-configurations down the road expect to be able to get one by type.

If you create your own DataSource, the auto-configuration backs off. In the following example, we provide the exact same feature set as the auto-configuration provides on the primary data source:

@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSourceProperties firstDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSource firstDataSource() {
    return firstDataSourceProperties().initializeDataSourceBuilder().build();
}

@Bean
@ConfigurationProperties("app.datasource.second")
public BasicDataSource secondDataSource() {
    return DataSourceBuilder.create().type(BasicDataSource.class).build();
}

firstDataSourceProperties has to be flagged as @Primary so that the database initializer feature uses your copy (if you use the initializer).

And your application.propoerties will look something like this:

app.datasource.first.url=jdbc:oracle:thin:@localhost/first
app.datasource.first.username=dbuser
app.datasource.first.password=dbpass
app.datasource.first.driver-class-name=oracle.jdbc.OracleDriver

app.datasource.second.url=jdbc:mariadb://localhost:3306/springboot_mariadb
app.datasource.second.username=dbuser
app.datasource.second.password=dbpass
app.datasource.second.driver-class-name=org.mariadb.jdbc.Driver

The above method is the correct to way to init multiple database in spring boot 2.0 migration and above. More read can be found here.

'ls' is not recognized as an internal or external command, operable program or batch file

I'm fairly certain that the ls command is for Linux, not Windows (I'm assuming you're using Windows as you referred to cmd, which is the command line for the Windows OS).

You should use dir instead, which is the Windows equivalent of ls.

Edit (since this post seems to be getting so many views :) ):

You can't use ls on cmd as it's not shipped with Windows, but you can use it on other terminal programs (such as GitBash). Note, ls might work on some FTP servers if the servers are linux based and the FTP is being used from cmd.

dir on Windows is similar to ls. To find out the various options available, just do dir/?.

If you really want to use ls, you could install 3rd party tools to allow you to run unix commands on Windows. Such a program is Microsoft Windows Subsystem for Linux (link to docs).

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

This worked for me!!!!

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>academy.learnprogramming</groupId>
    <artifactId>hello-maven</artifactId>
    <version>1.0-SNAPSHOT</version>
<dependencies>
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.3</version>
    </dependency>

</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <configuration>
                <target>10</target>
                <source>10</source>
                <release>10</release>
            </configuration>

        </plugin>
    </plugins>
</build>
</project>

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

VSCode single to double quote automatic replace

Correct solution :

I add .prettierrc.js file in my main root project and write

module.exports = {
    singleQuote: true
  };

js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check

You must use a .ts file - e.g. test.ts to get Typescript validation, intellisense typing of vars, return types, as well as "typed" error checking (e.g. passing a string to a method that expects an number param will error out).

It will be transpiled into (standard) .js via tsc.


Update (11/2018):

Clarification needed based on down-votes, very helpful comments and other answers.

types

  • Yes, you can do type checking in VS Code in .js files with @ts-check - as shown in the animation

  • What I originally was referring to for Typescript types is something like this in .ts which isn't quite the same thing:

    hello-world.ts

    function hello(str: string): string {
      return 1;
    }
    
    function foo(str:string):void{
       console.log(str);
    }
    

    This will not compile. Error: Type "1" is not assignable to String

  • if you tried this syntax in a Javascript hello-world.js file:

    //@ts-check
    
    function hello(str: string): string {
      return 1;
    }
    
    function foo(str:string):void{
       console.log(str);
    }
    

    The error message referenced by OP is shown: [js] 'types' can only be used in a .ts file

If there's something I missed that covers this as well as the OP's context, please add. Let's all learn.

Entity Framework Core: A second operation started on this context before a previous operation completed

Another possible case: if you use the connection direct, don't forget to close if. I needed to execute arbitrary SQL query, and read the result. This was a quick fix, I did not want to define a data class, not set up "normal" SQL connection. So simply I reused EFC's database connection as var connection = Context.Database.GetDbConnection() as SqlConnection. Make sure you call connection.Close() before you do Context.SaveChanges().

Angular-Material DateTime Picker Component?

For as long as there is no official date and time picker from angular itself, I would advise to make a combination of the default angular date picker and this Angular Material Timepicker. I've chosen that one because all the other ones I found at this time lack support for issues, are outdated or are not functioning well in the most recent angular versions. This guy seems to be very responsive.

I've wrapped them both in one component so that it looks like it is one unit. You just have to make sure to do a few things:

When no input has been given yet, I would advise:

  • On-click of the component, the datepicker should always be triggered first.
  • After the datepicker closes, have the timepicker automatically popup.
  • Use touchUi = true on the datepicker, so that both the datepicker and the timepicker come as a dialog after each other.
  • Make sure the datepicker also shows up when clicking on the form (instead of only on the icon which is the default).
  • Use this solution to use the timepicker also in a material form, when placing them behind each other, it looks like it is one form.

After a value has been given, it is clear that one part contains the time and the other part contains the date. At that moment it is clear that the user has to click on the time to change the time, and on the date to change the date. But before that, so when both fields are empty (and 'attached' to each other as one field) you should make sure the user cannot be confused by doing above recommendations.

My component is not complete yet, I will try to remember myself to share the code later. Shoot a comment if this question is more then a month old or so.

Edit: Result

enter image description here

<div fxLayout="row">
  <div *ngIf="!dateOnly" [formGroup]="timeFormGroup">
    <mat-form-field>
      <input matInput [ngxTimepicker]="endTime" [format]="24"  placeholder="{{placeholderTime}}" formControlName="endTime" />
    </mat-form-field>
    <ngx-material-timepicker #endTime (timeSet)="timeChange($event)" [minutesGap]="10"></ngx-material-timepicker>
  </div>
  <div>
    <mat-form-field>
      <input id="pickerId" matInput [matDatepicker]="datepicker" placeholder="{{placeholderDate}}" [formControl]="dateForm"
             [min]="config.minDate" [max]="config.maxDate" (dateChange)="dateChange($event)">
      <mat-datepicker-toggle matSuffix [for]="datepicker"></mat-datepicker-toggle>
      <mat-datepicker #datepicker [disabled]="disabled" [touchUi]="config.touchUi" startView="{{config.startView}}"></mat-datepicker>
    </mat-form-field>
  </div>
</div>
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { DateAdapter, MatDatepickerInputEvent } from '@angular/material';

import * as moment_ from 'moment';

const moment = moment_;

import { MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter';

class DateConfig {
  startView: 'month' | 'year' | 'multi-year';
  touchUi: boolean;
  minDate: moment_.Moment;
  maxDate: moment_.Moment;
}

@Component({
  selector: 'cb-datetimepicker',
  templateUrl: './cb-datetimepicker.component.html',
  styleUrls: ['./cb-datetimepicker.component.scss'],
})
export class DatetimepickerComponent implements OnInit {

  @Input() disabled: boolean;
  @Input() placeholderDate: string;
  @Input() placeholderTime: string;
  @Input() model: Date;
  @Input() purpose: string;
  @Input() dateOnly: boolean;

  @Output() dateUpdate = new EventEmitter<Date>();

  public pickerId: string = "_" + Math.random().toString(36).substr(2, 9);

  public dateForm: FormControl;
  public timeFormGroup: FormGroup;
  public endTime: FormControl;

  public momentDate: moment_.Moment;
  public config: DateConfig;

  //myGroup: FormGroup;


  constructor(private adapter : DateAdapter<any>) { }

  ngOnInit() {

    this.adapter.setLocale("nl-NL");//todo: configurable
    this.config = new DateConfig();
    if (this.purpose === "birthday") {
      this.config.startView = 'multi-year';
      this.config.maxDate = moment().add('year', -15);
      this.config.minDate = moment().add('year', -90);
      this.dateOnly = true;
    } //add more configurations
    else {
      this.config.startView = 'month';
      this.config.maxDate = moment().add('year', 100);
      this.config.minDate = moment().add('year', -100);
    }


    if (window.screen.width < 767) {
      this.config.touchUi = true;
    }



    if (this.model) {
      var mom = moment(this.model);
      if (mom.isBefore(moment('1900-01-01'))) {
        this.momentDate = moment();
      } else {
        this.momentDate = mom;
      }
    } else {
      this.momentDate = moment();
    }

    this.dateForm = new FormControl(this.momentDate);
    if (this.disabled) {
      this.dateForm.disable();
    }
    this.endTime = new FormControl(this.momentDate.format("HH:mm"));

    this.timeFormGroup = new FormGroup({
      endTime: this.endTime
    });


  }


  public dateChange(date: MatDatepickerInputEvent<any>) {

    if (moment.isMoment(date.value)) {
      this.momentDate = moment(date.value);
      if (this.dateOnly) {
        this.momentDate = this.momentDate.utc(true);
      } 
      var newDate = this.momentDate.toDate();
      this.model = newDate;
      this.dateUpdate.emit(newDate);
    }

    console.log("datechange",date);
  }

  public timeChange(time: string) {

    var splitted = time.split(':');
    var hour = splitted[0];
    var minute = splitted[1];

    console.log("time change", time);
   this.momentDate = this.momentDate.set('hour', parseInt(hour));
    this.momentDate = this.momentDate.set('minute', parseInt(minute));

    var newDate = this.momentDate.toDate();
    this.model = newDate;
    this.dateUpdate.emit(newDate);
  }
}

One important source: https://github.com/Agranom/ngx-material-timepicker/issues/126

I think it still deserves some tweaks, as I think it can work a bit better when I would have more time creating this. Most importantly I tried to solve the UTC issue as well, so all dates should be shown in local time but should be sent to the server in UTC format (or at least saved with the correct timezone added to it).

Failed linking file resources

You maybe having this error on your java files because there is one or more XML file with error.

Go through all your XML files and resolve errors, then clean or rebuild project from build menu

Start with your most recent edited XML file

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?

Old one but I would add my answer as per my findings:

var ancestralState = context.findAncestorStateOfType<ParentState>();
      ancestralState.setState(() {
        // here you can access public vars and update state.
        ...
      });

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

In my case, the problem was caused by not being logged in with Postman, so I opened a connection in another tab with a session cookie I took from the headers in my Chrome session.

ASP.NET Core - Swashbuckle not creating swagger.json file

I don't know if this is useful for someone, but in my case the problem was that the name had different casing.

V1 in the service configuration - V capital letter
v1 in Settings -- v lower case

The only thing I did was to use the same casing and it worked.

version name with capital V

ReferenceError: fetch is not defined

Best one is Axios library for fetching. use npm i --save axios for installng and use it like fetch, just write axios instead of fetch and then get response in then().

Changing directory in Google colab (breaking out of the python interpreter)

If you want to use the cd or ls functions , you need proper identifiers before the function names ( % and ! respectively) use %cd and !ls to navigate

.

!ls    # to find the directory you're in ,
%cd ./samplefolder  #if you wanna go into a folder (say samplefolder)

or if you wanna go out of the current folder

%cd ../      

and then navigate to the required folder/file accordingly

Issue in installing php7.2-mcrypt

@praneeth-nidarshan has covered mostly all the steps, except some:

  • Check if you have pear installed (or install):

$ sudo apt-get install php-pear

  • Install, if isn't already installed, php7.2-dev, in order to avoid the error:

sh: phpize: not found

ERROR: `phpize’ failed

$ sudo apt-get install php7.2-dev

  • Install mcrypt using pecl:

$ sudo pecl install mcrypt-1.0.1

  • Add the extention extension=mcrypt.so to your php.ini configuration file; if you don't know where it is, search with:

$ sudo php -i | grep 'Configuration File'

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs

See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm

document.getElementById replacement in angular4 / typescript?

You can just inject the DOCUMENT token into the constructor and use the same functions on it

import { Inject }  from '@angular/core';
import { DOCUMENT } from '@angular/common'; 

@Component({...})
export class AppCmp {
   constructor(@Inject(DOCUMENT) document) {
      document.getElementById('el');
   }
}

Or if the element you want to get is in that component, you can use template references.

How to iterate using ngFor loop Map containing key as string and values as map iteration

For Angular 6.1+ , you can use default pipe keyvalue ( Do review and upvote also ) :

<ul>
    <li *ngFor="let recipient of map | keyvalue">
        {{recipient.key}} --> {{recipient.value}}
    </li>
</ul>

WORKING DEMO


For the previous version :

One simple solution to this is convert map to array : Array.from

Component Side :

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

constructor(){
    this.map.set("sss","sss");
    this.map.set("aaa","sss");
    this.map.set("sass","sss");
    this.map.set("xxx","sss");
    this.map.set("ss","sss");
    this.map.forEach((value: string, key: string) => {
        console.log(key, value);
    });
}

getKeys(map){
    return Array.from(map.keys());
}

Template Side :

<ul>
  <li *ngFor="let recipient of getKeys(map)">
    {{recipient}}
   </li>
</ul>

WORKING DEMO

Read response headers from API response - Angular 5 + TypeScript

You should use the new HttpClient. You can find more information here.

http
  .get<any>('url', {observe: 'response'})
  .subscribe(resp => {
    console.log(resp.headers.get('X-Token'));
  });

how to format date in Component of angular 5

There is equally formatDate

const format = 'dd/MM/yyyy';
const myDate = '2019-06-29';
const locale = 'en-US';
const formattedDate = formatDate(myDate, format, locale);

According to the API it takes as param either a date string, a Date object, or a timestamp.

Gotcha: Out of the box, only en-US is supported.

If you need to add another locale, you need to add it and register it in you app.module, for example for Spanish:

import { registerLocaleData } from '@angular/common';
import localeES from "@angular/common/locales/es";
registerLocaleData(localeES, "es");

Don't forget to add corresponding import:

import { formatDate } from "@angular/common";

How to check if pytorch is using the GPU?

On the office site and the get start page, check GPU for PyTorch as below:

import torch
torch.cuda.is_available()

Reference: PyTorch|Get Start

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

Many people have given a fix, so I'll talk about the source of the problem.

According to the exception log:

Caused by: java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation
    at android.app.Activity.onCreate(Activity.java:1081)
    at android.support.v4.app.SupportActivity.onCreate(SupportActivity.java:66)
    at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:297)
    at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:84)
    at com.nut.blehunter.ui.DialogContainerActivity.onCreate(DialogContainerActivity.java:43)
    at android.app.Activity.performCreate(Activity.java:7372)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1218)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3147)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3302) 
    at android.app.ActivityThread.-wrap12(Unknown Source:0) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1891) 
    at android.os.Handler.dispatchMessage(Handler.java:108) 
    at android.os.Looper.loop(Looper.java:166)

The code that triggered the exception in Activity.java

    //Need to pay attention mActivityInfo.isFixedOrientation() and ActivityInfo.isTranslucentOrFloating(ta)
    if (getApplicationInfo().targetSdkVersion >= O_MR1 && mActivityInfo.isFixedOrientation()) {
        final TypedArray ta = obtainStyledAttributes(com.android.internal.R.styleable.Window);
        final boolean isTranslucentOrFloating = ActivityInfo.isTranslucentOrFloating(ta);
        ta.recycle();

        //Exception occurred
        if (isTranslucentOrFloating) {
            throw new IllegalStateException(
                    "Only fullscreen opaque activities can request orientation");
        }
    }

mActivityInfo.isFixedOrientation():

        /**
        * Returns true if the activity's orientation is fixed.
        * @hide
        */
        public boolean isFixedOrientation() {
            return isFixedOrientationLandscape() || isFixedOrientationPortrait()
                    || screenOrientation == SCREEN_ORIENTATION_LOCKED;
        }
        /**
        * Returns true if the activity's orientation is fixed to portrait.
        * @hide
        */
        boolean isFixedOrientationPortrait() {
            return isFixedOrientationPortrait(screenOrientation);
        }

        /**
        * Returns true if the activity's orientation is fixed to portrait.
        * @hide
        */
        public static boolean isFixedOrientationPortrait(@ScreenOrientation int orientation) {
            return orientation == SCREEN_ORIENTATION_PORTRAIT
                    || orientation == SCREEN_ORIENTATION_SENSOR_PORTRAIT
                    || orientation == SCREEN_ORIENTATION_REVERSE_PORTRAIT
                    || orientation == SCREEN_ORIENTATION_USER_PORTRAIT;
        }

        /**
        * Determines whether the {@link Activity} is considered translucent or floating.
        * @hide
        */
        public static boolean isTranslucentOrFloating(TypedArray attributes) {
            final boolean isTranslucent = attributes.getBoolean(com.android.internal.R.styleable.Window_windowIsTranslucent, false);
            final boolean isSwipeToDismiss = !attributes.hasValue(com.android.internal.R.styleable.Window_windowIsTranslucent)
                                            && attributes.getBoolean(com.android.internal.R.styleable.Window_windowSwipeToDismiss, false);
            final boolean isFloating = attributes.getBoolean(com.android.internal.R.styleable.Window_windowIsFloating, false);
            return isFloating || isTranslucent || isSwipeToDismiss;
        }

According to the above code analysis, when TargetSdkVersion>=27, when using SCREEN_ORIENTATION_LANDSCAPE, SCREEN_ORIENTATION_PORTRAIT, and other related attributes, the use of windowIsTranslucent, windowIsFloating, and windowSwipeToDismiss topic attributes will trigger an exception.

After the problem is found, you can change the TargetSdkVersion or remove the related attributes of the theme according to your needs.

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

I had the same issue, I could solve it by switching fom JDK 11 to JDK 8.

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

Edit file /usr/share/phpmyadmin/libraries/sql.lib.php using this command:

sudo nano +613 /usr/share/phpmyadmin/libraries/sql.lib.php

On line 613 the count function always evaluates to true since there is no closing parenthesis after $analyzed_sql_results['select_expr']. Making the below replacements resolves this, then you will need to delete the last closing parenthesis on line 614, as it's now an extra parenthesis.

Replace:

((empty($analyzed_sql_results['select_expr']))
    || (count($analyzed_sql_results['select_expr'] == 1)
        && ($analyzed_sql_results['select_expr'][0] == '*')))

With:

((empty($analyzed_sql_results['select_expr']))
    || (count($analyzed_sql_results['select_expr']) == 1)
        && ($analyzed_sql_results['select_expr'][0] == '*'))

Restart the server apache:

sudo service apache2 restart

How to start up spring-boot application via command line?

1.Run Spring Boot app with java -jar command

To run your Spring Boot app from a command line in a Terminal window you can use java -jar command. This is provided your Spring Boot app was packaged as an executable jar file.

java -jar target/app-0.0.1-SNAPSHOT.jar

2.Run Spring Boot app using Maven

You can also use Maven plugin to run your Spring Boot app. Use the below command to run your Spring Boot app with Maven plugin:

mvn spring-boot:run

3.Run Spring Boot App with Gradle

And if you use Gradle you can run the Spring Boot app with the following command:

gradle bootRun

Exception : AAPT2 error: check logs for details

AAPT2 Error solution.

If your Android studio has been updated.

Maybe, you would face an error in the studio like "AAPT 2 error: check the log for details"

This error will occur when you have done something wrong in your .xml file such as incorrect value, content not found, etc.

But, At that time you will not have the error specification there. Because the new version of Android Studio does not give you a specific error. It gives like AAPT2 error.

If you want to know where the actual error is then

Follow step.

  1. Look at the panel which is at the right of your Android studio Check out the "Gradle" tab and click on it.
  2. You will see the "app" option. Click on it.
  3. In the app options you will see [Tasks -> build] click on it.
  4. Then you will get options list and see "assembleDebug" double click on it.
  5. Keep the patience and See build tab at the bottom panel of Android studios, you will get an exact error there what you made a mistake in which file and which position.

Click on assembleDebug and see log you can get the actual error is where

The type WebMvcConfigurerAdapter is deprecated

Use org.springframework.web.servlet.config.annotation.WebMvcConfigurer

With Spring Boot 2.1.4.RELEASE (Spring Framework 5.1.6.RELEASE), do like this

package vn.bkit;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; // Deprecated.
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
public class MvcConfiguration implements WebMvcConfigurer {

    @Bean
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/");
        resolver.setSuffix(".html");
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

}

How to extract table as text from the PDF using Python?

This answer is for anyone encountering pdfs with images and needing to use OCR. I could not find a workable off-the-shelf solution; nothing that gave me the accuracy I needed.

Here are the steps I found to work.

  1. Use pdfimages from https://poppler.freedesktop.org/ to turn the pages of the pdf into images.

  2. Use Tesseract to detect rotation and ImageMagick mogrify to fix it.

  3. Use OpenCV to find and extract tables.

  4. Use OpenCV to find and extract each cell from the table.

  5. Use OpenCV to crop and clean up each cell so that there is no noise that will confuse OCR software.

  6. Use Tesseract to OCR each cell.

  7. Combine the extracted text of each cell into the format you need.

I wrote a python package with modules that can help with those steps.

Repo: https://github.com/eihli/image-table-ocr

Docs & Source: https://eihli.github.io/image-table-ocr/pdf_table_extraction_and_ocr.html

Some of the steps don't require code, they take advantage of external tools like pdfimages and tesseract. I'll provide some brief examples for a couple of the steps that do require code.

  1. Finding tables:

This link was a good reference while figuring out how to find tables. https://answers.opencv.org/question/63847/how-to-extract-tables-from-an-image/

import cv2

def find_tables(image):
    BLUR_KERNEL_SIZE = (17, 17)
    STD_DEV_X_DIRECTION = 0
    STD_DEV_Y_DIRECTION = 0
    blurred = cv2.GaussianBlur(image, BLUR_KERNEL_SIZE, STD_DEV_X_DIRECTION, STD_DEV_Y_DIRECTION)
    MAX_COLOR_VAL = 255
    BLOCK_SIZE = 15
    SUBTRACT_FROM_MEAN = -2

    img_bin = cv2.adaptiveThreshold(
        ~blurred,
        MAX_COLOR_VAL,
        cv2.ADAPTIVE_THRESH_MEAN_C,
        cv2.THRESH_BINARY,
        BLOCK_SIZE,
        SUBTRACT_FROM_MEAN,
    )
    vertical = horizontal = img_bin.copy()
    SCALE = 5
    image_width, image_height = horizontal.shape
    horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (int(image_width / SCALE), 1))
    horizontally_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, horizontal_kernel)
    vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, int(image_height / SCALE)))
    vertically_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, vertical_kernel)

    horizontally_dilated = cv2.dilate(horizontally_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (40, 1)))
    vertically_dilated = cv2.dilate(vertically_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (1, 60)))

    mask = horizontally_dilated + vertically_dilated
    contours, hierarchy = cv2.findContours(
        mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE,
    )

    MIN_TABLE_AREA = 1e5
    contours = [c for c in contours if cv2.contourArea(c) > MIN_TABLE_AREA]
    perimeter_lengths = [cv2.arcLength(c, True) for c in contours]
    epsilons = [0.1 * p for p in perimeter_lengths]
    approx_polys = [cv2.approxPolyDP(c, e, True) for c, e in zip(contours, epsilons)]
    bounding_rects = [cv2.boundingRect(a) for a in approx_polys]

    # The link where a lot of this code was borrowed from recommends an
    # additional step to check the number of "joints" inside this bounding rectangle.
    # A table should have a lot of intersections. We might have a rectangular image
    # here though which would only have 4 intersections, 1 at each corner.
    # Leaving that step as a future TODO if it is ever necessary.
    images = [image[y:y+h, x:x+w] for x, y, w, h in bounding_rects]
    return images
  1. Extract cells from table.

This is very similar to 2, so I won't include all the code. The part I will reference will be in sorting the cells.

We want to identify the cells from left-to-right, top-to-bottom.

We’ll find the rectangle with the most top-left corner. Then we’ll find all of the rectangles that have a center that is within the top-y and bottom-y values of that top-left rectangle. Then we’ll sort those rectangles by the x value of their center. We’ll remove those rectangles from the list and repeat.

def cell_in_same_row(c1, c2):
    c1_center = c1[1] + c1[3] - c1[3] / 2
    c2_bottom = c2[1] + c2[3]
    c2_top = c2[1]
    return c2_top < c1_center < c2_bottom

orig_cells = [c for c in cells]
rows = []
while cells:
    first = cells[0]
    rest = cells[1:]
    cells_in_same_row = sorted(
        [
            c for c in rest
            if cell_in_same_row(c, first)
        ],
        key=lambda c: c[0]
    )

    row_cells = sorted([first] + cells_in_same_row, key=lambda c: c[0])
    rows.append(row_cells)
    cells = [
        c for c in rest
        if not cell_in_same_row(c, first)
    ]

# Sort rows by average height of their center.
def avg_height_of_center(row):
    centers = [y + h - h / 2 for x, y, w, h in row]
    return sum(centers) / len(centers)

rows.sort(key=avg_height_of_center)

How to get query parameters from URL in Angular 5?

You can also Use HttpParams, such as:

  getParamValueQueryString( paramName ) {
    const url = window.location.href;
    let paramValue;
    if (url.includes('?')) {
      const httpParams = new HttpParams({ fromString: url.split('?')[1] });
      paramValue = httpParams.get(paramName);
    }
    return paramValue;
  }

Pandas: ValueError: cannot convert float NaN to integer

I know this has been answered but wanted to provide alternate solution for anyone in the future:

You can use .loc to subset the dataframe by only values that are notnull(), and then subset out the 'x' column only. Take that same vector, and apply(int) to it.

If column x is float:

df.loc[df['x'].notnull(), 'x'] = df.loc[df['x'].notnull(), 'x'].apply(int)

Convert Json string to Json object in Swift 4

Using JSONSerialization always felt unSwifty and unwieldy, but it is even more so with the arrival of Codable in Swift 4. If you wield a [String:Any] in front of a simple struct it will ... hurt. Check out this in a Playground:

import Cocoa

let data = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]".data(using: .utf8)!

struct Form: Codable {
    let id: Int
    let name: String
    let description: String?

    private enum CodingKeys: String, CodingKey {
        case id = "form_id"
        case name = "form_name"
        case description = "form_desc"
    }
}

do {
    let f = try JSONDecoder().decode([Form].self, from: data)
    print(f)
    print(f[0])
} catch {
    print(error)
}

With minimal effort handling this will feel a whole lot more comfortable. And you are given a lot more information if your JSON does not parse properly.

Conda activate not working?

For windows, Use the Anaconda Powershell Prompt

enter image description here

No provider for HttpClient

adding HttpClientModule in app.module.ts file in import section fixed my issue.

Failed to run sdkmanager --list with Java 9

It's very simple, just export the JAVA_HOME environment variable, set to the path of your JDK installation.

I installed Java manually on Ubuntu, and so for me this looks like:

export JAVA_HOME="$HOME/pkg-src/jdk1.8.0_251"

And make sure it exists in your path too...

export PATH="$PATH:$JAVA_HOME"

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

I had the same problem in docker and these steps worked for me:

apt update

then:

apt install libsm6 libxext6 libxrender-dev

Add items in array angular 4

Push object into your array. Try this:

export class FormComponent implements OnInit {
    name: string;
    empoloyeeID : number;
    empList: Array<{name: string, empoloyeeID: number}> = []; 
    constructor() {}
    ngOnInit() {}
    onEmpCreate(){
        console.log(this.name,this.empoloyeeID);
        this.empList.push({ name: this.name, empoloyeeID: this.empoloyeeID });
        this.name = "";
        this.empoloyeeID = 0;
    }
}

How to work with progress indicator in flutter?

This is my solution with stack

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';

final themeColor = new Color(0xfff5a623);
final primaryColor = new Color(0xff203152);
final greyColor = new Color(0xffaeaeae);
final greyColor2 = new Color(0xffE8E8E8);

class LoadindScreen extends StatefulWidget {
  LoadindScreen({Key key, this.title}) : super(key: key);
  final String title;
  @override
  LoginScreenState createState() => new LoginScreenState();
}

class LoginScreenState extends State<LoadindScreen> {
  SharedPreferences prefs;

  bool isLoading = false;

  Future<Null> handleSignIn() async {
    setState(() {
      isLoading = true;
    });
    prefs = await SharedPreferences.getInstance();
    var isLoadingFuture = Future.delayed(const Duration(seconds: 3), () {
      return false;
    });
    isLoadingFuture.then((response) {
      setState(() {
        isLoading = response;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(
            widget.title,
            style: TextStyle(color: primaryColor, fontWeight: FontWeight.bold),
          ),
          centerTitle: true,
        ),
        body: Stack(
          children: <Widget>[
            Center(
              child: FlatButton(
                  onPressed: handleSignIn,
                  child: Text(
                    'SIGN IN WITH GOOGLE',
                    style: TextStyle(fontSize: 16.0),
                  ),
                  color: Color(0xffdd4b39),
                  highlightColor: Color(0xffff7f7f),
                  splashColor: Colors.transparent,
                  textColor: Colors.white,
                  padding: EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0)),
            ),

            // Loading
            Positioned(
              child: isLoading
                  ? Container(
                      child: Center(
                        child: CircularProgressIndicator(
                          valueColor: AlwaysStoppedAnimation<Color>(themeColor),
                        ),
                      ),
                      color: Colors.white.withOpacity(0.8),
                    )
                  : Container(),
            ),
          ],
        ));
  }
}

Angular 4 - Select default value in dropdown [Reactive Forms]

As option, if you need just default text in dropdown without default value, try add <option disabled value="null">default text here</option> like this:

<select id="country" formControlName="country">
 <option disabled value="null">default text here</option>
 <option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select>

In Chrome and Firefox works fine.

How to convert column with string type to int form in pyspark data frame?

from pyspark.sql.types import IntegerType
data_df = data_df.withColumn("Plays", data_df["Plays"].cast(IntegerType()))
data_df = data_df.withColumn("drafts", data_df["drafts"].cast(IntegerType()))

You can run loop for each column but this is the simplest way to convert string column into integer.

How to know the git username and email saved during configuration?

Sometimes above solutions doesn't work in macbook to get username n password.

IDK why?, here i got another solution.

$ git credential-osxkeychain get
host=github.com
protocol=https

this will revert username and password

Getting value from appsettings.json in .net core

Program and Startup class

.NET Core 2.x

You don't need to new IConfiguration in the Startup constructor. Its implementation will be injected by the DI system.

// Program.cs
public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();            
}

// Startup.cs
public class Startup
{
    public IHostingEnvironment HostingEnvironment { get; private set; }
    public IConfiguration Configuration { get; private set; }

    public Startup(IConfiguration configuration, IHostingEnvironment env)
    {
        this.HostingEnvironment = env;
        this.Configuration = configuration;
    }
}

.NET Core 1.x

You need to tell Startup to load the appsettings files.

// Program.cs
public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseApplicationInsights()
            .Build();

        host.Run();
    }
}

//Startup.cs
public class Startup
{
    public IConfigurationRoot Configuration { get; private set; }

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

        this.Configuration = builder.Build();
    }
    ...
}

Getting Values

There are many ways you can get the value you configure from the app settings:

Let's say your appsettings.json looks like this:

{
    "ConnectionStrings": {
        ...
    },
    "AppIdentitySettings": {
        "User": {
            "RequireUniqueEmail": true
        },
        "Password": {
            "RequiredLength": 6,
            "RequireLowercase": true,
            "RequireUppercase": true,
            "RequireDigit": true,
            "RequireNonAlphanumeric": true
        },
        "Lockout": {
            "AllowedForNewUsers": true,
            "DefaultLockoutTimeSpanInMins": 30,
            "MaxFailedAccessAttempts": 5
        }
    },
    "Recaptcha": { 
        ...
    },
    ...
}

Simple Way

You can inject the whole configuration into the constructor of your controller/class (via IConfiguration) and get the value you want with a specified key:

public class AccountController : Controller
{
    private readonly IConfiguration _config;

    public AccountController(IConfiguration config)
    {
        _config = config;
    }

    [AllowAnonymous]
    public IActionResult ResetPassword(int userId, string code)
    {
        var vm = new ResetPasswordViewModel
        {
            PasswordRequiredLength = _config.GetValue<int>(
                "AppIdentitySettings:Password:RequiredLength"),
            RequireUppercase = _config.GetValue<bool>(
                "AppIdentitySettings:Password:RequireUppercase")
        };

        return View(vm);
    }
}

Options Pattern

The ConfigurationBuilder.GetValue<T> works great if you only need one or two values from the app settings. But if you want to get multiple values from the app settings, or you don't want to hard code those key strings in multiple places, it might be easier to use Options Pattern. The options pattern uses classes to represent the hierarchy/structure.

To use options pattern:

  1. Define classes to represent the structure
  2. Register the configuration instance which those classes bind against
  3. Inject IOptions<T> into the constructor of the controller/class you want to get values on

1. Define configuration classes to represent the structure

You can define classes with properties that need to exactly match the keys in your app settings. The name of the class does't have to match the name of the section in the app settings:

public class AppIdentitySettings
{
    public UserSettings User { get; set; }
    public PasswordSettings Password { get; set; }
    public LockoutSettings Lockout { get; set; }
}

public class UserSettings
{
    public bool RequireUniqueEmail { get; set; }
}

public class PasswordSettings
{
    public int RequiredLength { get; set; }
    public bool RequireLowercase { get; set; }
    public bool RequireUppercase { get; set; }
    public bool RequireDigit { get; set; }
    public bool RequireNonAlphanumeric { get; set; }
}

public class LockoutSettings
{
    public bool AllowedForNewUsers { get; set; }
    public int DefaultLockoutTimeSpanInMins { get; set; }
    public int MaxFailedAccessAttempts { get; set; }
}

2. Register the configuration instance

And then you need to register this configuration instance in ConfigureServices() in the start up:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
...

namespace DL.SO.UI.Web
{
    public class Startup
    {
        ...
        public void ConfigureServices(IServiceCollection services)
        {
            ...
            var identitySettingsSection = 
                _configuration.GetSection("AppIdentitySettings");
            services.Configure<AppIdentitySettings>(identitySettingsSection);
            ...
        }
        ...
    }
}

3. Inject IOptions

Lastly on the controller/class you want to get the values, you need to inject IOptions<AppIdentitySettings> through constructor:

public class AccountController : Controller
{
    private readonly AppIdentitySettings _appIdentitySettings;

    public AccountController(IOptions<AppIdentitySettings> appIdentitySettingsAccessor)
    {
        _appIdentitySettings = appIdentitySettingsAccessor.Value;
    }

    [AllowAnonymous]
    public IActionResult ResetPassword(int userId, string code)
    {
        var vm = new ResetPasswordViewModel
        {
            PasswordRequiredLength = _appIdentitySettings.Password.RequiredLength,
            RequireUppercase = _appIdentitySettings.Password.RequireUppercase
        };

        return View(vm);
    }
}

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

If you want to hide this warn, you just need to install fsevents as a optional dependency. Just execute:

npm i fsevents@latest -f --save-optional

..And the warn will no longer be a bother.

How to clear react-native cache?

For React Native Init approach (without expo) use:

npm start -- --reset-cache

Styling mat-select in Angular Material

Put your class name on the mat-form-field element. This works for all inputs.

Angular + Material - How to refresh a data source (mat-table)

Best way to do this is by adding an additional observable to your Datasource implementation.

In the connect method you should already be using Observable.merge to subscribe to an array of observables that include the paginator.page, sort.sortChange, etc. You can add a new subject to this and call next on it when you need to cause a refresh.

something like this:

export class LanguageDataSource extends DataSource<any> {

    recordChange$ = new Subject();

    constructor(private languages) {
      super();
    }

    connect(): Observable<any> {

      const changes = [
        this.recordChange$
      ];

      return Observable.merge(...changes)
        .switchMap(() => return Observable.of(this.languages));
    }

    disconnect() {
      // No-op
    }
}

And then you can call recordChange$.next() to initiate a refresh.

Naturally I would wrap the call in a refresh() method and call it off of the datasource instance w/in the component, and other proper techniques.

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

Since it's not possible to post code blocks into comments here's the POM template I am using in projects requiring JUnit 5. This allows to build and "Run as JUnit Test" in Eclipse and building the project with plain Maven.

<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>group</groupId>
    <artifactId>project</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>project name</name>

    <dependencyManagement>
      <dependencies>
        <dependency>
        <groupId>org.junit</groupId>
        <artifactId>junit-bom</artifactId>
        <version>5.3.1</version>
        <type>pom</type>
        <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>

    <dependencies>
      <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <scope>test</scope>
      </dependency>

      <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-launcher</artifactId>
        <scope>test</scope>
      </dependency>

      <dependency>
        <!-- only required when using parameterized tests -->
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-params</artifactId>
        <scope>test</scope>
      </dependency>
    </dependencies>
</project>

You can see that now you only have to update the version in one place if you want to update JUnit. Also the platform version number does not need to appear (in a compatible version) anywhere in your POM, it's automatically managed via the junit-bom import.

Is it safe to clean docker/overlay2/

also had problems with rapidly growing overlay2

/var/lib/docker/overlay2 - is a folder where docker store writable layers for your container. docker system prune -a - may work only if container is stopped and removed.

in my i was able to figure out what consumes space by going into overlay2 and investigating.

that folder contains other hash named folders. each of those has several folders including diff folder.

diff folder - contains actual difference written by a container with exact folder structure as your container (at least it was in my case - ubuntu 18...)

so i've used du -hsc /var/lib/docker/overlay2/LONGHASHHHHHHH/diff/tmp to figure out that /tmp inside of my container is the folder which gets polluted.

so as a workaround i've used -v /tmp/container-data/tmp:/tmp parameter for docker run command to map inner /tmp folder to host and setup a cron on host to cleanup that folder.

cron task was simple:

  • sudo nano /etc/crontab
  • */30 * * * * root rm -rf /tmp/container-data/tmp/*
  • save and exit

NOTE: overlay2 is system docker folder, and they may change it structure anytime. Everything above is based on what i saw in there. Had to go in docker folder structure only because system was completely out of space and even wouldn't allow me to ssh into docker container.

Is there a way to force npm to generate package-lock.json?

As several answer explained the you should run:

npm i

BUT if it does not solve...

Check the version of your npm executable. (For me it was 3.x.x which doesn't uses the package-lock.json (at all))

npm -v

It should be at least 5.x.x (which introduced the package-lock.json file.)

To update npm on Linux, follow these instructions.

For more details about package files, please read this medium story.

Angular - res.json() is not a function

Don't need to use this method:

 .map((res: Response) => res.json() );

Just use this simple method instead of the previous method. hopefully you'll get your result:

.map(res => res );

React - clearing an input value after form submit

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

state={
TemplateCode:"",
}

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

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

This is clear function Final STEP

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

when click button Templatecode is clear 2nd STEP

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

ERROR Error: No value accessor for form control with unspecified name attribute on switch

I was facing this issue while running unit tests. To fix I added the MatSlideToggleModule to the imports in my spect.ts file.

Angular HttpClient "Http failure during parsing"

You should also check you JSON (not in DevTools, but on a backend). Angular HttpClient having a hard time parsing JSON with \0 characters and DevTools will ignore then, so it's quite hard to spot in Chrome.

Based on this article

TypeScript error TS1005: ';' expected (II)

I had today a similar error message. What was peculiar is that it did not break the Application. It was running smoothly but the command prompt (Windows machine) indicated there was an error. I did not update the Typescript version but found another culprit. It turned there was a tiny omission of symbol - closing ")", which I believe The Typescript is compensating for. Just for reference the code is the following:

[new Object('First Characteristic','Second Characteristic',
'Third Characteristic'*] 

* notice here the ending ")" is missing.

Once brought back no more issues on the command prompt!

Enable/disable buttons with Angular

export class ClassComponent implements OnInit {
  classes = [
{
  name: 'string',
  level: 'string',
  code: 'number',
  currentLesson: '1'
}]


checkCurrentLession(current){

 this.classes.forEach((obj)=>{
    if(obj.currentLession == current){
      return true;
    }

  });
  return false;
}


<ul class="table lessonOverview">
        <li>
          <p>Lesson 1</p>
          <button [routerLink]="['/lesson1']" 
             [disabled]="checkCurrentLession(1)" class="primair">
               Start lesson</button>
        </li>
        <li>
          <p>Lesson 2</p>
          <button [routerLink]="['/lesson2']" 
             [disabled]="!checkCurrentLession(2)" class="primair">
               Start lesson</button>
        </li>
     </ul>

iOS Swift - Get the Current Local Time and Date Timestamp

you can even create a function to return different time stamps depending on your necessity:

func dataatual(_ tipo:Int) -> String {
        let date = Date()
        let formatter = DateFormatter()
        if tipo == 1{
            formatter.dateFormat = "dd/MM/yyyy"
        } else if tipo == 2{
            formatter.dateFormat = "yyyy-MM-dd HH:mm"
        } else {
            formatter.dateFormat = "dd-MM-yyyy"
        }

        return formatter.string(from: date)
    } 

MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

To remove all the documents in all the collections:

db.getCollectionNames().forEach( function(collection_name) { 
    if (collection_name.indexOf("system.") == -1) {
        print ( ["Removing: ", db[collection_name].count({}), " documents from ", collection_name].join('') );
        db[collection_name].remove({}); 
    }
});

Automatically set appsettings.json for dev and release environments in asp.net core?

In ASP.NET Core you should rather use Environment Variables instead of build configuration for proper appsettings.json

  1. Right click on you project > Properties > Debug > Environment Variables

    environment variables

  2. ASP.NET Core will use the appropriate appsettings.json file:

    example of appsettings files in solution explorer

  3. Now you can use that Environment Variable like this:

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
    
        Configuration = builder.Build();
    }
    

Note: If you use @Dmitry's answer, you can run into problems eg. when overriding appsettings.json values on Azure.

How do I use Safe Area Layout programmatically?

This extension helps you to constraint a UIVIew to its superview and superview+safeArea:

extension UIView {

    ///Constraints a view to its superview
    func constraintToSuperView() {
        guard let superview = superview else { return }
        translatesAutoresizingMaskIntoConstraints = false

        topAnchor.constraint(equalTo: superview.topAnchor).isActive = true
        leftAnchor.constraint(equalTo: superview.leftAnchor).isActive = true
        bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true
        rightAnchor.constraint(equalTo: superview.rightAnchor).isActive = true
    }

    ///Constraints a view to its superview safe area
    func constraintToSafeArea() {
        guard let superview = superview else { return }
        translatesAutoresizingMaskIntoConstraints = false

        topAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.topAnchor).isActive = true
        leftAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.leftAnchor).isActive = true
        bottomAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.bottomAnchor).isActive = true
        rightAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.rightAnchor).isActive = true
    }

}

Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

There seem to be a lot of issues related to the same error. For me it was the applications which I've installed from another iMac whose files where not present on my MacBook so Xcode was not able to find the files making the debugger to wait forever!

Solution: Deleting all the application which I've installed from the iMac helped me solve the problem.

intellij idea - Error: java: invalid source release 1.9

Select the project, then File > ProjectStructure > ProjectSettings > Modules -> sources You probably have the Language Level set at 9:

screenshot

Just change it to 8 (or whatever you need) and you're set to go.

Also, check the same Language Level settings mentioned above, under Project Settings > Project

enter image description here

Iterate over array of objects in Typescript

In Typescript and ES6 you can also use for..of:

for (var product of products) {
     console.log(product.product_desc)
}

which will be transcoded to javascript:

for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
    var product = products_1[_i];
    console.log(product.product_desc);
}

How to use log4net in Asp.net core 2.0

You need to install the Microsoft.Extensions.Logging.Log4Net.AspNetCore NuGet package and add a log4net.config-file to your application. Then this should work:

public class Program
{
    private readonly ILogger<Program> logger;

    public Program()
    {
        var services = new ServiceCollection()
            .AddLogging(logBuilder => logBuilder.SetMinimumLevel(LogLevel.Debug))
            .BuildServiceProvider();


        logger = services.GetService<ILoggerFactory>()
            .AddLog4Net()
            .CreateLogger<Program>();
    }

    static void Main(string[] args)
    {
        Program program = new Program();

        program.Run();

        Console.WriteLine("\n\nPress any key to continue...");
        Console.ReadKey();
    }

    private void Run()
    {
        logger.LogInformation("Logging is working");
    }
}

No converter found capable of converting from type to type

You may already have this working, but the I created a test project with the classes below allowing you to retrieve the data into an entity, projection or dto.

Projection - this will return the code column twice, once named code and also named text (for example only). As you say above, you don't need the @Projection annotation

import org.springframework.beans.factory.annotation.Value;

public interface DeadlineTypeProjection {
    String getId();

    // can get code and or change name of getter below
    String getCode();

    // Points to the code attribute of entity class
    @Value(value = "#{target.code}")
    String getText();
}

DTO class - not sure why this was inheriting from your base class and then redefining the attributes. JsonProperty just an example of how you'd change the name of the field passed back to a REST end point

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class DeadlineType {
    String id;

    // Use this annotation if you need to change the name of the property that is passed back from controller
    // Needs to be called code to be used in Repository
    @JsonProperty(value = "text")
    String code;

}

Entity class

import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Data
@Entity
@Table(name = "deadline_type")
public class ABDeadlineType {

    @Id
    private String id;
    private String code;
}

Repository - your repository extends JpaRepository<ABDeadlineType, Long> but the Id is a String, so updated below to JpaRepository<ABDeadlineType, String>

import com.example.demo.entity.ABDeadlineType;
import com.example.demo.projection.DeadlineTypeProjection;
import com.example.demo.transfer.DeadlineType;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, String> {

    List<ABDeadlineType> findAll();

    List<DeadlineType> findAllDtoBy();

    List<DeadlineTypeProjection> findAllProjectionBy();

}

Example Controller - accesses the repository directly to simplify code

@RequestMapping(value = "deadlinetype")
@RestController
public class DeadlineTypeController {

    private final ABDeadlineTypeRepository abDeadlineTypeRepository;

    @Autowired
    public DeadlineTypeController(ABDeadlineTypeRepository abDeadlineTypeRepository) {
        this.abDeadlineTypeRepository = abDeadlineTypeRepository;
    }

    @GetMapping(value = "/list")
    public ResponseEntity<List<ABDeadlineType>> list() {

        List<ABDeadlineType> types = abDeadlineTypeRepository.findAll();
        return ResponseEntity.ok(types);
    }

    @GetMapping(value = "/listdto")
    public ResponseEntity<List<DeadlineType>> listDto() {

        List<DeadlineType> types = abDeadlineTypeRepository.findAllDtoBy();
        return ResponseEntity.ok(types);
    }

    @GetMapping(value = "/listprojection")
    public ResponseEntity<List<DeadlineTypeProjection>> listProjection() {

        List<DeadlineTypeProjection> types = abDeadlineTypeRepository.findAllProjectionBy();
        return ResponseEntity.ok(types);
    }
}

Hope that helps

Les

Can't install laravel installer via composer

For PHP7.1 install this

sudo apt-get install php7.1-zip

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

Had the same issue installing angular material CDK:

npm install --save @angular/material @angular/cdk @angular/animations

Adding -dev like below worked for me:

npm install --save-dev @angular/material @angular/cdk @angular/animations

Property 'json' does not exist on type 'Object'

The other way to tackle it is to use this code snippet:

JSON.parse(JSON.stringify(response)).data

This feels so wrong but it works

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

You need jackson dependency for this serialization and deserialization.

Add this dependency:

Gradle:

compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.4")

Maven:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

After that, You need to tell Jackson ObjectMapper to use JavaTimeModule. To do that, Autowire ObjectMapper in the main class and register JavaTimeModule to it.

import javax.annotation.PostConstruct;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

@SpringBootApplication
public class MockEmployeeApplication {

  @Autowired
  private ObjectMapper objectMapper;

  public static void main(String[] args) {
    SpringApplication.run(MockEmployeeApplication.class, args);

  }

  @PostConstruct
  public void setUp() {
    objectMapper.registerModule(new JavaTimeModule());
  }
}

After that, Your LocalDate and LocalDateTime should be serialized and deserialized correctly.

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

Node.js has included experimental support for ES6 support. Read more about here: https://nodejs.org/docs/latest-v13.x/api/esm.html#esm_enabling.

TLDR;

Node.js >= v13

It's very simple in Node.js 13 and above. You need to either:

  • Save the file with .mjs extension, or
  • Add { "type": "module" } in the nearest package.json.

You only need to do one of the above to be able to use ECMAScript modules.

Node.js <= v12

If you are using Node.js version 8-12, save the file with ES6 modules with .mjs extension and run it like:

node --experimental-modules my-app.mjs

Node.js: Python not found exception due to node-sass and node-gyp

Hey I got this error resolved by following the steps

  • first I uninstalled python 3.8.6 (latest version)
  • then I installed python 2.7.1 (any Python 2 version will work, but not much older and this is recommended)
  • then I added c:\python27 to environment variables
  • my OS is windows, so I followed this link
  • It worked

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

There are a couple things missing, both from the solutions above and also from the Microsoft documentation. If you follow the link to the GitHub repository linked from the documentation above, you'll find the real solution.

I think the confusion lies with the fact that the default templates that many people are using do not contain the default constructor for Startup, so people don't necessarily know where the injected Configuration is coming from.

So, in Startup.cs, add:

 public IConfiguration Configuration { get; }
 public Startup(IConfiguration configuration) 
 {
     Configuration = configuration;
 }

and then in ConfigureServices method add what other people have said...

services.AddDbContext<ChromeContext>(options =>                    
    options.UseSqlServer(Configuration.GetConnectionString("DatabaseConnection")));

you also have to ensure that you've got your appsettings.json file created and have a connection strings section similar to this

{
  "ConnectionStrings": {
    "DatabaseConnection": "Server=MyServer;Database=MyDatabase;Persist Security Info=True;User ID=SA;Password=PASSWORD;MultipleActiveResultSets=True;"
  }
}

Of course, you will have to edit that to reflect your configuration.

Things to keep in mind. This was tested using Entity Framework Core 3 in a .Net Standard 2.1 project. I needed to add the nuget packages for: Microsoft.EntityFrameworkCore 3.0.0 Microsoft.EntityFrameworkCore.SqlServer 3.0.0 because that's what I'm using, and that's what is required to get access to the UseSqlServer.

Update some specific field of an entity in android Room

If you need to update user information for a specific user ID "x",

  1. you need to create a dbManager class that will initialise the database in its constructor and acts as a mediator between your viewModel and DAO, and also .
  2. The ViewModel will initialize an instance of dbManager to access the database. The code should look like this:

       @Entity
        class User{
        @PrimaryKey
        String userId;
        String username;
        }
    
        Interface UserDao{
        //forUpdate
        @Update
        void updateUser(User user)
        }
    
        Class DbManager{
        //AppDatabase gets the static object o roomDatabase.
        AppDatabase appDatabase;
        UserDao userDao;
        public DbManager(Application application ){
        appDatabase = AppDatabase.getInstance(application);
    
        //getUserDao is and abstract method of type UserDao declared in AppDatabase //class
        userDao = appDatabase.getUserDao();
        } 
    
        public void updateUser(User user, boolean isUpdate){
        new InsertUpdateUserAsyncTask(userDao,isUpdate).execute(user);
        }
    
    
    
        public static class InsertUpdateUserAsyncTask extends AsyncTask<User, Void, Void> {
    
    
         private UserDao userDAO;
         private boolean isInsert;
    
         public InsertUpdateBrandAsyncTask(BrandDAO userDAO, boolean isInsert) {
           this. userDAO = userDAO;
           this.isInsert = isInsert;
         }
    
         @Override
         protected Void doInBackground(User... users) {
           if (isInsert)
        userDAO.insertBrand(brandEntities[0]);
           else
        //for update
        userDAO.updateBrand(users[0]);
        //try {
        //  Thread.sleep(1000);
        //} catch (InterruptedException e) {
        //  e.printStackTrace();
        //}
           return null;
         }
          }
        }
    
         Class UserViewModel{
         DbManager dbManager;
         public UserViewModel(Application application){
         dbmanager = new DbMnager(application);
         }
    
         public void updateUser(User user, boolean isUpdate){
         dbmanager.updateUser(user,isUpdate);
         }
    
         }
    
    
    
    
    Now in your activity or fragment initialise your UserViewModel like this:
    
    UserViewModel userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
    

    Then just update your user item this way, suppose your userId is 1122 and userName is "xyz" which has to be changed to "zyx".

    Get an userItem of id 1122 User object

User user = new user();
 if(user.getUserId() == 1122){
   user.setuserName("zyx");
   userViewModel.updateUser(user);
 }

This is a raw code, hope it helps you.

Happy coding

Unable to create migrations after upgrading to ASP.NET Core 2.0

In my case I got the problem because I had a method named SeedData.EnsurePopulated() being called on my Startup.cs file.

public class Startup
{
    public Startup(IConfiguration configuration) => Configuration = configuration;
    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        //
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseDeveloperExceptionPage();
        app.UseStatusCodePages();
        app.UseStaticFiles();
        app.UseSession();
        app.UseMvc(routes =>
        {
            //
        });

        SeedData.EnsurePopulated(app);
    }
}

The work of SeedData class is to add initial data to the database table. It's code is:

public static void EnsurePopulated(IApplicationBuilder app)
    {
        ApplicationDbContext context = app.ApplicationServices.GetRequiredService<ApplicationDbContext>();
        context.Database.Migrate();
        if (!context.Products.Any())
        {
            context.Products.AddRange(
            new Product
            {
                Name = "Kayak",
                Description = "A boat for one person",
                Category = "Watersports",
                Price = 275
            },
            ....
            );
            context.SaveChanges();
        }
    }

SOLUTION

Before doing migration simply comment out the calling of SeedData class in the Startup.cs file.

// SeedData.EnsurePopulated(app);

That solved my problem and hope your problem is also solved in the same way.

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

Wrap your Container in SingleChildScrollView() widget. Then it will not come above when keyboard pops up.

Django - Reverse for '' not found. '' is not a valid view function or pattern name

In my case, what I did was a mistake in the url tag in the respective template. So, in my url tag I had something like

{% url 'polls:details' question.id %}

while in the views, I had written something like:

def details(request, question_id): code here

So, the first thing you might wanna check is whether things are spelled as they shoould be. The next thing then you can do is as the people above have suggested.

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

I just replaced version 11.2.0 with 11.0.0 and then it seemed to work fine, so that had to mean that 11.2.0 wasn't included with the latest Android SDK.

So, after struggling with all the available scattered documentation, I reached this document by pure chance (I guess it is not indexed high enough by Google): https://developers.google.com/android/guides/releases

I quote from there:

Highlights from the Google Play services 11.2 release. Google Play services dependencies are now available via maven.google.com

Now, even when that shouldn't necessarily mean that they are not available with the downloaded SDK anymore, it seems that this is actually the case.

Anyway, adding google() to my build.gradle didn't work (not found, undefined, or whatever...), so I used a different approach that I found in this document referenced from the previous one:

https://developer.android.com/studio/build/dependencies.html#google-maven

I modified my build.gradle file adding that line to allprojects/repositories, as in:

allprojects {
...
    repositories {
...
        maven { url "https://maven.google.com/"}
    }
}

And then also in the android section in the same build.gradle file:

project(":android") {
...
    dependencies {
...
        compile 'com.google.android.gms:play-services-ads:11.2.0'
    }
}

Those two lines were enough to make Gradle sync without problems. I didn't need to add any plugins apart from the ones that are already added in my libGDX project by default.

After that, I got a few different errors, but none about Gradle or dependencies. In a brief, JFTR:

First, I had a minSdkVersion of 8. Solved by raising it to 14. I think I could live without supporting all those devices below 14.

Second, I had problems with the dex upper limit of references. I've never faced this problem before, but maybe you've already noticed the solution I used: instead of compiling the whole 'com.google.android.gms:play-services' I used only 'com.google.android.gms:play-services-ads' that's the API I'm actually interested right now. For those other particular cases where a solution like this may not be useful, this document could provide some better insight: https://developer.android.com/studio/build/multidex.html

Third, even after that I got this "jumbo" thing problem described and answered here: https://stackoverflow.com/a/26248495/1160360

And that's it. As of now, everything builds and my game does finally shows those Admob banners.

I've spent hours with this, thought, which makes me wonder if all these building automation systems we are using lately are worth the extra load they add.

I mean, the first time I had to add Admob to an app five years ago or so, I just had to download a .jar file and put it on a directory on my project. It was pretty obvious and the whole process, from googling "how to setup Admob in my android project" to have my app showing an Admob banner took me just a few minutes. I'm gonna leave it here, since this is not the place for such kind of debate.

Nonetheless, I hope my own experience is useful for someone else further.

React: Expected an assignment or function call and instead saw an expression

Possible way is (sure you can change array declaration to getting from db or another external resource):

const MyPosts = () => {

  let postsRawData = [
    { id: 1, text: 'Post 1', likesCount: '1' },
    { id: 2, text: 'Post 2', likesCount: '231' },
    { id: 3, text: 'Post 3', likesCount: '547' }
  ];

  const postsItems = []
  for (const [key, value] of postsRawData.entries()) {
    postsItems.push(<Post text={value.text} likesCount={value.likesCount} />)
  }

  return (
      <div className={css.posts}>Posts:
          {postsItems}
      </div>
  )
}

MVC Razor Radio Button

<p>@Html.RadioButtonFor(x => x.type, "Item1")Item1</p>
<p>@Html.RadioButtonFor(x => x.type, "Item2")Item2</p>
<p>@Html.RadioButtonFor(x => x.type, "Item3")Item3</p>

How to decode a Base64 string?

Isn't encoding taking the text TO base64 and decoding taking base64 BACK to text? You seem be mixing them up here. When I decode using this online decoder I get:

BASE64: blahblah
UTF8: nVnV

not the other way around. I can't reproduce it completely in PS though. See sample below:

PS > [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("blahblah"))
nV?nV?

PS > [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("nVnV"))
blZuVg==

EDIT I believe you're using the wrong encoder for your text. The encoded base64 string is encoded from UTF8(or ASCII) string.

PS > [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
blahblah

PS > [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
????

PS > [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
blahblah

Can overridden methods differ in return type?

Broadly speaking yes return type of overriding method can be different. But it's not straight forward as there are some cases involved in this.

Case 1: If the return type is a primitive data type or void.

Output: If the return type is void or primitive then the data type of parent class method and overriding method should be the same. e.g. if the return type is int, float, string then it should be same

Case 2: If the return type is derived data type:

Output: If the return type of the parent class method is derived type then the return type of the overriding method is the same derived data type of subclass to the derived data type. e.g. Suppose I have a class A, B is a subclass to A, C is a subclass to B and D is a subclass to C; then if the super class is returning type A then the overriding method in subclass can return either A, or B/C/D type i.e. its sub types. This is also called as covariance.

CXF: No message body writer found for class - automatically mapping non-simple resources

I encountered this problem while upgrading from CXF 2.7.0 to 3.0.2. Here is what I did to resolve it:

Included the following in my pom.xml

    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-rs-extension-providers</artifactId>
        <version>3.0.2</version>
    </dependency>

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-jaxrs</artifactId>
        <version>1.9.0</version>
    </dependency>

and added the following provider

    <jaxrs:providers>
        <bean class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider" />
    </jaxrs:providers>

How to center a Window in Java?

The following code center the Window in the center of the current monitor (ie where the mouse pointer is located).

public static final void centerWindow(final Window window) {
    GraphicsDevice screen = MouseInfo.getPointerInfo().getDevice();
    Rectangle r = screen.getDefaultConfiguration().getBounds();
    int x = (r.width - window.getWidth()) / 2 + r.x;
    int y = (r.height - window.getHeight()) / 2 + r.y;
    window.setLocation(x, y);
}

Use the auto keyword in C++ STL

This is new item in the language which I think we are going to be struggling with for years to come. The 'auto' of the start presents not only readability problem , from now on when you encounter it you will have to spend considerable time trying to figure out wtf it is(just like the time that intern named all variables xyz :)), but you also will spend considerable time cleaning after easily excitable programmers , like the once who replied before me. Example from above , I can bet $1000 , will be written "for (auto it : s)", not "for (auto& it : s)", as a result invoking move semantics where you list expecting it, modifying your collection underneath .

Another example of the problem is your question itself. You clearly don't know much about stl iterators and you trying to overcome that gap through usage of the magic of 'auto', as a result you create the code that might be problematic later on

How to Find App Pool Recycles in Event Log

As link-only answers are not preferred, I will just copy and paste the content of the link of the accepted answer


It is definitely System Log.

Which Log file? Well -- you can check the physical path by right-clicking on the System Log (e.g. Server Manager | Diagnostics | Event Viewer | Windows Logs). The default physical path is %SystemRoot%\System32\Winevt\Logs\System.evtx.

You can create a Custom Filter and filter by "Source: WAS" to quickly see only entries generated by IIS.

You may need first to enable logging of such even for a specific App Pool -- by default App Pool has only 3 recycle events out of 8 enabled. To change it using GUI: II S Manager | Application Pools | Select App Pool -> Advanced Settings | Generate Recycle Event Log Entry.

Encrypt Password in Configuration Files?

A simple way of doing this is to use Password Based Encryption in Java. This allows you to encrypt and decrypt a text by using a password.

This basically means initializing a javax.crypto.Cipher with algorithm "AES/CBC/PKCS5Padding" and getting a key from javax.crypto.SecretKeyFactory with the "PBKDF2WithHmacSHA512" algorithm.

Here is a code example (updated to replace the less secure MD5-based variant):

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class ProtectedConfigFile {

    public static void main(String[] args) throws Exception {
        String password = System.getProperty("password");
        if (password == null) {
            throw new IllegalArgumentException("Run with -Dpassword=<password>");
        }

        // The salt (probably) can be stored along with the encrypted data
        byte[] salt = new String("12345678").getBytes();

        // Decreasing this speeds down startup time and can be useful during testing, but it also makes it easier for brute force attackers
        int iterationCount = 40000;
        // Other values give me java.security.InvalidKeyException: Illegal key size or default parameters
        int keyLength = 128;
        SecretKeySpec key = createSecretKey(password.toCharArray(),
                salt, iterationCount, keyLength);

        String originalPassword = "secret";
        System.out.println("Original password: " + originalPassword);
        String encryptedPassword = encrypt(originalPassword, key);
        System.out.println("Encrypted password: " + encryptedPassword);
        String decryptedPassword = decrypt(encryptedPassword, key);
        System.out.println("Decrypted password: " + decryptedPassword);
    }

    private static SecretKeySpec createSecretKey(char[] password, byte[] salt, int iterationCount, int keyLength) throws NoSuchAlgorithmException, InvalidKeySpecException {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
        PBEKeySpec keySpec = new PBEKeySpec(password, salt, iterationCount, keyLength);
        SecretKey keyTmp = keyFactory.generateSecret(keySpec);
        return new SecretKeySpec(keyTmp.getEncoded(), "AES");
    }

    private static String encrypt(String property, SecretKeySpec key) throws GeneralSecurityException, UnsupportedEncodingException {
        Cipher pbeCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        pbeCipher.init(Cipher.ENCRYPT_MODE, key);
        AlgorithmParameters parameters = pbeCipher.getParameters();
        IvParameterSpec ivParameterSpec = parameters.getParameterSpec(IvParameterSpec.class);
        byte[] cryptoText = pbeCipher.doFinal(property.getBytes("UTF-8"));
        byte[] iv = ivParameterSpec.getIV();
        return base64Encode(iv) + ":" + base64Encode(cryptoText);
    }

    private static String base64Encode(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    private static String decrypt(String string, SecretKeySpec key) throws GeneralSecurityException, IOException {
        String iv = string.split(":")[0];
        String property = string.split(":")[1];
        Cipher pbeCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(base64Decode(iv)));
        return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
    }

    private static byte[] base64Decode(String property) throws IOException {
        return Base64.getDecoder().decode(property);
    }
}

One problem remains: Where should you store the password that you use to encrypt the passwords? You can store it in the source file and obfuscate it, but it's not too hard to find it again. Alternatively, you can give it as a system property when you start the Java process (-DpropertyProtectionPassword=...).

The same issue remains if you use the KeyStore, which also is protected by a password. Basically, you will need to have one master password somewhere, and it's pretty hard to protect.

What is the easiest way to parse an INI File in C++?

If you are already using Qt

QSettings my_settings("filename.ini", QSettings::IniFormat);

Then read a value

my_settings.value("GroupName/ValueName", <<DEFAULT_VAL>>).toInt()

There are a bunch of other converter that convert your INI values into both standard types and Qt types. See Qt documentation on QSettings for more information.

TypeError: string indices must be integers, not str // working with dict

I see that you are looking for an implementation of the problem more than solving that error. Here you have a possible solution:

from itertools import chain

def involved(courses, person):
    courses_info = chain.from_iterable(x.values() for x in courses.values())
    return filter(lambda x: x['teacher'] == person, courses_info)

print involved(courses, 'Dave')

The first thing I do is getting the list of the courses and then filter by teacher's name.

How to select the first element of a set with JSTL?

If you only want the first element of a set (and you are certain there is at least one element) you can do the following:

<c:choose>
    <c:when test="${dealership.administeredBy.size() == 1}">
        Hello ${dealership.administeredBy.iterator().next().firstName},<br/>
    </c:when>
    <c:when test="${dealership.administeredBy.size() > 1}">
        Hello Administrators,<br/>
    </c:when>
    <c:otherwise>
    </c:otherwise>
</c:choose>

Joining two table entities in Spring Data JPA

This has been an old question but solution is very simple to that. If you are ever unsure about how to write criterias, joins etc in hibernate then best way is using native queries. This doesn't slow the performance and very useful. Eq. below

    @Query(nativeQuery = true, value = "your sql query")
returnTypeOfMethod methodName(arg1, arg2);

What is the best way to remove the first element from an array?

To sum up, the quick linkedlist method:

List<String> llist = new LinkedList<String>(Arrays.asList(oldArray));
llist.remove(0);

Moment.js get day name from date

var mydate = "2017-06-28T00:00:00";
var weekDayName =  moment(mydate).format('ddd');
console.log(weekDayName);

Result: Wed

var mydate = "2017-06-28T00:00:00";
var weekDayName =  moment(mydate).format('dddd');
console.log(weekDayName);

Result: Wednesday

How to use apply a custom drawable to RadioButton?

You should set android:button="@null" instead of "null".

You were soo close!

How to use if - else structure in a batch file?

Here's my code Example for if..else..if
which do the following

Prompt user for Process Name

If the process name is invalid
Then it's write to user

Error : The Processor above doesn't seem to be exist 

if the process name is services
Then it's write to user

Error : You can't kill the Processor above 

if the process name is valid and not services
Then it's write to user

the process has been killed via taskill

so i called it Process killer.bat
Here's my Code:

@echo off

:Start
Rem preparing the batch  
cls
Title Processor Killer
Color 0B
Echo Type Processor name to kill It (Without ".exe")
set /p ProcessorTokill=%=%  

:tasklist
tasklist|find /i "%ProcessorTokill%.exe">nul & if errorlevel 1 (
REM check if the process name is invalid 
Cls 
Title %ProcessorTokill% Not Found
Color 0A
echo %ProcessorTokill%
echo Error : The Processor above doesn't seem to be exist    

) else if %ProcessorTokill%==services (
REM check if the process name is services and doesn't kill it
Cls 
Color 0c
Title Permission denied 
echo "%ProcessorTokill%.exe"
echo Error : You can't kill the Processor above 

) else (
REM if the process name is valid and not services
Cls 
Title %ProcessorTokill% Found
Color 0e
echo %ProcessorTokill% Found
ping localhost -n 2 -w 1000>nul
echo Killing %ProcessorTokill% ...
taskkill /f /im %ProcessorTokill%.exe /t>nul
echo %ProcessorTokill% Killed...
)

pause>nul



REM If else if Template
REM if thing1 (
REM Command here 2 ! 
REM ) else if thing2 (
REM command here 2 !
REM ) else (
REM command here 3 !
REM )

Find a file by name in Visual Studio Code

It's Ctrl+Shift+O / Cmd+Shift+O on mac. You can see it if you close all tabs

Getting Error "Form submission canceled because the form is not connected"

I saw this message using angular, so i just took method="post" and action="" out, and the warning was gone.

Scala vs. Groovy vs. Clojure

Groovy is a dynamically typed language, whose syntax is very close to Java, with a number of syntax improvements that allow for lighter code and less boilerplate. It can run through an interpreter as well as being compiled, which makes it good for fast prototyping, scripts, and learning dynamic languages without having to learn a new syntax (assuming you know Java). As of Groovy 2.0, it also has growing support for static compilation. Groovy supports closures and has support for programming in a somewhat functional style, although it's still fairly far from the traditional definition of functional programming.

Clojure is a dialect of Lisp with a few advanced features like Software Transactional Memory. If you like Lisp and would like to use something like it under the JVM, Clojure is for you. It's possibly the most functional language running on the JVM, and certainly the most famous one. Also, it has a stronger emphasis on immutability than other Lisp dialects, which takes it closer to the heart of functional language enthusiasts.

Scala is a fully object oriented language, more so than Java, with one of the most advanced type systems available on non-research languages, and certainly the most advanced type system on the JVM. It also combines many concepts and features of functional languages, without compromising the object orientation, but its compromise on functional language characteristics put off some enthusiasts of the latter.

Groovy has good acceptance and a popular web framework in Grails. It also powers the Gradle build system, which is becoming a popular alternative to Maven. I personally think it is a language with limited utility, particularly as Jython and JRuby start making inroads on the JVM-land, compared to the others.

Clojure, even discounting some very interesting features, has a strong appeal just by being a Lisp dialect on JVM. It might limit its popularity, granted, but I expect it will have loyal community around it for a long time.

Scala can compete directly with Java, and give it a run for its money on almost all aspects. It can't compete in popularity at the moment, of course, and the lack of a strong corporate backing may hinder its acceptance on corporate environments. It's also a much more dynamic language than Java, in the sense of how the language evolves. From the perspective of the language, that's a good thing. From the perspective of users who plan on having thousands of lines of code written in it, not so.

As a final disclosure, I'm very familiar with Scala, and only acquainted with the other two.

Set CFLAGS and CXXFLAGS options using CMake

You must change the cmake C/CXX default FLAGS .

According to CMAKE_BUILD_TYPE={DEBUG/MINSIZEREL/RELWITHDEBINFO/RELEASE} put in the main CMakeLists.txt one of :

For C

set(CMAKE_C_FLAGS_DEBUG "put your flags")
set(CMAKE_C_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_C_FLAGS_RELEASE "put your flags")

For C++

set(CMAKE_CXX_FLAGS_DEBUG "put your flags")
set(CMAKE_CXX_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_CXX_FLAGS_RELEASE "put your flags")

This will override the values defined in CMakeCache.txt

How to install mcrypt extension in xampp

The recent versions of XAMPP for Windows runs PHP 7.x which are NOT compatible with mbcrypt. If you have a package like Laravel that requires mbcrypt, you will need to install an older version of XAMPP. OR, you can run XAMPP with multiple versions of PHP by downloading a PHP package from Windows.PHP.net, installing it in your XAMPP folder, and configuring php.ini and httpd.conf to use the correct version of PHP for your site.

Difference between a virtual function and a pure virtual function

For a virtual function you need to provide implementation in the base class. However derived class can override this implementation with its own implementation. Normally , for pure virtual functions implementation is not provided. You can make a function pure virtual with =0 at the end of function declaration. Also, a class containing a pure virtual function is abstract i.e. you can not create a object of this class.

JSON Java 8 LocalDateTime format in Spring Boot

Writing this answer as a reminder for me as well.

I combined several answers here and in the end mine worked with something like these. (I am using SpringBoot 1.5.7 and Lombok 1.16.16)

@Data
public Class someClass {

   @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
   @JsonSerialize(using = LocalDateTimeSerializer.class)
   @JsonDeserialize(using = LocalDateTimeDeserializer.class)
   private LocalDateTime someDate;

}

ORDER BY date and time BEFORE GROUP BY name in mysql

Another way to solve this would be with a LEFT JOIN, which could be more efficient. I'll first start with an example that considers only the date field, as probably it is more common to store date + time in one datetime column, and I also want to keep the query simple so it's easier to understand.

So, with this particular example, if you want to show the oldest record based on the date column, and assuming that your table name is called people you can use the following query:

SELECT p.* FROM people p
LEFT JOIN people p2 ON p.name = p2.name AND p.date > p2.date
WHERE p2.date is NULL
GROUP BY p.name

What the LEFT JOIN does, is when the p.date column is at its minimum value, there will be no p2.date with a smaller value on the left join and therefore the corresponding p2.date will be NULL. So, by adding WHERE p2.date is NULL, we make sure to show only the records with the oldest date.

And similarly, if you want to show the newest record instead, you can just change the comparison operator in the LEFT JOIN:

SELECT p.* FROM people p
LEFT JOIN people p2 ON p.name = p2.name AND p.date < p2.date
WHERE p2.date is NULL
GROUP BY p.name

Now, for this particular example where date+time are separate columns, you would need to add them in some way if you want to query based on the datetime of two columns combined, for example:

SELECT p.* FROM people p
LEFT JOIN people p2 ON p.name = p2.name AND p.date + INTERVAL TIME_TO_SEC(p.time) SECOND > p2.date + INTERVAL TIME_TO_SEC(p2.time) SECOND
WHERE p2.date is NULL
GROUP BY p.name

You can read more about this (and also see some other ways to accomplish this) on the The Rows Holding the Group-wise Maximum of a Certain Column page.

Bootstrap Modal before form Submit

I noticed some of the answers were not triggering the HTML5 required attribute (as stuff was being executed on the action of clicking rather than the action of form send, causing to bypass it when the inputs were empty):

  1. Have a <form id='xform'></form> with some inputs with the required attribute and place a <input type='submit'> at the end.
  2. A confirmation input where typing "ok" is expected <input type='text' name='xconf' value='' required>
  3. Add a modal_1_confirm to your html (to confirm the form of sending).
  4. (on modal_1_confirm) add the id modal_1_accept to the accept button.
  5. Add a second modal_2_errMsg to your html (to display form validation errors).
  6. (on modal_2_errMsg) add the id modal_2_accept to the accept button.
  7. (on modal_2_errMsg) add the id m2_Txt to the displayed text holder.
  8. The JS to intercept before the form is sent:

    $("#xform").submit(function(e){
        var msg, conf, preventSend;
    
        if($("#xform").attr("data-send")!=="ready"){
            msg="Error."; //default error msg
            preventSend=false;
    
            conf=$("[name='xconf']").val().toLowerCase().replace(/^"|"$/g, "");
    
            if(conf===""){
                msg="The field is empty.";
                preventSend=true;
            }else if(conf!=="ok"){
                msg="You didn't write \"ok\" correctly.";
                preventSend=true;
            }
    
            if(preventSend){ //validation failed, show the error
                $("#m2_Txt").html(msg); //displayed text on modal_2_errMsg
                $("#modal_2_errMsg").modal("show");
            }else{ //validation passed, now let's confirm the action
                $("#modal_1_confirm").modal("show");
            }
    
            e.preventDefault();
            return false;
        }
    });
    

`9. Also some stuff when clicking the Buttons from the modals:

$("#modal_1_accept").click(function(){
    $("#modal_1_confirm").modal("hide");
    $("#xform").attr("data-send", "ready").submit();
});

$("#modal_2_accept").click(function(){
    $("#modal_2_errMsg").modal("hide");
});

Important Note: So just be careful if you add an extra way to show the modal, as simply clicking the accept button $("#modal_1_accept") will assume the validation passed and it will add the "ready" attribute:

  • The reasoning for this is that $("#modal_1_confirm").modal("show"); is shown only when it passed the validation, so clicking $("#modal_1_accept") should be unreachable without first getting the form validated.

How to log in to phpMyAdmin with WAMP, what is the username and password?

http://localhost/phpmyadmin

Username: root

Password:

(No password set)

Ignore .classpath and .project from Git

Use a .gitignore file. This allows you to ignore certain files. http://git-scm.com/docs/gitignore

Here's an example Eclipse one, which handles your classpath and project files: https://github.com/github/gitignore/blob/master/Global/Eclipse.gitignore

"Could not find a valid gem in any repository" (rubygame and others)

Maybe you should try

gem list -r

then

gem install -r rubygame

Also note that with rvmon MacosX (Lion in my case) you should install ruby-1.9.3-p194 (for Xcode 4.x compiler considerations) then

rvm rubygems current

and in my case I had to use

rvm use ruby-1.9.3-p194@global

(which contains bundler, rake, rubygems-bundlerand rvm)

and not

rvm use ruby-1.9.3-p194

(which is empty)

Integrating Dropzone.js into existing HTML form with other fields

This is just another example of how you can use Dropzone.js in an existing form.

dropzone.js :

 init: function() {

   this.on("success", function(file, responseText) {
     //alert("HELLO ?" + responseText); 
     mylittlefix(responseText);
   });

   return noop;
 },

Then, later in the file I put

function mylittlefix(responseText) {
  $('#botofform').append('<input type="hidden" name="files[]" value="'+ responseText +'">');
}

This assumes you have a div with id #botofform that way when uploading you can use the uploaded files' names.

Note: my upload script returned theuploadedfilename.jpeg dubblenote you also would need to make a cleanup script that checks the upload directory for files not in use and deletes them ..if in a front end non authenticated form :)

How to make --no-ri --no-rdoc the default for gem install?

On Linux (and probably Mac):

echo 'gem: --no-document' >> ~/.gemrc

This one-liner used to be in comments here, but somehow disappeared.

How do I disable the security certificate check in Python requests

If you want to send exactly post request with verify=False option, fastest way is to use this code:

import requests

requests.api.request('post', url, data={'bar':'baz'}, json=None, verify=False)

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

Go to "Target" -> "Build Phases", select your target, select the “Build Phases” tab, click “Add Build Phase”, and select “Add Copy Files”. Change the destination to “Products Directory”. Drag your file into the “Add files” section.

Vue.js img src concatenate variable and text

If it helps, I am using the following to get a gravatar image:

<img
        :src="`https://www.gravatar.com/avatar/${this.gravatarHash(email)}?s=${size}&d=${this.defaultAvatar(email)}`"
        class="rounded-circle"
        :width="size"
    />

What is LDAP used for?

To take the definitions the other mentioned earlier a bit further, how about this perspective...

LDAP is Lightweight Directory Access Protocol. DAP, is an X.500 notion, and in X.500 is VERY heavy weight! (It sort of requires a full 7 layer ISO network stack, which basically only IBM's SNA protocol ever realistically implemented).

There are many other approaches to DAP. Novell has one called NDAP (NCP Novell Core Protocols are the transport, and NDAP is how it reads the directory).

LDAP is just a very lightweight DAP, as the name suggests.

In PHP, what is a closure and why does it use the "use" identifier?

closures are beautiful! they solve a lot of problems that come with anonymous functions, and make really elegant code possible (at least as long as we talk about php).

javascript programmers use closures all the time, sometimes even without knowing it, because bound variables aren't explicitly defined - that's what "use" is for in php.

there are better real-world examples than the above one. lets say you have to sort an multidimensional array by a sub-value, but the key changes.

<?php
    function generateComparisonFunctionForKey($key) {
        return function ($left, $right) use ($key) {
            if ($left[$key] == $right[$key])
                return 0;
            else
                return ($left[$key] < $right[$key]) ? -1 : 1;
        };
    }

    $myArray = array(
        array('name' => 'Alex', 'age' => 70),
        array('name' => 'Enrico', 'age' => 25)
    );

    $sortByName = generateComparisonFunctionForKey('name');
    $sortByAge  = generateComparisonFunctionForKey('age');

    usort($myArray, $sortByName);

    usort($myArray, $sortByAge);
?>

warning: untested code (i don't have php5.3 installed atm), but it should look like something like that.

there's one downside: a lot of php developers may be a bit helpless if you confront them with closures.

to understand the nice-ty of closures more, i'll give you another example - this time in javascript. one of the problems is the scoping and the browser inherent asynchronity. especially, if it comes to window.setTimeout(); (or -interval). so, you pass a function to setTimeout, but you can't really give any parameters, because providing parameters executes the code!

function getFunctionTextInASecond(value) {
    return function () {
        document.getElementsByName('body')[0].innerHTML = value; // "value" is the bound variable!
    }
}

var textToDisplay = prompt('text to show in a second', 'foo bar');

// this returns a function that sets the bodys innerHTML to the prompted value
var myFunction = getFunctionTextInASecond(textToDisplay);

window.setTimeout(myFunction, 1000);

myFunction returns a function with a kind-of predefined parameter!

to be honest, i like php a lot more since 5.3 and anonymous functions/closures. namespaces may be more important, but they're a lot less sexy.

Squash my last X commits together using Git

Simple one-liner that always works, given that you are currently on the branch you want to squash, master is the branch it originated from, and the latest commit contains the commit message and author you wish to use:

git reset --soft $(git merge-base HEAD master) && git commit --reuse-message=HEAD@{1}

Total Number of Row Resultset getRow Method

The best way to get number of rows from resultset is using count function query for database access and then rs.getInt(1) method to get number of rows. from my code look it:

    String query = "SELECT COUNT() FROM table";
ResultSet rs = new DatabaseConnection().selectData(query);
rs.getInt(1);

this will return int value number of rows fetched from database. Here DatabaseConnection().selectData() is my code for accessing database. I was also stuck here but then solved...

ASP.NET MVC DropDownListFor with model of type List<string>

If you have a List of type string that you want in a drop down list I do the following:

EDIT: Clarified, making it a fuller example.

public class ShipDirectory
{
    public string ShipDirectoryName { get; set; }
    public List<string> ShipNames { get; set; }
}

ShipDirectory myShipDirectory = new ShipDirectory()
{
    ShipDirectoryName = "Incomming Vessels",
    ShipNames = new List<string>(){"A", "A B"},
}

myShipDirectory.ShipNames.Add("Aunt Bessy");

@Html.DropDownListFor(x => x.ShipNames, new SelectList(Model.ShipNames), "Select a Ship...", new { @style = "width:500px" })

Which gives a drop down list like so:

<select id="ShipNames" name="ShipNames" style="width:500px">
    <option value="">Select a Ship...</option>
    <option>A</option>
    <option>A B</option>
    <option>Aunt Bessy</option>
</select>

To get the value on a controllers post; if you are using a model (e.g. MyViewModel) that has the List of strings as a property, because you have specified x => x.ShipNames you simply have the method signature as (because it will be serialised/deserialsed within the model):

public ActionResult MyActionName(MyViewModel model)

Access the ShipNames value like so: model.ShipNames

If you just want to access the drop down list on post then the signature becomes:

public ActionResult MyActionName(string ShipNames)

EDIT: In accordance with comments have clarified how to access the ShipNames property in the model collection parameter.

How to get only the date value from a Windows Forms DateTimePicker control?

Try this

var store = dtpDateTimePicker.Value.Date;

store can be anything entity object etc.

SQL using sp_HelpText to view a stored procedure on a linked server

It's the correct way to access linked DB:

EXEC  [ServerName].[DatabaseName].dbo.sp_HelpText 'storedProcName'

But make sure to mention dbo as it owns the sp_helptext.

Change DataGrid cell colour based on values

To do this in the Code Behind (VB.NET)

Dim txtCol As New DataGridTextColumn

Dim style As New Style(GetType(TextBlock))
Dim tri As New Trigger With {.Property = TextBlock.TextProperty, .Value = "John"}
tri.Setters.Add(New Setter With {.Property = TextBlock.BackgroundProperty, .Value = Brushes.Green})
style.Triggers.Add(tri)

xtCol.ElementStyle = style

Visual Studio loading symbols

Just encountered this issue. Deleting breakpoints didn't work, or at least not just on its own. After this failed I Went Tools > Options > Debugging > Symbols and "Empty Symbol Cache"

and then cleaned the solution and rebuilt.

Now seems to be working correctly. So if you try all the other things listed, and it still makes no differnce, these additional bits of info may help...

Convert cells(1,1) into "A1" and vice versa

The Address property of a cell can get this for you:

MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)

returns A1.

The other way around can be done with the Row and Column property of Range:

MsgBox Range("A1").Row & ", " & Range("A1").Column

returns 1,1.

How do I declare an array variable in VBA?

Further to RolandTumble's answer to Cody Gray's answer, both fine answers, here is another very simple and flexible way, when you know all of the array contents at coding time - e.g. you just want to build an array that contains 1, 10, 20 and 50. This also uses variant declaration, but doesn't use ReDim. Like in Roland's answer, the enumerated count of the number of array elements need not be specifically known, but is obtainable by using uBound.

sub Demo_array()
    Dim MyArray as Variant, MyArray2 as Variant, i as Long

    MyArray = Array(1, 10, 20, 50)  'The key - the powerful Array() statement
    MyArray2 = Array("Apple", "Pear", "Orange") 'strings work too

    For i = 0 to UBound(MyArray)
        Debug.Print i, MyArray(i)
    Next i
    For i = 0 to UBound(MyArray2)
        Debug.Print i, MyArray2(i)
    Next i
End Sub

I love this more than any of the other ways to create arrays. What's great is that you can add or subtract members of the array right there in the Array statement, and nothing else need be done to code. To add Egg to your 3 element food array, you just type

, "Egg"

in the appropriate place, and you're done. Your food array now has the 4 elements, and nothing had to be modified in the Dim, and ReDim is omitted entirely.

If a 0-based array is not desired - i.e., using MyArray(0) - one solution is just to jam a 0 or "" for that first element.

Note, this might be regarded badly by some coding purists; one fair objection would be that "hard data" should be in Const statements, not code statements in routines. Another beef might be that, if you stick 36 elements into an array, you should set a const to 36, rather than code in ignorance of that. The latter objection is debatable, because it imposes a requirement to maintain the Const with 36 rather than relying on uBound. If you add a 37th element but leave the Const at 36, trouble is possible.

Loaded nib but the 'view' outlet was not set

For me, the problem was caused by calling initWithNibName:bundle:. I am using table view cells from a nib file to define entry forms that sit on tableViews. As I don't have a view, doesn't make sense to hook to one. Instead, if I call the initWithStyle: method instead, and from within there, I load the nib file, then things work as expected.

How to quietly remove a directory with content in PowerShell

If you have your folder as an object, let's say that you created it in the same script using next command:

$folder = New-Item -ItemType Directory -Force -Path "c:\tmp" -Name "myFolder"

Then you can just remove it like this in the same script

$folder.Delete($true)

$true - states for recursive removal

C# winforms combobox dynamic autocomplete

Here is my final solution. It works fine with a large amount of data. I use Timer to make sure the user want find current value. It looks like complex but it doesn't. Thanks to Max Lambertini for the idea.

        private bool _canUpdate = true; 

        private bool _needUpdate = false;       

        //If text has been changed then start timer
        //If the user doesn't change text while the timer runs then start search
        private void combobox1_TextChanged(object sender, EventArgs e)
        {
            if (_needUpdate)
            {
                if (_canUpdate)
                {
                    _canUpdate = false;
                    UpdateData();                   
                }
                else
                {
                    RestartTimer();
                }
            }
        }

        private void UpdateData()
        {
            if (combobox1.Text.Length > 1)
            {
                List<string> searchData = Search.GetData(combobox1.Text);
                HandleTextChanged(searchData);
            }
        }       

        //If an item was selected don't start new search
        private void combobox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            _needUpdate = false;
        }

        //Update data only when the user (not program) change something
        private void combobox1_TextUpdate(object sender, EventArgs e)
        {
            _needUpdate = true;
        }

        //While timer is running don't start search
        //timer1.Interval = 1500;
        private void RestartTimer()
        {
            timer1.Stop();
            _canUpdate = false;
            timer1.Start();
        }

        //Update data when timer stops
        private void timer1_Tick(object sender, EventArgs e)
        {
            _canUpdate = true;
            timer1.Stop();
            UpdateData();
        }

        //Update combobox with new data
        private void HandleTextChanged(List<string> dataSource)
        {
            var text = combobox1.Text;

            if (dataSource.Count() > 0)
            {
                combobox1.DataSource = dataSource;  

                var sText = combobox1.Items[0].ToString();
                combobox1.SelectionStart = text.Length;
                combobox1.SelectionLength = sText.Length - text.Length;
                combobox1.DroppedDown = true;


                return;
            }
            else
            {
                combobox1.DroppedDown = false;
                combobox1.SelectionStart = text.Length;
            }
        }

This solution isn't very cool. So if someone has another solution please share it with me.

Ignoring SSL certificate in Apache HttpClient 4.3

If you are using PoolingHttpClientConnectionManager procedure above doesn't work, custom SSLContext is ignored. You have to pass socketFactoryRegistry in contructor when creating PoolingHttpClientConnectionManager.

SSLContextBuilder builder = SSLContexts.custom();
builder.loadTrustMaterial(null, new TrustStrategy() {
    @Override
    public boolean isTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
        return true;
    }
});
SSLContext sslContext = builder.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslContext, new X509HostnameVerifier() {
            @Override
            public void verify(String host, SSLSocket ssl)
                    throws IOException {
            }

            @Override
            public void verify(String host, X509Certificate cert)
                    throws SSLException {
            }

            @Override
            public void verify(String host, String[] cns,
                    String[] subjectAlts) throws SSLException {
            }

            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });

Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
        .<ConnectionSocketFactory> create().register("https", sslsf)
        .build();

PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
        socketFactoryRegistry);
CloseableHttpClient httpclient = HttpClients.custom()
        .setConnectionManager(cm).build();

Run a script in Dockerfile

In addition to the answers above:

If you created/edited your .sh script file in Windows, make sure it was saved with line ending in Unix format. By default many editors in Windows will convert Unix line endings to Windows format and Linux will not recognize shebang (#!/bin/sh) at the beginning of the file. So Linux will produce the error message like if there is no shebang.

Tips:

  • If you use Notepad++, you need to click "Edit/EOL Conversion/UNIX (LF)"
  • If you use Visual Studio, I would suggest installing "End Of Line" plugin. Then you can make line endings visible by pressing Ctrl-R, Ctrl-W. And to set Linux style endings you can press Ctrl-R, Ctrl-L. For Windows style, press Ctrl-R, Ctrl-C.

Foreign keys in mongo?

We can define the so-called foreign key in MongoDB. However, we need to maintain the data integrity BY OURSELVES. For example,

student
{ 
  _id: ObjectId(...),
  name: 'Jane',
  courses: ['bio101', 'bio102']   // <= ids of the courses
}

course
{
  _id: 'bio101',
  name: 'Biology 101',
  description: 'Introduction to biology'
}

The courses field contains _ids of courses. It is easy to define a one-to-many relationship. However, if we want to retrieve the course names of student Jane, we need to perform another operation to retrieve the course document via _id.

If the course bio101 is removed, we need to perform another operation to update the courses field in the student document.

More: MongoDB Schema Design

The document-typed nature of MongoDB supports flexible ways to define relationships. To define a one-to-many relationship:

Embedded document

  1. Suitable for one-to-few.
  2. Advantage: no need to perform additional queries to another document.
  3. Disadvantage: cannot manage the entity of embedded documents individually.

Example:

student
{
  name: 'Kate Monster',
  addresses : [
     { street: '123 Sesame St', city: 'Anytown', cc: 'USA' },
     { street: '123 Avenue Q', city: 'New York', cc: 'USA' }
  ]
}

Child referencing

Like the student/course example above.

Parent referencing

Suitable for one-to-squillions, such as log messages.

host
{
    _id : ObjectID('AAAB'),
    name : 'goofy.example.com',
    ipaddr : '127.66.66.66'
}

logmsg
{
    time : ISODate("2014-03-28T09:42:41.382Z"),
    message : 'cpu is on fire!',
    host: ObjectID('AAAB')       // Reference to the Host document
}

Virtually, a host is the parent of a logmsg. Referencing to the host id saves much space given that the log messages are squillions.

References:

  1. 6 Rules of Thumb for MongoDB Schema Design: Part 1
  2. 6 Rules of Thumb for MongoDB Schema Design: Part 2
  3. 6 Rules of Thumb for MongoDB Schema Design: Part 3
  4. Model One-to-Many Relationships with Document References

How do I create and read a value from cookie?

Here are functions you can use for creating and retrieving cookies.

function createCookie(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

nodejs - How to read and output jpg image?

Here is how you can read the entire file contents, and if done successfully, start a webserver which displays the JPG image in response to every request:

var http = require('http')
var fs = require('fs')

fs.readFile('image.jpg', function(err, data) {
  if (err) throw err // Fail if the file can't be read.
  http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'image/jpeg'})
    res.end(data) // Send the file data to the browser.
  }).listen(8124)
  console.log('Server running at http://localhost:8124/')
})

Note that the server is launched by the "readFile" callback function and the response header has Content-Type: image/jpeg.

[Edit] You could even embed the image in an HTML page directly by using an <img> with a data URI source. For example:

  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('<html><body><img src="data:image/jpeg;base64,')
  res.write(Buffer.from(data).toString('base64'));
  res.end('"/></body></html>');

Set a form's action attribute when submitting?

HTML5's formaction does not work on old IE browsers. An easy fix, based on some of the responses above, is:

<button onclick="this.form.action='/PropertiesList';" 
    Account Details </button>

Is there a simple way that I can sort characters in a string in alphabetical order

You can use this

string x = "ABCGH"

char[] charX = x.ToCharArray();

Array.Sort(charX);

This will sort your string.

Add left/right horizontal padding to UILabel

If you need a more specific text alignment than what adding spaces to the left of the text provides, you can always add a second blank label of exactly how much of an indent you need.

I've got buttons with text aligned left with an indent of 10px and needed a label below to look in line. It gave the label with text and left alignment and put it at x=10 and then made a small second label of the same background color with a width = 10, and lined it up next to the real label.

Minimal code and looks good. Just makes AutoLayout a little more of a hassle to get everything working.

How to cache Google map tiles for offline usage?

update:

I found the terms of use from Google Map:

Section 10.5

No caching or storage. You will not pre-fetch, cache, index, or store any Content to be used outside the Service, except that you may store limited amounts of Content solely for the purpose of improving the performance of your Maps API Implementation due to network latency (and not for the purpose of preventing Google from accurately tracking usage), and only if such storage: is temporary (and in no event more than 30 calendar days); is secure; does not manipulate or aggregate any part of the Content or Service; and does not modify attribution in any way.

It means we can cache for limited time actually

How do you create a temporary table in an Oracle database?

CREATE TABLE table_temp_list_objects AS
SELECT o.owner, o.object_name FROM sys.all_objects o WHERE o.object_type ='TABLE';

Converting Epoch time into the datetime

To convert your time value (float or int) to a formatted string, use:

time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1347517370))

Java 8 Lambda Stream forEach with multiple statements

List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");

//lambda
//Output : A,B,C,D,E
items.forEach(item->System.out.println(item));

//Output : C
items.forEach(item->{
    System.out.println(item);
    System.out.println(item.toLowerCase());
  }
});

convert base64 to image in javascript/jquery

This is not exactly the OP's scenario but an answer to those of some of the commenters. It is a solution based on Cordova and Angular 1, which should be adaptable to other frameworks like jQuery. It gives you a Blob from Base64 data which you can store somewhere and reference it from client side javascript / html.

It also answers the original question on how to get an image (file) from the Base 64 data:

The important part is the Base 64 - Binary conversion:

function base64toBlob(base64Data, contentType) {
    contentType = contentType || '';
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);

    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}

Slicing is required to avoid out of memory errors.

Works with jpg and pdf files (at least that's what I tested). Should work with other mimetypes/contenttypes too. Check the browsers and their versions you aim for, they need to support Uint8Array, Blob and atob.

Here's the code to write the file to the device's local storage with Cordova / Android:

...
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {

                    // Setup filename and assume a jpg file
                    var filename = attachment.id + "-" + (attachment.fileName ? attachment.fileName : 'image') + "." + (attachment.fileType ? attachment.fileType : "jpg");
                    dirEntry.getFile(filename, { create: true, exclusive: false }, function(fileEntry) {
                        // attachment.document holds the base 64 data at this moment
                        var binary = base64toBlob(attachment.document, attachment.mimetype);
                        writeFile(fileEntry, binary).then(function() {
                            // Store file url for later reference, base 64 data is no longer required
                            attachment.document = fileEntry.nativeURL;

                        }, function(error) {
                            WL.Logger.error("Error writing local file: " + error);
                            reject(error.code);
                        });

                    }, function(errorCreateFile) {
                        WL.Logger.error("Error creating local file: " + JSON.stringify(errorCreateFile));
                        reject(errorCreateFile.code);
                    });

                }, function(errorCreateFS) {
                    WL.Logger.error("Error getting filesystem: " + errorCreateFS);
                    reject(errorCreateFS.code);
                });
...

Writing the file itself:

function writeFile(fileEntry, dataObj) {
    return $q(function(resolve, reject) {
        // Create a FileWriter object for our FileEntry (log.txt).
        fileEntry.createWriter(function(fileWriter) {

            fileWriter.onwriteend = function() {
                WL.Logger.debug(LOG_PREFIX + "Successful file write...");
                resolve();
            };

            fileWriter.onerror = function(e) {
                WL.Logger.error(LOG_PREFIX + "Failed file write: " + e.toString());
                reject(e);
            };

            // If data object is not passed in,
            // create a new Blob instead.
            if (!dataObj) {
                dataObj = new Blob(['missing data'], { type: 'text/plain' });
            }

            fileWriter.write(dataObj);
        });
    })
}

I am using the latest Cordova (6.5.0) and Plugins versions:

I hope this sets everyone here in the right direction.

Convert an enum to List<string>

I want to add another solution: In my case, I need to use a Enum group in a drop down button list items. So they might have space, i.e. more user friendly descriptions needed:

  public enum CancelReasonsEnum
{
    [Description("In rush")]
    InRush,
    [Description("Need more coffee")]
    NeedMoreCoffee,
    [Description("Call me back in 5 minutes!")]
    In5Minutes
}

In a helper class (HelperMethods) I created the following method:

 public static List<string> GetListOfDescription<T>() where T : struct
    {
        Type t = typeof(T);
        return !t.IsEnum ? null : Enum.GetValues(t).Cast<Enum>().Select(x => x.GetDescription()).ToList();
    }

When you call this helper you will get the list of item descriptions.

 List<string> items = HelperMethods.GetListOfDescription<CancelReasonEnum>();

ADDITION: In any case, if you want to implement this method you need :GetDescription extension for enum. This is what I use.

 public static string GetDescription(this Enum value)
    {
        Type type = value.GetType();
        string name = Enum.GetName(type, value);
        if (name != null)
        {
            FieldInfo field = type.GetField(name);
            if (field != null)
            {
                DescriptionAttribute attr =Attribute.GetCustomAttribute(field,typeof(DescriptionAttribute)) as DescriptionAttribute;
                if (attr != null)
                {
                    return attr.Description;
                }
            }
        }
        return null;
        /* how to use
            MyEnum x = MyEnum.NeedMoreCoffee;
            string description = x.GetDescription();
        */

    }

Add a dependency in Maven

I'll assume that you're asking how to push a dependency out to a "well-known repository," and not simply asking how to update your POM.

If yes, then this is what you want to read.

And for anyone looking to set up an internal repository server, look here (half of the problem with using Maven 2 is finding the docs)

How to add hours to current time in python

from datetime import datetime, timedelta

nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)

And then use string formatting to get the relevant pieces:

>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'

If you're only formatting the datetime then you can use:

>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'

Or, as @eumiro has pointed out in comments - strftime

Application_Start not firing?

Did you check the Project settings? I had this problem and I had the Start URL going to a different port than my server specific port. It took me too long to figure out...

Filezilla FTP Server Fails to Retrieve Directory Listing

I had the same problem-what worked for me -in Windows OS-is adding FileZilla as a firewall exception-under allow a program through firewall features

NPM clean modules

Try https://github.com/voidcosmos/npkill

npx npkill

it will find all node_modules and let you remove them.

npkill

List Git aliases

I mentioned in June 2018 with "overview list - most used git commands" the Git 2.18 "use --list-cmds=alias (commit 3301d36)", that carej reports in his answer.

 git --list-cmds=alias

In addition of that or of git config --get-regexp alias, you can combine its output with git help, whose output will change with Git 2.14.x/2.15:

"git help co" now says "co is aliased to ...", not "git co is".

See commit b3a8076 (12 Sep 2017) by Kaartic Sivaraam (sivaraam).
(Merged by Junio C Hamano -- gitster -- in commit 5079cc8, 25 Sep 2017)

help: change a message to be more precise

When the user tries to use '--help' option on an aliased command information about the alias is printed as shown below:

$ git co --help
`git co' is aliased to `checkout'

This doesn't seem correct as the user has aliased only 'co' and not 'git co'.
This might even be incorrect in cases in which the user has used an alias like 'tgit'.

$ tgit co --help
`git co' is aliased to `checkout'

How to Specify Eclipse Proxy Authentication Credentials?

If you have still problems, try deactivating ("Clear") SOCKS

see: https://bugs.eclipse.org/bugs/show_bug.cgi?id=281384 "I believe the reason for this is because it uses the SOCKS proxy instead of the HTTP proxy if SOCKS is configured."

Using atan2 to find angle between two vectors

I think a better formula was posted here: http://www.mathworks.com/matlabcentral/answers/16243-angle-between-two-vectors-in-3d

angle = atan2(norm(cross(a,b)), dot(a,b))

So this formula works in 2 or 3 dimensions. For 2 dimensions this formula simplifies to the one stated above.

How do I get the information from a meta tag with JavaScript?

There is an easier way:

document.getElementsByName('name of metatag')[0].getAttribute('content')

Return None if Dictionary key is not available

If you can do it with False, then, there's also the hasattr built-in funtion:

e=dict()
hasattr(e, 'message'):
>>> False

"Submit is not a function" error in JavaScript

This topic has a lot of answers already, but the one that worked best (and simplest - one line!) for me was a modification of the comment made by Neil E. Pearson from Apr 21 2013:

If you're stuck with your submit button being #submit, you can get around it by stealing another form instance's submit() method.

My modification to his method, and what worked for me:

document.createElement('form').submit.call(document.getElementById(frmProduct));

What are the differences between JSON and JSONP?

JSONP stands for “JSON with Padding” and it is a workaround for loading data from different domains. It loads the script into the head of the DOM and thus you can access the information as if it were loaded on your own domain, thus by-passing the cross domain issue.

jsonCallback(
{
    "sites":
    [
        {
            "siteName": "JQUERY4U",
            "domainName": "http://www.jquery4u.com",
            "description": "#1 jQuery Blog for your Daily News, Plugins, Tuts/Tips &amp; Code Snippets."
        },
        {
            "siteName": "BLOGOOLA",
            "domainName": "http://www.blogoola.com",
            "description": "Expose your blog to millions and increase your audience."
        },
        {
            "siteName": "PHPSCRIPTS4U",
            "domainName": "http://www.phpscripts4u.com",
            "description": "The Blog of Enthusiastic PHP Scripters"
        }
    ]
});

(function($) {
var url = 'http://www.jquery4u.com/scripts/jquery4u-sites.json?callback=?';

$.ajax({
   type: 'GET',
    url: url,
    async: false,
    jsonpCallback: 'jsonCallback',
    contentType: "application/json",
    dataType: 'jsonp',
    success: function(json) {
       console.dir(json.sites);
    },
    error: function(e) {
       console.log(e.message);
    }
});

})(jQuery);

Now we can request the JSON via AJAX using JSONP and the callback function we created around the JSON content. The output should be the JSON as an object which we can then use the data for whatever we want without restrictions.

Can't create project on Netbeans 8.2

Yes it s working: remove the path of jdk 9.0 and uninstall this from Cantroll panel instead install jdk 8version and set it's path, it is working easily with netbean 8.2.

"Comparison method violates its general contract!"

In our case were were getting this error because we had accidentally flipped the order of comparison of s1 and s2. So watch out for that. It was obviously way more complicated than the following but this is an illustration:

s1 == s2   
    return 0;
s2 > s1 
    return 1;
s1 < s2 
    return -1;

Jenkins vs Travis-CI. Which one would you use for a Open Source project?

Travis-ci and Jenkins, while both are tools for continuous integration are very different.

Travis is a hosted service (free for open source) while you have to host, install and configure Jenkins.

Travis does not have jobs as in Jenkins. The commands to run to test the code are taken from a file named .travis.yml which sits along your project code. This makes it easy to have different test code per branch since each branch can have its own version of the .travis.yml file.

You can have a similar feature with Jenkins if you use one of the following plugins:

  • Travis YML Plugin - warning: does not seem to be popular, probably not feature complete in comparison to the real Travis.
  • Jervis - a modification of Jenkins to make it read create jobs from a .jervis.yml file found at the root of project code. If .jervis.yml does not exist, it will fall back to using .travis.yml file instead.

There are other hosted services you might also consider for continuous integration (non exhaustive list):


How to choose ?

You might want to stay with Jenkins because you are familiar with it or don't want to depend on 3rd party for your continuous integration system. Else I would drop Jenkins and go with one of the free hosted CI services as they save you a lot of trouble (host, install, configure, prepare jobs)

Depending on where your code repository is hosted I would make the following choices:

  • in-house ? Jenkins or gitlab-ci
  • Github.com ? Travis-CI

To setup Travis-CI on a github project, all you have to do is:

  • add a .travis.yml file at the root of your project
  • create an account at travis-ci.com and activate your project

The features you get are:

  • Travis will run your tests for every push made on your repo
  • Travis will run your tests on every pull request contributors will make

Shift elements in a numpy array

Benchmarks & introducing Numba

1. Summary

  • The accepted answer (scipy.ndimage.interpolation.shift) is the slowest solution listed in this page.
  • Numba (@numba.njit) gives some performance boost when array size smaller than ~25.000
  • "Any method" equally good when array size large (>250.000).
  • The fastest option really depends on
        (1)  Length of your arrays
        (2)  Amount of shift you need to do.
  • Below is the picture of the timings of all different methods listed on this page (2020-07-11), using constant shift = 10. As one can see, with small array sizes some methods are use more than +2000% time than the best method.

Relative timings, constant shift (10), all methods

2. Detailed benchmarks with the best options

  • Choose shift4_numba (defined below) if you want good all-arounder

Relative timings, best methods (Benchmarks)

3. Code

3.1 shift4_numba

  • Good all-arounder; max 20% wrt. to the best method with any array size
  • Best method with medium array sizes: ~ 500 < N < 20.000.
  • Caveat: Numba jit (just in time compiler) will give performance boost only if you are calling the decorated function more than once. The first call takes usually 3-4 times longer than the subsequent calls.
import numba

@numba.njit
def shift4_numba(arr, num, fill_value=np.nan):
    if num >= 0:
        return np.concatenate((np.full(num, fill_value), arr[:-num]))
    else:
        return np.concatenate((arr[-num:], np.full(-num, fill_value)))

3.2. shift5_numba

  • Best option with small (N <= 300.. 1500) array sizes. Treshold depends on needed amount of shift.
  • Good performance on any array size; max + 50% compared to the fastest solution.
  • Caveat: Numba jit (just in time compiler) will give performance boost only if you are calling the decorated function more than once. The first call takes usually 3-4 times longer than the subsequent calls.
import numba

@numba.njit
def shift5_numba(arr, num, fill_value=np.nan):
    result = np.empty_like(arr)
    if num > 0:
        result[:num] = fill_value
        result[num:] = arr[:-num]
    elif num < 0:
        result[num:] = fill_value
        result[:num] = arr[-num:]
    else:
        result[:] = arr
    return result

3.3. shift5

  • Best method with array sizes ~ 20.000 < N < 250.000
  • Same as shift5_numba, just remove the @numba.njit decorator.

4 Appendix

4.1 Details about used methods

  • shift_scipy: scipy.ndimage.interpolation.shift (scipy 1.4.1) - The option from accepted answer, which is clearly the slowest alternative.
  • shift1: np.roll and out[:num] xnp.nan by IronManMark20 & gzc
  • shift2: np.roll and np.put by IronManMark20
  • shift3: np.pad and slice by gzc
  • shift4: np.concatenate and np.full by chrisaycock
  • shift5: using two times result[slice] = x by chrisaycock
  • shift#_numba: @numba.njit decorated versions of the previous.

The shift2 and shift3 contained functions that were not supported by the current numba (0.50.1).

4.2 Other test results

4.2.1 Relative timings, all methods

4.2.2 Raw timings, all methods

4.2.3 Raw timings, few best methods

Convert a string to datetime in PowerShell

$invoice = "Jul-16"
[datetime]$newInvoice = "01-" + $invoice

$newInvoice.ToString("yyyy-MM-dd")

There you go, use a type accelerator, but also into a new var, if you want to use it elsewhere, use it like so: $newInvoice.ToString("yyyy-MM-dd")as $newInvoice will always be in the datetime format, unless you cast it as a string afterwards, but will lose the ability to perform datetime functions - adding days etc...

Use formula in custom calculated field in Pivot Table

Some of it is possible, specifically accessing subtotals:

"In Excel 2010+, you can right-click on the values and select Show Values As –> % of Parent Row Total." (or % of Parent Column Total)

enter image description here

  • And make sure the field in question is a number field that can be summed, it does not work for text fields for which only count is normally informative.

Source: http://datapigtechnologies.com/blog/index.php/excel-2010-pivottable-subtotals/

sorting and paging with gridview asp.net

<asp:GridView 
    ID="GridView1" runat="server" AutoGenerateColumns="false" AllowSorting="True" onsorting="GridView1_Sorting" EnableViewState="true"> 
    <Columns>
        <asp:BoundField DataField="bookid" HeaderText="BOOK ID"SortExpression="bookid"  />
        <asp:BoundField DataField="bookname" HeaderText="BOOK NAME" />
        <asp:BoundField DataField="writer" HeaderText="WRITER" />
        <asp:BoundField DataField="totalbook" HeaderText="TOTALBOOK" SortExpression="totalbook"  />
        <asp:BoundField DataField="availablebook" HeaderText="AVAILABLE BOOK" />
    </Columns>
</asp:GridView>

Code behind:

protected void Page_Load(object sender, EventArgs e) {
        if (!IsPostBack) {
            string query = "SELECT * FROM book";
            DataTable DT = new DataTable();
            SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);
            DA.Fill(DT);

            GridView1.DataSource = DT;
            GridView1.DataBind();
        }
    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) {

        string query = "SELECT * FROM book";
        DataTable DT = new DataTable();
        SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);
        DA.Fill(DT);

        GridView1.DataSource = DT;
        GridView1.DataBind();

        if (DT != null) {
            DataView dataView = new DataView(DT);
            dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

            GridView1.DataSource = dataView;
            GridView1.DataBind();
        }
    }

    private string GridViewSortDirection {
        get { return ViewState["SortDirection"] as string ?? "DESC"; }
        set { ViewState["SortDirection"] = value; }
    }

    private string ConvertSortDirectionToSql(SortDirection sortDirection) {
        switch (GridViewSortDirection) {
            case "ASC":
                GridViewSortDirection = "DESC";
                break;

            case "DESC":
                GridViewSortDirection = "ASC";
                break;
        }

        return GridViewSortDirection;
    }
}

Replace multiple strings with multiple other strings

You can use https://www.npmjs.com/package/union-replacer for this purpose. It is basically a string.replace(regexp, ...) counterpart, which allows multiple replaces to happen in one pass while preserving full power of string.replace(...).

Disclosure: I am the author. The library was developed to support more complex user-configurable replacements and it addresses all the problematic things like capture groups, backreferences and callback function replacements.

The solutions above are good enough for exact string replacements though.

Remove duplicates from an array of objects in JavaScript

es6 magic in one line... readable at that!

// returns the union of two arrays where duplicate objects with the same 'prop' are removed
const removeDuplicatesWith = (a, b, prop) => {
  a.filter(x => !b.find(y => x[prop] === y[prop]));
};

ORA-01031: insufficient privileges when selecting view

you may also create view with schema name for example create or replace view schema_name.view_name as select..

doGet and doPost in Servlets

If you do <form action="identification" > for your html form, data will be passed using 'Get' by default and hence you can catch this using doGet function in your java servlet code. This way data will be passed under the HTML header and hence will be visible in the URL when submitted. On the other hand if you want to pass data in HTML body, then USE Post: <form action="identification" method="post"> and catch this data in doPost function. This was, data will be passed under the html body and not the html header, and you will not see the data in the URL after submitting the form.

Examples from my html:

<body>  
<form action="StartProcessUrl" method="post">
.....
.....

Examples from my java servlet code:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        PrintWriter out = response.getWriter();
         String surname = request.getParameter("txtSurname");
         String firstname = request.getParameter("txtForename");
         String rqNo = request.getParameter("txtRQ6");
         String nhsNo = request.getParameter("txtNHSNo");

         String attachment1 = request.getParameter("base64textarea1");
         String attachment2 = request.getParameter("base64textarea2");

.........
.........

How to get the hours difference between two date objects?

Use the timestamp you get by calling valueOf on the date object:

var diff = date2.valueOf() - date1.valueOf();
var diffInHours = diff/1000/60/60; // Convert milliseconds to hours

Skip Git commit hooks

Maybe (from git commit man page):

git commit --no-verify

-n  
--no-verify

This option bypasses the pre-commit and commit-msg hooks. See also githooks(5).

As commented by Blaise, -n can have a different role for certain commands.
For instance, git push -n is actually a dry-run push.
Only git push --no-verify would skip the hook.


Note: Git 2.14.x/2.15 improves the --no-verify behavior:

See commit 680ee55 (14 Aug 2017) by Kevin Willford (``).
(Merged by Junio C Hamano -- gitster -- in commit c3e034f, 23 Aug 2017)

commit: skip discarding the index if there is no pre-commit hook

"git commit" used to discard the index and re-read from the filesystem just in case the pre-commit hook has updated it in the middle; this has been optimized out when we know we do not run the pre-commit hook.


Davi Lima points out in the comments the git cherry-pick does not support --no-verify.
So if a cherry-pick triggers a pre-commit hook, you might, as in this blog post, have to comment/disable somehow that hook in order for your git cherry-pick to proceed.
The same process would be necessary in case of a git rebase --continue, after a merge conflict resolution.

Is it possible to embed animated GIFs in PDFs?

Another possibility is LaTeX + animate package. You will need to provide the individual frames making the animation. The resulting pdf does NOT require any plugin, the animation is shown in Adobe reader

How to read data from a zip file without having to unzip the entire file

Zip files have a table of contents. Every zip utility should have the ability to query just the TOC. Or you can use a command line program like 7zip -t to print the table of contents and redirect it to a text file.

How to check in Javascript if one element is contained within another

TL;DR: a library

I advise using something like dom-helpers, written by the react team as a regular JS lib.

In their contains implementation you will see a Node#contains based implementation with a Node#compareDocumentPosition fallback.

Support for very old browsers e.g. IE <9 would not be given, which I find acceptable.

This answer incorporates the above ones, however I would advise against looping yourself.

How to redirect single url in nginx?

Put this in your server directive:

location /issue {
   rewrite ^/issue(.*) http://$server_name/shop/issues/custom_issue_name$1 permanent;
 }

Or duplicate it:

location /issue1 {
   rewrite ^/.* http://$server_name/shop/issues/custom_issue_name1 permanent;
}
location /issue2 {
   rewrite ^.* http://$server_name/shop/issues/custom_issue_name2 permanent;
}
 ...

How can I iterate JSONObject to get individual items

You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .

public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
    Iterator<String> keys = json.keys();
    while(keys.hasNext()){
        String key = keys.next();
        String val = null;
        try{
             JSONObject value = json.getJSONObject(key);
             parse(value,out);
        }catch(Exception e){
            val = json.getString(key);
        }

        if(val != null){
            out.put(key,val);
        }
    }
    return out;
}

 public static void main(String[] args) throws JSONException {

    String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";

    JSONObject object = new JSONObject(json);

    JSONObject info = object.getJSONObject("ipinfo");

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

    parse(info,out);

    String latitude = out.get("latitude");
    String longitude = out.get("longitude");
    String city = out.get("city");
    String state = out.get("state");
    String country = out.get("country");
    String postal = out.get("postal_code");

    System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);

    System.out.println("ALL VALUE " + out);

}

Output:

    Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}

Add/remove class with jquery based on vertical scroll?

Is this value intended? if (scroll <= 500) { ... This means it's happening from 0 to 500, and not 500 and greater. In the original post you said "after the user scrolls down a little"

What is the boundary in multipart/form-data?

Is the ??? free to be defined by the user?

Yes.

or is it supplied by the HTML?

No. HTML has nothing to do with that. Read below.

Is it possible for me to define the ??? as abcdefg?

Yes.

If you want to send the following data to the web server:

name = John
age = 12

using application/x-www-form-urlencoded would be like this:

name=John&age=12

As you can see, the server knows that parameters are separated by an ampersand &. If & is required for a parameter value then it must be encoded.

So how does the server know where a parameter value starts and ends when it receives an HTTP request using multipart/form-data?

Using the boundary, similar to &.

For example:

--XXX
Content-Disposition: form-data; name="name"

John
--XXX
Content-Disposition: form-data; name="age"

12
--XXX--

In that case, the boundary value is XXX. You specify it in the Content-Type header so that the server knows how to split the data it receives.

So you need to:

  • Use a value that won't appear in the HTTP data sent to the server.

  • Be consistent and use the same value everywhere in the request message.

Java SSLException: hostname in certificate didn't match

In httpclient-4.3.3.jar, there is another HttpClient to use:

public static void main (String[] args) throws Exception {
    // org.apache.http.client.HttpClient client = new DefaultHttpClient();
    org.apache.http.client.HttpClient client = HttpClientBuilder.create().build();
    System.out.println("HttpClient = " + client.getClass().toString());
    org.apache.http.client.methods.HttpPost post = new HttpPost("https://www.rideforrainbows.org/");
    org.apache.http.HttpResponse response = client.execute(post);
    java.io.InputStream is = response.getEntity().getContent();
    java.io.BufferedReader rd = new java.io.BufferedReader(new java.io.InputStreamReader(is));
    String line;
    while ((line = rd.readLine()) != null) { 
        System.out.println(line);
    }
}

This HttpClientBuilder.create().build() will return org.apache.http.impl.client.InternalHttpClient. It can handle the this hostname in certificate didn't match issue.

Capture characters from standard input without waiting for enter to be pressed

If you are on windows, you can use PeekConsoleInput to detect if there's any input,

HANDLE handle = GetStdHandle(STD_INPUT_HANDLE);
DWORD events;
INPUT_RECORD buffer;
PeekConsoleInput( handle, &buffer, 1, &events );

then use ReadConsoleInput to "consume" the input character ..

PeekConsoleInput(handle, &buffer, 1, &events);
if(events > 0)
{
    ReadConsoleInput(handle, &buffer, 1, &events);  
    return buffer.Event.KeyEvent.wVirtualKeyCode;
}
else return 0

to be honest this is from some old code I have, so you have to fiddle a bit with it.

The cool thing though is that it reads input without prompting for anything, so the characters are not displayed at all.

How to escape the % (percent) sign in C's printf?

Like this:

printf("hello%%");
//-----------^^ inside printf, use two percent signs together

useState set method not reflecting change immediately

useEffect has its own state/lifecycle, it will not update until you pass a function in parameters or effect destroyed.

object and array spread or rest will not work inside useEffect.

React.useEffect(() => {
    console.log("effect");
    (async () => {
        try {
            let result = await fetch("/query/countries");
            const res = await result.json();
            let result1 = await fetch("/query/projects");
            const res1 = await result1.json();
            let result11 = await fetch("/query/regions");
            const res11 = await result11.json();
            setData({
                countries: res,
                projects: res1,
                regions: res11
            });
        } catch {}
    })(data)
}, [setData])
# or use this
useEffect(() => {
    (async () => {
        try {
            await Promise.all([
                fetch("/query/countries").then((response) => response.json()),
                fetch("/query/projects").then((response) => response.json()),
                fetch("/query/regions").then((response) => response.json())
            ]).then(([country, project, region]) => {
                // console.log(country, project, region);
                setData({
                    countries: country,
                    projects: project,
                    regions: region
                });
            })
        } catch {
            console.log("data fetch error")
        }
    })()
}, [setData]);

How can I check the current status of the GPS receiver?

After a few years of working with GPS on windows mobile, I realized that the concept of "losing" a GPS fix can be subjective. To simply listen to what the GPS tells you, adding a NMEAListener and parsing the sentence will tell you whether the fix was "valid" or not. See http://www.gpsinformation.org/dale/nmea.htm#GGA . Unfortunately with some GPSes this value will fluctuate back and forth even during the normal course of operation in a "good fix" area.

So, the other solution is to compare the UTC time of the GPS location against the phone's time (converted to UTC). If they are a certain time difference apart, you can assume you lost the GPS position.

How to change color and font on ListView

Even better, you do not need to create separate android xml layout for list cell view. You can just use "android.R.layout.simple_list_item_1" if the list only contains textview.

private class ExampleAdapter extends ArrayAdapter<String>{

    public ExampleAdapter(Context context, int textViewResourceId, String[] objects) {
        super(context, textViewResourceId, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {


        View view =  super.getView(position, convertView, parent);

        TextView tv = (TextView) view.findViewById(android.R.id.text1);
        tv.setTextColor(0);

        return view;
    }

Test iOS app on device without apple developer program or jailbreak

Go to Build Settings, under Code Signing, set Code Signing Identity as iOS Developer & Provisioning Profile as Automatic.

Select your device (now visible) from drop down list and run your app.

enter image description here

How to Copy Text to Clip Board in Android?

use this code

   private ClipboardManager myClipboard;
   private ClipData myClip;
   TextView textView;
   Button copyText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainpage);
    textView = (TextView) findViewById(R.id.textview);
    copyText = (Button) findViewById(R.id.bCopy);
    myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);

    copyText.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub


           String text = textView.getText().toString();
           myClip = ClipData.newPlainText("text", text);
           myClipboard.setPrimaryClip(myClip);
           Toast.makeText(getApplicationContext(), "Text Copied", 
           Toast.LENGTH_SHORT).show(); 
        }
    });
}

In C#, how to check if a TCP port is available?

Since you're using a TcpClient, that means you're checking open TCP ports. There are lots of good objects available in the System.Net.NetworkInformation namespace.

Use the IPGlobalProperties object to get to an array of TcpConnectionInformation objects, which you can then interrogate about endpoint IP and port.


 int port = 456; //<--- This is your value
 bool isAvailable = true;

 // Evaluate current system tcp connections. This is the same information provided
 // by the netstat command line application, just in .Net strongly-typed object
 // form.  We will look through the list, and if our port we would like to use
 // in our TcpClient is occupied, we will set isAvailable to false.
 IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
 TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();

 foreach (TcpConnectionInformation tcpi in tcpConnInfoArray)
 {
   if (tcpi.LocalEndPoint.Port==port)
   {
     isAvailable = false;
     break;
   }
 }

 // At this point, if isAvailable is true, we can proceed accordingly.

Android Paint: .measureText() vs .getTextBounds()

My experience with this is that getTextBounds will return that absolute minimal bounding rect that encapsulates the text, not necessarily the measured width used when rendering. I also want to say that measureText assumes one line.

In order to get accurate measuring results, you should use the StaticLayout to render the text and pull out the measurements.

For example:

String text = "text";
TextPaint textPaint = textView.getPaint();
int boundedWidth = 1000;

StaticLayout layout = new StaticLayout(text, textPaint, boundedWidth , Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
int height = layout.getHeight();

Cannot connect to Database server (mysql workbench)

The issue is likely due to socket authentication being enabled for the root user by default when no password is set, during the upgrade to ubuntu 16.04.

The solution is to revert back to native password authentication. You can do this by logging in to MySQL using socket authentication by doing:

sudo mysql -u root

Once logged in:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

which will revert back to the native (old default) password authentication.

Now use password as the password whenever required by MySQL.

How do I make an HTTP request in Swift?

In Swift 4.1 and Xcode 9.4.1.

JSON POST approach example. To check internet connection add Reachability.h & .m files from https://developer.apple.com/library/archive/samplecode/Reachability/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007324-Intro-DontLinkElementID_2

func yourFunctionName {
    //Check internet connection
    let networkReachability = Reachability.forInternetConnection()
    let networkStatus:Int = (networkReachability?.currentReachabilityStatus())!.rawValue
    print(networkStatus)
    if networkStatus == NotReachable.rawValue {
        let msg = SharedClass.sharedInstance.noNetMsg//Message
        //Call alert from shared class
        SharedClass.sharedInstance.alert(view: self, title: "", message: msg)
    } else {
        //Call spinner from shared class
        SharedClass.sharedInstance.activityIndicator(view: self.view)//Play spinner

        let parameters = "Your parameters here"
        var request = URLRequest(url: URL(string: url)!)

        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"

        print("URL : \(request)")

        request.httpBody = parameters.data(using: .utf8)

        let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
            //Stop spinner
            SharedClass.sharedInstance.stopActivityIndicator() //Stop spinner
            //Print error in alert
            SharedClass.sharedInstance.alert(view: self, title: "", message: "\(String(describing: error!.localizedDescription))")
            return
            }

            SharedClass.sharedInstance.stopActivityIndicator() //Stop spinner

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }

            do {
                let response = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject]
                print(response!)
                //Your code here                    
            } catch let error as NSError {
                print(error)
            }
        }

        task.resume()

    }

}

If you have interest to use this function in SharedClass

//My shared class
import UIKit
class SharedClass: NSObject {

static let sharedInstance = SharedClass()

func postRequestFunction(apiName: String , parameters: String, onCompletion: @escaping (_ success: Bool, _ error: Error?, _ result: [String: Any]?)->()) {

    var URL =  "your URL here/index.php/***?"

    URL = URL.replacingOccurrences(of: "***", with: apiName)

    var request = URLRequest(url: URL(string: URL)!)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    print("shared URL : \(request)")
    request.httpBody = parameters.data(using: .utf8)

    var returnRes:[String:Any] = [:]
    let task = URLSession.shared.dataTask(with: request) { data, response, error in

        if let error = error {
            onCompletion(false, error, nil)
        } else {
            guard let data = data else {
                onCompletion(false, error, nil)
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
                do {
                   returnRes = try JSONSerialization.jsonObject(with: data, options: []) as! [String : Any]
                    onCompletion(true, nil, returnRes)

                } catch let error as NSError {
                   onCompletion(false, error, nil)
                }
            } else {
                onCompletion(false, error, nil)
            }
        }
    }
    task.resume()
}


private override init() {

}

And finally call this function like this....

SharedClass.sharedInstance.postRequestFunction(apiName: "Your API name", parameters: parameters) { (success, error, result) in
    print(result!)
    if success {
        //Your code here
    } else {
        print(error?.localizedDescription ?? "")
    }
}

Clicking a button within a form causes page refresh

I wonder why nobody proposed the possibly simplest solution:

don't use a <form>

A <whatever ng-form> does IMHO a better job and without an HTML form, there's nothing to be submitted by the browser itself. Which is exactly the right behavior when using angular.

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

If you are stuck with C++98 and don't want to use boost, here there is the solution I use when I need to initialize a static map:

typedef std::pair< int, char > elemPair_t;
elemPair_t elemPairs[] = 
{
    elemPair_t( 1, 'a'), 
    elemPair_t( 3, 'b' ), 
    elemPair_t( 5, 'c' ), 
    elemPair_t( 7, 'd' )
};

const std::map< int, char > myMap( &elemPairs[ 0 ], &elemPairs[ sizeof( elemPairs ) / sizeof( elemPairs[ 0 ] ) ] );

How to show the text on a ImageButton?

Guys I need to develop the setting and logout button, I used the below code. enter image description here

    <Button
        android:id="@+id/imageViewLogout"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/size_30dp"
        android:layout_alignParentLeft="true"
        android:text="Settings"
        android:drawablePadding="10dp"
        android:background="@android:color/transparent"
        android:layout_alignParentBottom="true"
        android:drawableTop="@drawable/logout" />

Java Multiple Inheritance

  1. Define interfaces for defining the capabilities. You can define multiple interfaces for multiple capabilities. These capabilities can be implemented by specific Animal or Bird.
  2. Use inheritance to establish relationships among classes by sharing non-static and non-public data/methods.
  3. Use Decorator_pattern to add capabilities dynamically. This will allow you to reduce number of inheritance classes & combinations.

Have a look at below example for better understanding

When to Use the Decorator Pattern?

Find OpenCV Version Installed on Ubuntu

There is also a flag CV_VERSION which will print out the full version of opencv

Make index.html default, but allow index.php to be visited if typed in

Hi,

Well, I have tried the methods mentioned above! it's working yes, but not exactly the way I wanted. I wanted to redirect the default page extension to the main domain with our further action.

Here how I do that...

# Accesible Index Page
<IfModule dir_module>
 DirectoryIndex index.php index.html
 RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.(html|htm|php|php3|php5|shtml|phtml) [NC]
 RewriteRule ^index\.html|htm|php|php3|php5|shtml|phtml$ / [R=301,L]
</IfModule>

The above code simply captures any index.* and redirect it to the main domain.

Thank you

Resolving LNK4098: defaultlib 'MSVCRT' conflicts with

IMO this link from Yochai Timmer was very good and relevant but painful to read. I wrote a summary.

Yochai, if you ever read this, please see the note at the end.


For the original post read : warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs

Error

LINK : warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs; use /NODEFAULTLIB:library

Meaning

one part of the system was compiled to use a single threaded standard (libc) library with debug information (libcd) which is statically linked

while another part of the system was compiled to use a multi-threaded standard library without debug information which resides in a DLL and uses dynamic linking

How to resolve

  • Ignore the warning, after all it is only a warning. However, your program now contains multiple instances of the same functions.

  • Use the linker option /NODEFAULTLIB:lib. This is not a complete solution, even if you can get your program to link this way you are ignoring a warning sign: the code has been compiled for different environments, some of your code may be compiled for a single threaded model while other code is multi-threaded.

  • [...] trawl through all your libraries and ensure they have the correct link settings

In the latter, as it in mentioned in the original post, two common problems can arise :

  • You have a third party library which is linked differently to your application.

  • You have other directives embedded in your code: normally this is the MFC. If any modules in your system link against MFC all your modules must nominally link against the same version of MFC.

For those cases, ensure you understand the problem and decide among the solutions.


Note : I wanted to include that summary of Yochai Timmer's link into his own answer but since some people have trouble to review edits properly I had to write it in a separate answer. Sorry

How do I create an .exe for a Java program?

If Java is installed on the target machine, there is no need to create an .exe file. A .jar file should be sufficient.

How can I get sin, cos, and tan to use degrees instead of radians?

Create your own conversion function that applies the needed math, and invoke those instead. http://en.wikipedia.org/wiki/Radian#Conversion_between_radians_and_degrees

Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

For those looking for solution with Apple TV, I just experience the exact problem "Apple TV is busy: Preparing debugger support for Apple TV” with Apple TV 4K with my Macbook Air (Early 2015)

The solution is not to unpair or restart devices. But to switch network. I brought it to a faster and more open network and it works perfectly.

Error: allowDefinition='MachineToApplication' beyond application level

I had this error when building the solution with Web Deployment Project created into my solution. I resolve the error by deleting the folder where Web Deployment Project is built to. This folder is specified in "Project Folder" attribute of WDP properties

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

First check for gmail's security related issues. You may have enabled double authentication in gmail. Also check your gmail inbox if you are getting any security alerts. In such cases check other answer of @mjb as below

Below is the very general thing that i always check first for such issues

client.UseDefaultCredentials = true;

set it to false.

Note @Joe King's answer - you must set client.UseDefaultCredentials before you set client.Credentials

How to resolve compiler warning 'implicit declaration of function memset'

A good way to findout what header file you are missing:

 man <section> <function call>

To find out the section use:

apropos <function call>

Example:

 man 3 memset
 man 2 send

Edit in response to James Morris:

  • Section | Description
  • 1 General commands
  • 2 System calls
  • 3 C library functions
  • 4 Special files (usually devices, those found in /dev) and drivers
  • 5 File formats and conventions
  • 6 Games and screensavers
  • 7 Miscellanea
  • 8 System administration commands and daemons

Source: Wikipedia Man Page

How to get the user input in Java?

You can use any of the following options based on the requirements.

Scanner class

import java.util.Scanner; 
//...
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();

BufferedReader and InputStreamReader classes

import java.io.BufferedReader;
import java.io.InputStreamReader;
//...
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int i = Integer.parseInt(s);

DataInputStream class

import java.io.DataInputStream;
//...
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();

The readLine method from the DataInputStream class has been deprecated. To get String value, you should use the previous solution with BufferedReader


Console class

import java.io.Console;
//...
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());

Apparently, this method does not work well in some IDEs.

Flash CS4 refuses to let go

Also, to use your new namespaced class you can also do

var jenine:com.newnamespace.subspace.Jenine = com.newnamespace.subspace.Jenine()

Django CSRF Cookie Not Set

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt 
def your_view(request):
    if request.method == "POST":
        # do something
    return HttpResponse("Your response")

How to display with n decimal places in Matlab

You can convert a number to a string with n decimal places using the SPRINTF command:

>> x = 1.23;
>> sprintf('%0.6f', x)

ans =

1.230000

>> x = 1.23456789;
>> sprintf('%0.6f', x)

ans =

1.234568

Cursor inside cursor

You have a variety of problems. First, why are you using your specific @@FETCH_STATUS values? It should just be @@FETCH_STATUS = 0.

Second, you are not selecting your inner Cursor into anything. And I cannot think of any circumstance where you would select all fields in this way - spell them out!

Here's a sample to go by. Folder has a primary key of "ClientID" that is also a foreign key for Attend. I'm just printing all of the Attend UIDs, broken down by Folder ClientID:

Declare @ClientID int;
Declare @UID int;

DECLARE Cur1 CURSOR FOR
    SELECT ClientID From Folder;

OPEN Cur1
FETCH NEXT FROM Cur1 INTO @ClientID;
WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT 'Processing ClientID: ' + Cast(@ClientID as Varchar);
    DECLARE Cur2 CURSOR FOR
        SELECT UID FROM Attend Where ClientID=@ClientID;
    OPEN Cur2;
    FETCH NEXT FROM Cur2 INTO @UID;
    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT 'Found UID: ' + Cast(@UID as Varchar);
        FETCH NEXT FROM Cur2 INTO @UID;
    END;
    CLOSE Cur2;
    DEALLOCATE Cur2;
    FETCH NEXT FROM Cur1 INTO @ClientID;
END;
PRINT 'DONE';
CLOSE Cur1;
DEALLOCATE Cur1;

Finally, are you SURE you want to be doing something like this in a stored procedure? It is very easy to abuse stored procedures and often reflects problems in characterizing your problem. The sample I gave, for example, could be far more easily accomplished using standard select calls.

Passing command line arguments from Maven as properties in pom.xml

For your property example do:

mvn install "-Dmyproperty=my property from command line"

Note quotes around whole property definition. You'll need them if your property contains spaces.

how to get the first and last days of a given month

cal_days_in_month() should give you the total number of days in the month, and therefore, the last one.

PostgreSQL error 'Could not connect to server: No such file or directory'

So for a lot of the issues here, it seems that people were already running psql and had to remove postmaster.pid. However, I did not have that issue as I never even had postgres installed in my system properly.

Here's a solution that worked for me in MAC OSX Yosemite

  1. I went to http://postgresapp.com/ and downloaded the app.
  2. I moved the app to Application/ directory
  3. I added it to $PATH by adding this to .bashrc or .bash_profile or .zshrc : export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/latest/bin
  4. I ran the postgres from the Applications directory and ran the command again and it worked.

Hope this helps! Toodles!

Also, this answer helped me the most: https://stackoverflow.com/a/21503349/3173748

Javascript negative number

In ES6 you can use Math.sign function to determine if,

1. its +ve no
2. its -ve no
3. its zero (0)
4. its NaN


console.log(Math.sign(1))        // prints 1 
console.log(Math.sign(-1))       // prints -1
console.log(Math.sign(0))        // prints 0
console.log(Math.sign("abcd"))   // prints NaN

Python unittest - opposite of assertRaises?

I am the original poster and I accepted the above answer by DGH without having first used it in the code.

Once I did use I realised that it needed a little tweaking to actually do what I needed it to do (to be fair to DGH he/she did say "or something similar" !).

I thought it was worth posting the tweak here for the benefit of others:

    try:
        a = Application("abcdef", "")
    except pySourceAidExceptions.PathIsNotAValidOne:
        pass
    except:
        self.assertTrue(False)

What I was attempting to do here was to ensure that if an attempt was made to instantiate an Application object with a second argument of spaces the pySourceAidExceptions.PathIsNotAValidOne would be raised.

I believe that using the above code (based heavily on DGH's answer) will do that.

Does JavaScript have a built in stringbuilder class?

When I find myself doing a lot of string concatenation in JavaScript, I start looking for templating. Handlebars.js works quite well keeping the HTML and JavaScript more readable. http://handlebarsjs.com

Docker expose all ports or range of ports from 7000 to 8000

Since Docker 1.5 you can now expose a range of ports to other linked containers using:

The Dockerfile EXPOSE command:

EXPOSE 7000-8000

or The Docker run command:

docker run --expose=7000-8000

Or instead you can publish a range of ports to the host machine via Docker run command:

docker run -p 7000-8000:7000-8000

android:drawableLeft margin and/or padding

Make your drawable resources.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <inset android:drawable="@drawable/small_m" android:insetLeft="10dp" android:insetTop="10dp" />
    </item>
    <item>
        <inset android:drawable="@drawable/small_p" android:insetLeft="10dp" android:insetTop="10dp" />
    </item>
</selector>

Correctly determine if date string is a valid date in that format

    /**** date check is a recursive function. it's need 3 argument 
    MONTH,DAY,YEAR. ******/

    $always_valid_date = $this->date_check($month,$day,$year);

    private function date_check($month,$day,$year){

        /** checkdate() is a php function that check a date is valid 
        or not. if valid date it's return true else false.   **/

        $status = checkdate($month,$day,$year);

        if($status == true){

            $always_valid_date = $year . '-' . $month . '-' . $day;

            return $always_valid_date;

        }else{
            $day = ($day - 1);

            /**recursive call**/

            return $this->date_check($month,$day,$year);
        }

    }

Exception from HRESULT: 0x800A03EC Error

Check your start indexes. Its start from 1 not 0 for Microsoft.Office.Interop.Excel range objects. I had received same error because of my loop start value.

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

I was working with talend V7.3.1 and I had poi version "4.1.0" and including xml-beans from the list of dependencies didnt fix my problem (i.e: 2.3.0 and 2.6.0).

It was fixed by downloading the jar "xmlbeans-3.0.1.jar" and adding it to the project

enter image description here

Create an ISO date object in javascript

try below:

var temp_datetime_obj = new Date();

collection.find({
    start_date:{
        $gte: new Date(temp_datetime_obj.toISOString())
    }
}).toArray(function(err, items) { 
    /* you can console.log here */ 
});

numpy get index where value is true

You can use nonzero function. it returns the nonzero indices of the given input.

Easy Way

>>> (e > 15).nonzero()

(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))

to see the indices more cleaner, use transpose method:

>>> numpy.transpose((e>15).nonzero())

[[1 6]
 [1 7]
 [1 8]
 [1 9]
 [2 0]
 ...

Not Bad Way

>>> numpy.nonzero(e > 15)

(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))

or the clean way:

>>> numpy.transpose(numpy.nonzero(e > 15))

[[1 6]
 [1 7]
 [1 8]
 [1 9]
 [2 0]
 ...

Update multiple rows with different values in a single SQL query

Use a comma ","

eg: 
UPDATE my_table SET rowOneValue = rowOneValue + 1, rowTwoValue  = rowTwoValue + ( (rowTwoValue / (rowTwoValue) ) + ?) * (v + 1) WHERE value = ?

What is the difference between a "line feed" and a "carriage return"?

Since I can not comment because of not having enough reward points I have to answer to correct answer given by @Burhan Khalid.
In very layman language Enter key press is combination of carriage return and line feed.
Carriage return points the cursor to the beginning of the line horizontly and Line feed shifts the cursor to the next line vertically.Combination of both gives you new line(\n) effect.
Reference - https://en.wikipedia.org/wiki/Carriage_return#Computers

Creating and Update Laravel Eloquent

$shopOwner = ShopMeta::firstOrNew(array('shopId' => $theID,'metadataKey' => 2001));

Then make your changes and save. Note the firstOrNew doesn't do the insert if its not found, if you do need that then its firstOrCreate.

Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error

Try using

Dir.glob(".") 

To see what's in the directory (and therefore what directory it's looking at).

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

Non-resolvable parent POM using Maven 3.0.3 and relativePath notation

'parent.relativePath' points at wrong local POM @ myGroup:myParentArtifactId:1.0, C:\myProjectDir\parent\pom.xml

This indicates that maven did search locally for the parent pom, but found that it was not the correct pom.

  • Does pom.xml of parentpom correctly define the parent pom as the pom.xml of rootpom?
  • Does rootpom folder contain pom.xml as well as the paretpom folder?

Check whether number is even or odd

Least significant bit (rightmost) can be used to check if the number is even or odd. For all Odd numbers, rightmost bit is always 1 in binary representation.

public static boolean checkOdd(long number){
   return ((number & 0x1) == 1);
}

What does numpy.random.seed(0) do?

A random seed specifies the start point when a computer generates a random number sequence.

For example, let’s say you wanted to generate a random number in Excel (Note: Excel sets a limit of 9999 for the seed). If you enter a number into the Random Seed box during the process, you’ll be able to use the same set of random numbers again. If you typed “77” into the box, and typed “77” the next time you run the random number generator, Excel will display that same set of random numbers. If you type “99”, you’ll get an entirely different set of numbers. But if you revert back to a seed of 77, then you’ll get the same set of random numbers you started with.

For example, “take a number x, add 900 +x, then subtract 52.” In order for the process to start, you have to specify a starting number, x (the seed). Let’s take the starting number 77:

Add 900 + 77 = 977 Subtract 52 = 925 Following the same algorithm, the second “random” number would be:

900 + 925 = 1825 Subtract 52 = 1773 This simple example follows a pattern, but the algorithms behind computer number generation are much more complicated

How can I get the URL of the current tab from a Google Chrome extension?

Warning! chrome.tabs.getSelected is deprecated. Please use chrome.tabs.query as shown in the other answers.


First, you've to set the permissions for the API in manifest.json:

"permissions": [
    "tabs"
]

And to store the URL :

chrome.tabs.getSelected(null,function(tab) {
    var tablink = tab.url;
});

Kill some processes by .exe file name

Quick Answer:

foreach (var process in Process.GetProcessesByName("whatever"))
{
    process.Kill();
}

(leave off .exe from process name)

How can I get the named parameters from a URL using Flask?

You can also use brackets <> on the URL of the view definition and this input will go into your view function arguments

@app.route('/<name>')
def my_view_func(name):
    return name

How do I access store state in React Redux?

If you want to do some high-powered debugging, you can subscribe to every change of the state and pause the app to see what's going on in detail as follows.

store.js
store.subscribe( () => {
  console.log('state\n', store.getState());
  debugger;
});

Place that in the file where you do createStore.

To copy the state object from the console to the clipboard, follow these steps:

  1. Right-click an object in Chrome's console and select Store as Global Variable from the context menu. It will return something like temp1 as the variable name.

  2. Chrome also has a copy() method, so copy(temp1) in the console should copy that object to your clipboard.

https://stackoverflow.com/a/25140576

https://scottwhittaker.net/chrome-devtools/2016/02/29/chrome-devtools-copy-object.html

You can view the object in a json viewer like this one: http://jsonviewer.stack.hu/

You can compare two json objects here: http://www.jsondiff.com/

AFNetworking Post Request

[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
[SVProgressHUD show];

NSDictionary *dictParam =@{@"user_id":@"31"};// Add perameter

NSString *URLString =@"your url string";

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
[manager.requestSerializer setValue:strGlobalLoginToken forHTTPHeaderField:@"Authorization"];//strGlobalLoginToken is your login token
//         [manager.requestSerializer setValue:setHeaderEnv forHTTPHeaderField:@"Env"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"application/rss+xml", nil];
[manager POST:URLString parameters:dictParam progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
 {

     NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];

     NSLog(@"Response DICT:%@",response);

     if ([[[[response objectForKey:@"response"] objectAtIndex:0] objectForKey:@"status"] isEqualToString:@"true"])
     {

         for (NSMutableDictionary *dicAll in [[[response objectForKey:@"response"]objectAtIndex:0]objectForKey:@"plans"])
         {
             [yourNsmutableArray addObject:[dicAll mutableCopy]];
         }
         //yourNsmutableArray Nsmutablearray  alloction in view didload

         NSLog(@"yourNsmutableArray  %@",yourNsmutableArray);
     }
     else
     {
         NSLog(@"False");
     }

     [SVProgressHUD dismiss];

 } failure:^(NSURLSessionDataTask  *_Nullable task, NSError  *_Nonnull error)
 {
     NSLog(@"RESPONSE STRING:%@",task.response);
     NSLog(@"error userInfo:%@",error.userInfo);

     NSString *errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
     NSLog(@"URLString :--->>   %@ Error********* %@",URLString,errResponse);

     [SVProgressHUD dismiss];

 }];

Show which git tag you are on?

Show all tags on current HEAD (or commit)

git tag --points-at HEAD

Remove by _id in MongoDB console

I've just bumped into this myself and this variation worked for me:

db.foo.remove({**_id**: new ObjectId("4f872685a64eed5a980ca536")})

How to delete directory content in Java?

To delete folder having files, no need of loops or recursive search. You can directly use:

FileUtils.deleteDirectory(<File object of directory>);

This function will directory delete the folder and all files in it.

Nullable types: better way to check for null or zero in c#

is there a better way?

Well, if you are really looking for a better way, you can probably add another layer of abstraction on top of Rate. Well here is something I just came up with using Nullable Design Pattern.

using System;
using System.Collections.Generic;

namespace NullObjectPatternTest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var items = new List
                            {
                                new Item(RateFactory.Create(20)),
                                new Item(RateFactory.Create(null))
                            };

            PrintPricesForItems(items);
        }

        private static void PrintPricesForItems(IEnumerable items)
        {
            foreach (var item in items)
                Console.WriteLine("Item Price: {0:C}", item.GetPrice());
        }
    }

    public abstract class ItemBase
    {
        public abstract Rate Rate { get; }
        public int GetPrice()
        {
            // There is NO need to check if Rate == 0 or Rate == null
            return 1 * Rate.Value;
        }
    }

    public class Item : ItemBase
    {
        private readonly Rate _Rate;
        public override Rate Rate { get { return _Rate; } }
        public Item(Rate rate) { _Rate = rate; }
    }

    public sealed class RateFactory
    {
        public static Rate Create(int? rateValue)
        {
            if (!rateValue || rateValue == 0) 
                return new NullRate();
            return new Rate(rateValue);
        }
    }

    public class Rate
    {
        public int Value { get; set; }
        public virtual bool HasValue { get { return (Value > 0); } }
        public Rate(int value) { Value = value; }
    }

    public class NullRate : Rate
    {
        public override bool HasValue { get { return false; } }
        public NullRate() : base(0) { }
    }
}

how to remove new lines and returns from php string?

You need to place the \n in double quotes.
Inside single quotes it is treated as 2 characters '\' followed by 'n'

You need:

$str = str_replace("\n", '', $str);

A better alternative is to use PHP_EOL as:

$str = str_replace(PHP_EOL, '', $str);

Convert string to nullable type (int, double, etc...)

You could try using the below extension method:

public static T? GetValueOrNull<T>(this string valueAsString)
    where T : struct 
{
    if (string.IsNullOrEmpty(valueAsString))
        return null;
    return (T) Convert.ChangeType(valueAsString, typeof(T));
}

This way you can do this:

double? amount = strAmount.GetValueOrNull<double>();
int? amount = strAmount.GetValueOrNull<int>();
decimal? amount = strAmount.GetValueOrNull<decimal>();

PHP Header redirect not working

Also see your php file text encoding. Mine was UTF-8 with BOM and it prevented the script to work. But now works flawlessly after removing the BOM...

How do I add an image to a JButton

I think that your problem is in the location of the image. You shall place it in your source, and then use it like this:

  JButton button = new JButton();
  try {
    Image img = ImageIO.read(getClass().getResource("resources/water.bmp"));
    button.setIcon(new ImageIcon(img));
  } catch (Exception ex) {
    System.out.println(ex);
  }

In this example, it is assumed that image is in src/resources/ folder.

Python send UDP packet

With Python3x, you need to convert your string to raw bytes. You would have to encode the string as bytes. Over the network you need to send bytes and not characters. You are right that this would work for Python 2x since in Python 2x, socket.sendto on a socket takes a "plain" string and not bytes. Try this:

print("UDP target IP:", UDP_IP)
print("UDP target port:", UDP_PORT)
print("message:", MESSAGE)

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(bytes(MESSAGE, "utf-8"), (UDP_IP, UDP_PORT))

upstream sent too big header while reading response header from upstream

Add the following to your conf file

fastcgi_buffers 16 16k; 
fastcgi_buffer_size 32k;

Can't find file executable in your configured search path for gnc gcc compiler

I'm a total noob but I reinstalled over the codeblocks giving me these "Can't find file executable in your configured search path for gnc gcc compiler" errors by downloading:

codeblocks-20.03mingw-setup.exe

(IMPORTANT: make sure it has the "mingw" in the file download name, that has the compiler build that is required to compile the code which doesn't automatically comes with the main codeblocks editor software download because codeblocks already assumes you already have another compiler installed on your computer {visual studio 2019 or such}).

Then when I created a new project (console application) and used the defaults to quickly test it out.

It gave me errors.

So I went to Settings > Compiler > Selected Compiler set to: GNU GCC Compiler > Click on the "Tooolchain executables" tab > Click on Auto-Detect > Should say "C:\Progam Files\CodeBlocks\MinGW" > Click OK.

Build and run a simple hello world code.

Should work! If not, look for the "MingGW" in the C:\Program Files\CodeBlocks and select it.

ng is not recognized as an internal or external command

With a command

npm install -g @angular/cli@latest

It works fine, I am able to run ng command now.

CSS "and" and "or"

A word of caution. Stringing together several not selectors increases the specificity of the resulting selector, which makes it harder to override: you'll basically need to find the selector with all the nots and copy-paste it into your new selector.

A not(X or Y) selector would be great to avoid inflating specificity, but I guess we'll have to stick to combining the opposites, like in this answer.

Convert hexadecimal string (hex) to a binary string

Integer.parseInt(hex,16);    
System.out.print(Integer.toBinaryString(hex));

Parse hex(String) to integer with base 16 then convert it to Binary String using toBinaryString(int) method

example

int num = (Integer.parseInt("A2B", 16));
System.out.print(Integer.toBinaryString(num));

Will Print

101000101011

Max Hex vakue Handled by int is FFFFFFF

i.e. if FFFFFFF0 is passed ti will give error

state machines tutorials

I prefer using function pointers over gigantic switch statements, but in contrast to qrdl's answer I normally don't use explicit return codes or transition tables.

Also, in most cases you'll want a mechanism to pass along additional data. Here's an example state machine:

#include <stdio.h>

struct state;
typedef void state_fn(struct state *);

struct state
{
    state_fn * next;
    int i; // data
};

state_fn foo, bar;

void foo(struct state * state)
{
    printf("%s %i\n", __func__, ++state->i);
    state->next = bar;
}

void bar(struct state * state)
{
    printf("%s %i\n", __func__, ++state->i);
    state->next = state->i < 10 ? foo : 0;
}

int main(void)
{
    struct state state = { foo, 0 };
    while(state.next) state.next(&state);
}

Algorithm to randomly generate an aesthetically-pleasing color palette

I'd strongly recommend using a CG HSVtoRGB shader function, they are awesome... it gives you natural color control like a painter instead of control like a crt monitor, which you arent presumably!

This is a way to make 1 float value. i.e. Grey, into 1000 ds of combinations of color and brightness and saturation etc:

int rand = a global color randomizer that you can control by script/ by a crossfader etc.
float h = perlin(grey,23.3*rand)
float s = perlin(grey,54,4*rand)
float v = perlin(grey,12.6*rand)

Return float4 HSVtoRGB(h,s,v);

result is AWESOME COLOR RANDOMIZATION! it's not natural but it uses natural color gradients and it looks organic and controlleably irridescent / pastel parameters.

For perlin, you can use this function, it is a fast zig zag version of perlin.

function  zig ( xx : float ): float{    //lfo nz -1,1
    xx= xx+32;
    var x0 = Mathf.Floor(xx);
    var x1 = x0+1;
    var v0 = (Mathf.Sin (x0*.014686)*31718.927)%1;
    var v1 = (Mathf.Sin  (x1*.014686)*31718.927)%1;
    return Mathf.Lerp( v0 , v1 , (xx)%1 )*2-1;
}

How to declare a global variable in C++

I have read that any variable declared outside a function is a global variable. I have done so, but in another *.cpp File that variable could not be found. So it was not realy global.

According to the concept of scope, your variable is global. However, what you've read/understood is overly-simplified.


Possibility 1

Perhaps you forgot to declare the variable in the other translation unit (TU). Here's an example:

a.cpp

int x = 5; // declaration and definition of my global variable

b.cpp

// I want to use `x` here, too.
// But I need b.cpp to know that it exists, first:
extern int x; // declaration (not definition)

void foo() {
   cout << x;  // OK
}

Typically you'd place extern int x; in a header file that gets included into b.cpp, and also into any other TU that ends up needing to use x.


Possibility 2

Additionally, it's possible that the variable has internal linkage, meaning that it's not exposed across translation units. This will be the case by default if the variable is marked const ([C++11: 3.5/3]):

a.cpp

const int x = 5; // file-`static` by default, because `const`

b.cpp

extern const int x;    // says there's a `x` that we can use somewhere...

void foo() {
   cout << x;    // ... but actually there isn't. So, linker error.
}

You could fix this by applying extern to the definition, too:

a.cpp

extern const int x = 5;

This whole malarky is roughly equivalent to the mess you go through making functions visible/usable across TU boundaries, but with some differences in how you go about it.

changing minDate option in JQuery DatePicker not working

Use minDate as string:

$('#datePickerId').datepicker({minDate: '0'});

This would set today as minimum selectable date .

When is it practical to use Depth-First Search (DFS) vs Breadth-First Search (BFS)?

Some algorithms depend on particular properties of DFS (or BFS) to work. For example the Hopcroft and Tarjan algorithm for finding 2-connected components takes advantage of the fact that each already visited node encountered by DFS is on the path from root to the currently explored node.

Multiple lines of input in <input type="text" />

Input doesn't support multiple lines. You need to use a textarea to achieve that feature.

<textarea name="Text1"></textarea>

Remeber that the <textarea> have the value inside the tag, not in attribute:

<textarea>INITIAL VALUE GOES HERE</textarea>

It cannot be self closed as: <textarea/>


For more information, take a look to this.

How to check null objects in jQuery

Calling length property on undefined or a null object will cause IE and webkit browsers to fail!

Instead try this:

if($("#something") !== null){
  // do something
}

or

if($("#something") === null){
  // don't do something
}

Formatting a float to 2 decimal places

You can pass the format in to the ToString method, e.g.:

myFloatVariable.ToString("0.00"); //2dp Number

myFloatVariable.ToString("n2"); // 2dp Number

myFloatVariable.ToString("c2"); // 2dp currency

Standard Number Format Strings

.mp4 file not playing in chrome

After running into the same issue - here're some of my thoughts:

  • due to Chrome removing support for h264, on some machines, mp4 videos encoded with it will either not work (throwing an Parser error when viewing under Firebug/Network tab - consistent with issue submitted here), or crash the browser, depending upon the encoding settings
  • it isn't consistent - it entirely depends upon the codecs installed on the computer - while I didn't encounter this issue on my machine, we did have one in the office where the issue occurred (and thus we used this one for testing)
  • it might to do with Quicktime / divX settings (the machine in question had an older version of Quicktime than my native one - we didn't want to loose our testing pc though, so we didn't update it).

As it affects only Chrome (other browsers work fine with VideoForEverybody solution) the solution I've used is:

for every mp4 file, create a Theora encoded mp4 file (example.mp4 -> example_c.mp4) apply following js:

if (window.chrome)
    $("[type=video\\\/mp4]").each(function()
    {
        $(this).attr('src', $(this).attr('src').replace(".mp4", "_c.mp4"));
    });

Unfortunately it's a bad Chrome hack, but hey, at least it works.

Source: user: eithedog

This also can help: chrome could play html5 mp4 video but html5test said chrome did not support mp4 video codec

Also check your version of crome here: html5test

HTTP response header content disposition for attachments

Problems

The code has the following issues:

  • An Ajax call (<a4j:commandButton .../>) does not work with attachments.
  • Creating the output content must happen first.
  • Displaying the error messages also cannot use Ajax-based a4j tags.

Solution

  1. Change <a4j:commandButton .../> to <h:commandButton .../>.
  2. Update the source code:
    1. Change bw.write( getDomainDocument() ); to bw.write( document );.
    2. Add String document = getDomainDocument(); to the first line of the try/catch.
  3. Change the <a4j:outputPanel.../> (not shown) to <h:messages showDetail="false"/>.

Essentially, remove all the Ajax facilities related to the commandButton. It is still possible to display error messages and leverage the RichFaces UI style.

References

How to read/process command line arguments?

I like getopt from stdlib, eg:

try:
    opts, args = getopt.getopt(sys.argv[1:], 'h', ['help'])
except getopt.GetoptError, err: 
    usage(err)

for opt, arg in opts:
    if opt in ('-h', '--help'): 
        usage()

if len(args) != 1:
    usage("specify thing...")

Lately I have been wrapping something similiar to this to make things less verbose (eg; making "-h" implicit).

Configuring ObjectMapper in Spring

Using Spring Boot (1.2.4) and Jackson (2.4.6) the following annotation based configuration worked for me.

@Configuration
public class JacksonConfiguration {

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);

        return mapper;
    }
}

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

CORS is Cross Origin Resource Sharing, you get this error if you are trying to access from one domain to another domain.

Try using JSONP. In your case, JSONP should work fine because it only uses the GET method.

Try something like this:

var url = "https://api.getevents.co/event?&lat=41.904196&lng=12.465974";
$http({
    method: 'JSONP',
    url: url
}).
success(function(status) {
    //your code when success
}).
error(function(status) {
    //your code when fails
});

How to disable logging on the standard error stream in Python?

I don't know the logging module very well, but I'm using it in the way that I usually want to disable only debug (or info) messages. You can use Handler.setLevel() to set the logging level to CRITICAL or higher.

Also, you could replace sys.stderr and sys.stdout by a file open for writing. See http://docs.python.org/library/sys.html#sys.stdout. But I wouldn't recommend that.

SQL How to replace values of select return?

I got the solution

   SELECT 
   CASE status
      WHEN 'VS' THEN 'validated by subsidiary'
      WHEN 'NA' THEN 'not acceptable'
      WHEN 'D'  THEN 'delisted'
      ELSE 'validated'
   END AS STATUS
   FROM SUPP_STATUS

This is using the CASE This is another to manipulate the selected value for more that two options.

Change URL parameters

you can do it via normal JS also

var url = document.URL
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var aditionalURL = tempArray[1]; 
var temp = "";
if(aditionalURL)
{
var tempArray = aditionalURL.split("&");
for ( var i in tempArray ){
    if(tempArray[i].indexOf("rows") == -1){
            newAdditionalURL += temp+tempArray[i];
                temp = "&";
            }
        }
}
var rows_txt = temp+"rows=10";
var finalURL = baseURL+"?"+newAdditionalURL+rows_txt;

adding 30 minutes to datetime php/mysql

MySQL has a function called ADDTIME for adding two times together - so you can do the whole thing in MySQL (provided you're using >= MySQL 4.1.3).

Something like (untested):

SELECT * FROM my_table WHERE ADDTIME(endTime + '0:30:00') < CONVERT_TZ(NOW(), @@global.time_zone, 'GMT')

how to list all sub directories in a directory

Easy as this:

string[] folders = System.IO.Directory.GetDirectories(@"C:\My Sample Path\","*", System.IO.SearchOption.AllDirectories);

How do I put all required JAR files in a library folder inside the final JAR file with Maven?

The executable packer maven plugin can be used for exactly that purpose: creating standalone java applications containing all dependencies as JAR files in a specific folder.

Just add the following to your pom.xml inside the <build><plugins> section (be sure to replace the value of mainClass accordingly):

<plugin>
    <groupId>de.ntcomputer</groupId>
    <artifactId>executable-packer-maven-plugin</artifactId>
    <version>1.0.1</version>
    <configuration>
        <mainClass>com.example.MyMainClass</mainClass>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>pack-executable-jar</goal>
            </goals>
        </execution>
    </executions>
</plugin>

The built JAR file is located at target/<YourProjectAndVersion>-pkg.jar after you run mvn package. All of its compile-time and runtime dependencies will be included in the lib/ folder inside the JAR file.

Disclaimer: I am the author of the plugin.

Put content in HttpResponseMessage object?

The easiest single-line solution is to use

return new HttpResponseMessage( HttpStatusCode.OK ) {Content =  new StringContent( "Your message here" ) };

For serialized JSON content:

return new HttpResponseMessage( HttpStatusCode.OK ) {Content =  new StringContent( SerializedString, System.Text.Encoding.UTF8, "application/json" ) };

How to make a promise from setTimeout

const setTimeoutAsync = (cb, delay) =>
  new Promise((resolve) => {
    setTimeout(() => {
      resolve(cb());
    }, delay);
  });

We can pass custom 'cb fxn' like this one

How to access form methods and controls from a class in C#?

If the form starts up first, in the form Load handler we can instantiate a copy of our class. We can have properties that reference whichever controls we want to reference. Pass the reference to the form 'this' to the constructor for the class.

public partial class Form1 : Form
{
    public ListView Lv
    {
        get { return lvProcesses; }
    }

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Utilities ut = new Utilities(this);
    }
}

In your class, the reference from the form is passed into the constructor and stored as a private member. This form reference can be used to access the form's properties.

class Utilities
{
    private Form1 _mainForm;
    public Utilities(Form1 mainForm)
    {
        _mainForm = mainForm;
        _mainForm.Lv.Items.Clear();
    }
}

How to list the size of each file and directory and sort by descending size in Bash?

Command

du -h --max-depth=0 * | sort -hr

Output

3,5M    asdf.6000.gz
3,4M    asdf.4000.gz
3,2M    asdf.2000.gz
2,5M    xyz.PT.gz
136K    xyz.6000.gz
116K    xyz.6000p.gz
88K test.4000.gz
76K test.4000p.gz
44K test.2000.gz
8,0K    desc.common.tcl
8,0K    wer.2000p.gz
8,0K    wer.2000.gz
4,0K    ttree.3

Explanation

  • du displays "disk usage"
  • h is for "human readable" (both, in sort and in du)
  • max-depth=0 means du will not show sizes of subfolders (remove that if you want to show all sizes of every file in every sub-, subsub-, ..., folder)
  • r is for "reverse" (biggest file first)

ncdu

When I came to this question, I wanted to clean up my file system. The command line tool ncdu is way better suited to this task.

Installation on Ubuntu:

$ sudo apt-get install ncdu

Usage:

Just type ncdu [path] in the command line. After a few seconds for analyzing the path, you will see something like this:

$ ncdu 1.11 ~ Use the arrow keys to navigate, press ? for help
--- / ---------------------------------------------------------
.  96,1 GiB [##########] /home
.  17,7 GiB [#         ] /usr
.   4,5 GiB [          ] /var
    1,1 GiB [          ] /lib
  732,1 MiB [          ] /opt
. 275,6 MiB [          ] /boot
  198,0 MiB [          ] /storage
. 153,5 MiB [          ] /run
.  16,6 MiB [          ] /etc
   13,5 MiB [          ] /bin
   11,3 MiB [          ] /sbin
.   8,8 MiB [          ] /tmp
.   2,2 MiB [          ] /dev
!  16,0 KiB [          ] /lost+found
    8,0 KiB [          ] /media
    8,0 KiB [          ] /snap
    4,0 KiB [          ] /lib64
e   4,0 KiB [          ] /srv
!   4,0 KiB [          ] /root
e   4,0 KiB [          ] /mnt
e   4,0 KiB [          ] /cdrom
.   0,0   B [          ] /proc
.   0,0   B [          ] /sys
@   0,0   B [          ]  initrd.img.old
@   0,0   B [          ]  initrd.img
@   0,0   B [          ]  vmlinuz.old
@   0,0   B [          ]  vmlinuz

Delete the currently highlighted element with d, exit with CTRL + c

What does the star operator mean, in a function call?

In a function call the single star turns a list into seperate arguments (e.g. zip(*x) is the same as zip(x1,x2,x3) if x=[x1,x2,x3]) and the double star turns a dictionary into seperate keyword arguments (e.g. f(**k) is the same as f(x=my_x, y=my_y) if k = {'x':my_x, 'y':my_y}.

In a function definition it's the other way around: the single star turns an arbitrary number of arguments into a list, and the double start turns an arbitrary number of keyword arguments into a dictionary. E.g. def foo(*x) means "foo takes an arbitrary number of arguments and they will be accessible through the list x (i.e. if the user calls foo(1,2,3), x will be [1,2,3])" and def bar(**k) means "bar takes an arbitrary number of keyword arguments and they will be accessible through the dictionary k (i.e. if the user calls bar(x=42, y=23), k will be {'x': 42, 'y': 23})".

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

Yes, installing previous a version of numpy solved the problem.

For those who uses PyCharm IDE:

in my IDE (Pycharm), File->Settings->Project Interpreter: I found my numpy to be 1.16.3, so I revert back to 1.16.1. Click + and type numpy in the search, tick "specify version" : 1.16.1 and choose--> install package.

Convert command line arguments into an array in Bash

Side-by-side view of how the array and $@ are practically the same.

Code:

#!/bin/bash

echo "Dollar-1 : $1"
echo "Dollar-2 : $2"
echo "Dollar-3 : $3"
echo "Dollar-AT: $@"
echo ""

myArray=( "$@" )

echo "A Val 0: ${myArray[0]}"
echo "A Val 1: ${myArray[1]}"
echo "A Val 2: ${myArray[2]}"
echo "A All Values: ${myArray[@]}"

Input:

./bash-array-practice.sh 1 2 3 4

Output:

Dollar-1 : 1
Dollar-2 : 2
Dollar-3 : 3
Dollar-AT: 1 2 3 4

A Val 0: 1
A Val 1: 2
A Val 2: 3
A All Values: 1 2 3 4

How can I convert a Timestamp into either Date or DateTime object?

java.sql.Timestamp is a subclass of java.util.Date. So, just upcast it.

Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");

Using SimpleDateFormat and creating Joda DateTime should be straightforward from this point on.

How do I remove the space between inline/inline-block elements?

I had this problem right now and from font-size:0; I've found that in Internet Explorer 7 the problem remains because Internet Explorer thinks "Font Size 0?!?! WTF are you crazy man?" - So, in my case I've Eric Meyer's CSS reset and with font-size:0.01em; I have a difference of 1 pixel from Internet Explorer 7 to Firefox 9, so, I think this can be a solution.

Where does PHP store the error log? (php5, apache, fastcgi, cpanel)

Linux

php --info | grep error 

The terminal will output the error log location.

Windows

php --info | findstr /r /c:"error_log"

The command prompt will output the error log location

To set the log location

Open your php.ini and add the following line:

error_log = /log/myCustomLog.log

Thanks @chelmertez, @Boom for these (comments on the question).

Cannot install node modules that require compilation on Windows 7 x64/VS2012

To do it without VS2010 installation, and only 2012, set the msvs_version flag:

node-gyp rebuild --msvs_version=2012

npm install <module> --msvs_version=2012

as per @Jacob comment

npm install --msvs_version=2013 if you have the 2013 version

Cast Int to enum in Java

You can iterate over values() of enum and compare integer value of enum with given id like below:

public enum  TestEnum {
    None(0),
    Value1(1),
    Value2(2),
    Value3(3),
    Value4(4),
    Value5(5);

    private final int value;
    private TestEnum(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public static TestEnum  getEnum(int value){
        for (TestEnum e:TestEnum.values()) {
            if(e.getValue() == value)
                return e;
        }
        return TestEnum.None;//For values out of enum scope
    }
}

And use just like this:
TestEnum x = TestEnum.getEnum(4);//Will return TestEnum.Value4
I hope this helps ;)

Limit text length to n lines using CSS

As far as I can see, this would be possible only using height: (some em value); overflow: hidden and even then it wouldn't have the fancy ... at the end.

If that is not an option, I think it's impossible without some server side pre-processing (difficult because text flow is impossible to predict reliably) or jQuery (possible but probably complicated).

What datatype should be used for storing phone numbers in SQL Server 2005?

Use SSIS to extract and process the information. That way you will have the processing of the XML files separated from SQL Server. You can also do the SSIS transformations on a separate server if needed. Store the phone numbers in a standard format using VARCHAR. NVARCHAR would be unnecessary since we are talking about numbers and maybe a couple of other chars, like '+', ' ', '(', ')' and '-'.

remote rejected master -> master (pre-receive hook declined)

I got the same error when I ran git status :

$ git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)
nothing to commit, working directory clean

To fix it I can run:

$ git push and run 
$ git push heroku master

How do I create a master branch in a bare Git repository?

A branch is just a reference to a commit. Until you commit anything to the repository, you don't have any branches. You can see this in a non-bare repository as well.

$ mkdir repo
$ cd repo
$ git init
Initialized empty Git repository in /home/me/repo/.git/
$ git branch
$ touch foo
$ git add foo
$ git commit -m "new file"
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 foo
$ git branch
* master