Programs & Examples On #Cc

cc is a common name for a C compiler executable or driver. It is the default for the $(CC) make variable. For email CC fields, please use [carbon-copy]. For Adobe CC, use [creative-cloud].

How to implement a simple scenario the OO way

The Chapter object should have reference to the book it came from so I would suggest something like chapter.getBook().getTitle();

Your database table structure should have a books table and a chapters table with columns like:

books

  • id
  • book specific info
  • etc

chapters

  • id
  • book_id
  • chapter specific info
  • etc

Then to reduce the number of queries use a join table in your search query.

How to make a variable accessible outside a function?

Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.

You have to nest the requests:

$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   obj = name;   // sID is only now available!   sID = obj.id;   console.log(sID); }); 


Clean up your code!

  • Put the second request into a function
  • and let it accept sID as a parameter, so you don't have to declare it globally anymore! (Global variables are almost always evil!)
  • Remove sID and obj variables - name.id is sufficient unless you really need the other variables outside the function.


$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   // We don't need sID or obj here - name.id is sufficient   console.log(name.id);    doSecondRequest(name.id); });  /// TODO Choose a better name function doSecondRequest(sID) {   $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){         console.log(stats);   }); } 

Hapy New Year :)

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

python variable NameError

I would approach it like this:

sizes = [100, 250] print "How much space should the random song list occupy?" print '\n'.join("{0}. {1}Mb".format(n, s)                 for n, s in enumerate(sizes, 1)) # present choices choice = int(raw_input("Enter choice:")) # throws error if not int size = sizes[0] # safe starting choice if choice in range(2, len(sizes) + 1):     size = sizes[choice - 1] # note index offset from choice print "You  want to create a random song list that is {0}Mb.".format(size) 

You could also loop until you get an acceptable answer and cover yourself in case of error:

choice = 0 while choice not in range(1, len(sizes) + 1): # loop     try: # guard against error         choice = int(raw_input(...))     except ValueError: # couldn't make an int         print "Please enter a number"         choice = 0 size = sizes[choice - 1] # now definitely valid 

Pass PDO prepared statement to variables

Instead of using ->bindParam() you can pass the data only at the time of ->execute():

$data = [   ':item_name' => $_POST['item_name'],   ':item_type' => $_POST['item_type'],   ':item_price' => $_POST['item_price'],   ':item_description' => $_POST['item_description'],   ':image_location' => 'images/'.$_FILES['file']['name'],   ':status' => 0,   ':id' => 0, ];  $stmt->execute($data); 

In this way you would know exactly what values are going to be sent.

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

Accessing AppDelegate from framework?

If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?

OS X Sprite Kit Game Optimal Default Window Size

You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.

Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.

You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.

The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.

You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.

Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.

But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).

You should provide @2x images for the Retina Macbook Pro and future Retina Macs.

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.

Intermediate language used in scalac?

maybe this will help you out:

http://lampwww.epfl.ch/~paltherr/phd/altherr-phd.pdf

or this page:

www.scala-lang.org/node/6372‎

Why there is this "clear" class before footer?

Most likely, as mentioned by others, it is a class carrying the css values:

.clear{clear: both;} 

in order to prevent any more page elements from extending into the footer element. It is a quick and easy way of making sure that pages with columns of varying heights don't cause the footer to render oddly, by possibly setting its top position at the end of a shorter column.

In many cases it is not necessary, but if you are using best-practice standards it is a good idea to use, if you are floating page elements left and right. It functions with page elements similar to the way a horizontal rule works with text, to ensure proper and complete sepperation.

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

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     } } 

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

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

NumberFormatException invoke when you ll try to convert inavlid String for eg:"abc" value to integer..

this is valid string is eg"123". in your case split by space..

split(" "); will split line by " " by space..

How is VIP swapping + CNAMEs better than IP swapping + A records?

A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.

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; 

Image steganography that could survive jpeg compression

Quite a few applications seem to implement Steganography on JPEG, so it's feasible:

http://www.jjtc.com/Steganography/toolmatrix.htm

Here's an article regarding a relevant algorithm (PM1) to get you started:

http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1

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.

Laravel 4 with Sentry 2 add user to a group on Registration

Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.

Do you have this:

use Cartalyst\Sentry\Sentry; 

In your code?

Ok, but if this line is working for you:

$user = $this->sentry->register(array(     'username' => e($data['username']),     'email' => e($data['email']),      'password' => e($data['password'])     )); 

So you already have it instantiated and you can surely do:

$adminGroup = $this->sentry->findGroupById(5); 

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.

How do I show a message in the foreach loop?

You are looking to see if a single value is in an array. Use in_array.

However note that case is important, as are any leading or trailing spaces. Use var_dump to find out the length of the strings too, and see if they fit.

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Xcode 12

Removing VALID_ARCH from Build settings under User-Defined group work for me.

enter image description here

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

I solved the same issue by following steps:

Check the angular version: Using command: ng version My angular version is: Angular CLI: 7.3.10

After that I have support version of ngx bootstrap from the link: https://www.npmjs.com/package/ngx-bootstrap

In package.json file update the version: "bootstrap": "^4.5.3", "@ng-bootstrap/ng-bootstrap": "^4.2.2",

Now after updating package.json, use the command npm update

After this use command ng serve and my error got resolved

TS1086: An accessor cannot be declared in ambient context

I got the same issue when adding @angular/flex-layout to my Angular 8 project now with

`npm install @angular/flex-layout --save`.

This since now that command installed the major 9th version of the flex-layout package. Instead of upgrading everything else to the last version, I solved it by installing the last 8th major version of the package instead.

 npm install @angular/[email protected] --save

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

I solved this another way. First of all I installed cuda 10.1 toolkit from this link

Where i selected installer type(exe(local)) and installed 10.1 in custom mode means (without visual studio integration, NVIDIA PhysX because previously I installed CUDA 10.2 so required dependencies were installed automatically)

After installation, From the Following Path (C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin) , in my case, I copied 'cudart64_101.dll' file and pasted in (C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.2\bin).

Then importing Tensorflow worked smoothly.

N.B. Sorry for Bad English

Message: Trying to access array offset on value of type null

This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

Template not provided using create-react-app

Clear your npm cache first then use yarn as follows:

  • npm cache clean --force
  • npm cache verify
  • yarn create react-app my-app

I hope this helps.

EDIT

...you might want to try the following after I have looked into this problem further:

  1. npm uninstall -g create-react-app
  2. yarn global remove create-react-app
  3. which create-react-app - If it returns something (e.g. /usr/local/bin/create-react-app), then do a rm -rf /usr/local/bin/create-react-app to delete manually.
  4. npm cache clean --force
  5. npm cache verify
  6. npx create-react-app@latest

These steps should remove globally installed create-react-app installs, you then manually remove the old directories linked to the old globally installed create-react-app scripts. It's then a good idea to clear your npm cache to ensure your not using any old cached versions of create-react-app. Lastly create a new reactjs app with the @latest option like so: npx create-react-app@latest. There has been much confusion on this issue where no template is created when using npx create-react-app, if you follow the steps I have stated above (1-6) then I hope you'll have success.

p.s.

If I wanted to then create a react app in a directory called client then I would type the following command into the terminal:

npx create-react-app@latest ./client

Good luck.

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;
}

SyntaxError: Cannot use import statement outside a module

Recently have the issue. The fix which work for me was to added this to babel.config.json in the plugins section

["@babel/plugin-transform-modules-commonjs", {
    "allowTopLevelThis": true,
    "loose": true,
    "lazy": true
  }],

I had some imported module with // and the error "cannot use import outside a module".

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

I have been experiencing this problem for the last week now as I've been trying to send DELETE requests to my PHP server through AJAX. I recently upgraded my hosting plan where I now have an SSL Certificate on my host which stores the PHP and JS files. Since adding an SSL Certificate I no longer experience this issue. Hoping this helps with this strange error.

Has been compiled by a more recent version of the Java Runtime (class file version 57.0)

I also encountered similar problem which is asked here. The issue was that some applications come with their own JRE and sometimes the installed JDK appears at lower priority level in environment path. Now there are two options:

  1. Uninstall the other application which has their own JDK/JRE.
  2. Sometimes it is not possible to remove the other application, which was my case. So I moved JDk installed by me to higher priority level in environment path.

enter image description here

I also removed the path as suggested by @CrazyCoder

Why powershell does not run Angular commands?

I solved my problem by running below command

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

A failure occurred while executing com.android.build.gradle.internal.tasks

I got an stacktrace similar to yours only when building to Lollipop or Marshmallow, and the solution was to disable Advanved profiling.

Find it here:

Run -> Edit Configurations -> Profiling -> Enable advanced profiling

https://stackoverflow.com/a/58029739/860488

error: This is probably not a problem with npm. There is likely additional logging output above

Delete node_module directory and run below in command line

rm -rf node_modules
rm package-lock.json yarn.lock
npm cache clear --force
npm install

If still not working, try below

npm install webpack --save

How to prevent Google Colab from disconnecting?

var startColabHandler = function startColabHandler(interval = 60000, enableConnectButton = false) {
    console.log("colabHandler - configure - start: " + new Date());
    
    var colabClick = function colabClick() {
        console.log("colabHandler - click - start: " + new Date());
        
        if (enableConnectButton === true) {
            var button1 = document.querySelector("#top-toolbar > colab-connect-button").shadowRoot.querySelector("#connect");
            
            if (button1) {
                button1.click()
            }
        }
        
        button2 = document.querySelector("html body colab-dialog.yes-no-dialog paper-dialog div.buttons paper-button#ok");
        
        if (button2) {
            button2.click()
        }
        
        console.log("colabHandler - click - end: " + new Date());
    };

    var intervalId = setInterval(colabClick, interval);

    window.stopColabHandler = function stopColabHandler() {
        console.log("colabHandler - stop - start: " + new Date());
        
        clearInterval(intervalId);
        
        console.log("colabHandler - stop - start: " + new Date());
    };

    console.log("colabHandler - configure - end: " + new Date());
};

"Permission Denied" trying to run Python on Windows 10

Workaround: If you have installed python from exe follow below steps.

Step 1: Uninstall python

Step 2: Install python and check Python path check box as highlighted in below screentshot(yellow).

This solved me the problem.

enter image description here

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

For anyone struggling with similar cases

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

trying to use it with simple objects (used as dicts) like:

DNATranscriber = {
   G:"C",
   C: "G",
   T: "A",
   A: "U"
}

and trying to dynamically access the value from a calculated key like:

const key = getFirstType(dnaChain);
const result = DNATranscriber[key];

and you faced the error as shown above, you can use the keyof operator and try something like

const key = getFirstType(dnaChain) as keyof typeof DNATranscriber;

certainly you will need a guard at the result but if it seems more intuitive than some custom types magic, it is ok.

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

You have to set the http header at the http response of your resource. So it needs to be set serverside, you can remove the "HTTP_OPTIONS"-header from your angular HTTP-Post request.

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

You are all good at Angular side even postman not raise the cors policy issue. This type of issue is solved at back-end side in major cases.

If you are using Spring boot the you can avoid this issue by placing this annotation at your controller class or at any particular method.

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

In case of global configuration with spring boot configure following two class:

`

@EnableWebSecurity
@AllArgsConstructor

public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
    public void configure(HttpSecurity httpSecurity) throws Exception{
        httpSecurity.csrf().disable()
        .authorizeRequests()
        .antMatchers("/api1/**").permitAll()
        .antMatchers("/api2/**").permitAll()
        .antMatchers("/api3/**").permitAll()
        
}
`

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry corsRegistry) {
        corsRegistry.addMapping("/**")
                .allowedOrigins("http://localhost:4200")
                .allowedMethods("*")
                .maxAge(3600L)
                .allowedHeaders("*")
                .exposedHeaders("Authorization")
                .allowCredentials(true);
    }

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.

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>
)
}

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

There's no need to downgrade Chrome anymore, when you get this error only means it's time to run webdriver-manager update again

The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel

I've seen your code in web.php as follows: Route::post('/edit/{id}','ProjectController@update');

Step 1: remove the {id} random parameter so it would be like this: Route::post('/edit','ProjectController@update');

Step 2: Then remove the @method('PUT') in your form, so let's say we'll just plainly use the POST method

Then how can I pass the ID to my method?

Step 1: make an input field in your form with the hidden attribute for example

<input type="hidden" value="{{$project->id}}" name="id">

Step 2: in your update method in your controller, fetch that ID for example:

$id = $request->input('id');

then you may not use it to find which project to edit

$project = Project::find($id)
//OR
$project = Project::where('id',$id);

How to Install pip for python 3.7 on Ubuntu 18?

For those who intend to use venv:

If you don't already have pip for Python 3:

sudo apt install python3-pip

Install venv package:

sudo apt install python3.7-venv

Create virtual environment (which will be bootstrapped with pip by default):

python3.7 -m venv /path/to/new/virtual/environment

To activate the virtual environment, source the appropriate script for the current shell, from the bin directory of the virtual environment. The appropriate scripts for the different shells are:

bash/zsh – activate

fish – activate.fish

csh/tcsh – activate.csh

For example, if using bash:

source /path/to/new/virtual/environment/bin/activate

Optionally, to update pip for the virtual environment (while it is activated):

pip install --upgrade pip

When you want to deactivate the virtual environment:

deactivate 

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

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

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

You can use the NonNullable Utility Type:

Example

type T0 = NonNullable<string | number | undefined>;  // string | number
type T1 = NonNullable<string[] | null | undefined>;  // string[]

Docs.

How do I prevent Conda from activating the base environment by default?

One thing that hasn't been pointed out, is that there is little to no difference between not having an active environment and and activating the base environment, if you just want to run applications from Conda's (Python's) scripts directory (as @DryLabRebel wants).

You can install and uninstall via conda and conda shows the base environment as active - which essentially it is:

> echo $Env:CONDA_DEFAULT_ENV
> conda env list
# conda environments:
#
base                  *  F:\scoop\apps\miniconda3\current

> conda activate
> echo $Env:CONDA_DEFAULT_ENV
base
> conda env list
# conda environments:
#
base                  *  F:\scoop\apps\miniconda3\current

"Failed to install the following Android SDK packages as some licences have not been accepted" error

use android-28 with build-tools at version 28.0.3; or build-tools at version 26.0.3.

or try this: yes | sudo sdkmanager --licenses

Error: Java: invalid target release: 11 - IntelliJ IDEA

I added these two lines to build.gradle file

compileJava.options.fork = true
                                              
compileJava.options.forkOptions.executable = 'C:\\Program Files\\Java\\jdk-11.0.8'

and it works

I am using windows and my project based on gradle

my jdk path -> 'C:\Program Files\Java\jdk-11.0.8'

please provide your jdk path

WARNING in budgets, maximum exceeded for initial

Open angular.json file and find budgets keyword.

It should look like:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "2mb",
          "maximumError": "5mb"
       }
    ]

As you’ve probably guessed you can increase the maximumWarning value to prevent this warning, i.e.:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "4mb", <===
          "maximumError": "5mb"
       }
    ]

What does budgets mean?

A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.

In our case budget is the limit for bundle sizes.

See also:

Git fatal: protocol 'https' is not supported

There is something fishy going on. Probably a github bug that is not consistent (A/B testing?)

I am on windows10, using firefox. I have just copied a checkout URL and got an extra character. But only the first time. A second time it wasn't there. I had to look at my history file to see it!

here is my history:

git clone --recursive https://github.com/amzeratul/halley-template
git clone --recursive http://github.com/amzeratul/halley-template
git clone --recursive github.com/amzeratul/halley-template
git clone --recursive https://github.com/amzeratul/halley-template

the history command doesn't show the extra char. Just like it wasn't rendered when i was copy-pasting it into the terminal. You can see how i tried to remove the 's' and then the entire protocol? I was only triggered to investigate further when the backspace key moved one less character than i was expecting!

I saved my shell history file onto a machine with an hex editor and:

00000000  xx xx xx xx xx xx xx 0a  67 69 74 20 63 6c 6f 6e  |xxxxxxx.git clon|
00000010  65 20 2d 2d 72 65 63 75  72 73 69 76 65 20 c2 96  |e --recursive ..|
00000020  68 74 74 70 73 3a 2f 2f  67 69 74 68 75 62 2e 63  |https://github.c|
00000030  6f 6d 2f 61 6d 7a 65 72  61 74 75 6c 2f 68 61 6c  |om/amzeratul/hal|
00000040  6c 65 79 2d 74 65 6d 70  6c 61 74 65 0a 67 69 74  |ley-template.git|
00000050  20 2d 2d 68 65 6c 70 0a  67 69 74 20 75 70 64 61  | --help.git upda|
00000060  74 65 2d 67 69 74 2d 66  6f 72 2d 77 69 6e 64 6f  |te-git-for-windo|
00000070  77 73 0a 67 69 74 20 63  6c 6f 6e 65 20 2d 2d 72  |ws.git clone --r|
00000080  65 63 75 72 73 69 76 65  20 c2 96 68 74 74 70 73  |ecursive ..https|
00000090  3a 2f 2f 67 69 74 68 75  62 2e 63 6f 6d 2f 61 6d  |://github.com/am|
000000a0  7a 65 72 61 74 75 6c 2f  68 61 6c 6c 65 79 2d 74  |zeratul/halley-t|
000000b0  65 6d 70 6c 61 74 65 0a  63 75 72 6c 20 2d 2d 76  |emplate.curl --v|
000000c0  65 72 73 69 6f 6e 0a 63  64 20 63 6f 64 65 0a 67  |ersion.cd code.g|
000000d0  69 74 20 63 6c 6f 6e 65  20 2d 2d 72 65 63 75 72  |it clone --recur|
000000e0  73 69 76 65 20 c2 96 68  74 74 70 73 3a 2f 2f 67  |sive ..https://g|
000000f0  69 74 68 75 62 2e 63 6f  6d 2f 61 6d 7a 65 72 61  |ithub.com/amzera|
00000100  74 75 6c 2f 68 61 6c 6c  65 79 2d 74 65 6d 70 6c  |tul/halley-templ|
00000110  61 74 65 0a 67 69 74 20  63 6c 6f 6e 65 20 2d 2d  |ate.git clone --|
00000120  72 65 63 75 72 73 69 76  65 20 c2 96 68 74 74 70  |recursive ..http|
00000130  3a 2f 2f 67 69 74 68 75  62 2e 63 6f 6d 2f 61 6d  |://github.com/am|
00000140  7a 65 72 61 74 75 6c 2f  68 61 6c 6c 65 79 2d 74  |zeratul/halley-t|
00000150  65 6d 70 6c 61 74 65 0a  67 69 74 20 63 6c 6f 6e  |emplate.git clon|
00000160  65 20 2d 2d 72 65 63 75  72 73 69 76 65 20 67 69  |e --recursive gi|
00000170  74 68 75 62 2e 63 6f 6d  2f 61 6d 7a 65 72 61 74  |thub.com/amzerat|
00000180  75 6c 2f 68 61 6c 6c 65  79 2d 74 65 6d 70 6c 61  |ul/halley-templa|
00000190  74 65 0a 67 69 74 20 63  6c 6f 6e 65 20 2d 2d 72  |te.git clone --r|
000001a0  65 63 75 72 73 69 76 65  20 68 74 74 70 73 3a 2f  |ecursive https:/|
000001b0  2f 67 69 74 68 75 62 2e  63 6f 6d 2f 61 6d 7a 65  |/github.com/amze|
000001c0  72 61 74 75 6c 2f 68 61  6c 6c 65 79 2d 74 65 6d  |ratul/halley-tem|
000001d0  70 6c 61 74 65 0a                                 |plate.|
000001d6

There i a c2 96 char inserted before the url. No idea what that is. Is it not extended ASCII (where it would be –) and it was hidden from almost every place i pasted while it was on the clipboard. The closest i've found with this hex value would be https://www.fileformat.info/info/unicode/char/c298/index.htm but i didn't see the utf prefix anywhere (again, might have been lost)

This all might be misleading as I lost the page/clipboard and am working exclusively from the saved shell history file, which might very well be missing data from the original bug/malicious injection.

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

Depending on how you open your webpage, you may not be causing a mounting. Such as using a <Link/> back to a page that was already mounted in the virtual DOM, so requiring data from a componentDidMount lifecycle is caught.

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

.catch(error => { throw error}) is a no-op. It results in unhandled rejection in route handler.

As explained in this answer, Express doesn't support promises, all rejections should be handled manually:

router.get("/emailfetch", authCheck, async (req, res, next) => {
  try {
  //listing messages in users mailbox 
    let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
    emailFetch = emailFetch.data
    res.send(emailFetch)
  } catch (err) {
    next(err);
  }
})

HTTP Error 500.30 - ANCM In-Process Start Failure

I had the same error and the issue was with Microsoft.Extension.Primitives version of the package was not compatible with the .net core version. And this was referencing from one of the projects references from my project was referencing.

Once I had changed the Microsoft.Extension.Primitives in that project. This issue got fixed.

In the Azure event logs, check what error you are getting and if it is related to a package reference. Try the above thing that I have mentioned.

Since nuget packages are tightly coupled with the .net version. Just have to make sure all packages referencing to the project should also be tightly coupled with the .net version.

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

I upgraded my IntelliJ Version from 2018.1 to 2018.3.6. It works !

FlutterError: Unable to load asset

Flutter uses the pubspec.yaml file, located at the root of your project, to identify assets required by an app.

Here is an example:

flutter:
  assets:
    - assets/my_icon.png
    - assets/background.png

To include all assets under a directory, specify the directory name with the / character at the end:

flutter:
  assets:
    - directory/
    - directory/subdirectory/

For more info, see https://flutter.dev/docs/development/ui/assets-and-images

Pandas Merging 101

This post will go through the following topics:

  • Merging with index under different conditions
    • options for index-based joins: merge, join, concat
    • merging on indexes
    • merging on index of one, column of other
  • effectively using named indexes to simplify merging syntax

BACK TO TOP



Index-based joins

TL;DR

There are a few options, some simpler than others depending on the use case.

  1. DataFrame.merge with left_index and right_index (or left_on and right_on using names indexes)
    • supports inner/left/right/full
    • can only join two at a time
    • supports column-column, index-column, index-index joins
  2. DataFrame.join (join on index)
    • supports inner/left (default)/right/full
    • can join multiple DataFrames at a time
    • supports index-index joins
  3. pd.concat (joins on index)
    • supports inner/full (default)
    • can join multiple DataFrames at a time
    • supports index-index joins

Index to index joins

Setup & Basics

import pandas as pd
import numpy as np

np.random.seed([3, 14])
left = pd.DataFrame(data={'value': np.random.randn(4)}, 
                    index=['A', 'B', 'C', 'D'])    
right = pd.DataFrame(data={'value': np.random.randn(4)},  
                     index=['B', 'D', 'E', 'F'])
left.index.name = right.index.name = 'idxkey'

left
           value
idxkey          
A      -0.602923
B      -0.402655
C       0.302329
D      -0.524349

right
 
           value
idxkey          
B       0.543843
D       0.013135
E      -0.326498
F       1.385076

Typically, an inner join on index would look like this:

left.merge(right, left_index=True, right_index=True)

         value_x   value_y
idxkey                    
B      -0.402655  0.543843
D      -0.524349  0.013135

Other joins follow similar syntax.

Notable Alternatives

  1. DataFrame.join defaults to joins on the index. DataFrame.join does a LEFT OUTER JOIN by default, so how='inner' is necessary here.

     left.join(right, how='inner', lsuffix='_x', rsuffix='_y')
    
              value_x   value_y
     idxkey                    
     B      -0.402655  0.543843
     D      -0.524349  0.013135
    

    Note that I needed to specify the lsuffix and rsuffix arguments since join would otherwise error out:

     left.join(right)
     ValueError: columns overlap but no suffix specified: Index(['value'], dtype='object')
    

    Since the column names are the same. This would not be a problem if they were differently named.

     left.rename(columns={'value':'leftvalue'}).join(right, how='inner')
    
             leftvalue     value
     idxkey                     
     B       -0.402655  0.543843
     D       -0.524349  0.013135
    
  2. pd.concat joins on the index and can join two or more DataFrames at once. It does a full outer join by default, so how='inner' is required here..

     pd.concat([left, right], axis=1, sort=False, join='inner')
    
                value     value
     idxkey                    
     B      -0.402655  0.543843
     D      -0.524349  0.013135
    

    For more information on concat, see this post.


Index to Column joins

To perform an inner join using index of left, column of right, you will use DataFrame.merge a combination of left_index=True and right_on=....

right2 = right.reset_index().rename({'idxkey' : 'colkey'}, axis=1)
right2
 
  colkey     value
0      B  0.543843
1      D  0.013135
2      E -0.326498
3      F  1.385076

left.merge(right2, left_index=True, right_on='colkey')

    value_x colkey   value_y
0 -0.402655      B  0.543843
1 -0.524349      D  0.013135

Other joins follow a similar structure. Note that only merge can perform index to column joins. You can join on multiple columns, provided the number of index levels on the left equals the number of columns on the right.

join and concat are not capable of mixed merges. You will need to set the index as a pre-step using DataFrame.set_index.


Effectively using Named Index [pandas >= 0.23]

If your index is named, then from pandas >= 0.23, DataFrame.merge allows you to specify the index name to on (or left_on and right_on as necessary).

left.merge(right, on='idxkey')

         value_x   value_y
idxkey                    
B      -0.402655  0.543843
D      -0.524349  0.013135

For the previous example of merging with the index of left, column of right, you can use left_on with the index name of left:

left.merge(right2, left_on='idxkey', right_on='colkey')

    value_x colkey   value_y
0 -0.402655      B  0.543843
1 -0.524349      D  0.013135


Continue Reading

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

* you are here

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

The provided solution here is correct. However, the same error can also occur from a user error, where your endpoint request method is NOT matching the method your using when making the request.

For example, the server endpoint is defined with "RequestMethod.PUT" while you are requesting the method as POST.

Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code

I was able to resolve this error by remove file in Pods -> Targets Support Files -> Pods-AppName -> Pods-AppName-frameworks.sh. After removing that file again install pod using command pod install.

OR.

Try this:

-> quit xcode -> install pod(again) -> start xcode

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

On Ubuntu 18.04, I ran into this issue because the apt package for wheel does not include the wheel command. I think pip tries to import the wheel python package, and if that succeeds assumes that the wheel command is also available. Ubuntu breaks that assumption.

The apt python3 code package is named python3-wheel. This is installed automatically because python3-pip recommends it.

The apt python3 wheel command package is named python-wheel-common. Installing this too fixes the "failed building wheel" errors for me.

Set the space between Elements in Row Flutter

To make an exact spacing, I use Padding. An example with two images:

Row(
    mainAxisAlignment: MainAxisAlignment.spaceAround,
    children: <Widget>[
      Expanded(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Image.asset('images/user1.png'),
        ),
      ),
      Expanded(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Image.asset('images/user2.png'),
        ),
      )
    ],
  ),

A fatal error occurred while creating a TLS client credential. The internal error state is 10013

I found this here: https://port135.com/schannel-the-internal-error-state-is-10013-solved/

"Correct file permissions Correct the permissions on the c:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder:

Everyone Access: Special Applies to 'This folder only' Network Service Access: Read & Execute Applies to 'This folder, subfolders and files' Administrators Access: Full Control Applies to 'This folder, subfolder and files' System Access: Full control Applies to 'This folder, subfolder and Files' IUSR Access: Full Control Applies to 'This folder, subfolder and files' The internal error state is 10013 After these changes, restart the server. The 10013 errors should disappear."

Flutter: RenderBox was not laid out

I had a similir problem, but in my case, I put a row in the leading of the ListView, and it was consuming all the space, of course. I just had to take the Row out of the leading, and it was solved. I would recommend to check if the problem is a larger widget than its container can have.

Expanded(child:MyListView())

pod has unbound PersistentVolumeClaims

You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.

When using storageClass Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.


To solve your issue:

  • Provide a PersistentVolume fulfilling the constraints of the claim (a size >= 100Mi)
  • Remove the storageClass-line from the PersistentVolumeClaim
  • Remove the StorageClass from your cluster

How do these pieces play together?

At creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.

The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.

The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.

A PersistentVolume without StorageClass is considered to be static.

"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.


Example PersistentVolume

In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: ckan-pv-home
  labels:
    type: local
spec:
  capacity:
    storage: 100Mi
  hostPath:
    path: "/mnt/data/ckan"

The PersistentVolumeSpec allows us to define multiple attributes. I chose a hostPath volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.


Additional Resources:

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

Open Terminal:

install XCode developer tools and fix the problem.

$ xcode-select --install

Reset the path to Xcode if you have several versions:

$ xcode-select --switch /Applications/Xcode.app
$ xcode-select --switch /Library/Developer/CommandLineTools

Can't compile C program on a Mac after upgrade to Mojave

@JL Peyret is right!

if you macos 10.14.6 Mojave, Xcode 11.0+

then

cd /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs

sudo ln -s MacOSX.sdk/ MacOSX10.14.sdk

Xcode 10: A valid provisioning profile for this executable was not found

Open Keychain Access on your Mac and delete the old expired Apple Development certificates. This solved the issue for me.

Jenkins pipeline how to change to another folder

You can use the dir step, example:

dir("folder") {
    sh "pwd"
}

The folder can be relative or absolute path.

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');

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

I used this command and it worked:

python -m pip install --user --upgrade pip

How to scroll page in flutter

You can try CustomScrollView. Put your CustomScrollView inside Column Widget.

Just for example -

class App extends StatelessWidget {

 App({Key key}): super(key: key);

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
          title: const Text('AppBar'),
      ),
      body: new Container(
          constraints: BoxConstraints.expand(),
          decoration: new BoxDecoration(
            image: new DecorationImage(
              alignment: Alignment.topLeft,
              image: new AssetImage('images/main-bg.png'),
              fit: BoxFit.cover,
            )
          ),
          child: new Column(
            children: <Widget>[               
              Expanded(
                child: new CustomScrollView(
                  scrollDirection: Axis.vertical,
                  shrinkWrap: false,
                  slivers: <Widget>[
                    new SliverPadding(
                      padding: const EdgeInsets.symmetric(vertical: 0.0),
                      sliver: new SliverList(
                        delegate: new SliverChildBuilderDelegate(
                          (context, index) => new YourRowWidget(),
                          childCount: 5,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          )),
    );
  }
}

In above code I am displaying a list of items ( total 5) in CustomScrollView. YourRowWidget widget gets rendered 5 times as list item. Generally you should render each row based on some data.

You can remove decoration property of Container widget, it is just for providing background image.

Find the smallest positive integer that does not occur in a given sequence

package Consumer;


import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class codility {
public static void main(String a[])
    {
        int[] A = {1,9,8,7,6,4,2,3};
        int B[]= {-7,-5,-9};
        int C[] ={1,-2,3};
        int D[] ={1,2,3};
        int E[] = {-1};
        int F[] = {0};
        int G[] = {-1000000};
        System.out.println(getSmall(F));
    }
    public static int getSmall(int[] A)
    {
        int j=0;
        if(A.length < 1 || A.length > 100000) return -1;
        List<Integer> intList = Arrays.stream(A).boxed().sorted().collect(Collectors.toList());
         if(intList.get(0) < -1000000 || intList.get(intList.size()-1) > 1000000) return -1;
         if(intList.get(intList.size()-1) < 0) return 1;
        int count=0;         
         for(int i=1; i<=intList.size();i++)
         {
             if(!intList.contains(i))return i;
             count++;
         }
         if(count==intList.size()) return ++count;
        return -1;
    } 
}

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

Run the Gradle build with a command line argument --warning-mode=all to see what exactly the deprecated features are.

It will give you a detailed description of found issues with links to the Gradle docs for instructions how to fix your build.

Adding --stacktrace to that, you will also be able to pinpoint where the warning comes from, if it's triggered by outdated code in one of the plugins and not your build script.

Rounded Corners Image in Flutter

With new version of flutter and material theme u need to use the "Padding" widgett too in order to have an image that doesn't fill its container.

For example if you want to insert a rounded image in the AppBar u must use padding or your image will always be as high as the AppBar.

Hope this will help someone

InkWell(
        onTap: () {
            print ('Click Profile Pic');
        },
        child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: ClipOval(
                child: Image.asset(
                    'assets/images/profile1.jpg',
                ),
            ),
        ),
    ),

Best way to "push" into C# array

I don't think there is another way other than assigning value to that particular index of that array.

standard_init_linux.go:190: exec user process caused "no such file or directory" - Docker

in my case I had to change line ending from CRLF to LF for the run.sh file and the error was gone.

I hope this helps,
Kirsten

How to use mouseover and mouseout in Angular 6

To avoid blinking problem use following code
its not mouseover and mouseout instead of that use mouseenter and mouseleave


**app.component.html**

    <div (mouseenter)="changeText=true" (mouseleave)="changeText=false">
      <span *ngIf="!changeText">Hide</span>
      <span *ngIf="changeText">Show</span>
    </div>

**app.component.ts**

@Component({
   selector: 'app-main',
   templateUrl: './app.component.html'
})
export class AppComponent {
    changeText: boolean;
    constructor() {
       this.changeText = false;
    }
}

git clone: Authentication failed for <URL>

Rather than escape my password I left it out and was prompted for it, but only when I included the domain name before my username:

git clone https://some-dom-name\[email protected]/tfs/...

Xcode couldn't find any provisioning profiles matching

I am now able to successfully build. Not sure exactly which step "fixed" things, but this was the sequence:

  • Tried automatic signing again. No go, so reverted to manual.
  • After reverting, I had no Eligible Profiles, all were ineligible. Strange.
  • I created a new certificate and profile, imported both. This too was "ineligible".
  • Removed the iOS platform and re-added it. I had tried this previously without luck.
  • After doing this, Xcode on its own defaulted to automatic signing. And this worked! Success!

While I am not sure exactly which parts were necessary, I think the previous certificates were the problem. I hate Xcode :(

Thanks for help.

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

I had the same issue and tried all suggestions above, but didnt work out. I am posting my answer for furture readers. Before it was working fine but somehow it apeared again. I resolved this issue by removing some unnecessary plugnins and depencies from pom.xml

  1. First of all, I changed default packaging type to jar (Spring Boot Initializer gives pom in packaging)

    <packaging>jar</packaging>

  2. I added unintentional some plugins:

    <plugin> <artifactId>maven-war-plugin</artifactId> <configuration> <attachClasses>true</attachClasses> <webXml>target/web.xml</webXml> <webResources> <resource> <directory>src/main/webapp</directory> <filtering>true</filtering> </resource> </webResources> </configuration> </plugin>

I hope my answer will help someone.

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

You are calling:

JSON.parse(scatterSeries)

But when you defined scatterSeries, you said:

var scatterSeries = []; 

When you try to parse it as JSON it is converted to a string (""), which is empty, so you reach the end of the string before having any of the possible content of a JSON text.

scatterSeries is not JSON. Do not try to parse it as JSON.

data is not JSON either (getJSON will parse it as JSON automatically).

ch is JSON … but shouldn't be. You should just create a plain object in the first place:

var ch = {
    "name": "graphe1",
    "items": data.results[1]
};

scatterSeries.push(ch);

In short, for what you are doing, you shouldn't have JSON.parse anywhere in your code. The only place it should be is in the jQuery library itself.

Axios Delete request with body and headers?

For those who tried everything above and still don't see the payload with the request - make sure you have:

"axios": "^0.21.1" (not 0.20.0)

Then, the above solutions work

axios.delete("URL", {
      headers: {
        Authorization: `Bearer ${token}`,
      },
      data: {
        var1: "var1",
        var2: "var2"
      },
    })

You can access the payload with

req.body.var1, req.body.var2

Here's the issue:

https://github.com/axios/axios/issues/3335

Enable CORS in fetch api

Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors at your server side.

You can fetch request using mode: 'cors'. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.

So in both condition you need to configure cors in your server or you need to use custom proxy server.

Axios having CORS issue

I have encountered with same issue. When I changed content type it has solved. I'm not sure this solution will help you but maybe it is. If you don't mind about content-type, it worked for me.

axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';

Cross-Origin Read Blocking (CORB)

In a Chrome extension, you can use

chrome.webRequest.onHeadersReceived.addListener

to rewrite the server response headers. You can either replace an existing header or add an additional header. This is the header you want:

Access-Control-Allow-Origin: *

https://developers.chrome.com/extensions/webRequest#event-onHeadersReceived

I was stuck on CORB issues, and this fixed it for me.

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

Simple answer

If you are behind a proxy server, please set the proxy for curl. The curl is not able to connect to server so it shows wrong version number. Set proxy by opening subl ~/.curlrc or use any other text editor. Then add the following line to file: proxy= proxyserver:proxyport For e.g. proxy = 10.8.0.1:8080

If you are not behind a proxy, make sure that the curlrc file does not contain the proxy settings.

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

Have you tried not setting the responseType and just type casting the response?

This is what worked for me:

/**
 * Client for consuming recordings HTTP API endpoint.
 */
@Injectable({
  providedIn: 'root'
})
export class DownloadUrlClientService {
  private _log = Log.create('DownloadUrlClientService');


  constructor(
    private _http: HttpClient,
  ) {}

  private async _getUrl(url: string): Promise<string> {
    const httpOptions = {headers: new HttpHeaders({'auth': 'false'})};
    // const httpOptions = {headers: new HttpHeaders({'auth': 'false'}), responseType: 'text'};
    const res = await (this._http.get(url, httpOptions) as Observable<string>).toPromise();
    // const res = await (this._http.get(url, httpOptions)).toPromise();
    return res;
  }
}

Android design support library for API 28 (P) not working

Google has introduced new AndroidX dependencies. You need to migrate to AndroidX, it's simple.

I replaced all dependencies to AndroidX dependencies

Old design dependency

implementation 'com.android.support:design:28.0.0'

New AndroidX design dependency

implementation 'com.google.android.material:material:1.0.0-rc01'

you can find AndroidX dependencies here https://developer.android.com/jetpack/androidx/migrate


Automatic AndroidX migration option (supported on android studio 3.3+)

Migrate an existing project to use AndroidX by selecting Refactor > Migrate to AndroidX from the menu bar.

On npm install: Unhandled rejection Error: EACCES: permission denied

Restore ownership of the user's npm related folders, to the current user, like this:

sudo chown -R $USER:$GROUP ~/.npm
sudo chown -R $USER:$GROUP ~/.config

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.

from pandas import DataFrame, concat

a = DataFrame([{'a':1,      'c':2,'d':3      }])
b = DataFrame([{'a':4,'b':5,      'd':6,'e':7}])

>>> concat([a,b],sort=False)
   a    c  d    b    e
0  1  2.0  3  NaN  NaN
0  4  NaN  6  5.0  7.0

>>> concat([a,b],sort=True)
   a    b    c  d    e
0  1  NaN  2.0  3  NaN
0  4  5.0  NaN  6  7.0

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

I was using mlab.com as the MongoDB database. I separated the connection string to a different folder named config and inside file keys.js I kept the connection string which was:

_x000D_
_x000D_
module.exports = {_x000D_
  mongoURI: "mongodb://username:[email protected]:47267/projectname"_x000D_
};
_x000D_
_x000D_
_x000D_

And the server code was

_x000D_
_x000D_
const express = require("express");_x000D_
const mongoose = require("mongoose");_x000D_
const app = express();_x000D_
_x000D_
// Database configuration_x000D_
const db = require("./config/keys").mongoURI;_x000D_
_x000D_
// Connect to MongoDB_x000D_
_x000D_
mongoose_x000D_
  .connect(_x000D_
    db,_x000D_
    { useNewUrlParser: true } // Need this for API support_x000D_
  )_x000D_
  .then(() => console.log("MongoDB connected"))_x000D_
  .catch(err => console.log(err));_x000D_
_x000D_
app.get("/", (req, res) => res.send("hello!!"));_x000D_
_x000D_
const port = process.env.PORT || 5000;_x000D_
_x000D_
app.listen(port, () => console.log(`Server running on port ${port}`)); // Tilde, not inverted comma
_x000D_
_x000D_
_x000D_

You need to write { useNewUrlParser: true } after the connection string as I did above.

Simply put, you need to do:

_x000D_
_x000D_
mongoose.connect(connectionString,{ useNewUrlParser: true } _x000D_
// Or_x000D_
MongoClient.connect(connectionString,{ useNewUrlParser: true } _x000D_
    
_x000D_
_x000D_
_x000D_

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

I am using mysql 8.0.12 and updating the mysql connector to mysql-connector-java-8.0.12 resolved the issue for me.

Hope it helps somebody.

destination path already exists and is not an empty directory

I got same issue while using cygwin to install nvm

In fact, the target directory where empty but the git binary used was the one from windows (and not git from cygwin git package).

After installing cygwin git package, the git clone from nvm install was ok!

How to remove package using Angular CLI?

I don't know about CLI, I had tried, but I couldn't. I deleted using IDE Idea history.

If You use an Intellij Idea, just open History changes.

Tap by main folder of the project -> right click -> local history -> show history.

Then from top to bottom revert changes.

enter image description here

It should help! Good luck!=)

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

Setting up the Two-tone color:

As described above you can use the color css key except for materials Two-tone theme which seems to be glitchy ;-)

A workaround is described in one of several angular material github issue's by using a custom css filter. This custom filter can be generated here.

E.g.:

Html:

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Round|Material+Icons+Two+Tone|Material+Icons+Sharp">

<i class="material-icons-two-tone red">home</i>

css:

.red {
filter: invert(8%) sepia(94%) saturate(4590%) hue-rotate(358deg) brightness(101%) contrast(112%);
}

Attachments:

HTTP POST with Json on Body - Flutter/Dart

This works!

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;

Future<http.Response> postRequest () async {
  var url ='https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';

  Map data = {
    'apikey': '12345678901234567890'
  }
  //encode Map to JSON
  var body = json.encode(data);

  var response = await http.post(url,
      headers: {"Content-Type": "application/json"},
      body: body
  );
  print("${response.statusCode}");
  print("${response.body}");
  return response;
}

what is an illegal reflective access

If you want to go with the add-open option, here's a command to find which module provides which package ->

java --list-modules | tr @ " " | awk '{ print $1 }' | xargs -n1 java -d

the name of the module will be shown with the @ while the name of the packages without it

NOTE: tested with JDK 11

IMPORTANT: obviously is better than the provider of the package does not do the illegal access

How to set environment via `ng serve` in Angular 6

You can use command ng serve -c dev for development environment ng serve -c prod for production environment

while building also same applies. You can use ng build -c dev for dev build

Angular 5 Button Submit On Enter Key Press

In case anyone is wondering what input value

<input (keydown.enter)="search($event.target.value)" />

Set focus on <input> element

I'm having same scenario, this worked for me but i'm not having the "hide/show" feature you have. So perhaps you could first check if you get the focus when you have the field always visible, and then try to solve why does not work when you change visibility (probably that's why you need to apply a sleep or a promise)

To set focus, this is the only change you need to do:

your Html mat input should be:

<input #yourControlName matInput>

in your TS class, reference like this in the variables section (

export class blabla...
    @ViewChild("yourControlName") yourControl : ElementRef;

Your button it's fine, calling:

  showSearch(){
       ///blabla... then finally:
       this.yourControl.nativeElement.focus();
}

and that's it. You can check this solution on this post that I found, so thanks to --> https://codeburst.io/focusing-on-form-elements-the-angular-way-e9a78725c04f

Access IP Camera in Python OpenCV

In pycharm I wrote the code for accessing the IP Camera like:

import cv2

cap=VideoCapture("rtsp://user_name:password@IP_address:port_number")

ret, frame=cap.read()

You will need to replace user_name, password, IP and port with suitable values

Axios handling errors

If you want to gain access to the whole the error body, do it as shown below:

 async function login(reqBody) {
  try {
    let res = await Axios({
      method: 'post',
      url: 'https://myApi.com/path/to/endpoint',
      data: reqBody
    });

    let data = res.data;
    return data;
  } catch (error) {
    console.log(error.response); // this is the main part. Use the response property from the error object

    return error.response;
  }

}

How to develop Android app completely using python?

There are two primary contenders for python apps on Android

Chaquopy

https://chaquo.com/chaquopy/

This integrates with the Android build system, it provides a Python API for all android features. To quote the site "The complete Android API and user interface toolkit are directly at your disposal."

Beeware (Toga widget toolkit)

https://pybee.org/

This provides a multi target transpiler, supports many targets such as Android and iOS. It uses a generic widget toolkit (toga) that maps to the host interface calls.

Which One?

Both are active projects and their github accounts shows a fair amount of recent activity.

Beeware Toga like all widget libraries is good for getting the basics out to multiple platforms. If you have basic designs, and a desire to expand to other platforms this should work out well for you.

On the other hand, Chaquopy is a much more precise in its mapping of the python API to Android. It also allows you to mix in Java, useful if you want to use existing code from other resources. If you have strict design targets, and predominantly want to target Android this is a much better resource.

phpMyAdmin on MySQL 8.0

To fix this issue I just run one query in my mysql console.

For this login to mysql console using this

mysql -u {username} -p{password}

After this I just run one query as given below:-

ALTER user '{USERNAME}'@'localhost' identified with mysql_native_password by '{PASSWORD}';

when I run this query I got message that query executed. Then login to PHPMYADMIN with username/password.

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

Might have todo with one of these:

  1. Install a newer SDK.
  2. In .csproj check for Reference Include="netstandard"
  3. Check the assembly versions in the compilation tags in the Views\Web.config and Web.config.

AttributeError: Module Pip has no attribute 'main'

This helps me, https://pip.pypa.io/en/stable/installing/

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py

If you are using python3 and not set it default. do this,

python3 get-pip.py

It works for me.

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.

Error: Local workspace file ('angular.json') could not be found

I was getting the same error messages. It was a silly mistake on my end, I was not running ng serve in the directory where my Angular project is. Make sure you are in the correct directory (project directory) before running this command.

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

I had the same error and I solved it by importing HttpModule in app.module.ts

import { HttpModule } from '@angular/http';

and then in the imports[] array:

HttpModule

How to make flutter app responsive according to different screen size?

You can use responsive_helper package to make your app responsive.

It's a very easy method to make your app responsive. Just take a look at the example page and then you'll figure it out how to use it.

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

I had the same issue and I fixed it this way:

  1. Deleted all projects from eclipse, not from the computer.
  2. Created a new project and as soon as you write the name of your project, you get another window, in which is written: "Create module-info.java". I just clicked "don't create".
  3. Created a package. Let us call the package mywork.
  4. Created a Java class inside the package myWork. Let us call the class HelloWorld.
  5. I run the file normally and it was working fine.

Note: First, make sure that Java is running properly using the CMD command in that way you will understand the problem is on eclipse and not on JDK.

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

If it happens, then it means you have to upgrade your node.js. Simply uninstall your current node from your pc or mac and download the latest version from https://nodejs.org/en/

Unable to compile simple Java 10 / Java 11 project with Maven

It might not exactly be the same error, but I had a similar one.

Check Maven Java Version

Since Maven is also runnig with Java, check first with which version your Maven is running on:

mvn --version | grep -i java 

It returns:

Java version 1.8.0_151, vendor: Oracle Corporation, runtime: C:\tools\jdk\openjdk1.8

Incompatible version

Here above my maven is running with Java Version 1.8.0_151. So even if I specify maven to compile with Java 11:

<properties>
    <java.version>11</java.version>
    <maven.compiler.source>${java.version}</maven.compiler.source>
    <maven.compiler.target>${java.version}</maven.compiler.target>
</properties>

It will logically print out this error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.0:compile (default-compile) on project efa-example-commons-task: Fatal error compiling: invalid target release: 11 -> [Help 1]

How to set specific java version to Maven

The logical thing to do is to set a higher Java Version to Maven (e.g. Java version 11 instead 1.8).

Maven make use of the environment variable JAVA_HOME to find the Java Version to run. So change this variable to the JDK you want to compile against (e.g. OpenJDK 11).

Sanity check

Then run again mvn --version to make sure the configuration has been taken care of:

mvn --version | grep -i java

yields

Java version: 11.0.2, vendor: Oracle Corporation, runtime: C:\tools\jdk\openjdk11

Which is much better and correct to compile code written with the Java 11 specifications.

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

For me the problem was solved by restarting the docker daemon:

sudo systemctl restart docker

Pyspark: Filter dataframe based on multiple conditions

Your logic condition is wrong. IIUC, what you want is:

import pyspark.sql.functions as f

df.filter((f.col('d')<5))\
    .filter(
        ((f.col('col1') != f.col('col3')) | 
         (f.col('col2') != f.col('col4')) & (f.col('col1') == f.col('col3')))
    )\
    .show()

I broke the filter() step into 2 calls for readability, but you could equivalently do it in one line.

Output:

+----+----+----+----+---+
|col1|col2|col3|col4|  d|
+----+----+----+----+---+
|   A|  xx|   D|  vv|  4|
|   A|   x|   A|  xx|  3|
|   E| xxx|   B|  vv|  3|
|   F|xxxx|   F| vvv|  4|
|   G| xxx|   G|  xx|  4|
+----+----+----+----+---+

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

In case you do need to define dataSource(), for example when you have multiple data sources, you can use:

@Autowired Environment env;

@Primary
@Bean
public DataSource customDataSource() {

    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getProperty("custom.datasource.driver-class-name"));
    dataSource.setUrl(env.getProperty("custom.datasource.url"));
    dataSource.setUsername(env.getProperty("custom.datasource.username"));
    dataSource.setPassword(env.getProperty("custom.datasource.password"));

    return dataSource;

}

By setting up the dataSource yourself (instead of using DataSourceBuilder), it fixed my problem which you also had.

The always knowledgeable Baeldung has a tutorial which explains in depth.

Flutter: how to make a TextField with HintText but no Underline?

            Container(
         height: 50,
          // margin: EdgeInsets.only(top: 20),
          decoration: BoxDecoration(
              color: Colors.tealAccent,
              borderRadius: BorderRadius.circular(32)),
          child: TextFormField(
            cursorColor: Colors.black,
            // keyboardType: TextInputType.,
            decoration: InputDecoration(
              hintStyle: TextStyle(fontSize: 17),
              hintText: 'Search your trips',
              suffixIcon: Icon(Icons.search),
              border: InputBorder.none,
              contentPadding: EdgeInsets.all(18),
            ),
          ),
        ),

Want to upgrade project from Angular v5 to Angular v6

Upgrade from Angular v6 to Angular v7

Version 7 of Angular has been released Official Angular blog link. Visit official angular update guide https://update.angular.io for detailed information. These steps will work for basic angular 6 apps using Angular Material.

ng update @angular/cli 
ng update @angular/core
ng update @angular/material

Upgrade from Angular v5 to Angular v6

Version 6 of Angular has been released Official Angular blog link. I have mentioned general upgrade steps below, but before and after the update you need to make changes in your code to make it workable in v6, for that detailed information visit official website https://update.angular.io .

Upgrade Steps (largely taken from the official Angular Update Guide for a basic Angular app using Angular Material):

  1. Make sure NodeJS version is 8.9+ if not update it.

  2. Update Angular cli globally and locally, and migrate the old configuration .angular-cli.json to the new angular.json format by running the following:

    npm install -g @angular/cli  
    npm install @angular/cli  
    ng update @angular/cli
    
  3. Update all of your Angular framework packages to v6,and the correct version of RxJS and TypeScript by running the following:

    ng update @angular/core
    
  4. Update Angular Material to the latest version by running the following:

    ng update @angular/material
    
  5. RxJS v6 has major changes from v5, v6 brings backwards compatibility package rxjs-compat that will keep your applications working, but you should refactor TypeScript code so that it doesn't depend on rxjs-compat. To refactor TypeScript code run following:

    npm install -g rxjs-tslint   
    rxjs-5-to-6-migrate -p src/tsconfig.app.json
    

    Note: Once all of your dependencies have updated to RxJS 6, remove rxjs- compat as it increases bundle size. please see this RxJS Upgrade Guide for more info.

    npm uninstall rxjs-compat
    
  6. Done run ng serve to check it.
    If you get errors in build refer https://update.angular.io for detailed info.

Upgrade from Angular v5 to Angular 6.0.0-rc.5

  1. Upgrade rxjs to 6.0.0-beta.0, please see this RxJS Upgrade Guide for more info. RxJS v6 has breaking change hence first make your code compatible to latest RxJS version.

  2. Update NodeJS version to 8.9+ (this is required by angular cli 6 version)

  3. Update Angular cli global package to next version.

    npm uninstall -g @angular/cli
    npm cache verify
    

    if npm version is < 5 then use npm cache clean

    npm install -g @angular/cli@next
    
  4. Change angular packages versions in package.json file to ^6.0.0-rc.5

    "dependencies": {
      "@angular/animations": "^6.0.0-rc.5",
      "@angular/cdk": "^6.0.0-rc.12",
      "@angular/common": "^6.0.0-rc.5",
      "@angular/compiler": "^6.0.0-rc.5",
      "@angular/core": "^6.0.0-rc.5",
      "@angular/forms": "^6.0.0-rc.5",
      "@angular/http": "^6.0.0-rc.5",
      "@angular/material": "^6.0.0-rc.12",
      "@angular/platform-browser": "^6.0.0-rc.5",
      "@angular/platform-browser-dynamic": "^6.0.0-rc.5",
      "@angular/router": "^6.0.0-rc.5",
      "core-js": "^2.5.5",
      "karma-jasmine": "^1.1.1",
      "rxjs": "^6.0.0-uncanny-rc.7",
      "rxjs-compat": "^6.0.0-uncanny-rc.7",
      "zone.js": "^0.8.26"
    },
    "devDependencies": {
      "@angular-devkit/build-angular": "~0.5.0",
      "@angular/cli": "^6.0.0-rc.5",
      "@angular/compiler-cli": "^6.0.0-rc.5",
      "@types/jasmine": "2.5.38",
      "@types/node": "~8.9.4",
      "codelyzer": "~4.1.0",
      "jasmine-core": "~2.5.2",
      "jasmine-spec-reporter": "~3.2.0",
      "karma": "~1.4.1",
      "karma-chrome-launcher": "~2.0.0",
      "karma-cli": "~1.0.1",
      "karma-coverage-istanbul-reporter": "^0.2.0",
      "karma-jasmine": "~1.1.0",
      "karma-jasmine-html-reporter": "^0.2.2",
      "postcss-loader": "^2.1.4",
      "protractor": "~5.1.0",
      "ts-node": "~5.0.0",
      "tslint": "~5.9.1",
      "typescript": "^2.7.2"
    }
    
  5. Next update Angular cli local package to next version and install above mentioned packages.

    rm -rf node_modules dist # use rmdir /S/Q node_modules dist in Windows 
    Command Prompt; use rm -r -fo node_modules,dist in Windows PowerShell
    npm install --save-dev @angular/cli@next
    npm install 
    
  6. The Angular CLI configuration format has been changed from angular cli 6.0.0-rc.2 version, and your existing configuration can be updated automatically by running the following command. It will remove old config file .angular-cli.json and will write new angular.json file.

    ng update @angular/cli --migrate-only --from=1.7.4

Note :- If you get following error "The Angular Compiler requires TypeScript >=2.7.2 and <2.8.0 but 2.8.3 was found instead". run following command :

npm install [email protected]

Error: EACCES: permission denied, access '/usr/local/lib/node_modules'

After long research i understood that nothing is required for mac OS to install angular cli just use sudo npm install -g @angular/cli your terminal will prompt password enter your password it will proceed to install cli. It worked for me.

Could not find a version that satisfies the requirement tensorflow

1.Go to https://www.tensorflow.org/install/pip website and look if the version you are using support the Tensorflow. some latest version does not support Tesnsorflow. until Tensorflow releases its latest version for that Python version.

  1. you must have 64 bit python installed

  2. have latest version of pip installed
    pip install --upgrade pip

pull access denied repository does not exist or may require docker login

This error message might possibly indicate something else.

In my case I defined another Docker-Image elsewhere from which the current Docker inherited its settings (docker-compos.yml):

FROM my_own_image:latest

The error message I got:

qohelet$ docker-compose up
Building web
Step 1/22 : FROM my_own_image:latest
ERROR: Service 'web' failed to build: pull access denied for my_own_image, repository does not exist or may require 'docker login'

Due to a reinstall the previous Docker were gone and I couldn't build my docker using docker-compose up with this command:

sudo docker build -t my_own_image:latest -f MyOwnImage.Dockerfile .

In your specific case you might have defined your own php-docker.

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

I treid all the solutions mentioned here, but no luck. I found in my build.gradle file as below:

dependencies {
        classpath 'com.android.tools.build:gradle:3.3.0'
    }

I just changed it as below and saved and tried build success.

dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0'
    }

Dart SDK is not configured

Many answers here, but I believe most are missing the point.

You're running this command from a shell, and most if not all answers are related to running inside an IDE. There's a difference.

If you're using the shell to run your Dart / Flutter commands, make sure you've set up the environment variables necessary for the commands to know where to look for the right tools.

Personally, as I mostly work on a laptop, I've offloaded my main drive from all the space required by the development tools, moving everything to an external drive as described in this answer, so I have to tell the system where I've placed the various components.

Same goes for running commands from the command line vs. from an IDE, as an IDE can store this configuration, while the shell will not, unless you store it in the shell's startup files.

I use macOS, Homebrew and the ZShell, and I like to have the Dart SDK as a separate install, so I can track the DEV branch for Dart via Homebrew, while my Flutter install is using the BETA branch.

So, in my ~/.zprofile I have:

export HOMEBREW_PREFIX="$(brew --prefix)"

# Android / Java, Dart / Flutter related
export FLUTTER_ROOT="${SSD}/Lib/flutter" # Path to your main Flutter install
export DART_SDK="${HOMEBREW_PREFIX}/opt/dart/libexec" # Separate Dart SDK install
export JAVA_HOME="/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home" # JDK
export ANDROID_SDK_ROOT="${SSD}/Lib/android/sdk" # Top-level Android SDK directory
export ANDROID_HOME="${SSD}/Lib/android/sdk" # Same as above, needed by other tools I use
export ANDROID_AVD_HOME="${SSD}/Lib/android/avd" # Path to the moved emulators etc

Then I make sure that the $PATH variable is set up in the right order, so when I do Dart specific commands, the up-to-date Dart DEV branch is being used, while Flutter commands will use the Flutter BETA branch.

If you're using Zsh or Bash, add the additional paths at the end of .zshrc or .bashrc respectively, as these are called for every Terminal / Shell you start after login:

# Prepending to already established PATH

export PATH="\
/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/bin:\
${HOME}/.pub-cache/bin:\
${HOMEBREW_PREFIX}/opt/dart/libexec/bin:\
${SSD}/Lib/flutter/.pub-cache/bin:\
${SSD}/Lib/flutter/bin:\
${SSD}/Lib/android/sdk/platform-tools:\
${SSD}/Lib/android/sdk/tools/bin:\
${SSD}/Lib/android/sdk/emulator:\
${PATH}"

# If you're using Zsh, add this to clean up duplicate entries building up from running this 
# in every Terminal you launch:
# Remove duplicates from $PATH
typeset -aU path;

# Not sure, but in Bash, to remove duplicates you could do something like:
echo -n $PATH | awk -v RS=: '!($0 in a) {a[$0]; printf("%s%s", length(a) > 1 ? ":" : "", $0)}'

Now, that was a mouthful of stuff, but this is the way I maintain the order of operations...

Failed linking file resources

I know this question has been answered already, however, I still would like to add to what a lot has posted here for others having a similar but not specific problem.

This error sometimes also comes as “Android resource linking failed”. It is sometimes vague. The solution sometimes could be quite boring and painful but, this error is absolutely nothing serious.

In this case, the error is not Vague because Android Studio pointed to the problem file.

General Cause The error shows up when Gradle encounters an error (Usually a syntax or typo error) in one or more of your XML files.

Most of the XML files are located in the res folder, however, you might still find some outside the res folder. For example, the AndroidManifest.xml located in “/src/main/AndroidManifest.xml”. Here is an example of a layout file that would give the “Error: failed linking file resources” error.

Solution To solve this problem, all you have to do is go through each of your XML files to figure out where the error might be. This could sometimes be time-consuming but be rest assured that the error will disappear as soon as you find and fix the problem XML.

You might be lucky and Android Studio will point you in the exact direction just like the one asked in the question......

Other times like when you are using an older version of Android Studio, the error would not be this specific.

Here are some Tips to finding the problem XML quickly If you have a lot of XML files and it would be just too difficult to go through them one after the other, you could use the following tips to make the process easier:

Undo: Most times, you are already halfway through a project before you experience this issue. Meaning that it was a recent change to one of your XML files that caused the issue. If that is the case, you can try to undo your recent change to the XML files. To undo, simply use the key combination: Ctrl+Z.

Open every XML file: The second method involves simply opening every single XML file in your project (Without scanning). The reason for this is that sometimes, after opening the problem XML file, Android Studio then detects the error and underlines the exact line.

PackagesNotFoundError: The following packages are not available from current channels:

If your base conda environment is active...

  • in which case "(base)" will most probably show at the start or your terminal command prompt.

... and pip is installed in your base environment ...

  • which it is: $ conda list | grep pip

... then install the not-found package simply by $ pip install <packagename>

Bootstrap 4: responsive sidebar menu to top navbar

Big screen:

navigation side bar in big screen size

Small screen (Mobile)

sidebar in small mobile size screen

if this is what you wanted this is code https://plnkr.co/edit/PCCJb9f7f93HT4OubLmM?p=preview

CSS + HTML + JQUERY :

_x000D_
_x000D_
    _x000D_
    @import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700";_x000D_
    body {_x000D_
      font-family: 'Poppins', sans-serif;_x000D_
      background: #fafafa;_x000D_
    }_x000D_
    _x000D_
    p {_x000D_
      font-family: 'Poppins', sans-serif;_x000D_
      font-size: 1.1em;_x000D_
      font-weight: 300;_x000D_
      line-height: 1.7em;_x000D_
      color: #999;_x000D_
    }_x000D_
    _x000D_
    a,_x000D_
    a:hover,_x000D_
    a:focus {_x000D_
      color: inherit;_x000D_
      text-decoration: none;_x000D_
      transition: all 0.3s;_x000D_
    }_x000D_
    _x000D_
    .navbar {_x000D_
      padding: 15px 10px;_x000D_
      background: #fff;_x000D_
      border: none;_x000D_
      border-radius: 0;_x000D_
      margin-bottom: 40px;_x000D_
      box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);_x000D_
    }_x000D_
    _x000D_
    .navbar-btn {_x000D_
      box-shadow: none;_x000D_
      outline: none !important;_x000D_
      border: none;_x000D_
    }_x000D_
    _x000D_
    .line {_x000D_
      width: 100%;_x000D_
      height: 1px;_x000D_
      border-bottom: 1px dashed #ddd;_x000D_
      margin: 40px 0;_x000D_
    }_x000D_
    /* ---------------------------------------------------_x000D_
    SIDEBAR STYLE_x000D_
----------------------------------------------------- */_x000D_
    _x000D_
    #sidebar {_x000D_
      width: 250px;_x000D_
      position: fixed;_x000D_
      top: 0;_x000D_
      left: 0;_x000D_
      height: 100vh;_x000D_
      z-index: 999;_x000D_
      background: #7386D5;_x000D_
      color: #fff !important;_x000D_
      transition: all 0.3s;_x000D_
    }_x000D_
    _x000D_
    #sidebar.active {_x000D_
      margin-left: -250px;_x000D_
    }_x000D_
    _x000D_
    #sidebar .sidebar-header {_x000D_
      padding: 20px;_x000D_
      background: #6d7fcc;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul.components {_x000D_
      padding: 20px 0;_x000D_
      border-bottom: 1px solid #47748b;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul p {_x000D_
      color: #fff;_x000D_
      padding: 10px;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul li a {_x000D_
      padding: 10px;_x000D_
      font-size: 1.1em;_x000D_
      display: block;_x000D_
      color:white;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul li a:hover {_x000D_
      color: #7386D5;_x000D_
      background: #fff;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul li.active>a,_x000D_
    a[aria-expanded="true"] {_x000D_
      color: #fff;_x000D_
      background: #6d7fcc;_x000D_
    }_x000D_
    _x000D_
    a[data-toggle="collapse"] {_x000D_
      position: relative;_x000D_
    }_x000D_
    _x000D_
    a[aria-expanded="false"]::before,_x000D_
    a[aria-expanded="true"]::before {_x000D_
      content: '\e259';_x000D_
      display: block;_x000D_
      position: absolute;_x000D_
      right: 20px;_x000D_
      font-family: 'Glyphicons Halflings';_x000D_
      font-size: 0.6em;_x000D_
    }_x000D_
    _x000D_
    a[aria-expanded="true"]::before {_x000D_
      content: '\e260';_x000D_
    }_x000D_
    _x000D_
    ul ul a {_x000D_
      font-size: 0.9em !important;_x000D_
      padding-left: 30px !important;_x000D_
      background: #6d7fcc;_x000D_
    }_x000D_
    _x000D_
    ul.CTAs {_x000D_
      padding: 20px;_x000D_
    }_x000D_
    _x000D_
    ul.CTAs a {_x000D_
      text-align: center;_x000D_
      font-size: 0.9em !important;_x000D_
      display: block;_x000D_
      border-radius: 5px;_x000D_
      margin-bottom: 5px;_x000D_
    }_x000D_
    _x000D_
    a.download {_x000D_
      background: #fff;_x000D_
      color: #7386D5;_x000D_
    }_x000D_
    _x000D_
    a.article,_x000D_
    a.article:hover {_x000D_
      background: #6d7fcc !important;_x000D_
      color: #fff !important;_x000D_
    }_x000D_
    /* ---------------------------------------------------_x000D_
    CONTENT STYLE_x000D_
----------------------------------------------------- */_x000D_
    _x000D_
    #content {_x000D_
      width: calc(100% - 250px);_x000D_
      padding: 40px;_x000D_
      min-height: 100vh;_x000D_
      transition: all 0.3s;_x000D_
      position: absolute;_x000D_
      top: 0;_x000D_
      right: 0;_x000D_
    }_x000D_
    _x000D_
    #content.active {_x000D_
      width: 100%;_x000D_
    }_x000D_
    /* ---------------------------------------------------_x000D_
    MEDIAQUERIES_x000D_
----------------------------------------------------- */_x000D_
    _x000D_
    @media (max-width: 768px) {_x000D_
      #sidebar {_x000D_
        margin-left: -250px;_x000D_
      }_x000D_
      #sidebar.active {_x000D_
        margin-left: 0;_x000D_
      }_x000D_
      #content {_x000D_
        width: 100%;_x000D_
      }_x000D_
      #content.active {_x000D_
        width: calc(100% - 250px);_x000D_
      }_x000D_
      #sidebarCollapse span {_x000D_
        display: none;_x000D_
      }_x000D_
    }
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
  <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
_x000D_
  <title>Collapsible sidebar using Bootstrap 3</title>_x000D_
_x000D_
  <!-- Bootstrap CSS CDN -->_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <!-- Our Custom CSS -->_x000D_
  <link rel="stylesheet" href="style2.css">_x000D_
  <!-- Scrollbar Custom CSS -->_x000D_
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css">_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
_x000D_
_x000D_
  <div class="wrapper">_x000D_
    <!-- Sidebar Holder -->_x000D_
    <nav id="sidebar">_x000D_
      <div class="sidebar-header">_x000D_
        <h3>Header as you want </h3>_x000D_
        </h3>_x000D_
      </div>_x000D_
_x000D_
      <ul class="list-unstyled components">_x000D_
        <p>Dummy Heading</p>_x000D_
        <li class="active">_x000D_
          <a href="#menu">Animación</a>_x000D_
_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#menu">Ilustración</a>_x000D_
_x000D_
_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#menu">Interacción</a>_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#">Blog</a>_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#">Acerca</a>_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#">contacto</a>_x000D_
        </li>_x000D_
_x000D_
_x000D_
      </ul>_x000D_
_x000D_
_x000D_
    </nav>_x000D_
_x000D_
    <!-- Page Content Holder -->_x000D_
    <div id="content">_x000D_
_x000D_
      <nav class="navbar navbar-default">_x000D_
        <div class="container-fluid">_x000D_
_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" id="sidebarCollapse" class="btn btn-info navbar-btn">_x000D_
                                <i class="glyphicon glyphicon-align-left"></i>_x000D_
                                <span>Toggle Sidebar</span>_x000D_
                            </button>_x000D_
          </div>_x000D_
_x000D_
          <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
            <ul class="nav navbar-nav navbar-right">_x000D_
              <li><a href="#">Page</a></li>_x000D_
            </ul>_x000D_
          </div>_x000D_
        </div>_x000D_
      </nav>_x000D_
_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
  <!-- jQuery CDN -->_x000D_
  <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>_x000D_
  <!-- Bootstrap Js CDN -->_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
  <!-- jQuery Custom Scroller CDN -->_x000D_
  <script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>_x000D_
_x000D_
  <script type="text/javascript">_x000D_
    $(document).ready(function() {_x000D_
_x000D_
_x000D_
      $('#sidebarCollapse').on('click', function() {_x000D_
        $('#sidebar, #content').toggleClass('active');_x000D_
        $('.collapse.in').toggleClass('in');_x000D_
        $('a[aria-expanded=true]').attr('aria-expanded', 'false');_x000D_
      });_x000D_
    });_x000D_
  </script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

if this is what you want .

Issue in installing php7.2-mcrypt

I followed below steps to install mcrypt for PHP7.2 using PECL.

  1. Install PECL

apt-get install php-pecl

  1. Before installing MCRYPT you must install libmcrypt

apt-get install libmcrypt-dev libreadline-dev

  1. Install MCRYPT 1.0.1 using PECL

pecl install mcrypt-1.0.1

  1. After the successful installation

You should add "extension=mcrypt.so" to php.ini

Please comment below if you need any assistance. :-)

IMPORTANT !

According to php.net reference many (all) mcrypt functions have been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

An ECMAScript 6 answer that makes use of Symbols:

const a = {value: 1};
a[Symbol.toPrimitive] = function() { return this.value++ };
console.log((a == 1 && a == 2 && a == 3));

Due to == usage, JavaScript is supposed to coerce a into something close to the second operand (1, 2, 3 in this case). But before JavaScript tries to figure coercing on its own, it tries to call Symbol.toPrimitive. If you provide Symbol.toPrimitive JavaScript would use the value your function returns. If not, JavaScript would call valueOf.

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.

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

This has happened to me. My issue was caused when I didn't mount Docker file system correctly, so I configured the Disk Image Location and re-bind File sharing mount, and this now worked correctly. For reference, I use Docker Desktop in Windows.

How to access Anaconda command prompt in Windows 10 (64-bit)

To run Anaconda Prompt using icon, I made an icon and put

%windir%\System32\cmd.exe "/K" C:\ProgramData\Anaconda3\Scripts\activate.bat C:\ProgramData\Anaconda3 The file location would be different in each computer.

at icon -> right click -> Property -> Shortcut -> Target

I see %HOMEPATH% at icon -> right click -> Property -> Start in

OS: Windows 10, Library: Anaconda 10 (64 bit)

GitLab remote: HTTP Basic: Access denied and fatal Authentication

I tried with browser URL for the repository then

git clone $(browserURL)

it prompted for my username and then my password

It worked fine then

db.collection is not a function when using MongoClient v3.0

MongoDB queries return a cursor to an array stored in memory. To access that array's result you must call .toArray() at the end of the query.

  db.collection("customers").find({}).toArray() 

Exception : AAPT2 error: check logs for details

some symbols should be transferred like '%'

<string name="test" formatted="false">95%</string>

The type WebMvcConfigurerAdapter is deprecated

I have been working on Swagger equivalent documentation library called Springfox nowadays and I found that in the Spring 5.0.8 (running at present), interface WebMvcConfigurer has been implemented by class WebMvcConfigurationSupport class which we can directly extend.

import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

public class WebConfig extends WebMvcConfigurationSupport { }

And this is how I have used it for setting my resource handling mechanism as follows -

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
            .addResourceLocations("classpath:/META-INF/resources/");

    registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

regex match any single character (one character only)

Match any single character

  • Use the dot . character as a wildcard to match any single character.

Example regex: a.c

abc   // match
a c   // match
azc   // match
ac    // no match
abbc  // no match

Match any specific character in a set

  • Use square brackets [] to match any characters in a set.
  • Use \w to match any single alphanumeric character: 0-9, a-z, A-Z, and _ (underscore).
  • Use \d to match any single digit.
  • Use \s to match any single whitespace character.

Example 1 regex: a[bcd]c

abc   // match
acc   // match
adc   // match
ac    // no match
abbc  // no match

Example 2 regex: a[0-7]c

a0c   // match
a3c   // match
a7c   // match
a8c   // no match
ac    // no match
a55c  // no match

Match any character except ...

Use the hat in square brackets [^] to match any single character except for any of the characters that come after the hat ^.

Example regex: a[^abc]c

aac   // no match
abc   // no match
acc   // no match
a c   // match
azc   // match
ac    // no match
azzc  // no match

(Don't confuse the ^ here in [^] with its other usage as the start of line character: ^ = line start, $ = line end.)

Match any character optionally

Use the optional character ? after any character to specify zero or one occurrence of that character. Thus, you would use .? to match any single character optionally.

Example regex: a.?c

abc   // match
a c   // match
azc   // match
ac    // match
abbc  // no match

See also

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

I have added dataType: 'jsonp' and it works!

$.ajax({
   type: 'POST',
   crossDomain: true,
   dataType: 'jsonp',
   url: '',
   success: function(jsondata){

   }
})

JSONP is a method for sending JSON data without worrying about cross-domain issues. Read More

No provider for Http StaticInjectorError

In ionic 4.6 I use the following technique and it works. I am adding this answer so that if anybody is facing similar issues in newer ionic version app, it may help them.

i) Open app.module.ts and add the following code block to import HttpModule and HttpClientModule

import { HttpModule } from '@angular/http';
import {   HttpClientModule } from '@angular/common/http';

ii) In @NgModule import sections add below lines:

HttpModule,
HttpClientModule,

So, in my case @NgModule, looks like this:

@NgModule({
  declarations: [AppComponent ],
  entryComponents: [ ],
  imports: [
    BrowserModule,
    HttpModule,
    HttpClientModule,
    IonicModule.forRoot(),
    AppRoutingModule, 
  ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})

That's it!

Where to declare variable in react js

Assuming that onMove is an event handler, it is likely that its context is something other than the instance of MyContainer, i.e. this points to something different.

You can manually bind the context of the function during the construction of the instance via Function.bind:

class MyContainer extends Component {
  constructor(props) {
    super(props);

    this.onMove = this.onMove.bind(this);

    this.test = "this is a test";
  }

  onMove() {
    console.log(this.test);
  }
}

Also, test !== testVariable.

How to add CORS request in header in Angular 5

You can also try the fetch function and the no-cors mode. I sometimes find it easier to configure it than Angular's built-in http module. You can right-click requests in the Chrome Dev tools network tab and copy them in the fetch syntax, which is great.

import { from } from 'rxjs';

// ...

result = from( // wrap the fetch in a from if you need an rxjs Observable
  fetch(
    this.baseurl,
    {
      body: JSON.stringify(data)
      headers: {
        'Content-Type': 'application/json',
      },
      method: 'POST',
      mode: 'no-cors'
    }
  )
);

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

When I used policy before I set the default authentication scheme into it as well. I had modified the DefaultPolicy so it was slightly different. However the same should work for add policy as well.

services.AddAuthorization(options =>
        {
            options.AddPolicy(DefaultAuthorizedPolicy, policy =>
            {
                policy.Requirements.Add(new TokenAuthRequirement());
                policy.AuthenticationSchemes = new List<string>()
                                {
                                    CookieAuthenticationDefaults.AuthenticationScheme
                                }
            });
        });

Do take into consideration that by Default AuthenticationSchemes property uses a read only list. I think it would be better to implement that instead of List as well.

How can I fix "Design editor is unavailable until a successful build" error?

Edit you xml file in Notepad++ and build it again. It's work for me

CSS class for pointer cursor

UPDATE for Bootstrap 4 stable

The cursor: pointer; rule has been restored, so buttons will now by default have the cursor on hover:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">_x000D_
<button type="button" class="btn btn-success">Sample Button</button>
_x000D_
_x000D_
_x000D_


No, there isn't. You need to make some custom CSS for this.

If you just need a link that looks like a button (with pointer), use this:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">_x000D_
<a class="btn btn-success" href="#" role="button">Sample Button</a>
_x000D_
_x000D_
_x000D_

ReactJS and images in public folder

You don't need any webpack configuration for this..

In your component just give image path. By default react will know its in public directory.

<img src="/image.jpg" alt="image" />

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

This error was occurring for me in Firefox but not Chrome while developing locally, and it turned out to be caused by Firefox not trusting my local API's ssl certificate (which is not valid, but I had added it to my local cert store, which let chrome trust it but not ff). Navigating to the API directly and adding an exception in Firefox fixed the issue.

How to remove an unpushed outgoing commit in Visual Studio?

I fixed it in Github Desktop Application by pushing my changes.

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

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

What worked for me tho is this library https://pypi.org/project/silence-tensorflow/

Install this library and do as instructed on the page, it works like a charm!

groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding

As pointed out by @Jayan in another post, the solution was to do the following

import jenkins.model.*
jenkins = Jenkins.instance

Then I was able to do the rest of my scripting the way it was.

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

I had to do rake clean --force. Then did gem install rake and so forth.

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

fsevents is dealt differently in mac and other linux system. Linux system ignores fsevents whereas mac install it. As the above error message states that fsevents is optional and it is skipped in installation process.

You can run npm install --no-optional command in linux system to avoid above warning.

Further information

https://github.com/npm/npm/issues/14185

https://github.com/npm/npm/issues/5095

How to clear react-native cache?

Here's a great discussion on GitHub which helped me a lot. Clearing the Cache of your React Native Project by Jarret Moses

There are solutions for 4 different instances.

  1. RN <0.50 -
    watchman watch-del-all && rm -rf $TMPDIR/react-* && rm -rf node_modules/ && npm cache clean && npm install && npm start -- --reset-cache

  2. RN >=0.50 - watchman watch-del-all && rm -rf $TMPDIR/react-native-packager-cache-* && rm -rf $TMPDIR/metro-bundler-cache-* && rm -rf node_modules/ && npm cache clean && npm install && npm start -- --reset-cache

  3. NPM >=5 - watchman watch-del-all && rm -rf $TMPDIR/react-* && rm -rf node_modules/ && npm cache verify && npm install && npm start -- --reset-cache
  4. Windows - del %appdata%\Temp\react-native-* & cd android & gradlew clean & cd .. & del node_modules/ & npm cache clean --force & npm install & npm start -- --reset-cache

The solution is similar to Vikram Biwal's Answer.

And there is a discussion below in the given link, so even if the above 4 cases don't work for you, you can scroll through and find a possible solution.

How to set the color of an icon in Angular Material?

color="white" is not a known attribute to Angular Material.

color attribute can changed to primary, accent, and warn. as said in this doc

your icon inside button works because its parent class button has css class of color:white, or may be your color="accent" is white. check the developer tools to find it.

By default, icons will use the current font color

Codesign wants to access key "access" in your keychain, I put in my login password but keeps asking me

For me, I realized one of the dialogs was opened in another workspace. Once I discovered that and input my password there it went through.

How to change the project in GCP using CLI commands

For what its worth if you have a more than a handful of projects, which I do, use:

gcloud init

This will list all your projects and give you the option to change current project settings, add a new project configuration or switch:

Pick configuration to use:
 [1] Re-initialize this configuration [esqimo-preprod] with new settings
 [2] Create a new configuration
 [3] Switch to and re-initialize existing configuration: [default]
 [4] Switch to and re-initialize existing configuration: [project 1]
 [5] Switch to and re-initialize existing configuration: [project 2]
Please enter your numeric choice:

It will always ask you to login and display options for different google accounts that you may have.

Given that I manage multiple organisations and projects this approach lets' me to simply switch between them.

How to update an "array of objects" with Firestore?

Other than the answers mentioned above. This will do it. Using Angular 5 and AngularFire2. or use firebase.firestore() instead of this.afs

  // say you have have the following object and 
  // database structure as you mentioned in your post
  data = { who: "[email protected]", when: new Date() };

  ...othercode


  addSharedWith(data) {

    const postDocRef = this.afs.collection('posts').doc('docID');

    postDocRef.subscribe( post => {

      // Grab the existing sharedWith Array
      // If post.sharedWith doesn`t exsit initiated with empty array
      const foo = { 'sharedWith' : post.sharedWith || []};

      // Grab the existing sharedWith Array
      foo['sharedWith'].push(data);

      // pass updated to fireStore
      postsDocRef.update(foo);
      // using .set() will overwrite everything
      // .update will only update existing values, 
      // so we initiated sharedWith with empty array
    });
 }  

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

You can just use the datasource connect function

this.datasource.connect().next(data);

like so. 'data' being the new values for the datatable

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

Add this line to the file xampp\phpMyAdmin\config.inc:

$cfg['Servers'][$i]['port'] = '3307';

Here, my port is 3307, you can change it to yours.

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

You can use only junit-jupiter as a test dependency instead of junit-jupiter-api, junit-platform-launcher, junit-jupiter-engine.

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.5.2</version>
    <scope>test</scope>
</dependency>

Convert np.array of type float64 to type uint8 scaling values

A better way to normalize your image is to take each value and divide by the largest value experienced by the data type. This ensures that images that have a small dynamic range in your image remain small and they're not inadvertently normalized so that they become gray. For example, if your image had a dynamic range of [0-2], the code right now would scale that to have intensities of [0, 128, 255]. You want these to remain small after converting to np.uint8.

Therefore, divide every value by the largest value possible by the image type, not the actual image itself. You would then scale this by 255 to produced the normalized result. Use numpy.iinfo and provide it the type (dtype) of the image and you will obtain a structure of information for that type. You would then access the max field from this structure to determine the maximum value.

So with the above, do the following modifications to your code:

import numpy as np
import cv2
[...]
info = np.iinfo(data.dtype) # Get the information of the incoming image type
data = data.astype(np.float64) / info.max # normalize the data to 0 - 1
data = 255 * data # Now scale by 255
img = data.astype(np.uint8)
cv2.imshow("Window", img)

Note that I've additionally converted the image into np.float64 in case the incoming data type is not so and to maintain floating-point precision when doing the division.

react-router (v4) how to go back?

Try:

this.props.router.goBack()

How to sign in kubernetes dashboard?

If you don't want to grant admin permission to dashboard service account, you can create cluster admin service account.

$ kubectl create serviceaccount cluster-admin-dashboard-sa
$ kubectl create clusterrolebinding cluster-admin-dashboard-sa \
  --clusterrole=cluster-admin \
  --serviceaccount=default:cluster-admin-dashboard-sa

And then, you can use the token of just created cluster admin service account.

$ kubectl get secret | grep cluster-admin-dashboard-sa
cluster-admin-dashboard-sa-token-6xm8l   kubernetes.io/service-account-token   3         18m
$ kubectl describe secret cluster-admin-dashboard-sa-token-6xm8l

I quoted it from giantswarm guide - https://docs.giantswarm.io/guides/install-kubernetes-dashboard/

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

This is answered in the comments; package-lock.json is a feature in npm v5 and higher. npm shrinkwrap is how you create a lockfile in all versions of npm.

Angular - res.json() is not a function

HttpClient.get() applies res.json() automatically and returns Observable<HttpResponse<string>>. You no longer need to call this function yourself.

See Difference between HTTP and HTTPClient in angular 4?

Uncaught SyntaxError: Unexpected token u in JSON at position 0

I had this issue for 2 days, let me show you how I fixed it.

This was how the code looked when I was getting the error:

request.onload = function() {
    // This is where we begin accessing the Json
    let data = JSON.parse(this.response);
    console.log(data)
}

This is what I changed to get the result I wanted:

request.onload = function() {
    // This is where we begin accessing the Json
    let data = JSON.parse(this.responseText);
    console.log(data)
}

So all I really did was change this.response to this.responseText.

How to import cv2 in python3?

Make a virtual enviroment using python3

virtualenv env_name --python="python3"

and run the following command

pip3 install opencv-python

How to use switch statement inside a React component?

I was not absolutely happy with any of the answers. But I have picked up some ideas from @Matt Way.

Here is my solution:

Definitions:

const Switch = props => {
    const { test, children = null } = props;
    return children && children.find(child => child && child.props && child.props.casevalue === test) || null;
}

const Case = ({ casevalue = false, children = null }) => <div casevalue={`${casevalue}`}>{children}</div>;

Case.propTypes = {
    casevalue: PropTypes.string.isRequired,
    children: PropTypes.node.isRequired,
}

const Default = ({ children }) => children || <h1>NO_RESULT</h1>;

const SwitchCase = ({ test, cases = [], defaultValue = null }) => {

    const defaultVal = defaultValue
        && React.cloneElement(defaultValue, { key: 'default-key', casevalue: `${test}` })
        || <Default key='default-key' casevalue={`${test}`} />;

    return (
        <Switch test={`${test}`} >
            {
                cases.map((cas, i) => {
                    const { props = {} } = cas || {};
                    const { casevalue = false, ...rest } = props || {};

                    return <Case key={`case-key-${i}`} casevalue={`${casevalue}`}>{ React.cloneElement(cas, rest)}</Case>
                })
                .concat(defaultVal)
            }
        </Switch>
    );
}

Usage:

<SwitchCase
  cases={[
    <div casevalue={`${false}`}>#1</div>,
    <div casevalue={`${true}`}>#2</div>,
    <div casevalue={`${false}`}>#3</div>,
  ]}
  defaultValue={<h1>...nothing to see here</h1>} // You can leave it blank.
  test={`${true}`}
/>

firestore: PERMISSION_DENIED: Missing or insufficient permissions

npm i --save firebase @angular/fire

in app.module make sure you imported

import { AngularFireModule } from '@angular/fire';
import { AngularFirestoreModule } from '@angular/fire/firestore';

in imports

AngularFireModule.initializeApp(environment.firebase),
    AngularFirestoreModule,
    AngularFireAuthModule,

in realtime database rules make sure you have

{
  /* Visit  rules. */
  "rules": {
    ".read": true,
    ".write": true
  }
}

in cloud firestore rules make sure you have

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

Tensorflow import error: No module named 'tensorflow'

The reason Python 3.5 environment is unable to import Tensorflow is that Anaconda does not store the tensorflow package in the same environment.

One solution is to create a new separate environment in Anaconda dedicated to TensorFlow with its own Spyder

conda create -n newenvt anaconda python=3.5
activate newenvt

and then install tensorflow into newenvt

I found this primer helpful

Select all occurrences of selected word in VSCode

I needed to extract all the matched search lines (using regex) in a file

  1. Ctrl+F Open find. Select regex icon and enter search pattern
  2. (optional) Enable select highlights by opening settings and search for selectHighlights (Ctrl+,, selectHighlights)
  3. Ctrl+L Select all search items
  4. Ctrl+C Copy all selected lines
  5. Ctrl+N Open new document
  6. Ctrl+V Paste all searched lines.

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

You won't believe this, Make sure to add "." at the end of the "url"

I got a similar error with this code:

fetch(https://itunes.apple.com/search?term=jack+johnson)
.then( response => {
    return response.json();
})
.then(data => {
    console.log(data.results);
}).catch(error => console.log('Request failed:', error))

The error I got:

 Access to fetch at 'https://itunes.apple.com/search?term=jack+johnson'
 from origin 'http://127.0.0.1:5500' has been blocked by CORS policy:
 No 'Access-Control-Allow-Origin' header is present on the requested
 resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

But I realized after a lot of research that the problem was that I did not copy the right URL address from the iTunes API documentation.

It should have been

https://itunes.apple.com/search?term=jack+johnson.

not

https://itunes.apple.com/search?term=jack+johnson

Notice the dot at the end

There is a huge explanation about why the dot is important quoting issues about DNS and character encoding but the truth is you probably do not care. Try adding the dot it might work for you too.

When I added the "." everything worked like a charm.

I hope it works for you too.

Ajax LARAVEL 419 POST error

419 error happens when you don`t post csrf_token. in your post method you must add this token along other variables.

Laravel 5.5 ajax call 419 (unknown status)

This is similar to Kannan's answer. However, this fixes an issue where the token should not be sent to cross-domain sites. This will only set the header if it is a local request.

HTML:

<meta name="csrf-token" content="{{ csrf_token() }}">

JS:

$.ajaxSetup({
    beforeSend: function(xhr, type) {
        if (!type.crossDomain) {
            xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
        }
    },
});

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.

Downgrade npm to an older version

Even I run npm install -g npm@4, it is not ok for me.

Finally, I download and install the old node.js version.

https://nodejs.org/download/release/v7.10.1/

It is npm version 4.

You can choose any version here https://nodejs.org/download/release/

Angular HttpClient "Http failure during parsing"

if you have options

return this.http.post(`${this.endpoint}/account/login`,payload, { ...options, responseType: 'text' })

LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'

As string data types have variable length, it is by default stored as object type. I faced this problem after treating missing values too. Converting all those columns to type 'category' before label encoding worked in my case.

df[cat]=df[cat].astype('category')

And then check df.dtypes and perform label encoding.

Pipenv: Command Not Found

OSX GUYS, OVER HERE!!!

As @charlax answered (for me the best one), you can use a more dynamic command to set PATH, buuut for mac users this could not work, sometimes your USER_BASE path got from site is wrong, so you need to find out where your python installation is.

$ which python3
/usr/local/bin/python3.6

you'll get a symlink, then you need to find the source's symlink.

$ ls -la /usr/local/bin/python3.6
  lrwxr-xr-x  1 root  wheel  71 Mar 14 17:56 /usr/local/bin/python3.6 -> ../../../Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6

(this ../../../ means root)

So you found the python path (/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6), then you just need to put in you ~/.bashrc as follows:

export PATH="$PATH:/Library/Frameworks/Python.framework/Versions/3.6/bin"

How to check the Angular version?

First install the Angular/cli globally in machine. to install the angular/cli run the command npm install -g @angular/cli

Above Angular7 , use these two commands enter image description hereto know the version of Angular/Cli 1. ng --version, 2.ng version

Set cookies for cross origin requests

What you need to do

To allow receiving & sending cookies by a CORS request successfully, do the following.

Back-end (server): Set the HTTP header Access-Control-Allow-Credentials value to true. Also, make sure the HTTP headers Access-Control-Allow-Origin and Access-Control-Allow-Headers are set and not with a wildcard *.

Recommended Cookie settings per Chrome and Firefox update in 2021: SameSite=None and Secure. See MDN documentation

For more info on setting CORS in express js read the docs here

Front-end (client): Set the XMLHttpRequest.withCredentials flag to true, this can be achieved in different ways depending on the request-response library used:

Or

Avoid having to use CORS in combination with cookies. You can achieve this with a proxy.

If you for whatever reason don't avoid it. The solution is above.

It turned out that Chrome won't set the cookie if the domain contains a port. Setting it for localhost (without port) is not a problem. Many thanks to Erwin for this tip!

intellij idea - Error: java: invalid source release 1.9

Sometimes the problem occurs because of the incorrect version of the project bytecode.

So verify it : File -> Settings -> Build, Execution, Deployment -> Compiler -> Java Compiler -> Project bytecode version and set its value to 8

Example

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

Unable to merge dex

Change you buildToolsVersion to some other version and sync, change it back and sync again. It will work again.

Cordova app not displaying correctly on iPhone X (Simulator)

There is 3 steps you have to do

for iOs 11 status bar & iPhone X header problems


1. Viewport fit cover

Add viewport-fit=cover to your viewport's meta in <header>

<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0,viewport-fit=cover">

Demo: https://jsfiddle.net/gq5pt509 (index.html)


  1. Add more splash images to your config.xml inside <platform name="ios">

Dont skip this step, this required for getting screen fit for iPhone X work

<splash src="your_path/Default@2x~ipad~anyany.png" />   <!-- 2732x2732 -->
<splash src="your_path/Default@2x~ipad~comany.png" />   <!-- 1278x2732 -->
<splash src="your_path/Default@2x~iphone~anyany.png" /> <!-- 1334x1334 -->
<splash src="your_path/Default@2x~iphone~comany.png" /> <!-- 750x1334  -->
<splash src="your_path/Default@2x~iphone~comcom.png" /> <!-- 1334x750  -->
<splash src="your_path/Default@3x~iphone~anyany.png" /> <!-- 2208x2208 -->
<splash src="your_path/Default@3x~iphone~anycom.png" /> <!-- 2208x1242 -->
<splash src="your_path/Default@3x~iphone~comany.png" /> <!-- 1242x2208 -->

Demo: https://jsfiddle.net/mmy885q4 (config.xml)


  1. Fix your style on CSS

Use safe-area-inset-left, safe-area-inset-right, safe-area-inset-top, or safe-area-inset-bottom

Example: (Use in your case!)

#header {
   position: fixed;
   top: 1.25rem; // iOs 10 or lower
   top: constant(safe-area-inset-top); // iOs 11
   top: env(safe-area-inset-top); // iOs 11+ (feature)

   // or use calc()
   top: calc(constant(safe-area-inset-top) + 1rem);
   top: env(constant(safe-area-inset-top) + 1rem);
  
   // or SCSS calc()
   $nav-height: 1.25rem;
   top: calc(constant(safe-area-inset-top) + #{$nav-height});
   top: calc(env(safe-area-inset-top) + #{$nav-height});
}

Bonus: You can add body class like is-android or is-ios on deviceready

var platformId = window.cordova.platformId;
if (platformId) {
   document.body.classList.add('is-' + platformId);
}

So you can do something like this on CSS

.is-ios #header {
 // Properties
}

Iterate over array of objects in Typescript

You can use the built-in forEach function for arrays.

Like this:

//this sets all product descriptions to a max length of 10 characters
data.products.forEach( (element) => {
    element.product_desc = element.product_desc.substring(0,10);
});

Your version wasn't wrong though. It should look more like this:

for(let i=0; i<data.products.length; i++){
    console.log(data.products[i].product_desc); //use i instead of 0
}

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

I tried all the above answers, none of them worked, in my case even docker container ls doesn't show any container running. It looks like the problem is due to the fact that the docker proxy is still using ports although there are no containers running. In my case I was using ubuntu. Here's what I tried and got the problem solved, just run the following two commands:

sudo service docker stop
sudo rm -f /var/lib/docker/network/files/local-kv.db

Vuex - passing multiple parameters to mutation

i think this can be as simple let as assume that you are going to pass multiple parameters to you action as you read up there actions accept only two parameters context and payload which is your data you want to pass in action so let take an example

Setting up Action

instead of

actions: {
        authenticate: ({ commit }, token, expiration) => commit('authenticate', token, expiration)
    }

do

actions: {
        authenticate: ({ commit }, {token, expiration}) => commit('authenticate', token, expiration)
    }

Calling (dispatching) Action

instead of

this.$store.dispatch({
                  type: 'authenticate',
                  token: response.body.access_token,
                  expiration: response.body.expires_in + Date.now()
              })

do

this.$store.dispatch('authenticate',{
                  token: response.body.access_token,
                  expiration: response.body.expires_in + Date.now()
              })

hope this gonna help

No converter found capable of converting from type to type

Turns out, when the table name is different than the model name, you have to change the annotations to:

@Entity
@Table(name = "table_name")
class WhateverNameYouWant {
    ...

Instead of simply using the @Entity annotation.

What was weird for me, is that the class it was trying to convert to didn't exist. This worked for me.

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

How to Update a Component without refreshing full page - Angular

To update component

 @Injectable()
    export class LoginService{
    private isUserLoggedIn: boolean = false;

    public setLoggedInUser(flag) { // you need set header flag true false from other components on basis of your requirements, header component will be visible as per this flag then
    this.isUserLoggedIn= flag;
    }


public getUserLoggedIn(): boolean {
return this.isUserLoggedIn;
}

Login Component ts
            Login Component{
             constructor(public service: LoginService){}

public login(){
service.setLoggedInUser(true);
}
            }
Inside Header component

 Header Component ts
        HeaderComponent {
         constructor(public service: LoginService){}

         public getUserLoggedIn(): boolean { return this.service.getUserLoggedIn()}
        }

template of header component: Check for user sign in here

<button *ngIf="getUserLoggedIn()">Sign Out</button>
<button *ngIf="!getUserLoggedIn()">Sign In</button>

You can use many approach like show hide using ngIf

App Component ts
AppComponent {
 public showHeader: boolean = true;
}
App Component html
<div *ngIf='showHeader'> // you show hide on basis of this ngIf and header component always get visible with it's lifecycle hook ngOnInit() called all the time when it get visible
<app-header></app-header>
</div>
<router-outlet></router-outlet>
<app-footer></app-footer>

You can also use service

@Injectable()
export class AppService {
private showHeader: boolean = false;

public setHeader(flag) { // you need set header flag true false from other components on basis of your requirements, header component will be visible as per this flag then
this.showHeader = flag;
}

public getHeader(): boolean {
return this.showHeader;
}
}

App Component.ts
    AppComponent {
     constructor(public service: AppService){}
    }

App Component.html
    <div *ngIf='service.showHeader'> // you show hide on basis of this ngIf and header component always get visible with it's lifecycle hook ngOnInit() called all the time when it get visible
    <app-header></app-header>
    </div>
    <router-outlet></router-outlet>
    <app-footer></app-footer>

Angular 4 - Observable catch error

If you want to use the catch() of the Observable you need to use Observable.throw() method before delegating the error response to a method

_x000D_
_x000D_
import { Injectable } from '@angular/core';_x000D_
import { Headers, Http, ResponseOptions} from '@angular/http';_x000D_
import { AuthHttp } from 'angular2-jwt';_x000D_
_x000D_
import { MEAT_API } from '../app.api';_x000D_
_x000D_
import { Observable } from 'rxjs/Observable';_x000D_
import 'rxjs/add/operator/map';_x000D_
import 'rxjs/add/operator/catch';_x000D_
_x000D_
@Injectable()_x000D_
export class CompareNfeService {_x000D_
_x000D_
_x000D_
  constructor(private http: AuthHttp) {}_x000D_
_x000D_
  envirArquivos(order): Observable < any > {_x000D_
    const headers = new Headers();_x000D_
    return this.http.post(`${MEAT_API}compare/arquivo`, order,_x000D_
        new ResponseOptions({_x000D_
          headers: headers_x000D_
        }))_x000D_
      .map(response => response.json())_x000D_
      .catch((e: any) => Observable.throw(this.errorHandler(e)));_x000D_
  }_x000D_
_x000D_
  errorHandler(error: any): void {_x000D_
    console.log(error)_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Using Observable.throw() worked for me

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

Angular 4 setting selected option in Dropdown

Remove [selected] from option tag:

<option *ngFor="let opt of question.options" [value]="opt.key">
  {{opt.selected+opt.value}}
</option>

And in your form builder add:

key: this.question.options.filter(val => val.selected === true).map(data => data.key)

How to specify credentials when connecting to boto3 S3?

This is older but placing this here for my reference too. boto3.resource is just implementing the default Session, you can pass through boto3.resource session details.

Help on function resource in module boto3:

resource(*args, **kwargs)
    Create a resource service client by name using the default session.

    See :py:meth:`boto3.session.Session.resource`.

https://github.com/boto/boto3/blob/86392b5ca26da57ce6a776365a52d3cab8487d60/boto3/session.py#L265

you can see that it just takes the same arguments as Boto3.Session

import boto3
S3 = boto3.resource('s3', region_name='us-west-2', aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY, aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY)
S3.Object( bucket_name, key_name ).delete()

Access Control Origin Header error using Axios in React Web throwing error in Chrome

$ npm install cors

After installing cors from npm add the code below to your node app file. It solved my problem.

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

Build .so file from .c file using gcc command line

To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

gcc -c -fPIC hello.c -o hello.o

This will generate an object file (.o), now you take it and create the .so file:

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

You can use

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch

Set JavaScript variable = null, or leave undefined?

Generally speak I defined null as it indicates a human set the value and undefined to indicate no setting has taken place.

jquery : focus to div is not working

a <div> can be focused if it has a tabindex attribute. (the value can be set to -1)

For example:

$("#focus_point").attr("tabindex",-1).focus();

In addition, consider setting outline: none !important; so it displayed without a focus rectangle.

var element = $("#focus_point");
element.css('outline', 'none !important')
       .attr("tabindex", -1)
       .focus();

INFO: No Spring WebApplicationInitializer types detected on classpath

This is common error, make sure that your file.war is built correctly. Just open .war file and check that your WebApplicationInitializer is there.

How to write a std::string to a UTF-8 text file

What is the easiest and simple way to do so?

The most intuitive and thus easiest handling of utf8 in C++ is for sure using a drop-in replacement for std::string. As the internet still lacks of one, I went to implement the functionality on my own:

tinyutf8 (EDIT: now Github).

This library provides a very lightweight drop-in preplacement for std::string (or std::u32string if you will, because you iterate over codepoints rather that chars). Ity is implemented succesfully in the middle between fast access and small memory consumption, while being very robust. This robustness to 'invalid' UTF8-sequences makes it (nearly completely) compatible with ANSI (0-255).

Hope this helps!

HTTP Status 504

CheckUpDown has a nice explanation of the 504 error:

A server (not necessarily a Web server) is acting as a gateway or proxy to fulfil the request by the client (e.g. your Web browser or our CheckUpDown robot) to access the requested URL. This server did not receive a timely response from an upstream server it accessed to deal with your HTTP request.

This usually means that the upstream server is down (no response to the gateway/proxy), rather than that the upstream server and the gateway/proxy do not agree on the protocol for exchanging data.

This problem is entirely due to slow IP communication between back-end computers, possibly including the Web server. Only the people who set up the network at the site which hosts the Web server can fix this problem.

Jackson JSON custom serialization for certain fields

You can create a custom serializer inline in the mixin. Then annotate a field with it. See example below that appends " - something else " to lang field. This is kind of hackish - if your serializer requires something like a repository or anything injected by spring, this is going to be a problem. Probably best to use a custom deserializer/serializer instead of a mixin.

package com.test;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.test.Argument;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//Serialize only fields explicitly mentioned by this mixin.
@JsonAutoDetect(
    fieldVisibility = Visibility.NONE,
    setterVisibility = Visibility.NONE,
    getterVisibility = Visibility.NONE,
    isGetterVisibility = Visibility.NONE,
    creatorVisibility = Visibility.NONE
)
@JsonPropertyOrder({"lang", "name", "value"})
public abstract class V2ArgumentMixin {

  @JsonProperty("name")
  private String name;

  @JsonSerialize(using = LangCustomSerializer.class, as=String.class)
  @JsonProperty("lang")
  private String lang;

  @JsonProperty("value")
  private Object value;


  
  public static class LangCustomSerializer extends JsonSerializer<String> {

    @Override
    public void serialize(String value,
                          JsonGenerator jsonGenerator,
                          SerializerProvider serializerProvider)
        throws IOException, JsonProcessingException {
      jsonGenerator.writeObject(value.toString() + "  - something else");
    }
  }
}

React - How to pass HTML tags in props?

You can successfully utilize React fragments for this task. Depending on the React version you use, you can use short syntax: <> or the full tag: <React.Fragment>. Works especially well if you don't want to wrap entire string within HTML tags.

<MyComponent text={<>Hello World. <u>Don't be so ruthless</u>.</>} />

Having both a Created and Last Updated timestamp columns in MySQL 4.0

You can have them both, just take off the "CURRENT_TIMESTAMP" flag on the created field. Whenever you create a new record in the table, just use "NOW()" for a value.

Or.

On the contrary, remove the 'ON UPDATE CURRENT_TIMESTAMP' flag and send the NOW() for that field. That way actually makes more sense.

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

It's mentioned by @watsonic that in Sublime Text 3 on Mac OS, starting with an empty selection, simply ^?G (AltF3 on Windows) does the trick, instead of ?D + ^?G in Sublime Text 2.

Force the origin to start at 0

In the latest version of ggplot2, this can be more easy.

p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p+ geom_point() + scale_x_continuous(expand = expansion(mult = c(0, 0))) + scale_y_continuous(expand = expansion(mult = c(0, 0)))

enter image description here

See ?expansion() for more details.

Converting cv::Mat to IplImage*

Here is the recent fix for dlib users link

cv::Mat img = ...
IplImage iplImage = cvIplImage(img);

System.drawing namespace not found under console application

Add reference .dll file to project. Right, Click on Project reference folder --> click on Add Reference -->.Net tab you will find System.Drawing --> click on ok this will add a reference to System.Drawing

Incrementing a date in JavaScript

Not entirelly sure if it is a BUG(Tested Firefox 32.0.3 and Chrome 38.0.2125.101), but the following code will fail on Brazil (-3 GMT):

Date.prototype.shiftDays = function(days){    
  days = parseInt(days, 10);
  this.setDate(this.getDate() + days);
  return this;
}

$date = new Date(2014, 9, 16,0,1,1);
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");

Result:

Fri Oct 17 2014 00:01:01 GMT-0300
Sat Oct 18 2014 00:01:01 GMT-0300
Sat Oct 18 2014 23:01:01 GMT-0300
Sun Oct 19 2014 23:01:01 GMT-0200

Adding one Hour to the date, will make it work perfectly (but does not solve the problem).

$date = new Date(2014, 9, 16,0,1,1);

Result:

Fri Oct 17 2014 01:01:01 GMT-0300
Sat Oct 18 2014 01:01:01 GMT-0300
Sun Oct 19 2014 01:01:01 GMT-0200
Mon Oct 20 2014 01:01:01 GMT-0200

How can I pass arguments to anonymous functions in JavaScript?

Event handlers expect one parameter which is the event that was fired. You happen to be renaming that to 'myMessage' and therefore you are alerting the event object rather than your message.

A closure can allow you to reference the variable you have defined outside the function however if you are using Jquery you may want to look at its event specific API e.g.

http://docs.jquery.com/Events/bind#typedatafn

This has an option for passing in your own data.

PHP code to get selected text of a combo box

Change your select box options value:

<select id="cmbMake" name="Make" >
     <option value="">Select Manufacturer</option>
     <option value="Any">--Any--</option>
     <option value="Toyota">Toyota</option>
     <option value="Nissan">Nissan</option>
  </select>

You cann't get the text of selected option in php. it will give only the value of selected option.

EDITED:

<select id="cmbMake" name="Make" >
     <option value="0">Select Manufacturer</option>
     <option value="1_Any">--Any--</option>
     <option value="2_Toyota">Toyota</option>
     <option value="3_Nissan">Nissan</option>
  </select>

ON php file:

$maker = mysql_real_escape_string($_POST['Make']);
$maker = explode("_",$maker);
echo $maker[1]; //give the Toyota
echo $maker[0]; //give the key 2

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

You can create a subclass of UITextField as shown below:

class TextField : UITextField {

    override var tintColor: UIColor! {

        didSet {
            setNeedsDisplay()
        }
    }

    override func draw(_ rect: CGRect) {

        let startingPoint   = CGPoint(x: rect.minX, y: rect.maxY)
        let endingPoint     = CGPoint(x: rect.maxX, y: rect.maxY)

        let path = UIBezierPath()

        path.move(to: startingPoint)
        path.addLine(to: endingPoint)
        path.lineWidth = 2.0

        tintColor.setStroke()

        path.stroke()
    }
}

Plotting histograms from grouped data in a pandas DataFrame

Your function is failing because the groupby dataframe you end up with has a hierarchical index and two columns (Letter and N) so when you do .hist() it's trying to make a histogram of both columns hence the str error.

This is the default behavior of pandas plotting functions (one plot per column) so if you reshape your data frame so that each letter is a column you will get exactly what you want.

df.reset_index().pivot('index','Letter','N').hist()

The reset_index() is just to shove the current index into a column called index. Then pivot will take your data frame, collect all of the values N for each Letter and make them a column. The resulting data frame as 400 rows (fills missing values with NaN) and three columns (A, B, C). hist() will then produce one histogram per column and you get format the plots as needed.

JCheckbox - ActionListener and ItemListener?

For reference, here's an sscce that illustrates the difference. Console:

SELECTED
ACTION_PERFORMED
DESELECTED
ACTION_PERFORMED

Code:

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

/** @see http://stackoverflow.com/q/9882845/230513 */
public class Listeners {

    private void display() {
        JFrame f = new JFrame("Listeners");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JCheckBox b = new JCheckBox("JCheckBox");
        b.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(e.getID() == ActionEvent.ACTION_PERFORMED
                    ? "ACTION_PERFORMED" : e.getID());
            }
        });
        b.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                System.out.println(e.getStateChange() == ItemEvent.SELECTED
                    ? "SELECTED" : "DESELECTED");
            }
        });
        JPanel p = new JPanel();
        p.add(b);
        f.add(p);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Listeners().display();
            }
        });
    }
}

Adding image inside table cell in HTML

Try using "/" instead of "\" for the path to your image. Some comments here seem to come from people that do not understand some of us are simply learning web development which in many cases is best done locally. So instead of using src=C:\Pics\H.gif use src="C:/Pics/H.gif" for an absolute path or just src="Pics/H.gif" for a relative path if your Pics are in a sub-directory of your html page's location). Note also, it is good practice to surround your path with quotes. otherwise you will have problems with paths that include spaces and other odd characters.

What's the difference between JavaScript and Java?

Everything. They're unrelated languages.

When do I need a fb:app_id or fb:admins?

To use the Like Button and have the Open Graph inspect your website, you need an application.

So you need to associate the Like Button with a fb:app_id

If you want other users to see the administration page for your website on Facebook you add fb:admins. So if you are the developer of the application and the website owner there is no need to add fb:admins

Unsetting array values in a foreach loop

Try that:

foreach ($images[1] as $key => &$image) {
    if (yourConditionGoesHere) {
        unset($images[1][$key])
    }
}
unset($image); // detach reference after loop  

Normally, foreach operates on a copy of your array so any changes you make, are made to that copy and don't affect the actual array.

So you need to unset the values via $images[$key];

The reference on &$image prevents the loop from creating a copy of the array which would waste memory.

iPhone 6 and 6 Plus Media Queries

iPhone X

/* Portrait and Landscape */
@media only screen 
  and (min-device-width: 375px) 
  and (max-device-width: 812px) 
  and (-webkit-min-device-pixel-ratio: 3)
  /* uncomment for only portrait: */
  /* and (orientation: portrait) */
  /* uncomment for only landscape: */
  /* and (orientation: landscape) */ { 

}

iPhone 6+, 7+ and 8+

/* Portrait and Landscape */
@media only screen 
  and (min-device-width: 414px) 
  and (max-device-width: 736px) 
  and (-webkit-min-device-pixel-ratio: 3)
  /* uncomment for only portrait: */
  /* and (orientation: portrait) */
  /* uncomment for only landscape: */
  /* and (orientation: landscape) */ { 

}

iPhone 6, 6S, 7 and 8

/* Portrait and Landscape */
@media only screen 
  and (min-device-width: 375px) 
  and (max-device-width: 667px) 
  and (-webkit-min-device-pixel-ratio: 2)
  /* uncomment for only portrait: */
  /* and (orientation: portrait) */
  /* uncomment for only landscape: */
  /* and (orientation: landscape) */ { 

}

Source: Media Queries for Standard Devices

What are the different usecases of PNG vs. GIF vs. JPEG vs. SVG?

JPEG is not the lightest for all kinds of images(or even most). Corners and straight lines and plain "fills"(blocks of solid color) will appear blurry or have artifacts in them depending on the compression level. It is a lossy format, and works best for photographs where you can't see artifacts clearly. Straight lines(such as in drawings and comics and such) compress very nicely in PNG and it's lossless. GIF should only be used when you want transparency to work in IE6 or you want animation. GIF only supports a 256 color pallete but is also lossless.

So basically here is a way to decide the image format:

  • GIF if needs animation or transparency that works on IE6(note, PNG transparency works after IE6)
  • JPEG if the image is a photograph.
  • PNG if straight lines as in a comic or other drawing or if a wide color range is needed with transparency(and IE6 is not a factor)

And as commented, if you are unsure of what would qualify, try each format with different compression ratios and weigh the quality and size of the picture and choose which one you think is best. I am only giving rules of thumb.

HTML Entity Decode

Because @Robert K and @mattcasey both have good code, I thought I'd contribute here with a CoffeeScript version, in case anyone in the future could use it:

    String::unescape = (strict = false) ->
      ###
      # Take escaped text, and return the unescaped version
      #
      # @param string str | String to be used
      # @param bool strict | Stict mode will remove all HTML
      #
      # Test it here:
      # https://jsfiddle.net/tigerhawkvok/t9pn1dn5/
      #
      # Code: https://gist.github.com/tigerhawkvok/285b8631ed6ebef4446d
      ###
      # Create a dummy element
      element = document.createElement("div")
      decodeHTMLEntities = (str) ->
        if str? and typeof str is "string"
          unless strict is true
            # escape HTML tags
            str = escape(str).replace(/%26/g,'&').replace(/%23/g,'#').replace(/%3B/g,';')
          else
            str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '')
            str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '')
          element.innerHTML = str
          if element.innerText
            # Do we support innerText?
            str = element.innerText
            element.innerText = ""
          else
            # Firefox
            str = element.textContent
            element.textContent = ""
        unescape(str)
      # Remove encoded or double-encoded tags
      fixHtmlEncodings = (string) ->
        string = string.replace(/\&amp;#/mg, '&#') # The rest, for double-encodings
        string = string.replace(/\&quot;/mg, '"')
        string = string.replace(/\&quote;/mg, '"')
        string = string.replace(/\&#95;/mg, '_')
        string = string.replace(/\&#39;/mg, "'")
        string = string.replace(/\&#34;/mg, '"')
        string = string.replace(/\&#62;/mg, '>')
        string = string.replace(/\&#60;/mg, '<')
        string
      # Run it
      tmp = fixHtmlEncodings(this)
      decodeHTMLEntities(tmp)

See https://jsfiddle.net/tigerhawkvok/t9pn1dn5/7/ or https://gist.github.com/tigerhawkvok/285b8631ed6ebef4446d (includes compiled JS, and is probably updated compared to this answer)

deleting rows in numpy array

import numpy as np 
arr = np.array([[ 0.96488889, 0.73641667, 0.67521429, 0.592875, 0.53172222],[ 0.78008333, 0.5938125, 0.481, 0.39883333, 0.]])
print(arr[np.where(arr != 0.)])

Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?

The default API level in the Cordova Android platform has been upgraded. On an Android 9 device, clear text communication is now disabled by default.

To allow clear text communication again, set the android:usesCleartextTraffic on your application tag to true:

<platform name="android">
  <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application">
      <application android:usesCleartextTraffic="true" />
  </edit-config>
</platform>

As noted in the comments, if you have not defined the android XML namespace previously, you will receive an error: unbound prefix during build. This indicates that you need to add it to your widget tag in the same config.xml, like so:

<widget id="you-app-id" version="1.2.3"
xmlns="http://www.w3.org/ns/widgets" 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cdv="http://cordova.apache.org/ns/1.0">

Is there a simple way to increment a datetime object one month in Python?

Check out from dateutil.relativedelta import * for adding a specific amount of time to a date, you can continue to use timedelta for the simple stuff i.e.

use_date = use_date + datetime.timedelta(minutes=+10)
use_date = use_date + datetime.timedelta(hours=+1)
use_date = use_date + datetime.timedelta(days=+1)
use_date = use_date + datetime.timedelta(weeks=+1)

or you can start using relativedelta

use_date = use_date+relativedelta(months=+1)

use_date = use_date+relativedelta(years=+1)

for the last day of next month:

use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)

Right now this will provide 29/02/2016

for the penultimate day of next month:

use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)
use_date = use_date+relativedelta(days=-1)

last Friday of the next month:

use_date = use_date+relativedelta(months=+1, day=31, weekday=FR(-1))

2nd Tuesday of next month:

new_date = use_date+relativedelta(months=+1, day=1, weekday=TU(2))

As @mrroot5 points out dateutil's rrule functions can be applied, giving you an extra bang for your buck, if you require date occurences.
for example:
Calculating the last day of the month for 9 months from the last day of last month.
Then, calculate the 2nd Tuesday for each of those months.

from dateutil.relativedelta import *
from dateutil.rrule import *
from datetime import datetime
use_date = datetime(2020,11,21)

#Calculate the last day of last month
use_date = use_date+relativedelta(months=-1)
use_date = use_date+relativedelta(day=31)

#Generate a list of the last day for 9 months from the calculated date
x = list(rrule(freq=MONTHLY, count=9, dtstart=use_date, bymonthday=(-1,)))
print("Last day")
for ld in x:
    print(ld)

#Generate a list of the 2nd Tuesday in each of the next 9 months from the calculated date
print("\n2nd Tuesday")
x = list(rrule(freq=MONTHLY, count=9, dtstart=use_date, byweekday=TU(2)))
for tuesday in x:
    print(tuesday)

Last day
2020-10-31 00:00:00
2020-11-30 00:00:00
2020-12-31 00:00:00
2021-01-31 00:00:00
2021-02-28 00:00:00
2021-03-31 00:00:00
2021-04-30 00:00:00
2021-05-31 00:00:00
2021-06-30 00:00:00

2nd Tuesday
2020-11-10 00:00:00
2020-12-08 00:00:00
2021-01-12 00:00:00
2021-02-09 00:00:00
2021-03-09 00:00:00
2021-04-13 00:00:00
2021-05-11 00:00:00
2021-06-08 00:00:00
2021-07-13 00:00:00

This is by no means an exhaustive list of what is available. Documentation is available here: https://dateutil.readthedocs.org/en/latest/

Changing CSS style from ASP.NET code

I find that code gets messy fast when C# code is used to modify CSS values. Perhaps a better approach is for your code to dynamically set the class attribute on the div tag and then store any specific CSS settings in the style sheet.

That might not work for your situation, but its a decent default position if you need to change the style on the fly in server side code.

How to remove \n from a list element?

It sounds like you want something like the Perl chomp() function.

That's trivial to do in Python:

def chomp(s):
    return s[:-1] if s.endswith('\n') else s

... assuming you're using Python 2.6 or later. Otherwise just use the slightly more verbose:

def chomp(s):
    if s.endwith('\n'):
        return s[:-1]
    else:
        return s

If you want to remove all new lines from the end of a string (in the odd case where one might have multiple trailing newlines for some reason):

def chomps(s):
    return s.rstrip('\n')

Obviously you should never see such a string returned by any normal Python file object's readline() nor readlines() methods.

I've seen people blindly remove the last characters (using s[:-1] slicing) from the results of file readline() and similar functions. This is a bad idea because it can lead to an error on the last line of the file (in the case where a file ends with anything other than a newline).

At first you might be lulled into a false sense of security when blindly stripping final characters off lines you've read. If you use a normal text editor to create your test suite files you'll have a newline silently added to the end of the last line by most of them. To create a valid test file use code something like:

f = open('sometest.txt', 'w')
f.write('some text')
f.close()

... and then if you re-open that file and use the readline() or readlines() file methods on it you'll find that the text is read without the trailing newline.

This failure to account for text files ending in non-newline characters has plagued many UNIX utilities and scripting languages for many years. It's a stupid corner base bug that creeps into code just often enough to be a pest but not often enough for people to learn from it. We could argue that "text" files without the ultimate newline are "corrupt" or non-standard; and that may be valid for some programming specifications.

However, it's all too easy to ignore corner cases in our coding and have that ignorance bite people who are depending on your code later. As my wife says: when it comes to programming ... practice safe hex!

Update MySQL using HTML Form and PHP

you have error in your sql syntax.

please use this query and checkout.

$query = mysql_query("UPDATE `anstalld` SET mandag = '$mandag', tisdag = '$tisdag', onsdag = '$onsdag', torsdag = '$torsdag', fredag = '$fredag' WHERE namn = '$namn' ");

Run javascript script (.js file) in mongodb including another file inside js

for running mutilple js files

#!/bin/bash
cd /root/migrate/

ls -1 *.js | sed 's/.js$//' | while read name; do
     start=`date +%s`
     mongo localhost:27017/wbars $name.js;
     end=`date +%s`
     runtime1=$((end-start))
     runtime=$(printf '%dh:%dm:%ds\n' $(($runtime1/3600)) $(($secs%3600/60)) $(($secs%60)))
     echo @@@@@@@@@@@@@ $runtime $name.js completed @@@@@@@@@@@
     echo "$name.js completed"
     sync
     echo 1 > /proc/sys/vm/drop_caches
     echo 2 > /proc/sys/vm/drop_caches
     echo 3 > /proc/sys/vm/drop_caches
done

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

What version of tomcat are you using ? What appears to me is that the tomcat version is not supporting the servlet & jsp versions you're using. You can change to something like below or look into your version of tomcat on what it supports and change the versions accordingly.

 <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>

Adding multiple columns AFTER a specific column in MySQL

You cannot mention multiple column names with commas using ADD COLUMN. You need to mention ADD COLUMN every time you define a new column.

Svn switch from trunk to branch

  • Short version of (correct) tzaman answer will be (for fresh SVN)

    svn switch ^/branches/v1p2p3
    
  • --relocate switch is deprecated anyway, when it needed you'll have to use svn relocate command

  • Instead of creating snapshot-branch (ReadOnly) you can use tags (conventional RO labels for history)

On Windows, the caret character (^) must be escaped:

svn switch ^^/branches/v1p2p3

Centering FontAwesome icons vertically and horizontally

If you are using twitter Bootstrap add the class text-center to your code.

<div class='login-icon'><i class="icon-lock text-center"></i></div>

How to set up a Web API controller for multipart/form-data

This is what solved my problem
Add the following line to WebApiConfig.cs

config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));

Detecting locked tables (locked by LOCK TABLE)

You can create your own lock with GET_LOCK(lockName,timeOut)

If you do a GET_LOCK(lockName, 0) with a 0 time out before you lock the tables and then follow that with a RELEASE_LOCK(lockName) then all other threads performing a GET_LOCK() will get a value of 0 which will tell them that the lock is being held by another thread.

However this won't work if you don't have all threads calling GET_LOCK() before locking tables. The documentation for locking tables is here

Hope that helps!

How to get the innerHTML of selectable jquery element?

Use .val() instead of .innerHTML for getting value of selected option

Use .text() for getting text of selected option

Thanks for correcting :)

How to get the current time in milliseconds in C Programming

quick answer

#include<stdio.h>   
#include<time.h>   

int main()   
{   
    clock_t t1, t2;  
    t1 = clock();   
    int i;
    for(i = 0; i < 1000000; i++)   
    {   
        int x = 90;  
    }   

    t2 = clock();   

    float diff = ((float)(t2 - t1) / 1000000.0F ) * 1000;   
    printf("%f",diff);   

    return 0;   
}

Liquibase lock - reasons?

Sometimes if the update application is abruptly stopped, then the lock remains stuck.

Then running

UPDATE DATABASECHANGELOGLOCK SET LOCKED=0, LOCKGRANTED=null, LOCKEDBY=null where ID=1;

against the database helps.

You may also need to replace LOCKED=0 with LOCKED=FALSE.

Or you can simply drop the DATABASECHANGELOGLOCK table, it will be recreated.

Substitute multiple whitespace with single whitespace in Python

A regular expression can be used to offer more control over the whitespace characters that are combined.

To match unicode whitespace:

import re

_RE_COMBINE_WHITESPACE = re.compile(r"\s+")

my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str).strip()

To match ASCII whitespace only:

import re

_RE_COMBINE_WHITESPACE = re.compile(r"(?a:\s+)")
_RE_STRIP_WHITESPACE = re.compile(r"(?a:^\s+|\s+$)")

my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str)
my_str = _RE_STRIP_WHITESPACE.sub("", my_str)

Matching only ASCII whitespace is sometimes essential for keeping control characters such as x0b, x0c, x1c, x1d, x1e, x1f.

Reference:

About \s:

For Unicode (str) patterns: Matches Unicode whitespace characters (which includes [ \t\n\r\f\v], and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the ASCII flag is used, only [ \t\n\r\f\v] is matched.

About re.ASCII:

Make \w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns. Corresponds to the inline flag (?a).

strip() will remote any leading and trailing whitespaces.

Word count from a txt file program

#!/usr/bin/python
file=open("D:\\zzzz\\names2.txt","r+")
wordcount={}
for word in file.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1
for k,v in wordcount.items():
    print k, v

How to set default font family in React Native?

For React Native 0.56.0+ check if defaultProps is defined first:

Text.defaultProps = Text.defaultProps || {}

Then add:

Text.defaultProps.style =  { fontFamily: 'some_font' }

Add the above in the constructor of the App.js file (or any root component you have).

In order to override the style you can create a style object and spread it then add your additional style (e.g { ...baseStyle, fontSize: 16 })

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

In a shameless attempt to steal some votes, SecurityProtocol is an Enum with the [Flags] attribute. So you can do this:

[Net.ServicePointManager]::SecurityProtocol = 
  [Net.SecurityProtocolType]::Tls12 -bor `
  [Net.SecurityProtocolType]::Tls11 -bor `
  [Net.SecurityProtocolType]::Tls

Or since this is PowerShell, you can let it parse a string for you:

[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"

Then you don't technically need to know the TLS version.

I copied and pasted this from a script I created after reading this answer because I didn't want to cycle through all the available protocols to find one that worked. Of course, you could do that if you wanted to.

Final note - I have the original (minus SO edits) statement in my PowerShell profile so it's in every session I start now. It's not totally foolproof since there are still some sites that just fail but I surely see the message in question much less frequently.

Getting each individual digit from a whole integer

I've made this solution, it-s simple instead read an integer, i read a string (char array in C), then write with a for bucle, the code also write the sum of digits

// #include<string.h>

scanf("%s", n);
int total = 0;

for (int i = 0; i< strlen(n); i++){
    printf("%c", n[i]);
    total += (int)(n[i]) -48;
}

printf("%d", total);

Converting string into datetime

You can use easy_date to make it easy:

import date_converter
converted_date = date_converter.string_to_datetime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

How to tag docker image with docker-compose

Original answer Nov 20 '15:

No option for a specific tag as of Today. Docker compose just does its magic and assigns a tag like you are seeing. You can always have some script call docker tag <image> <tag> after you call docker-compose.

Now there's an option as described above or here

build: ./dir
image: webapp:tag

Redirect echo output in shell script to logfile

I tried to manage using the below command. This will write the output in log file as well as print on console.

#!/bin/bash

# Log Location on Server.
LOG_LOCATION=/home/user/scripts/logs
exec > >(tee -i $LOG_LOCATION/MylogFile.log)
exec 2>&1

echo "Log Location should be: [ $LOG_LOCATION ]"

Please note: This is bash code so if you run it using sh it will through syntax error

How do you decrease navbar height in Bootstrap 3?

Instead of <nav class="navbar ... use <nav class="navbar navbar-xs...

and add these 3 line of css

.navbar-xs { min-height:28px; height: 28px; }
.navbar-xs .navbar-brand{ padding: 0px 12px;font-size: 16px;line-height: 28px; }
.navbar-xs .navbar-nav > li > a {  padding-top: 0px; padding-bottom: 0px; line-height: 28px; }

Output :

enter image description here

Serializing class instance to JSON

The basic problem is that the JSON encoder json.dumps() only knows how to serialize a limited set of object types by default, all built-in types. List here: https://docs.python.org/3.3/library/json.html#encoders-and-decoders

One good solution would be to make your class inherit from JSONEncoder and then implement the JSONEncoder.default() function, and make that function emit the correct JSON for your class.

A simple solution would be to call json.dumps() on the .__dict__ member of that instance. That is a standard Python dict and if your class is simple it will be JSON serializable.

class Foo(object):
    def __init__(self):
        self.x = 1
        self.y = 2

foo = Foo()
s = json.dumps(foo) # raises TypeError with "is not JSON serializable"

s = json.dumps(foo.__dict__) # s set to: {"x":1, "y":2}

The above approach is discussed in this blog posting:

    Serializing arbitrary Python objects to JSON using __dict__

Is it possible to indent JavaScript code in Notepad++?

Try the notepad++ plugin JSMinNpp(Changed name to JSTool since 1.15)

http://www.sunjw.us/jsminnpp/

Insertion sort vs Bubble Sort Algorithms

well bubble sort is better than insertion sort only when someone is looking for top k elements from a large list of number i.e. in bubble sort after k iterations you'll get top k elements. However after k iterations in insertion sort, it only assures that those k elements are sorted.

.war vs .ear file

Refer: http://www.wellho.net/mouth/754_tar-jar-war-ear-sar-files.html

tar (tape archives) - Format used is file written in serial units of fileName, fileSize, fileData - no compression. can be huge

Jar (java archive) - compression techniques used - generally contains java information like class/java files. But can contain any files and directory structure

war (web application archives) - similar like jar files only have specific directory structure as per JSP/Servlet spec for deployment purposes

ear (enterprise archives) - similar like jar files. have directory structure following J2EE requirements so that it can be deployed on J2EE application servers. - can contain multiple JAR and WAR files

Java method to sum any number of ints

Use var args

public long sum(int... numbers){
      if(numbers == null){ return 0L;}
      long result = 0L;
      for(int number: numbers){
         result += number;
      }
      return result;   
}

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

If you just want to suppress warnings from a function, you can add an @ sign in front:

<?php @function_that_i_dont_want_to_see_errors_from(parameters); ?>

Javascript regular expression password validation having special characters

Don't try and do too much in one step. Keep each rule separate.

function validatePassword() {
    var p = document.getElementById('newPassword').value,
        errors = [];
    if (p.length < 8) {
        errors.push("Your password must be at least 8 characters");
    }
    if (p.search(/[a-z]/i) < 0) {
        errors.push("Your password must contain at least one letter."); 
    }
    if (p.search(/[0-9]/) < 0) {
        errors.push("Your password must contain at least one digit.");
    }
    if (errors.length > 0) {
        alert(errors.join("\n"));
        return false;
    }
    return true;
}

How to disable scrolling the document body?

add this css

body.disable-scroll {
    overflow: hidden;
}

and when to disable run this code

$("body").addClass("disable-scroll");

and when to enabled run this code

$("body").removeClass("disable-scroll")

IOError: [Errno 2] No such file or directory trying to open a file

Even though @Ignacio gave you a straightforward solution, I thought I might add an answer that gives you some more details about the issues with your code...

# You are not saving this result into a variable to reuse
os.path.join(src_dir, f)
# Should be
src_path = os.path.join(src_dir, f)

# you open the file but you dont again use a variable to reference
with open(f)
# should be
with open(src_path) as fh

# this is actually just looping over each character 
# in each result of your os.listdir
for line in f
# you should loop over lines in the open file handle
for line in fh

# write? Is this a method you wrote because its not a python builtin function
write(line)
# write to the file
fh.write(line)

what is the difference between $_SERVER['REQUEST_URI'] and $_GET['q']?

In the context of Drupal, the difference will depend whether clean URLs are on or not.

With them off, $_SERVER['REQUEST_URI'] will have the full path of the page as called w/ /index.php, while $_GET["q"] will just have what is assigned to q.

With them on, they will be nearly identical w/o other arguments, but $_GET["q"] will be missing the leading /. Take a look towards the end of the default .htaccess to see what is going on. They will also differ if additional arguments are passed into the page, eg when a pager is active.

Concat all strings inside a List<string> using LINQ

I think that if you define the logic in an extension method the code will be much more readable:

public static class EnumerableExtensions { 
  public static string Join<T>(this IEnumerable<T> self, string separator) {  
    return String.Join(separator, self.Select(e => e.ToString()).ToArray()); 
  } 
} 

public class Person {  
  public string FirstName { get; set; }  
  public string LastName { get; set; }  
  public override string ToString() {
    return string.Format("{0} {1}", FirstName, LastName);
  }
}  

// ...

List<Person> people = new List<Person>();
// ...
string fullNames = people.Join(", ");
string lastNames = people.Select(p => p.LastName).Join(", ");

Simplest code for array intersection in javascript

I extended tarulen's answer to work with any number of arrays. It also should work with non-integer values.

function intersect() { 
    const last = arguments.length - 1;
    var seen={};
    var result=[];
    for (var i = 0; i < last; i++)   {
        for (var j = 0; j < arguments[i].length; j++)  {
            if (seen[arguments[i][j]])  {
                seen[arguments[i][j]] += 1;
            }
            else if (!i)    {
                seen[arguments[i][j]] = 1;
            }
        }
    }
    for (var i = 0; i < arguments[last].length; i++) {
        if ( seen[arguments[last][i]] === last)
            result.push(arguments[last][i]);
        }
    return result;
}

How to calculate time difference in java?

Java 8 has a cleaner solution - Instant and Duration

Example:

import java.time.Duration;
import java.time.Instant;
...
Instant start = Instant.now();
//your code
Instant end = Instant.now();
Duration timeElapsed = Duration.between(start, end);
System.out.println("Time taken: "+ timeElapsed.toMillis() +" milliseconds");

Clear text area

This works:

$('#textareaName').val('');

Best way to concatenate List of String objects?

Use one of the the StringUtils.join methods in Apache Commons Lang.

import org.apache.commons.lang3.StringUtils;

String result = StringUtils.join(list, ", ");

If you are fortunate enough to be using Java 8, then it's even easier...just use String.join

String result = String.join(", ", list);

Function to close the window in Tkinter

class App():
    def __init__(self):
        self.root = Tkinter.Tk()
        button = Tkinter.Button(self.root, text = 'root quit', command=self.quit)
        button.pack()
        self.root.mainloop()

    def quit(self):
        self.root.destroy()

app = App()

Find the last time table was updated

If you're talking about last time the table was updated in terms of its structured has changed (new column added, column changed etc.) - use this query:

SELECT name, [modify_date] FROM sys.tables

If you're talking about DML operations (insert, update, delete), then you either need to persist what that DMV gives you on a regular basis, or you need to create triggers on all tables to record that "last modified" date - or check out features like Change Data Capture in SQL Server 2008 and newer.

Show loading screen when navigating between routes in Angular 2

UPDATE:3 Now that I have upgraded to new Router, @borislemke's approach will not work if you use CanDeactivate guard. I'm degrading to my old method, ie: this answer

UPDATE2: Router events in new-router look promising and the answer by @borislemke seems to cover the main aspect of spinner implementation, I havent't tested it but I recommend it.

UPDATE1: I wrote this answer in the era of Old-Router, when there used to be only one event route-changed notified via router.subscribe(). I also felt overload of the below approach and tried to do it using only router.subscribe(), and it backfired because there was no way to detect canceled navigation. So I had to revert back to lengthy approach(double work).


If you know your way around in Angular2, this is what you'll need


Boot.ts

import {bootstrap} from '@angular/platform-browser-dynamic';
import {MyApp} from 'path/to/MyApp-Component';
import { SpinnerService} from 'path/to/spinner-service';

bootstrap(MyApp, [SpinnerService]);

Root Component- (MyApp)

import { Component } from '@angular/core';
import { SpinnerComponent} from 'path/to/spinner-component';
@Component({
  selector: 'my-app',
  directives: [SpinnerComponent],
  template: `
     <spinner-component></spinner-component>
     <router-outlet></router-outlet>
   `
})
export class MyApp { }

Spinner-Component (will subscribe to Spinner-service to change the value of active accordingly)

import {Component} from '@angular/core';
import { SpinnerService} from 'path/to/spinner-service';
@Component({
  selector: 'spinner-component',
  'template': '<div *ngIf="active" class="spinner loading"></div>'
})
export class SpinnerComponent {
  public active: boolean;

  public constructor(spinner: SpinnerService) {
    spinner.status.subscribe((status: boolean) => {
      this.active = status;
    });
  }
}

Spinner-Service (bootstrap this service)

Define an observable to be subscribed by spinner-component to change the status on change, and function to know and set the spinner active/inactive.

import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/share';

@Injectable()
export class SpinnerService {
  public status: Subject<boolean> = new Subject();
  private _active: boolean = false;

  public get active(): boolean {
    return this._active;
  }

  public set active(v: boolean) {
    this._active = v;
    this.status.next(v);
  }

  public start(): void {
    this.active = true;
  }

  public stop(): void {
    this.active = false;
  }
}

All Other Routes' Components

(sample):

import { Component} from '@angular/core';
import { SpinnerService} from 'path/to/spinner-service';
@Component({
   template: `<div *ngIf="!spinner.active" id="container">Nothing is Loading Now</div>`
})
export class SampleComponent {

  constructor(public spinner: SpinnerService){} 

  ngOnInit(){
    this.spinner.stop(); // or do it on some other event eg: when xmlhttp request completes loading data for the component
  }

  ngOnDestroy(){
    this.spinner.start();
  }
}

How to prevent custom views from losing state across screen orientation changes

Based on @Fletcher Johns answer I came up with:

  • custom layout
  • can inflate from XML
  • is able to save/restore direct and indirect children. I improved @Fletcher Johns' answer to save the ids in String->Id map instead of IntArray.
  • the only small drawback is that you must declare your saveable child views beforehand.

open class AddressView @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0,
        defStyleRes: Int = 0
) : LinearLayout(context, attrs, defStyleAttr, defStyleRes) {

    protected lateinit var countryInputLayout: TextInputLayout
    protected lateinit var countryAutoCompleteTextView: CountryAutoCompleteTextView
    protected lateinit var cityInputLayout: TextInputLayout
    protected lateinit var cityEditText: CityEditText
    protected lateinit var postCodeInputLayout: TextInputLayout
    protected lateinit var postCodeEditText: PostCodeEditText
    protected lateinit var streetInputLayout: TextInputLayout
    protected lateinit var streetEditText: StreetEditText
    
    init {
        initView()
    }

    private fun initView() {
        val view = inflate(context, R.layout.view_address, this)

        orientation = VERTICAL

        countryInputLayout = view.findViewById(R.id.countryInputLayout)
        countryAutoCompleteTextView = view.findViewById(R.id.countryAutoCompleteTextView)

        streetInputLayout = view.findViewById(R.id.streetInputLayout)
        streetEditText = view.findViewById(R.id.streetEditText)

        cityInputLayout = view.findViewById(R.id.cityInputLayout)
        cityEditText = view.findViewById(R.id.cityEditText)

        postCodeInputLayout = view.findViewById(R.id.postCodeInputLayout)
        postCodeEditText = view.findViewById(R.id.postCodeEditText)
    }

    // Declare your direct and indirect child views that need to be saved
    private val childrenToSave get() = mapOf<String, View>(
            "coutryIL" to countryInputLayout,
            "countryACTV" to countryAutoCompleteTextView,
            "streetIL" to streetInputLayout,
            "streetET" to streetEditText,
            "cityIL" to cityInputLayout,
            "cityET" to cityEditText,
            "postCodeIL" to postCodeInputLayout,
            "postCodeET" to postCodeEditText,
    )
    private var viewIds: HashMap<String, Int>? = null

    override fun onSaveInstanceState(): Parcelable? {
        // Create a bundle to put super parcelable in
        val bundle = Bundle()
        bundle.putParcelable(SUPER_INSTANCE_STATE, super.onSaveInstanceState())
        // Store viewIds in the bundle - initialize if necessary.
        if (viewIds == null) {
            childrenToSave.values.forEach { view -> view.id = generateViewId() }
            viewIds = HashMap<String, Int>(childrenToSave.mapValues { (key, view) -> view.id })
        }

        bundle.putSerializable(STATE_VIEW_IDS, viewIds)

        return bundle
    }

    override fun onRestoreInstanceState(state: Parcelable?) {
        // We know state is a Bundle:
        val bundle = state as Bundle
        // Get mViewIds out of the bundle
        viewIds = bundle.getSerializable(STATE_VIEW_IDS) as HashMap<String, Int>
        // For each id, assign to the view of same index
        if (viewIds != null) {
            viewIds!!.forEach { (key, id) -> childrenToSave[key]!!.id = id }
        }
        super.onRestoreInstanceState(bundle.getParcelable(SUPER_INSTANCE_STATE))
    }

    companion object {
        private const val SUPER_INSTANCE_STATE = "saved_instance_state_parcelable"
        private const val STATE_VIEW_IDS = "state_view_ids"
    }
}

Run PowerShell scripts on remote PC

After further investigating on PSExec tool, I think I got the answer. I need to add -i option to tell PSExec to launch process on remote in interactive mode:

PSExec \\RPC001 -i -u myID -p myPWD PowerShell C:\script\StartPS.ps1 par1 par2

Without -i, powershell.exe is running on the remote in waiting mode. Interesting point is that if I run a simple bat (without PS in bat), it works fine. Maybe this is something special for PS case? Welcome comments and explanations.

Create a GUID in Java

This answer contains 2 generators for random-based and name-based UUIDs, compliant with RFC-4122. Feel free to use and share.

RANDOM-BASED (v4)

This utility class that generates random-based UUIDs:

package your.package.name;

import java.security.SecureRandom;
import java.util.Random;
import java.util.UUID;

/**
 * Utility class that creates random-based UUIDs.
 * 
 */
public abstract class RandomUuidCreator {

    private static final int RANDOM_VERSION = 4;

    /**
     * Returns a random-based UUID.
     * 
     * It uses a thread local {@link SecureRandom}.
     * 
     * @return a random-based UUID
     */
    public static UUID getRandomUuid() {
        return getRandomUuid(SecureRandomLazyHolder.THREAD_LOCAL_RANDOM.get());
    }

    /**
     * Returns a random-based UUID.
     * 
     * It uses any instance of {@link Random}.
     * 
     * @return a random-based UUID
     */
    public static UUID getRandomUuid(Random random) {

        long msb = 0;
        long lsb = 0;

        // (3) set all bit randomly
        if (random instanceof SecureRandom) {
            // Faster for instances of SecureRandom
            final byte[] bytes = new byte[16];
            random.nextBytes(bytes);
            msb = toNumber(bytes, 0, 8); // first 8 bytes for MSB
            lsb = toNumber(bytes, 8, 16); // last 8 bytes for LSB
        } else {
            msb = random.nextLong(); // first 8 bytes for MSB
            lsb = random.nextLong(); // last 8 bytes for LSB
        }

        // Apply version and variant bits (required for RFC-4122 compliance)
        msb = (msb & 0xffffffffffff0fffL) | (RANDOM_VERSION & 0x0f) << 12; // apply version bits
        lsb = (lsb & 0x3fffffffffffffffL) | 0x8000000000000000L; // apply variant bits

        // Return the UUID
        return new UUID(msb, lsb);
    }

    private static long toNumber(final byte[] bytes, final int start, final int length) {
        long result = 0;
        for (int i = start; i < length; i++) {
            result = (result << 8) | (bytes[i] & 0xff);
        }
        return result;
    }

    // Holds thread local secure random
    private static class SecureRandomLazyHolder {
        static final ThreadLocal<Random> THREAD_LOCAL_RANDOM = ThreadLocal.withInitial(SecureRandom::new);
    }

    /**
     * For tests!
     */
    public static void main(String[] args) {

        System.out.println("// Using thread local `java.security.SecureRandom` (DEFAULT)");
        System.out.println("RandomUuidCreator.getRandomUuid()");
        System.out.println();
        for (int i = 0; i < 5; i++) {
            System.out.println(RandomUuidCreator.getRandomUuid());
        }

        System.out.println();
        System.out.println("// Using `java.util.Random` (FASTER)");
        System.out.println("RandomUuidCreator.getRandomUuid(new Random())");
        System.out.println();
        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            System.out.println(RandomUuidCreator.getRandomUuid(random));
        }
    }
}

This is the output:

// Using thread local `java.security.SecureRandom` (DEFAULT)
RandomUuidCreator.getRandomUuid()

'ef4f5ad2-8147-46cb-8389-c2b8c3ef6b10'
'adc0305a-df29-4f08-9d73-800fde2048f0'
'4b794b59-bff8-4013-b656-5d34c33f4ce3'
'22517093-ee24-4120-96a5-ecee943992d1'
'899fb1fb-3e3d-4026-85a8-8a2d274a10cb'

// Using `java.util.Random` (FASTER)
RandomUuidCreator.getRandomUuid(new Random())

'4dabbbc2-fcb2-4074-a91c-5e2977a5bbf8'
'078ec231-88bc-4d74-9774-96c0b820ceda'
'726638fa-69a6-4a18-b09f-5fd2a708059b'
'15616ebe-1dfd-4f5c-b2ed-cea0ac1ad823'
'affa31ad-5e55-4cde-8232-cddd4931923a'

NAME-BASED (v3 and v5)

This utility class that generates name-based UUIDs (MD5 and SHA1):

package your.package.name;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * Utility class that creates UUIDv3 (MD5) and UUIDv5 (SHA1).
 *
 */
public class HashUuidCreator {

    // Domain Name System
    public static final UUID NAMESPACE_DNS = new UUID(0x6ba7b8109dad11d1L, 0x80b400c04fd430c8L);
    // Uniform Resource Locator
    public static final UUID NAMESPACE_URL = new UUID(0x6ba7b8119dad11d1L, 0x80b400c04fd430c8L);
    // ISO Object ID
    public static final UUID NAMESPACE_ISO_OID = new UUID(0x6ba7b8129dad11d1L, 0x80b400c04fd430c8L);
    // X.500 Distinguished Name
    public static final UUID NAMESPACE_X500_DN = new UUID(0x6ba7b8149dad11d1L, 0x80b400c04fd430c8L);

    private static final int VERSION_3 = 3; // UUIDv3 MD5
    private static final int VERSION_5 = 5; // UUIDv5 SHA1

    private static final String MESSAGE_DIGEST_MD5 = "MD5"; // UUIDv3
    private static final String MESSAGE_DIGEST_SHA1 = "SHA-1"; // UUIDv5

    private static UUID getHashUuid(UUID namespace, String name, String algorithm, int version) {

        final byte[] hash;
        final MessageDigest hasher;

        try {
            // Instantiate a message digest for the chosen algorithm
            hasher = MessageDigest.getInstance(algorithm);

            // Insert name space if NOT NULL
            if (namespace != null) {
                hasher.update(toBytes(namespace.getMostSignificantBits()));
                hasher.update(toBytes(namespace.getLeastSignificantBits()));
            }

            // Generate the hash
            hash = hasher.digest(name.getBytes(StandardCharsets.UTF_8));

            // Split the hash into two parts: MSB and LSB
            long msb = toNumber(hash, 0, 8); // first 8 bytes for MSB
            long lsb = toNumber(hash, 8, 16); // last 8 bytes for LSB

            // Apply version and variant bits (required for RFC-4122 compliance)
            msb = (msb & 0xffffffffffff0fffL) | (version & 0x0f) << 12; // apply version bits
            lsb = (lsb & 0x3fffffffffffffffL) | 0x8000000000000000L; // apply variant bits

            // Return the UUID
            return new UUID(msb, lsb);

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Message digest algorithm not supported.");
        }
    }

    public static UUID getMd5Uuid(String string) {
        return getHashUuid(null, string, MESSAGE_DIGEST_MD5, VERSION_3);
    }

    public static UUID getSha1Uuid(String string) {
        return getHashUuid(null, string, MESSAGE_DIGEST_SHA1, VERSION_5);
    }

    public static UUID getMd5Uuid(UUID namespace, String string) {
        return getHashUuid(namespace, string, MESSAGE_DIGEST_MD5, VERSION_3);
    }

    public static UUID getSha1Uuid(UUID namespace, String string) {
        return getHashUuid(namespace, string, MESSAGE_DIGEST_SHA1, VERSION_5);
    }

    private static byte[] toBytes(final long number) {
        return new byte[] { (byte) (number >>> 56), (byte) (number >>> 48), (byte) (number >>> 40),
                (byte) (number >>> 32), (byte) (number >>> 24), (byte) (number >>> 16), (byte) (number >>> 8),
                (byte) (number) };
    }

    private static long toNumber(final byte[] bytes, final int start, final int length) {
        long result = 0;
        for (int i = start; i < length; i++) {
            result = (result << 8) | (bytes[i] & 0xff);
        }
        return result;
    }

    /**
     * For tests!
     */
    public static void main(String[] args) {

        String string = "JUST_A_TEST_STRING";
        UUID namespace = UUID.randomUUID(); // A custom name space

        System.out.println("Java's generator");
        System.out.println("UUID.nameUUIDFromBytes():      '" + UUID.nameUUIDFromBytes(string.getBytes()) + "'");
        System.out.println();
        System.out.println("This generator");
        System.out.println("HashUuidCreator.getMd5Uuid():  '" + HashUuidCreator.getMd5Uuid(string) + "'");
        System.out.println("HashUuidCreator.getSha1Uuid(): '" + HashUuidCreator.getSha1Uuid(string) + "'");
        System.out.println();
        System.out.println("This generator WITH name space");
        System.out.println("HashUuidCreator.getMd5Uuid():  '" + HashUuidCreator.getMd5Uuid(namespace, string) + "'");
        System.out.println("HashUuidCreator.getSha1Uuid(): '" + HashUuidCreator.getSha1Uuid(namespace, string) + "'");
    }
}

This is the output:

// Java's generator
UUID.nameUUIDFromBytes():      '9e120341-627f-32be-8393-58b5d655b751'

// This generator
HashUuidCreator.getMd5Uuid():  '9e120341-627f-32be-8393-58b5d655b751'
HashUuidCreator.getSha1Uuid(): 'e4586bed-032a-5ae6-9883-331cd94c4ffa'

// This generator WITH name space
HashUuidCreator.getMd5Uuid():  '2b098683-03c9-3ed8-9426-cf5c81ab1f9f'
HashUuidCreator.getSha1Uuid(): '1ef568c7-726b-58cc-a72a-7df173463bbb'

ALTERNATE GENERATOR

You can also use the uuid-creator library. See these examples:

// Create a random-based UUID
UUID uuid = UuidCreator.getRandomBased();
// Create a name based UUID (SHA1)
String name = "JUST_A_TEST_STRING";
UUID uuid = UuidCreator.getNameBasedSha1(name);

Project page: https://github.com/f4b6a3/uuid-creator

Reading a text file with SQL Server

Just discovered this:

SELECT * FROM OPENROWSET(BULK N'<PATH_TO_FILE>', SINGLE_CLOB) AS Contents

It'll pull in the contents of the file as varchar(max). Replace SINGLE_CLOB with:

SINGLE_NCLOB for nvarchar(max) SINGLE_BLOB for varbinary(max)

Thanks to http://www.mssqltips.com/sqlservertip/1643/using-openrowset-to-read-large-files-into-sql-server/ for this!

How to get JavaScript variable value in PHP

Here is the Working example: Get javascript variable value on the same page.

<script>
var p1 = "success";
</script>

<?php
echo "<script>document.writeln(p1);</script>";
?>

android:drawableLeft margin and/or padding

android:drawablePadding is the easiest way to give padding to drawable icon but You can not give specific one side padding like paddingRight or paddingLeft of drawable icon.To achieve that you have to dig into it. And If you apply paddingLeft or paddingRight to EditText then it will place padding to entire EditText along with drawable icon.

<TextView android:layout_width="match_parent"
    android:padding="5dp"
    android:id="@+id/date"
    android:gravity="center|start"
    android:drawableEnd="@drawable/ic_calendar"
    android:background="@drawable/edit_background"
    android:hint="Not Selected"
    android:drawablePadding="10dp"
    android:paddingStart="10dp"
    android:paddingEnd="10dp"
    android:textColor="@color/black"
    android:layout_height="wrap_content"/>

Making an image act like a button

It sounds like you want an image button:

<input type="image" src="logg.png" name="saveForm" class="btTxt submit" id="saveForm" />

Alternatively, you can use CSS to make the existing submit button use your image as its background.

In any case, you don't want a separate <img /> element on the page.

How to increase executionTimeout for a long-running query?

in my case, I need to have my wcf running for more than 2 hours. Setting and did not work at all. The wcf did not execute longer than maybe 20~30 minutes. So I changed the idle timeout setting of application pool in IIS manager then it worked! In IIS manager, choose your application pool and right click on it and choose advanced settings then change the idle timeout setting to any minutes you want. So, I think setting the web.config and setting the application pool are both needed.

How Stuff and 'For Xml Path' work in SQL Server?

I did debugging and finally returned my 'stuffed' query to it it's normal way.

Simply

select * from myTable for xml path('myTable')

gives me contents of the table to write to a log table from a trigger I debug.

PHPExcel auto size column width

In case somebody was looking for this.

The resolution below also works on PHPSpreadsheet, their new version of PHPExcel.

// assuming $spreadsheet is instance of PhpOffice\PhpSpreadsheet\Spreadsheet
// assuming $worksheet = $spreadsheet->getActiveSheet();
foreach(range('A',$worksheet->getHighestColumn()) as $column) {
    $spreadsheet->getColumnDimension($column)->setAutoSize(true);
}

Note: getHighestColumn() can be replaced with getHighestDataColumn() or the last actual column.

What these methods do:

getHighestColumn($row = null) - Get highest worksheet column.

getHighestDataColumn($row = null) - Get highest worksheet column that contains data.

getHighestRow($column = null) - Get highest worksheet row

getHighestDataRow($column = null) - Get highest worksheet row that contains data.

Eclipse Build Path Nesting Errors

Got similar issue. Did following steps, issue resolved:

  1. Remove project in eclipse.
  2. Delete .Project file and . Settings folder.
  3. Import project as existing maven project again to eclipse.

How do I dump an object's fields to the console?

The to_yaml method seems to be useful sometimes:

$foo = {:name => "Clem", :age => 43}

puts $foo.to_yaml

returns

--- 
:age: 43
:name: Clem

(Does this depend on some YAML module being loaded? Or would that typically be available?)

What jar should I include to use javax.persistence package in a hibernate based application?

In the latest and greatest Hibernate, I was able to resolve the dependency by including the hibernate-jpa-2.0-api-1.0.0.Final.jar within lib/jpa directory. I didn't find the ejb-persistence jar in the most recent download.

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

this works for me, so try it :

Microsoft.Office.Interop.Excel.Range rng =(Microsoft.Office.Interop.Excel.Range)XcelApp.Cells[1, i];
rng.Font.Bold = true; 
rng.Interior.Color =System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
rng.BorderAround(); 

Join/Where with LINQ and Lambda

Daniel has a good explanation of the syntax relationships, but I put this document together for my team in order to make it a little simpler for them to understand. Hope this helps someoneenter image description here

How to extract a string using JavaScript Regex?

Your regular expression most likely wants to be

/\nSUMMARY:(.*)$/g

A helpful little trick I like to use is to default assign on match with an array.

var arr = iCalContent.match(/\nSUMMARY:(.*)$/g) || [""]; //could also use null for empty value
return arr[0];

This way you don't get annoying type errors when you go to use arr

How to change the decimal separator of DecimalFormat from comma to dot/point?

Europe is quite huge. I'm not sure if they use the same format all over. However this or this answer will be of help.

String text = "1,234567";
NumberFormat nf_in = NumberFormat.getNumberInstance(Locale.GERMANY);
double val = nf_in.parse(text).doubleValue();

NumberFormat nf_out = NumberFormat.getNumberInstance(Locale.UK);
nf_out.setMaximumFractionDigits(3);
String output = nf_out.format(val);

I.e. use the correct locale.

Selecting fields from JSON output

Assume you stored that dictionary in a variable called values. To get id in to a variable, do:

idValue = values['criteria'][0]['id']

If that json is in a file, do the following to load it:

import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()

If that json is from a URL, do the following to load it:

import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)
f.close()

To print ALL of the criteria, you could:

for criteria in values['criteria']:
    for key, value in criteria.iteritems():
        print key, 'is:', value
    print ''

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

Arrays should be used in preference to List when the immutability of the collection itself is part of the contract between the client & provider code (not necessarily immutability of the items within the collection) AND when IEnumerable is not suitable.

For example,

var str = "This is a string";
var strChars = str.ToCharArray();  // returns array

It is clear that modification of "strChars" will not mutate the original "str" object, irrespective implementation-level knowledge of "str"'s underlying type.

But suppose that

var str = "This is a string";
var strChars = str.ToCharList();  // returns List<char>
strChars.Insert(0, 'X');

In this case, it's not clear from that code-snippet alone if the insert method will or will not mutate the original "str" object. It requires implementation level knowledge of String to make that determination, which breaks Design by Contract approach. In the case of String, it's not a big deal, but it can be a big deal in almost every other case. Setting the List to read-only does help but results in run-time errors, not compile-time.

How do I register a DLL file on Windows 7 64-bit?

On a x64 system, system32 is for 64 bit and syswow64 is for 32 bit (not the other way around as stated in another answer). WOW (Windows on Windows) is the 32 bit subsystem that runs under the 64 bit subsystem).

It's a mess in naming terms, and serves only to confuse, but that's the way it is.

Again ...

syswow64 is 32 bit, NOT 64 bit.

system32 is 64 bit, NOT 32 bit.

There is a regsrv32 in each of these directories. One is 64 bit, and the other is 32 bit. It is the same deal with odbcad32 and et al. (If you want to see 32-bit ODBC drivers which won't show up with the default odbcad32 in system32 which is 64-bit.)

How do I rename a repository on GitHub?

It is worth noting that if you fork a GitHub project and then rename the newly spawned copy, the new name appears in the members network graph of the parent project. The complementary relationship is preserved as well. This should address any reservations associated with the first point in the original question related to redirects, i.e. you can still get here from there, so to speak. I, too, was hesitant because of the irrevocability implied by the warning, so hopefully this will save others that delay.

Why does Lua have no "continue" statement?

The way that the language manages lexical scope creates issues with including both goto and continue. For example,

local a=0
repeat 
    if f() then
        a=1 --change outer a
    end
    local a=f() -- inner a
until a==0 -- test inner a

The declaration of local a inside the loop body masks the outer variable named a, and the scope of that local extends across the condition of the until statement so the condition is testing the innermost a.

If continue existed, it would have to be restricted semantically to be only valid after all of the variables used in the condition have come into scope. This is a difficult condition to document to the user and enforce in the compiler. Various proposals around this issue have been discussed, including the simple answer of disallowing continue with the repeat ... until style of loop. So far, none have had a sufficiently compelling use case to get them included in the language.

The work around is generally to invert the condition that would cause a continue to be executed, and collect the rest of the loop body under that condition. So, the following loop

-- not valid Lua 5.1 (or 5.2)
for k,v in pairs(t) do
  if isstring(k) then continue end
  -- do something to t[k] when k is not a string
end

could be written

-- valid Lua 5.1 (or 5.2)
for k,v in pairs(t) do
  if not isstring(k) then 
    -- do something to t[k] when k is not a string
  end
end

It is clear enough, and usually not a burden unless you have a series of elaborate culls that control the loop operation.

Telegram Bot - how to get a group chat id?

If you are implementing your bot, keep stored a group name -> id table, and ask it with a command. Then you can also send per name.

How to get the first non-null value in Java?

Just for completness, the "several variables" case is indeed possible, though not elegant at all. For example, for variables o, p, and q:

Optional.ofNullable( o ).orElseGet(()-> Optional.ofNullable( p ).orElseGet(()-> q ) )

Please note the use of orElseGet() attending to the case that o, p, and q are not variables but expressions either expensive or with undesired side-effects.

In the most general case coalesce(e[1],e[2],e[3],...,e[N])

coalesce-expression(i) ==  e[i]  when i = N
coalesce-expression(i) ==  Optional.ofNullable( e[i] ).orElseGet(()-> coalesce-expression(i+1) )  when i < N

This can generate expressions excessively long. However, if we are trying to move to a world without null, then v[i] are most probably already of type Optional<String>, as opposed to simply String. In this case,

result= o.orElse(p.orElse(q.get())) ;

or in the case of expressions:

result= o.orElseGet(()-> p.orElseGet(()-> q.get() ) ) ;

Furthermore, if you are also moving to a functional-declarative style, o, p, and q should be of type Supplier<String> like in:

Supplier<String> q= ()-> q-expr ;
Supplier<String> p= ()-> Optional.ofNullable(p-expr).orElseGet( q ) ;
Supplier<String> o= ()-> Optional.ofNullable(o-expr).orElseGet( p ) ;

And then the whole coalesce reduces simply to o.get().

For a more concrete example:

Supplier<Integer> hardcodedDefaultAge= ()-> 99 ;
Supplier<Integer> defaultAge= ()-> defaultAgeFromDatabase().orElseGet( hardcodedDefaultAge ) ;
Supplier<Integer> ageInStore= ()-> ageFromDatabase(memberId).orElseGet( defaultAge ) ;
Supplier<Integer> effectiveAge= ()-> ageFromInput().orElseGet( ageInStore ) ;

defaultAgeFromDatabase(), ageFromDatabase(), and ageFromInput() would already return Optional<Integer>, naturally.

And then the coalesce becomes effectiveAge.get() or simply effectiveAge if we are happy with a Supplier<Integer>.

IMHO, with Java 8 we will see more and more code structured like this, as it's extremely self-explainatory and efficient at the same time, especially in more complex cases.

I do miss a class Lazy<T> that invokes a Supplier<T> only one time, but lazily, as well as consistency in the definition of Optional<T> (i.e. Optional<T>-Optional<T> operators, or even Supplier<Optional<T>>).

How do I overload the square-bracket operator in C#?

public class CustomCollection : List<Object>
{
    public Object this[int index]
    {
        // ...
    }
}

Difference between /res and /assets directories

Following are some key points :

  1. Raw files Must have names that are valid Java identifiers , whereas files in Assets Have no location and name restrictions. In other words they can be grouped in whatever directories we wish
  2. Raw files Are easy to refer to from Java as well as from xml (i.e you can refer a file in raw from manifest or other xml file).
  3. Saving asset files here instead of in the assets/ directory only differs in the way that you access them as documented here http://developer.android.com/tools/projects/index.html.
  4. Resources defined in a library project are automatically imported to application projects that depend on the library. For assets, that doesn't happen; asset files must be present in the assets directory of the application project(s)
  5. The assets directory is more like a filesystem provides more freedom to put any file you would like in there. You then can access each of the files in that system as you would when accessing any file in any file system through Java . like Game data files , Fonts , textures etc.
  6. Unlike Resources, Assets can can be organized into subfolders in the assets directory However, the only thing you can do with an asset is get an input stream. Thus, it does not make much sense to store your strings or bitmaps in assets, but you can store custom-format data such as input correction dictionaries or game maps.
  7. Raw can give you a compile time check by generating your R.java file however If you want to copy your database to private directory you can use Assets which are made for streaming.

Conclusion

  1. Android API includes a very comfortable Resources framework that is also optimized for most typical use cases for various mobile apps. You should master Resources and try to use them wherever possible.
  2. However, if you need more flexibility for your special case, Assets are there to give you a lower level API that allows organizing and processing your resources with a higher degree of freedom.

Iterate keys in a C++ map

Without Boost, you could do it like this. It would be nice if you could write a cast operator instead of getKeyIterator(), but I can't get it to compile.

#include <map>
#include <unordered_map>


template<typename K, typename V>
class key_iterator: public std::unordered_map<K,V>::iterator {

public:

    const K &operator*() const {
        return std::unordered_map<K,V>::iterator::operator*().first;
    }

    const K *operator->() const {
        return &(**this);
    }
};

template<typename K,typename V>
key_iterator<K,V> getKeyIterator(typename std::unordered_map<K,V>::iterator &it) {
    return *static_cast<key_iterator<K,V> *>(&it);
}

int _tmain(int argc, _TCHAR* argv[])
{
    std::unordered_map<std::string, std::string> myMap;
    myMap["one"]="A";
    myMap["two"]="B";
    myMap["three"]="C";
    key_iterator<std::string, std::string> &it=getKeyIterator<std::string,std::string>(myMap.begin());
    for (; it!=myMap.end(); ++it) {
        printf("%s\n",it->c_str());
    }
}

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

Using this HTML:

<div id="myElement" style="position: absolute">This stays at the top</div>

This is the javascript you want to use. It attaches an event to the window's scroll and moves the element down as far as you've scrolled.

$(window).scroll(function() {
    $('#myElement').css('top', $(this).scrollTop() + "px");
});

As pointed out in the comments below, it's not recommended to attach events to the scroll event - as the user scrolls, it fires A LOT, and can cause performance issues. Consider using it with Ben Alman's debounce/throttle plugin to reduce overhead.

jQuery animate backgroundColor

Bitstorm has the best jquery color animation plugin I've seen. It's an improvement to the jquery color project. It also supports rgba.

http://www.bitstorm.org/jquery/color-animation/

Error Dropping Database (Can't rmdir '.test\', errno: 17)

You may need to check two things.

1- Database Foleder's permission The database you wants to delete must have the same owner as mysql process has.

2- Directory Must be empty Goto the mysql data directory and verify that directory is empty

After that connect your mysql cli and run drop database command again.

openCV video saving in python

As an example :

fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out_corner = cv2.VideoWriter('img_corner_1.avi',fourcc, 20.0, (640, 480))

At that place, have to define X,Y as width and height

But, when you create an image (a blank image for instance) you have to define Y,X as height and width :

    img_corner = np.zeros((480, 640, 3), np.uint8)

How can I process each letter of text using Javascript?

How to process each letter of text (with benchmarks)

https://jsperf.com/str-for-in-of-foreach-map-2

for

Classic and by far the one with the most performance. You should go with this one if you are planning to use it in a performance critical algorithm, or that it requires the maximum compatibility with browser versions.

for (var i = 0; i < str.length; i++) {
  console.info(str[i]);
}

for...of

for...of is the new ES6 for iterator. Supported by most modern browsers. It is visually more appealing and is less prone to typing mistakes. If you are going for this one in a production application, you should be probably using a transpiler like Babel.

let result = '';
for (let letter of str) {
  result += letter;
}

forEach

Functional approach. Airbnb approved. The biggest downside of doing it this way is the split(), that creates a new array to store each individual letter of the string.

Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.

// ES6 version.
let result = '';
str.split('').forEach(letter => {
  result += letter;
});

or

var result = '';
str.split('').forEach(function(letter) {
  result += letter;
});

The following are the ones I dislike.

for...in

Unlike for...of, you get the letter index instead of the letter. It performs pretty badly.

var result = '';
for (var letterIndex in str) {
  result += str[letterIndex];
}

map

Function approach, which is good. However, map isn't meant to be used for that. It should be used when needing to change the values inside an array, which is not the case.

// ES6 version.
var result = '';
str.split('').map(letter => {
  result += letter;
});

or

let result = '';
str.split('').map(function(letter) {
  result += letter;
});

jquery dialog save cancel button styling

after looking at some other threads I came up with this solution to add icons to the buttons in a confirm dialog, which seems to work well in version 1.8.1 and can be modified to do other styling:

$("#confirmBox").dialog({
    modal:true,
    autoOpen:false,        
    buttons: { 
        "Save": function() { ... },                
        "Cancel": function() { ... }
        }
});

var buttons = $('.ui-dialog-buttonpane').children('button');
buttons.removeClass('ui-button-text-only').addClass('ui-button-text-icon');

$(buttons[0]).append("<span class='ui-icon ui-icon-check'></span>");
$(buttons[1]).append("<span class='ui-icon ui-icon-close'></span>");

I'd be interested in seeing if there was a better way to do it, but this seems pretty efficient.

Change Background color (css property) using Jquery

Try below jQuery snippet, you can change color :

<script type="text/javascript">
    $(document).ready(function(){
        $("#co").click(function() {
            $("body").css("background-color", "yellow");
        });
    });
</script>

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $("#co").click(function() {_x000D_
        $("body").css("background-color", "yellow");_x000D_
    });_x000D_
});
_x000D_
body {_x000D_
    background-color:red;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="co" click="change()">hello</div>
_x000D_
_x000D_
_x000D_

How to set java_home on Windows 7?

goto Mycomputer(This PC) -> rightclick ->select properties -> Advanced system settings -> environment variables-> in system variables click "New" button and write JAVA_HOME in variable name and path C:\Program Files\Java\jdk1.8.0_131 were jdk is present in variable value-> click ok.

close and reopen the command prompt after setting JAVA_HOME. Sometimes changes does not reflect in the cmd opened before setting the JAVA_HOME.

you can also set JAVA_HOME through terminal itself: SET JAVA_HOME="C:\Program Files (x86)\Java\jdk1.8.0_131"

List<object>.RemoveAll - How to create an appropriate Predicate

Little bit off topic but say i want to remove all 2s from a list. Here's a very elegant way to do that.

void RemoveAll<T>(T item,List<T> list)
{
    while(list.Contains(item)) list.Remove(item);
}

With predicate:

void RemoveAll<T>(Func<T,bool> predicate,List<T> list)
{
    while(list.Any(predicate)) list.Remove(list.First(predicate));
}

+1 only to encourage you to leave your answer here for learning purposes. You're also right about it being off-topic, but I won't ding you for that because of there is significant value in leaving your examples here, again, strictly for learning purposes. I'm posting this response as an edit because posting it as a series of comments would be unruly.

Though your examples are short & compact, neither is elegant in terms of efficiency; the first is bad at O(n2), the second, absolutely abysmal at O(n3). Algorithmic efficiency of O(n2) is bad and should be avoided whenever possible, especially in general-purpose code; efficiency of O(n3) is horrible and should be avoided in all cases except when you know n will always be very small. Some might fling out their "premature optimization is the root of all evil" battle axes, but they do so naïvely because they do not truly understand the consequences of quadratic growth since they've never coded algorithms that have to process large datasets. As a result, their small-dataset-handling algorithms just run generally slower than they could, and they have no idea that they could run faster. The difference between an efficient algorithm and an inefficient algorithm is often subtle, but the performance difference can be dramatic. The key to understanding the performance of your algorithm is to understand the performance characteristics of the primitives you choose to use.

In your first example, list.Contains() and Remove() are both O(n), so a while() loop with one in the predicate & the other in the body is O(n2); well, technically O(m*n), but it approaches O(n2) as the number of elements being removed (m) approaches the length of the list (n).

Your second example is even worse: O(n3), because for every time you call Remove(), you also call First(predicate), which is also O(n). Think about it: Any(predicate) loops over the list looking for any element for which predicate() returns true. Once it finds the first such element, it returns true. In the body of the while() loop, you then call list.First(predicate) which loops over the list a second time looking for the same element that had already been found by list.Any(predicate). Once First() has found it, it returns that element which is passed to list.Remove(), which loops over the list a third time to yet once again find that same element that was previously found by Any() and First(), in order to finally remove it. Once removed, the whole process starts over at the beginning with a slightly shorter list, doing all the looping over and over and over again starting at the beginning every time until finally no more elements matching the predicate remain. So the performance of your second example is O(m*m*n), or O(n3) as m approaches n.

Your best bet for removing all items from a list that match some predicate is to use the generic list's own List<T>.RemoveAll(predicate) method, which is O(n) as long as your predicate is O(1). A for() loop technique that passes over the list only once, calling list.RemoveAt() for each element to be removed, may seem to be O(n) since it appears to pass over the loop only once. Such a solution is more efficient than your first example, but only by a constant factor, which in terms of algorithmic efficiency is negligible. Even a for() loop implementation is O(m*n) since each call to Remove() is O(n). Since the for() loop itself is O(n), and it calls Remove() m times, the for() loop's growth is O(n2) as m approaches n.

How to show multiline text in a table cell

Two suggestions to solving this problem:

SOLUTION 1: <div style="white-space:pre;">{database text}</div> or <pre>{database text}</pre>

This is good solution if your text has no html tags or css properties. Also allows to maintain tabs for example.

SOLUTION 2: Replace \n with <p></p> or <br/>

This is a solution if you would just like to add break-lines, without losing other text properties or formatting. An example in php would be $text = str_replace("\n","<br />",$database_text);

You can also use <p></p> or <div></div>, but this requires a bit more text parsing.

How to check if a String is numeric in Java

// please check below code

public static boolean isDigitsOnly(CharSequence str) {
    final int len = str.length();
    for (int i = 0; i < len; i++) {
        if (!Character.isDigit(str.charAt(i))) {
            return false;
        }
    }
    return true;
}

Is it possible to override / remove background: none!important with jQuery?

Several problems arise in this question.

Problem #1 - css Specificity (how to override important rule).

According to specification - to override this selector your selector should be 'stronger' which mean it should be!important and have at least 1 id, 1 class and something else - according to you creating this selector is impossible(as you can't alter page content). So the only possible option is to put something into element style which (could be done with js). Note: style rule should also have !important to override.

Problem #2 - background is not a single property - it is a set of properties (see specification)

So you really need to know what are exact names of properties you want to change (in your case it would be background-image)

Problem #3 - How to remove rule already applied (to get previous value)?

Unfortunately css have no mechanism to dismiss rule which qualify for an element - only to override with "stronger" rule. So you won't be able to solve this task with just setting value to something like 'inherit' or 'default' cause value you want to see is neither inherit from parent nor default. To solve this problem you have couple of options.

1) You may already know what is the value you want to apply. For example you can find out this value based on selector used. So in this case you may know that for selector ".image-list li" you need background-image: url("http://placekitten.com/150/50"). If so - just you this script:

jQuery(".image-list li").attr('style', 'background-image: url("http://placekitten.com/150/50") !important; ');

2) If you don't know the value then you can try to alter page content in such a way, that rule you want to dismiss is no longer qualify for element, whereas rule you want to be shown - still qualify. In this case you may temporary remove id from container element. Here is the code:

jQuery("#an-element").attr('id', '');
var backgroundImage = jQuery(".image-list li").css('background-image');
jQuery("#an-element").attr('id', 'an-element');
jQuery(".image-list li").attr('style', 'background-image: ' + backgroundImage + ' !important; ');

Here is link to fiddle http://jsfiddle.net/o3jn9mzo/

3) As third solution - you may generate element which will qualify for desired selection to find out property value - something like this:

var backgroundImage = jQuery("<div class='image-list'><li></li></div>").find('li').css('background-image');
jQuery(".image-list li").attr('style', 'background-image: ' + backgroundImage + ' !important; ');

P.S.: Sorry for really late response.

Writing a dictionary to a text file?

import json

with open('tokenler.json', 'w') as file:
     file.write(json.dumps(mydict, ensure_ascii=False))

How to declare local variables in postgresql?

Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
  one int;
  two int;
BEGIN
  one := 1;
  two := 2;
  RETURN one + two;
END
$$;
SELECT somefuncname();

The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

mysql: get record count between two date-time

May be with:

SELECT count(*) FROM `table` 
where 
    created_at>='2011-03-17 06:42:10' and created_at<='2011-03-17 07:42:50';

or use between:

SELECT count(*) FROM `table` 
where 
    created_at between '2011-03-17 06:42:10' and '2011-03-17 07:42:50';

You can change the datetime as per your need. May be use curdate() or now() to get the desired dates.

How to split data into trainset and testset randomly?

You can try this approach

import pandas
import sklearn
csv = pandas.read_csv('data.csv')
train, test = sklearn.cross_validation.train_test_split(csv, train_size = 0.5)

UPDATE: train_test_split was moved to model_selection so the current way (scikit-learn 0.22.2) to do it is this:

import pandas
import sklearn
csv = pandas.read_csv('data.csv')
train, test = sklearn.model_selection.train_test_split(csv, train_size = 0.5)

How to generate the JPA entity Metamodel?

For Hibernate as provider which is most common IMHO:

In case of build tools like Gradle, Maven you need to have Hibernate JPA 2 Metamodel Generator jar in the classpath and compiler level>=1.6 that is all you need build the project and metamodel will be generated automatically.

In case of IDE Eclipse 1. goto Project->Properties->Java Compiler->Annotation Processing and enable it. 2. Expand Annotation Processing->Factory Path-> Add External Jar add Hibernate JPA 2 Metamodel Generator jar check the newly added jar and say OK. Clean and Build done!

Link Hibernate JPA 2 Metamodel Generator jar link from maven repo https://mvnrepository.com/artifact/org.hibernate/hibernate-jpamodelgen

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

The answer I have finally found is that the SMTP service on the server is not using the same certificate as https.

The diagnostic steps I had read here make the assumption they use the same certificate and every time I've tried this in the past they have done and the diagnostic steps are exactly what I've done to solve the problem several times.

In this case those steps didn't work because the certificates in use were different, and the possibility of this is something I had never come across.

The solution is either to export the actual certificate from the server and then install it as a trusted certificate on my machine, or to get a different valid/trusted certificate for the SMTP service on the server. That is currently with our IT department who administer the servers to decide which they want to do.

Displaying standard DataTables in MVC

This is not "wrong" at all, it's just not what the cool guys typically do with MVC. As an aside, I wish some of the early demos of ASP.NET MVC didn't try to cram in Linq-to-Sql at the same time. It's pretty awesome and well suited for MVC, sure, but it's not required. There is nothing about MVC that prevents you from using ADO.NET. For example:

Controller action:

public ActionResult Index()
{
    ViewData["Message"] = "Welcome to ASP.NET MVC!";

    DataTable dt = new DataTable("MyTable");
    dt.Columns.Add(new DataColumn("Col1", typeof(string)));
    dt.Columns.Add(new DataColumn("Col2", typeof(string)));
    dt.Columns.Add(new DataColumn("Col3", typeof(string)));

    for (int i = 0; i < 3; i++)
    {
        DataRow row = dt.NewRow();
        row["Col1"] = "col 1, row " + i;
        row["Col2"] = "col 2, row " + i;
        row["Col3"] = "col 3, row " + i;
        dt.Rows.Add(row);
    }

    return View(dt); //passing the DataTable as my Model
}

View: (w/ Model strongly typed as System.Data.DataTable)

<table border="1">
    <thead>
        <tr>
            <%foreach (System.Data.DataColumn col in Model.Columns) { %>
                <th><%=col.Caption %></th>
            <%} %>
        </tr>
    </thead>
    <tbody>
    <% foreach(System.Data.DataRow row in Model.Rows) { %>
        <tr>
            <% foreach (var cell in row.ItemArray) {%>
                <td><%=cell.ToString() %></td>
            <%} %>
        </tr>
    <%} %>         
    </tbody>
</table>

Now, I'm violating a whole lot of principles and "best-practices" of ASP.NET MVC here, so please understand this is just a simple demonstration. The code creating the DataTable should reside somewhere outside of the controller, and the code in the View might be better isolated to a partial, or html helper, to name a few ways you should do things.

You absolutely are supposed to pass objects to the View, if the view is supposed to present them. (Separation of concerns dictates the view shouldn't be responsible for creating them.) In this case I passed the DataTable as the actual view Model, but you could just as well have put it in ViewData collection. Alternatively you might make a specific IndexViewModel class that contains the DataTable and other objects, such as the welcome message.

I hope this helps!

How to show text on image when hovering?

You can also use the title attribute in your image tag

<img src="content/assets/thumbnails/transparent_150x150.png" alt="" title="hover text" />

How do I associate file types with an iPhone application?

In addition to Brad's excellent answer, I have found out that (on iOS 4.2.1 at least) when opening custom files from the Mail app, your app is not fired or notified if the attachment has been opened before. The "open with…" popup appears, but just does nothing.

This seems to be fixed by (re)moving the file from the Inbox directory. A safe approach seems to be to both (re)move the file as it is opened (in -(BOOL)application:openURL:sourceApplication:annotation:) as well as going through the Documents/Inbox directory, removing all items, e.g. in applicationDidBecomeActive:. That last catch-all may be needed to get the app in a clean state again, in case a previous import causes a crash or is interrupted.

std::wstring VS std::string

I frequently use std::string to hold utf-8 characters without any problems at all. I heartily recommend doing this when interfacing with API's which use utf-8 as the native string type as well.

For example, I use utf-8 when interfacing my code with the Tcl interpreter.

The major caveat is the length of the std::string, is no longer the number of characters in the string.

READ_EXTERNAL_STORAGE permission for Android

Has your problem been resolved? What is your target SDK? Try adding android;maxSDKVersion="21" to <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Eclipse error "Could not find or load main class"

Removing the JRE System Library and adding the default one worked for me.

Passing data between different controller action methods

If you need to pass data from one controller to another you must pass data by route values.Because both are different request.if you send data from one page to another then you have to user query string(same as route values).

But you can do one trick :

In your calling action call the called action as a simple method :

public class ServerController : Controller
{
 [HttpPost]
 public ActionResult ApplicationPoolsUpdate(ServiceViewModel viewModel)
 {
      XDocument updatedResultsDocument = myService.UpdateApplicationPools();
      ApplicationPoolController pool=new ApplicationPoolController(); //make an object of ApplicationPoolController class.

      return pool.UpdateConfirmation(updatedResultsDocument); // call the ActionMethod you want as a simple method and pass the model as an argument.
      // Redirect to ApplicationPool controller and pass
      // updatedResultsDocument to be used in UpdateConfirmation action method
 }
}

How to install ia32-libs in Ubuntu 14.04 LTS (Trusty Tahr)

Install gcc multiple library.

sudo apt-get install gcc-multilib

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

Convert string to Python class object?

I've looked at how django handles this

django.utils.module_loading has this

def import_string(dotted_path):
    """
    Import a dotted module path and return the attribute/class designated by the
    last name in the path. Raise ImportError if the import failed.
    """
    try:
        module_path, class_name = dotted_path.rsplit('.', 1)
    except ValueError:
        msg = "%s doesn't look like a module path" % dotted_path
        six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])

    module = import_module(module_path)

    try:
        return getattr(module, class_name)
    except AttributeError:
        msg = 'Module "%s" does not define a "%s" attribute/class' % (
            module_path, class_name)
        six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])

You can use it like import_string("module_path.to.all.the.way.to.your_class")

Getting GET "?" variable in laravel

It is not very nice to use native php resources like $_GET as Laravel gives us easy ways to get the variables. As a matter of standard, whenever possible use the resources of the laravel itself instead of pure PHP.

There is at least two modes to get variables by GET in Laravel ( Laravel 5.x or greater):

Mode 1

Route:

Route::get('computers={id}', 'ComputersController@index');

Request (POSTMAN or client...):

http://localhost/api/computers=500

Controler - You can access the {id} paramter in the Controlller by:

public function index(Request $request, $id){
   return $id;
}

Mode 2

Route:

Route::get('computers', 'ComputersController@index');

Request (POSTMAN or client...):

http://localhost/api/computers?id=500

Controler - You can access the ?id paramter in the Controlller by:

public function index(Request $request){
   return $request->input('id');
}

Sql Server trigger insert values from new row into another table

Create 
trigger `[dbo].[mytrigger]` on `[dbo].[Patients]` after update , insert as
begin
     --Sql logic
     print 'Hello world'     
 end 

Detecting value change of input[type=text] in jQuery

you can also use textbox events -

<input id="txt1" type="text" onchange="SetDefault($(this).val());" onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();">

function SetDefault(Text){
  alert(Text);
}

Try This

How do you create a dropdownlist from an enum in ASP.NET MVC?

I found an answer here. However, some of my enums have [Description(...)] attribute, so I've modified the code to provide support for that:

    enum Abc
    {
        [Description("Cba")]
        Abc,

        Def
    }


    public static MvcHtmlString EnumDropDownList<TEnum>(this HtmlHelper htmlHelper, string name, TEnum selectedValue)
    {
        IEnumerable<TEnum> values = Enum.GetValues(typeof(TEnum))
            .Cast<TEnum>();

        List<SelectListItem> items = new List<SelectListItem>();
        foreach (var value in values)
        {
            string text = value.ToString();

            var member = typeof(TEnum).GetMember(value.ToString());
            if (member.Count() > 0)
            {
                var customAttributes = member[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (customAttributes.Count() > 0)
                {
                    text = ((DescriptionAttribute)customAttributes[0]).Description;
                }
            }

            items.Add(new SelectListItem
            {
                Text = text,
                Value = value.ToString(),
                Selected = (value.Equals(selectedValue))
            });
        }

        return htmlHelper.DropDownList(
            name,
            items
            );
    }

Hope that helps.

C++ Calling a function from another class

in A you have used a definition of B which is not given until then , that's why the compiler is giving error .

How do I execute .js files locally in my browser?

If you're using Google Chrome you can use the Chrome Dev Editor: https://github.com/dart-lang/chromedeveditor

PDO get the last ID inserted

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

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

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

MySQL JOIN with LIMIT 1 on joined table

Another example with 3 nested tables: 1/ User 2/ UserRoleCompanie 3/ Companie

  • 1 user has many UserRoleCompanie.
  • 1 UserRoleCompanie has 1 user and 1 Company
  • 1 Companie has many UserRoleCompanie
SELECT 
u.id as userId, 
u.firstName,
u.lastName,
u.email,
urc.id ,
urc.companieRole,
c.id as companieId,
c.name as companieName
FROM User as u 
JOIN UserRoleCompanie as urc ON u.id = urc.userId
    AND urc.id = (
        SELECT urc2.id
        FROM UserRoleCompanie urc2 
        JOIN Companie ON urc2.companieId = Companie.id
        AND urc2.userId = u.id 
        AND Companie.isPersonal = false
        order by Companie.createdAt DESC
        
        limit 1
    )
    
LEFT JOIN Companie as c ON urc.companieId = c.id
+---------------------------+-----------+--------------------+---------------------------+---------------------------+--------------+---------------------------+-------------------+
| userId                    | firstName | lastName           | email                     | id                        | companieRole | companieId                | companieName      |
+---------------------------+-----------+--------------------+---------------------------+---------------------------+--------------+---------------------------+-------------------+
| cjjt9s9iw037f0748raxmnnde | henry     | pierrot            | [email protected]           | cjtuflye81dwt0748e4hnkiv0 | OWNER        | cjtuflye71dws0748r7vtuqmg | leclerc           |

How to know if an object has an attribute in Python

Hope you expecting hasattr(), but try to avoid hasattr() and please prefer getattr(). getattr() is faster than hasattr()

using hasattr():

 if hasattr(a, 'property'):
     print a.property

same here i am using getattr to get property if there is no property it return none

   property = getattr(a,"property",None)
    if property:
        print property

JavaScript: Get image dimensions

This uses the function and waits for it to complete.

http://jsfiddle.net/SN2t6/118/

function getMeta(url){
    var r = $.Deferred();

  $('<img/>').attr('src', url).load(function(){
     var s = {w:this.width, h:this.height};
     r.resolve(s)
  });
  return r;
}

getMeta("http://www.google.hr/images/srpr/logo3w.png").done(function(test){
    alert(test.w + ' ' + test.h);
});

SQL Server: Database stuck in "Restoring" state

I had a similar incident with stopping a log shipping secondary server. After the command to remove the server from log shipping and stopped the log shipping from primary server the database on secondary server got stuck in restoring status after the command

RESTORE DATABASE <database name> WITH RECOVERY

The database messages:

RESTORE DATABASE successfully processed 0 pages in 18.530 seconds (0.000 MB/sec).

The database was usable again after those 18 seconds.

What is POCO in Entity Framework?

POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like

  • Lazy loading
  • Change tracking

Here is a good start for this

POCO Entity framework

You can also generate POCOs so easily from your existing Entity framework project using Code generators.

EF 5.X DbContext code generator

Batch files - number of command line arguments

The last answer was two years ago now, but I needed a version for more than nine command line arguments. May be another one also does...

@echo off
setlocal

set argc_=1
set arg0_=%0
set argv_=

:_LOOP
set arg_=%1
if defined arg_ (
  set arg%argc_%_=%1
  set argv_=%argv_% %1
  set /a argc_+=1
  shift
  goto _LOOP
)
::dont count arg0
set /a argc_-=1
echo %argc_% arg(s)

for /L %%i in (0,1,%argc_%) do (
  call :_SHOW_ARG arg%%i_ %%arg%%i_%%
)

echo converted to local args
call :_LIST_ARGS %argv_%
exit /b


:_LIST_ARGS
setlocal
set argc_=0
echo arg0=%0

:_LOOP_LIST_ARGS
set arg_=%1
if not defined arg_ exit /b
set /a argc_+=1
call :_SHOW_ARG arg%argc_% %1
shift
goto _LOOP_LIST_ARGS


:_SHOW_ARG
echo %1=%2
exit /b

The solution is the first 19 lines and converts all arguments to variables in a c-like style. All other stuff just probes the result and shows conversion to local args. You can reference arguments by index in any function.

JQuery create new select option

A really simple way to do this...

// create the option
var opt = $("<option>").val("myvalue").text("my text");

//append option to the select element
$(#my-select).append(opt);

This could be done in lots of ways, even in a single line if really you want to.

How to create an executable .exe file from a .m file

mcc -?

explains that the syntax to make *.exe (Standalone Application) with *.m is:

 mcc -m <matlabFile.m> 

For example:

mcc -m file.m

will create file.exe in the curent directory.

How to get min, seconds and milliseconds from datetime.now() in python?

Sorry to open an old thread but I'm posting just in case it helps someone. This seems to be the easiest way to do this in Python 3.

from datetime import datetime

Date = str(datetime.now())[:10]
Hour = str(datetime.now())[11:13]
Minute = str(datetime.now())[14:16]
Second = str(datetime.now())[17:19]
Millisecond = str(datetime.now())[20:]

If you need the values as a number just cast them as an int e.g

Hour = int(str(datetime.now())[11:13])

Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {
    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Using json-simple:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...

jquery find class and get the value

var myVar = $("#start").find('myClass').val();

needs to be

var myVar = $("#start").find('.myClass').val();

Remember the CSS selector rules require "." if selecting by class name. The absence of "." is interpreted to mean searching for <myclass></myclass>.

cocoapods - 'pod install' takes forever

As of 15th August 2016, the repo is a massive 2.39GB file. I opened the Activity Monitor to look at what the terminal was doing. It was downloading this huge file.

Telling gcc directly to link a library statically

It is possible of course, use -l: instead of -l. For example -l:libXYZ.a to link with libXYZ.a. Notice the lib written out, as opposed to -lXYZ which would auto expand to libXYZ.

HTML/CSS font color vs span style

Use style. The font tag is deprecated (W3C Wiki).

cursor.fetchall() vs list(cursor) in Python

You could use list comprehensions to bring the item in your tuple into a list:

conn = mysql.connector.connect()
cursor = conn.cursor()
sql = "SELECT column_name FROM db.table_name;"
cursor.execute(sql)

results = cursor.fetchall()
# bring the first item of the tuple in your results here
item_0_in_result = [_[0] for _ in results]

How can I print the contents of an array horizontally?

The below solution is the simplest one:

Console.WriteLine("[{0}]", string.Join(", ", array));

Output: [1, 2, 3, 4, 5]

Another short solution:

Array.ForEach(array,  val => Console.Write("{0} ", val));

Output: 1 2 3 4 5. Or if you need to add add ,, use the below:

int i = 0;
Array.ForEach(array,  val => Console.Write(i == array.Length -1) ? "{0}" : "{0}, ", val));

Output: 1, 2, 3, 4, 5

How do I decode a base64 encoded string?

The m000493 method seems to perform some kind of XOR encryption. This means that the same method can be used for both encrypting and decrypting the text. All you have to do is reverse m0001cd:

string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));

string result = m000493(p0, "_p0lizei.");
//    result == "gaia^unplugged^Ta..."

with return m0001cd(builder3.ToString()); changed to return builder3.ToString();.

Getting RAW Soap Data from a Web Reference Client running in ASP.net

Try Fiddler2 it will let you inspect the requests and response. It might be worth noting that Fiddler works with both http and https traffic.

How do I declare and initialize an array in Java?

Array is a sequential list of items

int item = value;

int [] one_dimensional_array = { value, value, value, .., value };

int [][] two_dimensional_array =
{
  { value, value, value, .. value },
  { value, value, value, .. value },
    ..     ..     ..        ..
  { value, value, value, .. value }
};

If it's an object, then it's the same concept

Object item = new Object();

Object [] one_dimensional_array = { new Object(), new Object(), .. new Object() };

Object [][] two_dimensional_array =
{
  { new Object(), new Object(), .. new Object() },
  { new Object(), new Object(), .. new Object() },
    ..            ..               ..
  { new Object(), new Object(), .. new Object() }
};

In case of objects, you need to either assign it to null to initialize them using new Type(..), classes like String and Integer are special cases that will be handled as following

String [] a = { "hello", "world" };
// is equivalent to
String [] a = { new String({'h','e','l','l','o'}), new String({'w','o','r','l','d'}) };

Integer [] b = { 1234, 5678 };
// is equivalent to
Integer [] b = { new Integer(1234), new Integer(5678) };

In general you can create arrays that's M dimensional

int [][]..[] array =
//  ^ M times [] brackets

    {{..{
//  ^ M times { bracket

//            this is array[0][0]..[0]
//                         ^ M times [0]

    }}..}
//  ^ M times } bracket
;

It's worthy to note that creating an M dimensional array is expensive in terms of Space. Since when you create an M dimensional array with N on all the dimensions, The total size of the array is bigger than N^M, since each array has a reference, and at the M-dimension there is an (M-1)-dimensional array of references. The total size is as following

Space = N^M + N^(M-1) + N^(M-2) + .. + N^0
//      ^                              ^ array reference
//      ^ actual data

What does --net=host option in Docker command really do?

After the docker installation you have 3 networks by default:

docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
f3be8b1ef7ce        bridge              bridge              local
fbff927877c1        host                host                local
023bb5940080        none                null                local

I'm trying to keep this simple. So if you start a container by default it will be created inside the bridge (docker0) network.

$ docker run -d jenkins
1498e581cdba        jenkins             "/bin/tini -- /usr..."   3 minutes ago       Up 3 minutes        8080/tcp, 50000/tcp   friendly_bell

In the dockerfile of jenkins the ports 8080 and 50000 are exposed. Those ports are opened for the container on its bridge network. So everything inside that bridge network can access the container on port 8080 and 50000. Everything in the bridge network is in the private range of "Subnet": "172.17.0.0/16", If you want to access them from the outside you have to map the ports with -p 8080:8080. This will map the port of your container to the port of your real server (the host network). So accessing your server on 8080 will route to your bridgenetwork on port 8080.

Now you also have your host network. Which does not containerize the containers networking. So if you start a container in the host network it will look like this (it's the first one):

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                 NAMES
1efd834949b2        jenkins             "/bin/tini -- /usr..."   6 minutes ago       Up 6 minutes                              eloquent_panini
1498e581cdba        jenkins             "/bin/tini -- /usr..."   10 minutes ago      Up 10 minutes       8080/tcp, 50000/tcp   friendly_bell

The difference is with the ports. Your container is now inside your host network. So if you open port 8080 on your host you will acces the container immediately.

$ sudo iptables -I INPUT 5 -p tcp -m tcp --dport 8080 -j ACCEPT

I've opened port 8080 in my firewall and when I'm now accesing my server on port 8080 I'm accessing my jenkins. I think this blog is also useful to understand it better.

npm - how to show the latest version of a package

There is also another easy way to check the latest version without going to NPM if you are using VS Code.

In package.json file check for the module you want to know the latest version. Remove the current version already present there and do CTRL + space or CMD + space(mac).The VS code will show the latest versions

image shows the latest versions of modules in vscode

Remove a prefix from a string

I think you can use methods of the str type to do this. There's no need for regular expressions:

def remove_prefix(text, prefix):
    if text.startswith(prefix): # only modify the text if it starts with the prefix
         text = text.replace(prefix, "", 1) # remove one instance of prefix
    return text

FIX CSS <!--[if lt IE 8]> in IE

[if lt IE 8] means "if lower than IE8" - and thats why it isn't working in IE8.

wahat you want is [if lte IE 8] which means "if lower than or equal IE8".

How can I write an anonymous function in Java?

if you mean an anonymous function, and are using a version of Java before Java 8, then in a word, no. (Read about lambda expressions if you use Java 8+)

However, you can implement an interface with a function like so :

Comparator<String> c = new Comparator<String>() {
    int compare(String s, String s2) { ... }
};

and you can use this with inner classes to get an almost-anonymous function :)

Modify SVG fill color when being served as Background-Image

You can store the SVG in a variable. Then manipulate the SVG string depending on your needs (i.e., set width, height, color, etc). Then use the result to set the background, e.g.

$circle-icon-svg: '<svg xmlns="http://www.w3.org/2000/svg"><circle cx="10" cy="10" r="10" /></svg>';

$icon-color: #f00;
$icon-color-hover: #00f;

@function str-replace($string, $search, $replace: '') {
    $index: str-index($string, $search);

    @if $index {
        @return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
    }

    @return $string;
}

@function svg-fill ($svg, $color) {
  @return str-replace($svg, '<svg', '<svg fill="#{$color}"');
}

@function svg-size ($svg, $width, $height) {
  $svg: str-replace($svg, '<svg', '<svg width="#{$width}"');
  $svg: str-replace($svg, '<svg', '<svg height="#{$height}"');

  @return $svg;
}

.icon {
  $icon-svg: svg-size($circle-icon-svg, 20, 20);

  width: 20px; height: 20px; background: url('data:image/svg+xml;utf8,#{svg-fill($icon-svg, $icon-color)}');

  &:hover {
    background: url('data:image/svg+xml;utf8,#{svg-fill($icon-svg, $icon-color-hover)}');
  }
}

I have made a demo too, http://sassmeister.com/gist/4cf0265c5d0143a9e734.

This code makes a few assumptions about the SVG, e.g. that <svg /> element does not have an existing fill colour and that neither width or height properties are set. Since the input is hardcoded in the SCSS document, it is quite easy to enforce these constraints.

Do not worry about the code duplication. compression makes the difference negligible.

Failed to add the host to the list of know hosts

In your specific case, your known_hosts is a folder, so you need to remove it first.

For other people which experiencing similar issue, please check the right permission to your ~/ssh/known_hosts as it may be owned by different user (e.g. root). So you may try to run:

sudo chown -v $USER ~/.ssh/known_hosts

to fix it.

How do I rename a column in a database table using SQL?

In Informix, you can use:

RENAME COLUMN TableName.OldName TO NewName;

This was implemented before the SQL standard addressed the issue - if it is addressed in the SQL standard. My copy of the SQL 9075:2003 standard does not show it as being standard (amongst other things, RENAME is not one of the keywords). I don't know whether it is actually in SQL 9075:2008.

What method in the String class returns only the first N characters?

Partially for the sake of summarization (excluding LINQ solution), here's two one-liners that address the int maxLength caveat of allowing negative values and also the case of null string:

  1. The Substring way (from Paul Ruane's answer):
public static string Truncate(this string s, uint maxLength) =>
    s?.Substring(0, Math.Min(s.Length, (int)maxLength));
  1. The Remove way (from kbrimington's answer):
public static string Truncate(this string s, uint maxLength) =>
    s?.Length > maxLength ? s.Remove((int)maxLength) : s;

Correct format specifier to print pointer or address?

As an alternative to the other (very good) answers, you could cast to uintptr_t or intptr_t (from stdint.h/inttypes.h) and use the corresponding integer conversion specifiers. This would allow more flexibility in how the pointer is formatted, but strictly speaking an implementation is not required to provide these typedefs.

How do you read CSS rule values with JavaScript?

Some browser differences to be aware of:

Given the CSS:

div#a { ... }
div#b, div#c { ... }

and given InsDel's example, classes will have 2 classes in FF and 3 classes in IE7.

My example illustrates this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <style>
    div#a { }
    div#b, div#c { }
    </style>
    <script>
    function PrintRules() {
    var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules
        for(var x=0;x<rules.length;x++) {
            document.getElementById("rules").innerHTML += rules[x].selectorText + "<br />";
        }
    }
    </script>
</head>
<body>
    <input onclick="PrintRules()" type="button" value="Print Rules" /><br />
    RULES:
    <div id="rules"></div>
</body>
</html>

Cannot get to $rootScope

I don't suggest you to use syntax like you did. AngularJs lets you to have different functionalities as you want (run, config, service, factory, etc..), which are more professional.In this function you don't even have to inject that by yourself like

MainCtrl.$inject = ['$scope', '$rootScope', '$location', 'socket', ...];

you can use it, as you know.

[Vue warn]: Property or method is not defined on the instance but referenced during render

If you use two times vue instance. Then it will give you this error. For example in app.js and your own script tag in view file. Just use one time

 const app = new Vue({
    el: '#app',
});

Query to convert from datetime to date mysql

Use the DATE function:

SELECT DATE(orders.date_purchased) AS date

How to trigger HTML button when you press Enter in textbox?

This should do it, I am using jQuery you can write plain javascript.
Replace sendMessage() with your functionality.

$('#addLinks').keypress(function(e) {
    if (e.which == 13) {
        sendMessage();
        e.preventDefault();
    }
});

View/edit ID3 data for MP3 files

UltraID3Lib...

Be aware that UltraID3Lib is no longer officially available, and thus no longer maintained. See comments below for the link to a Github project that includes this library

//using HundredMilesSoftware.UltraID3Lib;
UltraID3 u = new UltraID3();
u.Read(@"C:\mp3\song.mp3");
//view
Console.WriteLine(u.Artist);
//edit
u.Artist = "New Artist";
u.Write();

Best way to store time (hh:mm) in a database

Are you sure you will only ever need the hours and minutes? If you want to do anything meaningful with it (like for example compute time spans between two such data points) not having information about time zones and DST may give incorrect results. Time zones do maybe not apply in your case, but DST most certainly will.

Number of days between past date and current date in Google spreadsheet

If you are using the two formulas at the same time, it will not work... Here is a simple spreadsheet with it working: https://docs.google.com/spreadsheet/ccc?key=0AiOy0YDBXjt4dDJSQWg1Qlp6TEw5SzNqZENGOWgwbGc If you are still getting problems I would need to know what type of erroneous result you are getting.

Today() returns a numeric integer value: Returns the current computer system date. The value is updated when your document recalculates. TODAY is a function without arguments.

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

You did not include jquery library. In jsfiddle its already there. Just include this line in your head section.

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">

Where Sticky Notes are saved in Windows 10 1607

Here what i found. C:\Users\User\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\TempState

There is snapshot of your sticky note in .png format. Open it and create your new note.

How to read large text file on windows?

If all you need is a tool for reading, then this thing will open the file instantly http://www.readfileonline.com/

Submit form without page reloading

A further possibility is to make a direct javascript link to your function:

<form action="javascript:your_function();" method="post">

...

Run Batch File On Start-up

To start the batch file at the start of your system, you can also use a registry key.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

Here you can create a string. As name you can choose anything and the data is the full path to your file.

There is also the registry key

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce

to run something at only the next start of your system.

Convert time in HH:MM:SS format to seconds only?

function time2sec($time) {
    $durations = array_reverse(explode(':', $item->duration));
    $second = array_shift($durations);
    foreach ($durations as $duration) {
        $second += (60 * $duration);
    }
    return $second;
}
echo time2sec('4:52'); // 292
echo time2sec('2:01:42'); // 7302

What is the difference between required and ng-required?

I would like to make a addon for tiago's answer:

Suppose you're hiding element using ng-show and adding a required attribute on the same:

<div ng-show="false">
    <input required name="something" ng-model="name"/>
</div>

will throw an error something like :

An invalid form control with name='' is not focusable

This is because you just cannot impose required validation on hidden elements. Using ng-required makes it easier to conditionally apply required validation which is just awesome!!

VBA Macro On Timer style to run code every set number of seconds, i.e. 120 seconds

My solution:

Option Explicit
Public datHora As Date

Function Cronometro(action As Integer) As Integer 
'This return the seconds between two >calls
Cronometro = 0
  If action = 1 Then 'Start
    datHora = Now
  End If
  If action = 2 Then 'Time until that moment
    Cronometro = DateDiff("s", datHora, Now)
  End If
End Function

How to use? Easy...

dummy= Cronometro(1) ' This starts the timer

seconds= Cronometro(2) ' This returns the seconds between the first call and this one

Getting fb.me URL

I'm not aware of any way to programmatically create these URLs, but the existing username space (www.facebook.com/something) works on fb.me also (e.g. http://fb.me/facebook )

Transposing a 1D NumPy array

You can only transpose a 2D array. You can use numpy.matrix to create a 2D array. This is three years late, but I am just adding to the possible set of solutions:

import numpy as np
m = np.matrix([2, 3])
m.T

How do you import an Eclipse project into Android Studio now?

Simple steps: 1.Go to Android Studio. 2.Close all open projects if any. 3.There will be an option which says import non Android Studio Projects(Eclipse ect). 4.Click on it and choose ur project Thats't it enjoy!!!

Generating random number between 1 and 10 in Bash Shell Script

Here is example of pseudo-random generator when neither $RANDOM nor /dev/urandom is available

echo $(date +%S) | grep -o .$ | sed s/0/10/

Have a variable in images path in Sass?

No need for a function:

$assetPath : "/assets/images";

...

body {
  margin: 0 auto;
  background: url(#{$assetPath}/site/background.jpg) repeat-x fixed 0 0;
  width: 100%; }

See the interpolation docs for details.

Visual Studio 2010 always thinks project is out of date, but nothing has changed

I had a similar issue with Visual Studio 2005, and my solution consisted of five projects in the following dependency (first built at top):

Video_Codec depends on nothing
Generic_Graphics depends on Video_Codec
SpecificAPI_Graphics depends on Generic_Graphics
Engine depends on Specific_Graphics
Application depends on Engine.

I was finding that the Video_Codec project wanted a full build even after a full clean then rebuild of the solution.

I fixed this by ensuring the pdb output file of both the C/C++ and linker matched the location used by the other working projects. I also switched RTTI on.

Why are C# 4 optional parameters defined on interface not enforced on implementing class?

Just want to add my take here, as the other answers do provide reasonable explanations, but not ones that fully satisfy me.

Optional parameters are syntactic sugar for compile-time injection of the default value at the call site. This doesn't have anything to do with interfaces/implementations, and it can be seen as purely a side-effect of methods with optional parameters. So, when you call the method,

public void TestMethod(bool value = false) { /*...*/ }

like SomeClass.TestMethod(), it is actually SomeClass.TestMethod(false). If you call this method on an interface, from static type-checking, the method signature has the optional parameter. If you call this method on a deriving class's instance that doesn't have the optional parameter, from static type-checking, the method signature does not have the optional parameter, and must be called with full arguments.

Due to how optional parameters are implemented, this is the natural design result.

XPath - Difference between node() and text()

Select the text of all items under produce:

//produce/item/text()

Select all the manager nodes in all departments:

//department/*

How to create a simple proxy in C#?

The browser is connected to the proxy so the data that the proxy gets from the web server is just sent via the same connection that the browser initiated to the proxy.

How to update column with null value

use is instead of =

Eg: Select * from table_name where column is null

How can I autoplay a video using the new embed code style for Youtube?

Just add ?autoplay=1 after url in embed code, example :

<iframe width="420" height="315" src="http://www.youtube.com/embed/
oHg5SJYRHA0" frameborder="0"></iframe>

Change it to:

<iframe width="420" height="315" src="http://www.youtube.com/embed/
oHg5SJYRHA0?autoplay=1" frameborder="0"></iframe>

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

If you want it short this should work.

Uri uri= data.getData();
File file= new File(uri.getPath());
file.getName();

Static Block in Java

It's a block of code which is executed when the class gets loaded by a classloader. It is meant to do initialization of static members of the class.

It is also possible to write non-static initializers, which look even stranger:

public class Foo {
    {
        // This code will be executed before every constructor
        // but after the call to super()
    }

    Foo() {

    }
}

Regular expression to match any character being repeated more than 10 times

use the {10,} operator:

$: cat > testre
============================
==
==============

$: grep -E '={10,}' testre
============================
==============

ggplot with 2 y axes on each side and different scales

The answer by Hadley gives an interesting reference to Stephen Few's report Dual-Scaled Axes in Graphs Are They Ever the Best Solution?.

I do not know what the OP means with "counts" and "rate" but a quick search gives me Counts and Rates, so I get some data about Accidents in North American Mountaineering1:

Years<-c("1998","1999","2000","2001","2002","2003","2004")
Persons.Involved<-c(281,248,301,276,295,231,311)
Fatalities<-c(20,17,24,16,34,18,35)
rate=100*Fatalities/Persons.Involved
df<-data.frame(Years=Years,Persons.Involved=Persons.Involved,Fatalities=Fatalities,rate=rate)
print(df,row.names = FALSE)

 Years Persons.Involved Fatalities      rate
  1998              281         20  7.117438
  1999              248         17  6.854839
  2000              301         24  7.973422
  2001              276         16  5.797101
  2002              295         34 11.525424
  2003              231         18  7.792208
  2004              311         35 11.254019

And then I tried to do the graph as Few suggested at page 7 of the aforementioned report (and following the request of OP to graph the counts as a bar chart and the rates as a line chart) :

The other less obvious solution, which works only for time series, is to convert all sets of values to a common quantitative scale by displaying percentage differences between each value and a reference (or index) value. For instance, select a particular point in time, such as the first interval that appears in the graph, and express each subsequent value as the percentage difference between it and the initial value. This is done by dividing the value at each point in time by the value for the initial point in time and then multiplying it by 100 to convert the rate to a percentage, as illustrated below.

df2<-df
df2$Persons.Involved <- 100*df$Persons.Involved/df$Persons.Involved[1]
df2$rate <- 100*df$rate/df$rate[1]
plot(ggplot(df2)+
  geom_bar(aes(x=Years,weight=Persons.Involved))+
  geom_line(aes(x=Years,y=rate,group=1))+
  theme(text = element_text(size=30))
  )

And this is the result: enter image description here

But I do not like it a lot and I am not able to easily put a legend on it...

1 WILLIAMSON, Jed, et al. Accidents in North American Mountaineering 2005. The Mountaineers Books, 2005.

Ajax post request in laravel 5 return error 500 (Internal Server Error)

I guess this has been solved by now but still the best thing to do here is to send the token with your form

{!! csrf_field() !!}

and then in your ajax

$("#try").click(function(){
var url = $(this).attr("data-link");
$.ajax({
    url: "test",
    type:"POST",
    data: { '_token': token, 'someOtherData': someOtherData },
    success:function(data){
        alert(data);
    },error:function(){ 
        alert("error!!!!");
    }
}); //end of ajax
});

What is an 'undeclared identifier' error and how do I fix it?

These error meassages

1.For the Visual Studio compiler: error C2065: 'printf' : undeclared identifier
2.For the GCC compiler: `printf' undeclared (first use in this function)

mean that you use name printf but the compiler does not see where the name was declared and accordingly does not know what it means.

Any name used in a program shall be declared before its using. The compiler has to know what the name denotes.

In this particular case the compiler does not see the declaration of name printf . As we know (but not the compiler) it is the name of standard C function declared in header <stdio.h> in C or in header <cstdio> in C++ and placed in standard (std::) and global (::) (not necessarily) name spaces.

So before using this function we have to provide its name declaration to the compiler by including corresponding headers.

For example C:

#include <stdio.h>

int main( void )
{
   printf( "Hello World\n" );
}

C++:

#include <cstdio>

int main()
{
   std::printf( "Hello World\n" );
   // or printf( "Hello World\n" );
   // or ::printf( "Hello World\n" );
}

Sometimes the reason of such an error is a simple typo. For example let's assume that you defined function PrintHello

void PrintHello()
{
    std::printf( "Hello World\n" );
}

but in main you made a typo and instead of PrintHello you typed printHello with lower case letter 'p'.

#include <cstdio>

void PrintHello()
{
    std::printf( "Hello World\n" );
}

int main()
{
   printHello();
}

In this case the compiler will issue such an error because it does not see the declaration of name printHello. PrintHello and printHello are two different names one of which was declared and other was not declared but used in the body of main

How can I make window.showmodaldialog work in chrome 37?

The window.returnValue property does not work directly when you are opening a window using window.open() while it does work when you are using window.showModalDialog()

So in your case you have two options to achieve what you are trying to do.

Option 1 - Using window.showModalDialog()

In your parent page

var answer = window.showModalDialog(<your page and other arguments>)
if (answer == 1)
 { do some thing with answer }

and inside your child page you can make use of the window.returnValue directly like

window.returnValue = 'value that you want to return';

showModalDialog halts the executions of the JavaScript until the dialog box is closed and can get a return value from the opened dialog box when its closing.But the problem with showModalDialog is that it is not supported on many modern browsers. In contrast window.open just opens a window asynchronously (User can access both the parent window and the opened window). And the JavaScript execution will continue immediately. Which bring us to Option 2

Option 2 - Using window.open() In your parent page write a function that deals with opening of your dialog.

function openDialog(url, width, height, callback){
if(window.showModalDialog){
    options = 'dialogHeight: '+ height + '; dialogWidth: '+ width + '; scroll=no'
    var returnValue = window.showModalDialog(url,this,options);
    callback(returnValue)
}
else {
    options ='toolbar=no, directories=no, location=no, status=yes, menubar=no, resizable=yes, scrollbars=no, width=' + width + ', height=' + height; 
        var childWindow = window.open(url,"",options);
        $(childWindow).on('unload',function(){
            if (childWindow.isOpened == null) {
                childWindow.isOpened = 1;
            }
            else {
                if(callback){
                    callback(childWindow.returnValue);
                }
            }
        });
}

}

And whenever you want to use open a dialog. Write a callback that deals with the return value and pass it as a parameter to openDialog function

function callback(returnValue){
if(returnValue){
    do something nice with the returnValue
}}

And when calling the function

openDialog(<your page>, 'width px', 'height px', callbak);

Check out an article on how to replace window.showModalDialog with window.open

How do you change the launcher logo of an app in Android Studio?

In the manifest file, under the tag, there will be a similar line:

android:icon="drawable_resource_path"

Place the launcher icon you want in drawable folder and write its resource path.

Getting DOM node from React child element

This may be possible by using the refs attribute.

In the example of wanting to to reach a <div> what you would want to do is use is <div ref="myExample">. Then you would be able to get that DOM node by using React.findDOMNode(this.refs.myExample).

From there getting the correct DOM node of each child may be as simple as mapping over this.refs.myExample.children(I haven't tested that yet) but you'll at least be able to grab any specific mounted child node by using the ref attribute.

Here's the official react documentation on refs for more info.