Programs & Examples On #Cinema 4d

Cinema 4d is 3D modeling tool developed by MAXON Computer GmbH.

What are the differences between a clustered and a non-clustered index?

// Copied from MSDN, the second point of non-clustered index is not clearly mentioned in the other answers.

Clustered

  • Clustered indexes sort and store the data rows in the table or view based on their key values. These are the columns included in the index definition. There can be only one clustered index per table, because the data rows themselves can be stored in only one order.
  • The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. When a table has a clustered index, the table is called a clustered table. If a table has no clustered index, its data rows are stored in an unordered structure called a heap.

Nonclustered

  • Nonclustered indexes have a structure separate from the data rows. A nonclustered index contains the nonclustered index key values and
    each key value entry has a pointer to the data row that contains the key value.
  • The pointer from an index row in a nonclustered index to a data row is called a row locator. The structure of the row locator depends on whether the data pages are stored in a heap or a clustered table. For a heap, a row locator is a pointer to the row. For a clustered table, the row locator is the clustered index key.

How to send a model in jQuery $.ajax() post request to MVC controller method

In ajax call mention-

data:MakeModel(),

use the below function to bind data to model

function MakeModel() {

    var MyModel = {};

    MyModel.value = $('#input element id').val() or your value;

    return JSON.stringify(MyModel);
}

Attach [HttpPost] attribute to your controller action

on POST this data will get available

html div onclick event

The problem was that clicking the anchor still triggered a click in your <div>. That's called "event bubbling".

In fact, there are multiple solutions:

  • Checking in the DIV click event handler whether the actual target element was the anchor
    → jsFiddle

    $('.expandable-panel-heading').click(function (evt) {
        if (evt.target.tagName != "A") {
            alert('123');
        }
    
        // Also possible if conditions:
        // - evt.target.id != "ancherComplaint"
        // - !$(evt.target).is("#ancherComplaint")
    });
    
    $("#ancherComplaint").click(function () {
        alert($(this).attr("id"));
    });
    
  • Stopping the event propagation from the anchor click listener
    → jsFiddle

    $("#ancherComplaint").click(function (evt) {
        evt.stopPropagation();
        alert($(this).attr("id"));
    });
    


As you may have noticed, I have removed the following selector part from my examples:

:not(#ancherComplaint)

This was unnecessary because there is no element with the class .expandable-panel-heading which also have #ancherComplaint as its ID.

I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.

REST API Token-based Authentication

In the web a stateful protocol is based on having a temporary token that is exchanged between a browser and a server (via cookie header or URI rewriting) on every request. That token is usually created on the server end, and it is a piece of opaque data that has a certain time-to-live, and it has the sole purpose of identifying a specific web user agent. That is, the token is temporary, and becomes a STATE that the web server has to maintain on behalf of a client user agent during the duration of that conversation. Therefore, the communication using a token in this way is STATEFUL. And if the conversation between client and server is STATEFUL it is not RESTful.

The username/password (sent on the Authorization header) is usually persisted on the database with the intent of identifying a user. Sometimes the user could mean another application; however, the username/password is NEVER intended to identify a specific web client user agent. The conversation between a web agent and server based on using the username/password in the Authorization header (following the HTTP Basic Authorization) is STATELESS because the web server front-end is not creating or maintaining any STATE information whatsoever on behalf of a specific web client user agent. And based on my understanding of REST, the protocol states clearly that the conversation between clients and server should be STATELESS. Therefore, if we want to have a true RESTful service we should use username/password (Refer to RFC mentioned in my previous post) in the Authorization header for every single call, NOT a sension kind of token (e.g. Session tokens created in web servers, OAuth tokens created in authorization servers, and so on).

I understand that several called REST providers are using tokens like OAuth1 or OAuth2 accept-tokens to be be passed as "Authorization: Bearer " in HTTP headers. However, it appears to me that using those tokens for RESTful services would violate the true STATELESS meaning that REST embraces; because those tokens are temporary piece of data created/maintained on the server side to identify a specific web client user agent for the valid duration of a that web client/server conversation. Therefore, any service that is using those OAuth1/2 tokens should not be called REST if we want to stick to the TRUE meaning of a STATELESS protocol.

Rubens

UnicodeEncodeError: 'latin-1' codec can't encode character

Character U+201C Left Double Quotation Mark is not present in the Latin-1 (ISO-8859-1) encoding.

It is present in code page 1252 (Western European). This is a Windows-specific encoding that is based on ISO-8859-1 but which puts extra characters into the range 0x80-0x9F. Code page 1252 is often confused with ISO-8859-1, and it's an annoying but now-standard web browser behaviour that if you serve your pages as ISO-8859-1, the browser will treat them as cp1252 instead. However, they really are two distinct encodings:

>>> u'He said \u201CHello\u201D'.encode('iso-8859-1')
UnicodeEncodeError
>>> u'He said \u201CHello\u201D'.encode('cp1252')
'He said \x93Hello\x94'

If you are using your database only as a byte store, you can use cp1252 to encode and other characters present in the Windows Western code page. But still other Unicode characters which are not present in cp1252 will cause errors.

You can use encode(..., 'ignore') to suppress the errors by getting rid of the characters, but really in this century you should be using UTF-8 in both your database and your pages. This encoding allows any character to be used. You should also ideally tell MySQL you are using UTF-8 strings (by setting the database connection and the collation on string columns), so it can get case-insensitive comparison and sorting right.

How to listen to route changes in react router v4?

import React, { useEffect } from 'react';
import { useLocation } from 'react-router';

function MyApp() {

  const location = useLocation();

  useEffect(() => {
      console.log('route has been changed');
      ...your code
  },[location.pathname]);

}

with hooks

Does "git fetch --tags" include "git fetch"?

Note: starting with git 1.9/2.0 (Q1 2014), git fetch --tags fetches tags in addition to what are fetched by the same command line without the option.

See commit c5a84e9 by Michael Haggerty (mhagger):

Previously, fetch's "--tags" option was considered equivalent to specifying the refspec

refs/tags/*:refs/tags/*

on the command line; in particular, it caused the remote.<name>.refspec configuration to be ignored.

But it is not very useful to fetch tags without also fetching other references, whereas it is quite useful to be able to fetch tags in addition to other references.
So change the semantics of this option to do the latter.

If a user wants to fetch only tags, then it is still possible to specifying an explicit refspec:

git fetch <remote> 'refs/tags/*:refs/tags/*'

Please note that the documentation prior to 1.8.0.3 was ambiguous about this aspect of "fetch --tags" behavior.
Commit f0cb2f1 (2012-12-14) fetch --tags made the documentation match the old behavior.
This commit changes the documentation to match the new behavior (see Documentation/fetch-options.txt).

Request that all tags be fetched from the remote in addition to whatever else is being fetched.


Since Git 2.5 (Q2 2015) git pull --tags is more robust:

See commit 19d122b by Paul Tan (pyokagan), 13 May 2015.
(Merged by Junio C Hamano -- gitster -- in commit cc77b99, 22 May 2015)

pull: remove --tags error in no merge candidates case

Since 441ed41 ("git pull --tags": error out with a better message., 2007-12-28, Git 1.5.4+), git pull --tags would print a different error message if git-fetch did not return any merge candidates:

It doesn't make sense to pull all tags; you probably meant:
       git fetch --tags

This is because at that time, git-fetch --tags would override any configured refspecs, and thus there would be no merge candidates. The error message was thus introduced to prevent confusion.

However, since c5a84e9 (fetch --tags: fetch tags in addition to other stuff, 2013-10-30, Git 1.9.0+), git fetch --tags would fetch tags in addition to any configured refspecs.
Hence, if any no merge candidates situation occurs, it is not because --tags was set. As such, this special error message is now irrelevant.

To prevent confusion, remove this error message.


With Git 2.11+ (Q4 2016) git fetch is quicker.

See commit 5827a03 (13 Oct 2016) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 9fcd144, 26 Oct 2016)

fetch: use "quick" has_sha1_file for tag following

When fetching from a remote that has many tags that are irrelevant to branches we are following, we used to waste way too many cycles when checking if the object pointed at by a tag (that we are not going to fetch!) exists in our repository too carefully.

This patch teaches fetch to use HAS_SHA1_QUICK to sacrifice accuracy for speed, in cases where we might be racy with a simultaneous repack.

Here are results from the included perf script, which sets up a situation similar to the one described above:

Test            HEAD^               HEAD
----------------------------------------------------------
5550.4: fetch   11.21(10.42+0.78)   0.08(0.04+0.02) -99.3%

That applies only for a situation where:

  1. You have a lot of packs on the client side to make reprepare_packed_git() expensive (the most expensive part is finding duplicates in an unsorted list, which is currently quadratic).
  2. You need a large number of tag refs on the server side that are candidates for auto-following (i.e., that the client doesn't have). Each one triggers a re-read of the pack directory.
  3. Under normal circumstances, the client would auto-follow those tags and after one large fetch, (2) would no longer be true.
    But if those tags point to history which is disconnected from what the client otherwise fetches, then it will never auto-follow, and those candidates will impact it on every fetch.

Git 2.21 (Feb. 2019) seems to have introduced a regression when the config remote.origin.fetch is not the default one ('+refs/heads/*:refs/remotes/origin/*')

fatal: multiple updates for ref 'refs/tags/v1.0.0' not allowed

Git 2.24 (Q4 2019) adds another optimization.

See commit b7e2d8b (15 Sep 2019) by Masaya Suzuki (draftcode).
(Merged by Junio C Hamano -- gitster -- in commit 1d8b0df, 07 Oct 2019)

fetch: use oidset to keep the want OIDs for faster lookup

During git fetch, the client checks if the advertised tags' OIDs are already in the fetch request's want OID set.
This check is done in a linear scan.
For a repository that has a lot of refs, repeating this scan takes 15+ minutes.

In order to speed this up, create a oid_set for other refs' OIDs.

mat-form-field must contain a MatFormFieldControl

Note Some time Error occurs, when we use "mat-form-field" tag around submit button like:

<mat-form-field class="example-full-width">
   <button mat-raised-button type="submit" color="primary">  Login</button>
   </mat-form-field>

So kindly don't use this tag around submit button

Visual Studio loading symbols

Just encountered this issue. Deleting breakpoints didn't work, or at least not just on its own. After this failed I Went Tools > Options > Debugging > Symbols and "Empty Symbol Cache"

and then cleaned the solution and rebuilt.

Now seems to be working correctly. So if you try all the other things listed, and it still makes no differnce, these additional bits of info may help...

What is the significance of url-pattern in web.xml and how to configure servlet?

Servlet-mapping has two child tags, url-pattern and servlet-name. url-pattern specifies the type of urls for which, the servlet given in servlet-name should be called. Be aware that, the container will use case-sensitive for string comparisons for servlet matching.

First specification of url-pattern a web.xml file for the server context on the servlet container at server .com matches the pattern in <url-pattern>/status/*</url-pattern> as follows:

http://server.com/server/status/synopsis               = Matches
http://server.com/server/status/complete?date=today    = Matches
http://server.com/server/status                        = Matches
http://server.com/server/server1/status                = Does not match

Second specification of url-pattern A context located at the path /examples on the Agent at example.com matches the pattern in <url-pattern>*.map</url-pattern> as follows:

 http://server.com/server/US/Oregon/Portland.map    = Matches
 http://server.com/server/US/server/Seattle.map     = Matches
 http://server.com/server/Paris.France.map          = Matches
 http://server.com/server/US/Oregon/Portland.MAP    = Does not match, the extension is uppercase
 http://example.com/examples/interface/description/mail.mapi  =Does not match, the extension is mapi rather than map`

Third specification of url-mapping,A mapping that contains the pattern <url-pattern>/</url-pattern> matches a request if no other pattern matches. This is the default mapping. The servlet mapped to this pattern is called the default servlet.

The default mapping is often directed to the first page of an application. Explicitly providing a default mapping also ensures that malformed URL requests into the application return are handled by the application rather than returning an error.

The servlet-mapping element below maps the server servlet instance to the default mapping.

<servlet-mapping>
  <servlet-name>server</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

For the context that contains this element, any request that is not handled by another mapping is forwarded to the server servlet.

And Most importantly we should Know about Rule for URL path mapping

  1. The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the servlet.
  2. The container will recursively try to match the longest path-prefix. This is done by stepping down the path tree a directory at a time, using the ’/’ character as a path separator. The longest match determines the servlet selected.
  3. If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container will try to match a servlet that handles requests for the extension. An extension is defined as the part of the last segment after the last ’.’ character.
  4. If neither of the previous three rules result in a servlet match, the container will attempt to serve content appropriate for the resource requested. If a “default” servlet is defined for the application, it will be used.

Reference URL Pattern

Selected tab's color in Bottom Navigation View

Instead of creating selector, Best way to create a style.

<style name="AppTheme.BottomBar">
    <item name="colorPrimary">@color/colorAccent</item> 
</style>

and to change the text size, selected or non selected.

<dimen name="design_bottom_navigation_text_size" tools:override="true">11sp</dimen>
<dimen name="design_bottom_navigation_active_text_size" tools:override="true">12sp</dimen>

Enjoy Android!

How do I position a div relative to the mouse pointer using jQuery?

There are plenty of examples of using JQuery to retrieve the mouse coordinates, but none fixed my issue.

The Body of my webpage is 1000 pixels wide, and I centre it in the middle of the user's browser window.

body {
    position:absolute;
    width:1000px;
    left: 50%;
    margin-left:-500px;
}

Now, in my JavaScript code, when the user right-clicked on my page, I wanted a div to appear at the mouse position.

Problem is, just using e.pageX value wasn't quite right. It'd work fine if I resized my browser window to be about 1000 pixels wide. Then, the pop div would appear at the correct position.

But if increased the size of my browser window to, say, 1200 pixels wide, then the div would appear about 100 pixels to the right of where the user had clicked.

The solution is to combine e.pageX with the bounding rectangle of the body element. When the user changes the size of their browser window, the "left" value of body element changes, and we need to take this into account:

// Temporary variables to hold the mouse x and y position
var tempX = 0;
var tempY = 0;

jQuery(document).ready(function () {
    $(document).mousemove(function (e) {
        var bodyOffsets = document.body.getBoundingClientRect();
        tempX = e.pageX - bodyOffsets.left;
        tempY = e.pageY;
    });
}) 

Phew. That took me a while to fix ! I hope this is useful to other developers !

A button to start php script, how?

This one works for me:

index.php

    <?php
       if(isset($_GET['action']))
              {
                 //your code
                 echo 'Welcome';
              }
    ?>


    <form id="frm" method="post"  action="?action" >
    <input type="submit" value="Submit" id="submit" />
    </form>

This link can be helpful:

https://blogs.msdn.microsoft.com/brian_swan/2010/02/08/getting-started-with-the-sql-server-driver-for-php/

Converting float to char*

In Arduino:

//temporarily holds data from vals
char charVal[10];                

//4 is mininum width, 3 is precision; float value is copied onto buff
dtostrf(123.234, 4, 3, charVal);

monitor.print("charVal: ");
monitor.println(charVal);

Get the value in an input text box

You have to use various ways to get current value of an input element.

METHOD - 1

If you want to use a simple .val(), try this:

<input type="text" id="txt_name" />

Get values from Input

// use to select with DOM element.
$("input").val();

// use the id to select the element.
$("#txt_name").val();

// use type="text" with input to select the element
$("input:text").val();

Set value to Input

// use to add "text content" to the DOM element.
$("input").val("text content");

// use the id to add "text content" to the element.
$("#txt_name").val("text content");

// use type="text" with input to add "text content" to the element
$("input:text").val("text content");

METHOD - 2

Use .attr() to get the content.

<input type="text" id="txt_name" value="" />

I just add one attribute to the input field. value="" attribute is the one who carry the text content that we entered in input field.

$("input").attr("value");

METHOD - 3

you can use this one directly on your input element.

$("input").keyup(function(){
    alert(this.value);
});

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

StreamWriter is available for NET 1.1. and for the Compact framework. Just open the file and apply the ToString to your StringBuilder:

    StringBuilder sb = new StringBuilder();
    sb.Append(......);

    StreamWriter sw = new StreamWriter("\\hereIAm.txt", true);
    sw.Write(sb.ToString());
    sw.Close();

Also, note that you say that you want to append debug messages to the file (like a log). In this case, the correct constructor for StreamWriter is the one that accepts an append boolean flag. If true then it tries to append to an existing file or create a new one if it doesn't exists.

Convert JsonNode into POJO

This should do the trick:

mapper.readValue(fileReader, MyClass.class);

I say should because I'm using that with a String, not a BufferedReader but it should still work.

Here's my code:

String inputString = // I grab my string here
MySessionClass sessionObject;
try {
    ObjectMapper objectMapper = new ObjectMapper();
    sessionObject = objectMapper.readValue(inputString, MySessionClass.class);

Here's the official documentation for that call: http://jackson.codehaus.org/1.7.9/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(java.lang.String, java.lang.Class)

You can also define a custom deserializer when you instantiate the ObjectMapper: http://wiki.fasterxml.com/JacksonHowToCustomDeserializers

Edit: I just remembered something else. If your object coming in has more properties than the POJO has and you just want to ignore the extras you'll want to set this:

    objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Or you'll get an error that it can't find the property to set into.

@ variables in Ruby on Rails

The difference is in the scope of the variable. The @version is available to all methods of the class instance.

The short answer, if you're in the controller and you need to make the variable available to the view then use @variable.

For a much longer answer try this: http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_classes.html

destination path already exists and is not an empty directory

An engineered way to solve this if you already have files you need to push to Github/Server:

  1. In Github/Server where your repo will live:

    • Create empty Git Repo (Save <YourPathAndRepoName>)
    • $git init --bare
  2. Local Computer (Just put in any folder):

    • $touch .gitignore
    • (Add files you want to ignore in text editor to .gitignore)
    • $git clone <YourPathAndRepoName>

    • (This will create an empty folder with your Repo Name from Github/Server)

    • (Legitimately copy and paste all your files from wherever and paste them into this empty Repo)

    • $git add . && git commit -m "First Commit"

    • $git push origin master

Select something that has more/less than x character

JonH has covered very well the part on how to write the query. There is another significant issue that must be mentioned too, however, which is the performance characteristics of such a query. Let's repeat it here (adapted to Oracle):

SELECT EmployeeName FROM EmployeeTable WHERE LENGTH(EmployeeName) > 4;

This query is restricting the result of a function applied to a column value (the result of applying the LENGTH function to the EmployeeName column). In Oracle, and probably in all other RDBMSs, this means that a regular index on EmployeeName will be useless to answer this query; the database will do a full table scan, which can be really costly.

However, various databases offer a function indexes feature that is designed to speed up queries like this. For example, in Oracle, you can create an index like this:

CREATE INDEX EmployeeTable_EmployeeName_Length ON EmployeeTable(LENGTH(EmployeeName));

This might still not help in your case, however, because the index might not be very selective for your condition. By this I mean the following: you're asking for rows where the name's length is more than 4. Let's assume that 80% of the employee names in that table are longer than 4. Well, then the database is likely going to conclude (correctly) that it's not worth using the index, because it's probably going to have to read most of the blocks in the table anyway.

However, if you changed the query to say LENGTH(EmployeeName) <= 4, or LENGTH(EmployeeName) > 35, assuming that very few employees have names with fewer than 5 character or more than 35, then the index would get picked and improve performance.

Anyway, in short: beware of the performance characteristics of queries like the one you're trying to write.

How can I count the occurrences of a string within a file?

The number of string occurrences (not lines) can be obtained using grep with -o option and wc (word count):

$ echo "echo 1234 echo" | grep -o echo
echo
echo
$ echo "echo 1234 echo" | grep -o echo | wc -l
2

So the full solution for your problem would look like this:

$ grep -o "echo" FILE | wc -l

Get the current URL with JavaScript?

For those who want an actual URL object, potentially for a utility which takes URLs as an argument:

const url = new URL(window.location.href)

https://developer.mozilla.org/en-US/docs/Web/API/URL

MySQL Error 1093 - Can't specify target table for update in FROM clause

As far as concerns, you want to delete rows in story_category that do not exist in category.

Here is your original query to identify the rows to delete:

SELECT * 
FROM  story_category 
WHERE category_id NOT IN (
    SELECT DISTINCT category.id 
    FROM category INNER JOIN 
       story_category ON category_id=category.id
);

Combining NOT IN with a subquery that JOINs the original table seems unecessarily convoluted. This can be expressed in a more straight-forward manner with not exists and a correlated subquery:

select sc.*
from story_category sc
where not exists (select 1 from category c where c.id = sc.category_id);

Now it is easy to turn this to a delete statement:

delete from story_category
where not exists (select 1 from category c where c.id = story_category.category_id);    

This quer would run on any MySQL version, as well as in most other databases that I know.

Demo on DB Fiddle:

-- set-up
create table story_category(category_id int);
create table category (id int);
insert into story_category values (1), (2), (3), (4), (5);
insert into category values (4), (5), (6), (7);

-- your original query to identify offending rows
SELECT * 
FROM  story_category 
WHERE category_id NOT IN (
    SELECT DISTINCT category.id 
    FROM category INNER JOIN 
       story_category ON category_id=category.id);
| category_id |
| ----------: |
|           1 |
|           2 |
|           3 |
-- a functionally-equivalent, simpler query for this
select sc.*
from story_category sc
where not exists (select 1 from category c where c.id = sc.category_id)
| category_id |
| ----------: |
|           1 |
|           2 |
|           3 |
-- the delete query
delete from story_category
where not exists (select 1 from category c where c.id = story_category.category_id);

-- outcome
select * from story_category;
| category_id |
| ----------: |
|           4 |
|           5 |

Changing PowerShell's default output encoding to UTF-8

To be short, use:

write-output "your text" | out-file -append -encoding utf8 "filename"

In Django, how do I check if a user is in a certain group?

If you need the list of users that are in a group, you can do this instead:

from django.contrib.auth.models import Group
users_in_group = Group.objects.get(name="group name").user_set.all()

and then check

 if user in users_in_group:
     # do something

to check if the user is in the group.

Recursively add the entire folder to a repository

I ran into this problem that cost me a little time, then remembered that git won't store empty folders. Remember that if you have a folder tree you want stored, put a file in at least the deepest folder of that tree, something like a file called ".gitkeep", just to affect storage by git.

When to use RabbitMQ over Kafka?

The most voted answer covers most part but I would like to high light use case point of view. Can kafka do that rabbit mq can do, answer is yes but can rabbit mq do everything that kafka does, the answer is no.

The thing that rabbit mq cannot do that makes kafka apart, is distributed message processing. With this now read back the most voted answer and it will make more sense.

To elaborate, take a use case where you need to create a messaging system that has super high throughput for example "likes" in facebook and You have chosen rabbit mq for that. You created an exchange and queue and a consumer where all publishers (in this case FB users) can publish 'likes' messages. Since your throughput is high, you will create multiple threads in consumer to process messages in parallel but you still bounded by the hardware capacity of the machine where consumer is running. Assuming that one consumer is not sufficient to process all messages - what would you do?

  • Can you add one more consumer to queue - no you cant do that.
  • Can you create a new queue and bind that queue to exchange that publishes 'likes' message, answer is no cause you will have messages processed twice.

That is the core problem that kafka solves. It lets you create distributed partitions (Queue in rabbit mq) and distributed consumer that talk to each other. That ensures your messages in a topic get processed by consumers distributed in various nodes (Machines).

Kafka brokers ensure that messages get load balanced across all partitions of that topic. Consumer group make sure that all consumer talk to each other and message does not get processed twice.

But in real life you will not face this problem unless your throughput is seriously high because rabbit mq can also process data very fast even with one consumer.

Save bitmap to location

Some new devices don't save bitmap So I explained a little more..

make sure you have added below Permission

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

and create a xml file under xml folder name provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="external_files"
        path="." />
</paths>

and in AndroidManifest under

<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

then simply call saveBitmapFile(passYourBitmapHere)

public static void saveBitmapFile(Bitmap bitmap) throws IOException {
        File mediaFile = getOutputMediaFile();
        FileOutputStream fileOutputStream = new FileOutputStream(mediaFile);
        bitmap.compress(Bitmap.CompressFormat.JPEG, getQualityNumber(bitmap), fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();
    }

where

File getOutputMediaFile() {
        File mediaStorageDir = new File(
                Environment.getExternalStorageDirectory(),
                "easyTouchPro");
        if (mediaStorageDir.isDirectory()) {

            // Create a media file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                    .format(Calendar.getInstance().getTime());
            String mCurrentPath = mediaStorageDir.getPath() + File.separator
                            + "IMG_" + timeStamp + ".jpg";
            File mediaFile = new File(mCurrentPath);
            return mediaFile;
        } else { /// error handling for PIE devices..
            mediaStorageDir.delete();
            mediaStorageDir.mkdirs();
            galleryAddPic(mediaStorageDir);

            return (getOutputMediaFile());
        }
    }

and other methods

public static int getQualityNumber(Bitmap bitmap) {
        int size = bitmap.getByteCount();
        int percentage = 0;

        if (size > 500000 && size <= 800000) {
            percentage = 15;
        } else if (size > 800000 && size <= 1000000) {
            percentage = 20;
        } else if (size > 1000000 && size <= 1500000) {
            percentage = 25;
        } else if (size > 1500000 && size <= 2500000) {
            percentage = 27;
        } else if (size > 2500000 && size <= 3500000) {
            percentage = 30;
        } else if (size > 3500000 && size <= 4000000) {
            percentage = 40;
        } else if (size > 4000000 && size <= 5000000) {
            percentage = 50;
        } else if (size > 5000000) {
            percentage = 75;
        }

        return percentage;
    }

and

void galleryAddPic(File f) {
        Intent mediaScanIntent = new Intent(
                "android.intent.action.MEDIA_SCANNER_SCAN_FILE");
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);

        this.sendBroadcast(mediaScanIntent);
    }

How can I do DNS lookups in Python, including referring to /etc/hosts?

I found this way to expand a DNS RR hostname that expands into a list of IPs, into the list of member hostnames:

#!/usr/bin/python

def expand_dnsname(dnsname):
    from socket import getaddrinfo
    from dns import reversename, resolver
    namelist = [ ]
    # expand hostname into dict of ip addresses
    iplist = dict()
    for answer in getaddrinfo(dnsname, 80):
        ipa = str(answer[4][0])
        iplist[ipa] = 0
    # run through the list of IP addresses to get hostnames
    for ipaddr in sorted(iplist):
        rev_name = reversename.from_address(ipaddr)
        # run through all the hostnames returned, ignoring the dnsname
        for answer in resolver.query(rev_name, "PTR"):
            name = str(answer)
            if name != dnsname:
                # add it to the list of answers
                namelist.append(name)
                break
    # if no other choice, return the dnsname
    if len(namelist) == 0:
        namelist.append(dnsname)
    # return the sorted namelist
    namelist = sorted(namelist)
    return namelist

namelist = expand_dnsname('google.com.')
for name in namelist:
    print name

Which, when I run it, lists a few 1e100.net hostnames:

Unit Testing: DateTime.Now

Add a fake assembly for System (right click on System reference=>Add fake assembly).

And write into your test method:

using (ShimsContext.Create())
{
   System.Fakes.ShimDateTime.NowGet = () => new DateTime(2014, 3, 10);
   MethodThatUsesDateTimeNow();
}

An implementation of the fast Fourier transform (FFT) in C#

Math.NET's Iridium library provides a fast, regularly updated collection of math-related functions, including the FFT. It's licensed under the LGPL so you are free to use it in commercial products.

How to include clean target in Makefile?

The best thing is probably to create a variable that holds your binaries:

binaries=code1 code2

Then use that in the all-target, to avoid repeating:

all: clean $(binaries)

Now, you can use this with the clean-target, too, and just add some globs to catch object files and stuff:

.PHONY: clean

clean:
    rm -f $(binaries) *.o

Note use of the .PHONY to make clean a pseudo-target. This is a GNU make feature, so if you need to be portable to other make implementations, don't use it.

How to $http Synchronous call with AngularJS

Here's a way you can do it asynchronously and manage things like you would normally. Everything is still shared. You get a reference to the object that you want updated. Whenever you update that in your service, it gets updated globally without having to watch or return a promise. This is really nice because you can update the underlying object from within the service without ever having to rebind. Using Angular the way it's meant to be used. I think it's probably a bad idea to make $http.get/post synchronous. You'll get a noticeable delay in the script.

app.factory('AssessmentSettingsService', ['$http', function($http) {
    //assessment is what I want to keep updating
    var settings = { assessment: null };

    return {
        getSettings: function () {
             //return settings so I can keep updating assessment and the
             //reference to settings will stay in tact
             return settings;
        },
        updateAssessment: function () {
            $http.get('/assessment/api/get/' + scan.assessmentId).success(function(response) {
                //I don't have to return a thing.  I just set the object.
                settings.assessment = response;
            });
        }
    };
}]);

    ...
        controller: ['$scope', '$http', 'AssessmentSettingsService', function ($scope, as) {
            $scope.settings = as.getSettings();
            //Look.  I can even update after I've already grabbed the object
            as.updateAssessment();

And somewhere in a view:

<h1>{{settings.assessment.title}}</h1>

Random number between 0 and 1 in python

I want a random number between 0 and 1, like 0.3452

random.random() is what you are looking for:

From python docs: random.random() Return the next random floating point number in the range [0.0, 1.0).


And, btw, Why your try didn't work?:

Your try was: random.randrange(0, 1)

From python docs: random.randrange() Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object.

So, what you are doing here, with random.randrange(a,b) is choosing a random element from range(a,b); in your case, from range(0,1), but, guess what!: the only element in range(0,1), is 0, so, the only element you can choose from range(0,1), is 0; that's why you were always getting 0 back.

How to create EditText with rounded corners?

Just to add to the other answers, I found that the simplest solution to achieve the rounded corners was to set the following as a background to your Edittext.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="@android:color/white"/>
    <corners android:radius="8dp"/>

</shape>

Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

Change

<serviceMetadata httpsGetEnabled="true"/>

to

<serviceMetadata httpsGetEnabled="false"/>

You're telling WCF to use https for the metadata endpoint and I see that your'e exposing your service on http, and then you get the error in the title.

You also have to set <security mode="None" /> if you want to use HTTP as your URL suggests.

How to disable scrolling the document body?

Answer : document.body.scroll = 'no';

Oracle insert if not exists statement

insert into OPT (email, campaign_id) 
select '[email protected]',100
from dual
where not exists(select * 
                 from OPT 
                 where (email ='[email protected]' and campaign_id =100));

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> 

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

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

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

or

if 'List contents' in UserInput: 

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

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

how to get docker-compose to use the latest image from repository

I've seen this occur in our 7-8 docker production system. Another solution that worked for me in production was to run

docker-compose down
docker-compose up -d

this removes the containers and seems to make 'up' create new ones from the latest image.

This doesn't yet solve my dream of down+up per EACH changed container (serially, less down time), but it works to force 'up' to update the containers.

"Object doesn't support this property or method" error in IE11

We were also facing this issue when using IE version 11 to access our React app (create-react-app with react version 16.0.0 with jQuery v3.1.1) on the enterprise intranet. To solve it, i simply followed the directions at this url which are also listed below:

  1. Make sure to set the DOCTYPE to standards mode by making sure the first line of the master file is: <!DOCTYPE html>

  2. Force IE 11 to use the latest internal version by including the following meta tag in the head tag: <meta http-equiv="X-UA-Compatible" content="IE=edge;" />

NOTE: I did not face the problem when using IE to access the app in development mode on my local machine (localhost:3000). The problem occurred only when accessing the app deployed to the DEV server on the company Intranet, probably because of some company wide Windows OS policy settings and/or IE Internet Options.

Setting the JVM via the command line on Windows

If you have 2 installations of the JVM. Place the version upfront. Linux : export PATH=/usr/lib/jvm/java-8-oracle/bin:$PATH

This eliminates the ambiguity.

How does Java handle integer underflows and overflows and how would you check for it?

It doesn't do anything -- the under/overflow just happens.

A "-1" that is the result of a computation that overflowed is no different from the "-1" that resulted from any other information. So you can't tell via some status or by inspecting just a value whether it's overflowed.

But you can be smart about your computations in order to avoid overflow, if it matters, or at least know when it will happen. What's your situation?

Is 'bool' a basic datatype in C++?

Allthough it's now a native type, it's still defined behind the scenes as an integer (int I think) where the literal false is 0 and true is 1. But I think all logic still consider anything but 0 as true, so strictly speaking the true literal is probably a keyword for the compiler to test if something is not false.

if(someval == true){

probably translates to:

if(someval !== false){ // e.g. someval !== 0

by the compiler

Can I use Class.newInstance() with constructor arguments?

I think this is exactly what you want http://da2i.univ-lille1.fr/doc/tutorial-java/reflect/object/arg.html

Although it seems a dead thread, someone might find it useful

Perl read line by line

With these types of complex programs, it's better to let Perl generate the Perl code for you:

$ perl -MO=Deparse -pe'exit if $.>2'

Which will gladly tell you the answer,

LINE: while (defined($_ = <ARGV>)) {
    exit if $. > 2;
}
continue {
    die "-p destination: $!\n" unless print $_;
}

Alternatively, you can simply run it as such from the command line,

$ perl -pe'exit if$.>2' file.txt

PHP: HTML: send HTML select option attribute in POST

You can use jquery function.

<form name='add'>
   <input type='text' name='stud_name' id="stud_name" value=""/>
   Age: <select name='age' id="age">
   <option value='1' stud_name='sre'>23</option>
   <option value='2' stud_name='sam'>24</option>
   <option value='5' stud_name='john'>25</option>
   </select>
   <input type='submit' name='submit'/>
</form>

jquery code :

<script type="text/javascript" src="jquery.js"></script>

<script>
    $(function() {
          $("#age").change(function(){
          var option = $('option:selected', this).attr('stud_name');
          $('#stud_name').val(option);
       });
    });
</script>

Postgres: clear entire database before re-creating / re-populating from bash script

I'd just drop the database and then re-create it. On a UNIX or Linux system, that should do it:

$ dropdb development_db_name
$ createdb developmnent_db_name

That's how I do it, actually.

Force table column widths to always be fixed regardless of contents

You can also use percentages, and/or specify in the column headers:

<table width="300">  
  <tr>
    <th width="20%">Column 1</th>
    <th width="20%">Column 2</th>
    <th width="20%">Column 3</th>
    <th width="20%">Column 4</th>
    <th width="20%">Column 5</th>
  </tr>
  <tr>
    <!--- row data -->
  </tr>
</table>

The bonus with percentages is lower code maintenance: you can change your table width without having to re-specify the column widths.

Caveat: It is my understanding that table width specified in pixels isn't supported in HTML 5; you need to use CSS instead.

Remove useless zero digits from decimals in PHP

If you want to remove the zero digits just before to display on the page or template.

You can use the sprintf() function

sprintf('%g','125.00');
//125

??sprintf('%g','966.70');
//966.7

????sprintf('%g',844.011);
//844.011

Redirect within component Angular 2

first configure routing

import {RouteConfig, Router, ROUTER_DIRECTIVES} from 'angular2/router';

and

@RouteConfig([
  { path: '/addDisplay', component: AddDisplay, as: 'addDisplay' },
  { path: '/<secondComponent>', component: '<secondComponentName>', as: 'secondComponentAs' },
])

then in your component import and then inject Router

import {Router} from 'angular2/router'

export class AddDisplay {
  constructor(private router: Router)
}

the last thing you have to do is to call

this.router.navigateByUrl('<pathDefinedInRouteConfig>');

or

this.router.navigate(['<aliasInRouteConfig>']);

How do I get the current date in JavaScript?

What's the big deal with this.. The cleanest way to do this is

var currentDate=new Date().toLocaleString().slice(0,10);

Limiting the number of characters in a JTextField

Here is an optimized version of npinti's answer:

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;
import java.awt.*;

public class TextComponentLimit extends PlainDocument
{
    private int charactersLimit;

    private TextComponentLimit(int charactersLimit)
    {
        this.charactersLimit = charactersLimit;
    }

    @Override
    public void insertString(int offset, String input, AttributeSet attributeSet) throws BadLocationException
    {
        if (isAllowed(input))
        {
            super.insertString(offset, input, attributeSet);
        } else
        {
            Toolkit.getDefaultToolkit().beep();
        }
    }

    private boolean isAllowed(String string)
    {
        return (getLength() + string.length()) <= charactersLimit;
    }

    public static void addTo(JTextComponent textComponent, int charactersLimit)
    {
        TextComponentLimit textFieldLimit = new TextComponentLimit(charactersLimit);
        textComponent.setDocument(textFieldLimit);
    }
}

To add a limit to your JTextComponent, simply write the following line of code:

JTextFieldLimit.addTo(myTextField, myMaximumLength);

How to write and read java serialized objects into a file

if you serialize the whole list you also have to de-serialize the file into a list when you read it back. This means that you will inevitably load in memory a big file. It can be expensive. If you have a big file, and need to chunk it line by line (-> object by object) just proceed with your initial idea.

Serialization:

LinkedList<YourObject> listOfObjects = <something>;
try {
    FileOutputStream file = new FileOutputStream(<filePath>);
    ObjectOutputStream writer = new ObjectOutputStream(file);
    for (YourObject obj : listOfObjects) {
        writer.writeObject(obj);
    }
    writer.close();
    file.close();
} catch (Exception ex) {
    System.err.println("failed to write " + filePath + ", "+ ex);
}

De-serialization:

try {
    FileInputStream file = new FileInputStream(<filePath>);
    ObjectInputStream reader = new ObjectInputStream(file);
    while (true) {
        try { 
            YourObject obj = (YourObject)reader.readObject();
            System.out.println(obj)
        } catch (Exception ex) {
            System.err.println("end of reader file ");
            break;
        }
    }
} catch (Exception ex) {
    System.err.println("failed to read " + filePath + ", "+ ex);
}

font-weight is not working properly?

For me the bold work when I change the font style from font-family: 'Open Sans', sans-serif; to Arial

In Java, how to find if first character in a string is upper case without regex

Actually, this is subtler than it looks.

The code above would give the incorrect answer for a lower case character whose code point was above U+FFFF (such as U+1D4C3, MATHEMATICAL SCRIPT SMALL N). String.charAt would return a UTF-16 surrogate pair, which is not a character, but rather half the character, so to speak. So you have to use String.codePointAt, which returns an int above 0xFFFF (not a char). You would do:

Character.isUpperCase(s.codePointAt(0));

Don't feel bad overlooked this; almost all Java coders handle UTF-16 badly, because the terminology misleadingly makes you think that each "char" value represents a character. UTF-16 sucks, because it is almost fixed width but not quite. So non-fixed-width edge cases tend not to get tested. Until one day, some document comes in which contains a character like U+1D4C3, and your entire system blows up.

Select folder dialog WPF

If you don't want to use Windows Forms nor edit manifest files, I came up with a very simple hack using WPF's SaveAs dialog for actually selecting a directory.

No using directive needed, you may simply copy-paste the code below !

It should still be very user-friendly and most people will never notice.

The idea comes from the fact that we can change the title of that dialog, hide files, and work around the resulting filename quite easily.

It is a big hack for sure, but maybe it will do the job just fine for your usage...

In this example I have a textbox object to contain the resulting path, but you may remove the related lines and use a return value if you wish...

// Create a "Save As" dialog for selecting a directory (HACK)
var dialog = new Microsoft.Win32.SaveFileDialog();
dialog.InitialDirectory = textbox.Text; // Use current value for initial dir
dialog.Title = "Select a Directory"; // instead of default "Save As"
dialog.Filter = "Directory|*.this.directory"; // Prevents displaying files
dialog.FileName = "select"; // Filename will then be "select.this.directory"
if (dialog.ShowDialog() == true) {
    string path = dialog.FileName;
    // Remove fake filename from resulting path
    path = path.Replace("\\select.this.directory", "");
    path = path.Replace(".this.directory", "");
    // If user has changed the filename, create the new directory
    if (!System.IO.Directory.Exists(path)) {
        System.IO.Directory.CreateDirectory(path);
    }
    // Our final value is in path
    textbox.Text = path;
}

The only issues with this hack are :

  • Acknowledge button still says "Save" instead of something like "Select directory", but in a case like mines I "Save" the directory selection so it still works...
  • Input field still says "File name" instead of "Directory name", but we can say that a directory is a type of file...
  • There is still a "Save as type" dropdown, but its value says "Directory (*.this.directory)", and the user cannot change it for something else, works for me...

Most people won't notice these, although I would definitely prefer using an official WPF way if microsoft would get their heads out of their asses, but until they do, that's my temporary fix.

Find the IP address of the client in an SSH session

Search for SSH connections for "myusername" account;

Take first result string;

Take 5th column;

Split by ":" and return 1st part (port number don't needed, we want just IP):

netstat -tapen | grep "sshd: myusername" | head -n1 | awk '{split($5, a, ":"); print a[1]}'


Another way:

who am i | awk '{l = length($5) - 2; print substr($5, 2, l)}'

Update row values where certain condition is met in pandas

I think you can use loc if you need update two columns to same value:

df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2        aaaa         aaaa
c       2        aaaa         aaaa
d       3  some_value   some_value

If you need update separate, one option is use:

df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2          10   some_value
c       2          10   some_value
d       3  some_value   some_value

Another common option is use numpy.where:

df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
   stream  feat another_feat
a       1    20   some_value
b       2    10   some_value
c       2    10   some_value
d       3    20   some_value

EDIT: If you need divide all columns without stream where condition is True, use:

print df1
   stream  feat  another_feat
a       1     4             5
b       2     4             5
c       2     2             9
d       3     1             7

#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']

df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
   stream  feat  another_feat
a       1   4.0           5.0
b       2   2.0           2.5
c       2   1.0           4.5
d       3   1.0           7.0

If working with multiple conditions is possible use multiple numpy.where or numpy.select:

df0 = pd.DataFrame({'Col':[5,0,-6]})

df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing', 
                          np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))

df0['New Col2'] = np.select([df0['Col'] > 0, df0['Col'] < 0],
                            ['Increasing',  'Decreasing'], 
                            default='No Change')

print (df0)
   Col    New Col1    New Col2
0    5  Increasing  Increasing
1    0   No Change   No Change
2   -6  Decreasing  Decreasing

How do I drop a function if it already exists?

IF EXISTS
      (SELECT * 
      FROM schema.sys.objects
      WHERE name = 'func_name')
    DROP FUNCTION [dbo].[func_name]
GO

LogCat message: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included

I also had the same problem. In starting, it was working fine then, but sometime later I uninstalled my application completely from my device (I was running it on my mobile) and ran it again, and it shows me the same error.

I had all lib and resources included as it was working, but still I was getting this error so I removed all references and lib from my project build, updated google service play to revision 10, uninstalled application completely from the device and then again added all resources and libs and ran it and it started working again.

One thing to note here is while running I am still seeing this error message in my LogCat, but on my device it is working fine now.

How to set default Checked in checkbox ReactJS?

<div className="display__lbl_input">
              <input
                type="checkbox"
                onChange={this.handleChangeFilGasoil}
                value="Filter Gasoil"
                name="Filter Gasoil"
                id=""
              />
              <label htmlFor="">Filter Gasoil</label>
            </div>

handleChangeFilGasoil = (e) => {
    if(e.target.checked){
        this.setState({
            checkedBoxFG:e.target.value
        })
        console.log(this.state.checkedBoxFG)
    }
    else{
     this.setState({
        checkedBoxFG : ''
     })
     console.log(this.state.checkedBoxFG)
    }
  };

Can I convert a boolean to Yes/No in a ASP.NET GridView

This works:

Protected Sub grid_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grid.RowDataBound
    If e.Row.RowType = DataControlRowType.DataRow Then
        If e.Row.Cells(3).Text = "True" Then
            e.Row.Cells(3).Text = "Si"
        Else
            e.Row.Cells(3).Text = "No"
        End If
    End If
End Sub

Where cells(3) is the column of the column that has the boolean field.

How to access model hasMany Relation with where condition?

Just in case anyone else encounters the same problems.

Note, that relations are required to be camelcase. So in my case available_videos() should have been availableVideos().

You can easily find out investigating the Laravel source:

// Illuminate\Database\Eloquent\Model.php
...
/**
 * Get an attribute from the model.
 *
 * @param  string  $key
 * @return mixed
 */
public function getAttribute($key)
{
    $inAttributes = array_key_exists($key, $this->attributes);

    // If the key references an attribute, we can just go ahead and return the
    // plain attribute value from the model. This allows every attribute to
    // be dynamically accessed through the _get method without accessors.
    if ($inAttributes || $this->hasGetMutator($key))
    {
        return $this->getAttributeValue($key);
    }

    // If the key already exists in the relationships array, it just means the
    // relationship has already been loaded, so we'll just return it out of
    // here because there is no need to query within the relations twice.
    if (array_key_exists($key, $this->relations))
    {
        return $this->relations[$key];
    }

    // If the "attribute" exists as a method on the model, we will just assume
    // it is a relationship and will load and return results from the query
    // and hydrate the relationship's value on the "relationships" array.
    $camelKey = camel_case($key);

    if (method_exists($this, $camelKey))
    {
        return $this->getRelationshipFromMethod($key, $camelKey);
    }
}

This also explains why my code worked, whenever I loaded the data using the load() method before.

Anyway, my example works perfectly okay now, and $model->availableVideos always returns a Collection.

Calculate date from week number

One of the biggest problems I found was to convert from weeks to dates, and then from dates to weeks.

The main problem is when trying to get the correct week year from a date that belongs to a week of the previous year. Luckily System.Globalization.ISOWeek.GetYear handles this.

Here is my solution:

public class WeekOfYear
{
    public static (int Year, int Week) DateToWeekOfYear(DateTime date) =>
        (ISOWeek.GetYear(date), ISOWeek.GetWeekOfYear(date));

    public static bool ValidYearAndWeek(int year, int week) =>
           year >= 1 && year <= 9999 && week >= 1 && week <= 53 // bounds of year/week
        && !(year <= 1 && week <= 1) && !(year >= 9999 && week >= 53); // bounds of DateTime

    public int Year { get; }
    public int Week { get; }
    public virtual DateTime StartOfWeek { get; protected set; }
    public virtual DateTime EndOfWeek { get; protected set; }

    public virtual IEnumerable<DateTime> DaysInWeek =>
        Enumerable.Range(1, 10).Select(i => StartOfWeek.AddDays(i));

    public WeekOfYear(int year, int week)
    {
        if (!ValidYearAndWeek(year, week))
            throw new ArgumentException($"DateTime can't represent {week} of year {year}.");

        Year = year;
        Week = week;
        StartOfWeek = ISOWeek.ToDateTime(year, week, DayOfWeek.Monday);
        EndOfWeek = ISOWeek.ToDateTime(year, week, DayOfWeek.Sunday).AddDays(1).AddTicks(-1);
    }

    public WeekOfYear((int Year, int Week) week) : this(week.Year, week.Week) { }
    public WeekOfYear(DateTime date) : this(DateToWeekOfYear(date)) { }
}

The second biggest problem was the preference for weeks starting on Sundays in the US.

The solution I cam up with subclasses WeekOfYear from above, and manages the offset of the in the constructor (which converts week to dates) and DateToWeekOfYear (which converts from date to week).

public class UsWeekOfYear : WeekOfYear
{
    public static new (int Year, int Week) DateToWeekOfYear(DateTime date)
    {
        // if date is a sunday, return the next week
        if (date.DayOfWeek == DayOfWeek.Sunday) date = date.AddDays(1);
        return WeekOfYear.DateToWeekOfYear(date);
    }

    public UsWeekOfYear(int year, int week) : base(year, week)
    {
        StartOfWeek = ISOWeek.ToDateTime(year, week, DayOfWeek.Monday).AddDays(-1);
        EndOfWeek = ISOWeek.ToDateTime(year, week, DayOfWeek.Sunday).AddTicks(-1);
    }

    public UsWeekOfYear((int Year, int Week) week) : this(week.Year, week.Week) { }
    public UsWeekOfYear(DateTime date) : this(DateToWeekOfYear(date)) { }
}

Here is some test code:

public static void Main(string[] args)
{
    Console.WriteLine("== Last Week / First Week");
    Log(new WeekOfYear(2020, 53));
    Log(new UsWeekOfYear(2020, 53));

    Log(new WeekOfYear(2021, 1));
    Log(new UsWeekOfYear(2021, 1));

    Console.WriteLine("\n== Year Crossover (iso)");
    var start = new DateTime(2020, 12, 26);
    var i = 0;
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-26 - Sat
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-27 - Sun
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-28 - Mon
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-29 - Tue
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-30 - Wed
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2020-12-30 - Thu
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-01 - Fri
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-02 - Sat
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-03 - Sun
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-04 - Mon
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-05 - Tue
    Log(start.AddDays(i), new WeekOfYear(start.AddDays(i++))); // 2021-01-06 - Wed

    Console.WriteLine("\n== Year Crossover (us)");
    i = 0;
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-26 - Sat
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-27 - Sun
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-28 - Mon
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-29 - Tue
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-30 - Wed
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2020-12-30 - Thu
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-01 - Fri
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-02 - Sat
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-03 - Sun
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-04 - Mon
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-05 - Tue
    Log(start.AddDays(i), new UsWeekOfYear(start.AddDays(i++))); // 2021-01-06 - Wed

    var x = new UsWeekOfYear(2020, 53) as WeekOfYear;
}

public static void Log(WeekOfYear week)
{
    Console.WriteLine($"{week} - {week.StartOfWeek:yyyy-MM-dd} ({week.StartOfWeek:ddd}) - {week.EndOfWeek:yyyy-MM-dd} ({week.EndOfWeek:ddd})");
}

public static void Log(DateTime date, WeekOfYear week)
{
    Console.WriteLine($"{date:yyyy-MM-dd (ddd)} - {week} - {week.StartOfWeek:yyyy-MM-dd (ddd)} - {week.EndOfWeek:yyyy-MM-dd (ddd)}");
}

Remote Linux server to remote linux server dir copy. How?

There are two ways I usually do this, both use ssh:

scp -r sourcedir/ [email protected]:/dest/dir/

or, the more robust and faster (in terms of transfer speed) method:

rsync -auv -e ssh --progress sourcedir/ [email protected]:/dest/dir/

Read the man pages for each command if you want more details about how they work.

ElasticSearch - Return Unique Values

I am looking for this kind of solution for my self as well. I found reference in terms aggregation.

So, according to that following is the proper solution.

{
"aggs" : {
    "langs" : {
        "terms" : { "field" : "language",  
                    "size" : 500 }
    }
}}

But if you ran into following error:

"error": {
        "root_cause": [
            {
                "type": "illegal_argument_exception",
                "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [fastest_method] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead."
            }
        ]}

In that case, you have to add "KEYWORD" in the request, like following:

   {
    "aggs" : {
        "langs" : {
            "terms" : { "field" : "language.keyword",  
                        "size" : 500 }
        }
    }}

Haskell: Converting Int to String

Anyone who is just starting with Haskell and trying to print an Int, use:

module Lib
    ( someFunc
    ) where

someFunc :: IO ()
x = 123
someFunc = putStrLn (show x)

python int( ) function

Integers (int for short) are the numbers you count with 0, 1, 2, 3 ... and their negative counterparts ... -3, -2, -1 the ones without the decimal part.

So once you introduce a decimal point, your not really dealing with integers. You're dealing with rational numbers. The Python float or decimal types are what you want to represent or approximate these numbers.

You may be used to a language that automatically does this for you(Php). Python, though, has an explicit preference for forcing code to be explicit instead implicit.

Creating new database from a backup of another Database on the same server?

I think that is easier than this.

  • First, create a blank target database.
  • Then, in "SQL Server Management Studio" restore wizard, look for the option to overwrite target database. It is in the 'Options' tab and is called 'Overwrite the existing database (WITH REPLACE)'. Check it.
  • Remember to select target files in 'Files' page.

You can change 'tabs' at left side of the wizard (General, Files, Options)

How to format string to money

decimal value = 0.00M;
value = Convert.ToDecimal(12345.12345);
Console.WriteLine(value.ToString("C"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C1"));
//OutPut : $12345.1
Console.WriteLine(value.ToString("C2"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C3"));
//OutPut : $12345.123
Console.WriteLine(value.ToString("C4"));
//OutPut : $12345.1234
Console.WriteLine(value.ToString("C5"));
//OutPut : $12345.12345
Console.WriteLine(value.ToString("C6"));
//OutPut : $12345.123450

Console output:

Styling input radio with css

Trident provides the ::-ms-check pseudo-element for checkbox and radio button controls. For example:

<input type="checkbox">
<input type="radio">

::-ms-check {
    color: red;
    background: black;
    padding: 1em;
}

This displays as follows in IE10 on Windows 8:

enter image description here

Execute a batch file on a remote PC using a batch file on local PC

While I would recommend against this.

But you can use shutdown as client if the target machine has remote shutdown enabled and is in the same workgroup.

Example:

shutdown.exe /s /m \\<target-computer-name> /t 00

replacing <target-computer-name> with the URI for the target machine,

Otherwise, if you want to trigger this through Apache, you'll need to configure the batch script as a CGI script by putting AddHandler cgi-script .bat and Options +ExecCGI into either a local .htaccess file or in the main configuration for your Apache install.

Then you can just call the .bat file containing the shutdown.exe command from your browser.

Global Angular CLI version greater than local version

Run the following Command: npm install --save-dev @angular/cli@latest

After running the above command the console might popup the below message

The Angular CLI configuration format has been changed, and your existing configuration can be updated automatically by running the following command: ng update @angular/cli

How to move screen without moving cursor in Vim?

Here's my solution in vimrc:

"keep cursor in the middle all the time :)
nnoremap k kzz
nnoremap j jzz
nnoremap p pzz
nnoremap P Pzz
nnoremap G Gzz
nnoremap x xzz
inoremap <ESC> <ESC>zz
nnoremap <ENTER> <ENTER>zz
inoremap <ENTER> <ENTER><ESC>zzi
nnoremap o o<ESC>zza
nnoremap O O<ESC>zza
nnoremap a a<ESC>zza

So that the cursor will stay in the middle of the screen, and the screen will move up or down.

Visual Studio 2008 Product Key in Registry?

For Visual Studio 2005:

If you do have an installed Visual Studio 2005 however, and want to find out the serial number you’ve used to install it because you don’t have a clue where you put that shiny sticker, you can. It is, like most things in Windows, in the registry.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0\Registration\PIDKEY

In order to convert the value in that key to an actual serial number you have to put a dash ( – ) after evert 5 characters of the code.

From: http://www.gooli.org/blog/visual-studio-2005-serial-number/

For Visual Studio 2008 it's supposed to be:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Registration\PIDKEY

However I noted that the the Data field for PIDKEY is only filled in the 1000.0x000 (or 2000.0x000) sub folder of the above paths.

How to print all session variables currently set?

You could use the following code.

print_r($_SESSION);

how to check if List<T> element contains an item with a Particular Property Value

This is pretty easy to do using LINQ:

var match = pricePublicList.FirstOrDefault(p => p.Size == 200);
if (match == null)
{
    // Element doesn't exist
}

How to remove the first Item from a list?

If you are working with numpy you need to use the delete method:

import numpy as np

a = np.array([1, 2, 3, 4, 5])

a = np.delete(a, 0)

print(a) # [2 3 4 5]

How can I count occurrences with groupBy?

Here are slightly different options to accomplish the task at hand.

using toMap:

list.stream()
    .collect(Collectors.toMap(Function.identity(), e -> 1, Math::addExact));

using Map::merge:

Map<String, Integer> accumulator = new HashMap<>();
list.forEach(s -> accumulator.merge(s, 1, Math::addExact));

How do you format code on save in VS Code

If you would like to auto format on save just with Javascript source, add this one into Users Setting (press Cmd, or Ctrl,):

"[javascript]": { "editor.formatOnSave": true }

How to add headers to a multicolumn listbox in an Excel userform using VBA

I was looking at this problem just now and found this solution. If your RowSource points to a range of cells, the column headings in a multi-column listbox are taken from the cells immediately above the RowSource.

Using the example pictured here, inside the listbox, the words Symbol and Name appear as title headings. When I changed the word Name in cell AB1, then opened the form in the VBE again, the column headings changed.

Screenshot displaying a named range and the column headings outside the range.

The example came from a workbook in VBA For Modelers by S. Christian Albright, and I was trying to figure out how he got the column headings in his listbox :)

Uncaught syntaxerror: unexpected identifier?

There are errors here :

var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");

The code must change to:

var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");

By the way, there is another error at line 129 :

var createLi.appendChild(createSubList);

Replace it with:

createLi.appendChild(createSubList);

Define global constants

The best way to create application wide constants in Angular 2 is by using environment.ts files. The advantage of declaring such constants is that you can vary them according to the environment as there can be a different environment file for each environment.

Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

If you are doing VANILLA plain JavaScript without jQuery, then you must use (Internet Explorer 9 or later):

document.addEventListener("DOMContentLoaded", function(event) {
    // Your code to run since DOM is loaded and ready
});

Above is the equivalent of jQuery .ready:

$(document).ready(function() {
    console.log("Ready!");
});

Which ALSO could be written SHORTHAND like this, which jQuery will run after the ready even occurs.

$(function() {
    console.log("ready!");
});

NOT TO BE CONFUSED with BELOW (which is not meant to be DOM ready):

DO NOT use an IIFE like this that is self executing:

 Example:

(function() {
   // Your page initialization code here  - WRONG
   // The DOM will be available here   - WRONG
})();

This IIFE will NOT wait for your DOM to load. (I'm even talking about latest version of Chrome browser!)

Convert Rows to columns using 'Pivot' in SQL Server

Just give you some idea how other databases solve this problem. DolphinDB also has built-in support for pivoting and the sql looks much more intuitive and neat. It is as simple as specifying the key column (Store), pivoting column (Week), and the calculated metric (sum(xCount)).

//prepare a 10-million-row table
n=10000000
t=table(rand(100, n) + 1 as Store, rand(54, n) + 1 as Week, rand(100, n) + 1 as xCount)

//use pivot clause to generate a pivoted table pivot_t
pivot_t = select sum(xCount) from t pivot by Store, Week

DolphinDB is a columnar high performance database. The calculation in the demo costs as low as 546 ms on a dell xps laptop (i7 cpu). To get more details, please refer to online DolphinDB manual https://www.dolphindb.com/help/index.html?pivotby.html

Copying data from one SQLite database to another

If you use DB Browser for SQLite, you can copy the table from one db to another in following steps:

  1. Open two instances of the app and load the source db and target db side by side.
  2. If the target db does not have the table, "Copy Create Statement" from the source db and then paste the sql statement in "Execute SQL" tab and run the sql to create the table.
  3. In the source db, export the table as a CSV file.
  4. In the target db, import the CSV file to the table with the same table name. The app will ask you do you want to import the data to the existing table, click yes. Done.

Pressing Ctrl + A in Selenium WebDriver

To click Ctrl+A, you can do it with Actions

  Actions action = new Actions(); 
  action.keyDown(Keys.CONTROL).sendKeys(String.valueOf('\u0061')).perform();

\u0061 represents the character 'a'

\u0041 represents the character 'A'

To press other characters refer the unicode character table - http://unicode.org/charts/PDF/U0000.pdf

Installing Google Protocol Buffers on mac

It's a new year and there's a new mismatch between the version of protobuf in Homebrew and the cutting edge release. As of February 2016, brew install protobuf will give you version 2.6.1.

If you want the 3.0 beta release instead, you can install it with:

brew install --devel protobuf

Python def function: How do you specify the end of the function?

It uses indentation

 def func():
     funcbody
     if cond: 
         ifbody
     outofif

 outof_func 

Reading e-mails from Outlook with Python through MAPI

I had the same problem you did - didn't find much that worked. The following code, however, works like a charm.

import win32com.client

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
                                    # the inbox. You can change that number to reference
                                    # any other folder
messages = inbox.Items
message = messages.GetLast()
body_content = message.body
print body_content

jQuery - adding elements into an array

Try this, at the end of the each loop, ids array will contain all the hexcodes.

var ids = [];

    $(document).ready(function($) {
    var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
    $(".color_cell").each(function() {
        code = $(this).attr('id');
        ids.push(code);
        $div.append(code + "<br />");
    });



});

How to replace all special character into a string using C#

Yes, you can use regular expressions in C#.

Using regular expressions with C#:

using System.Text.RegularExpressions;

string your_String = "Hello@Hello&Hello(Hello)";
string my_String =  Regex.Replace(your_String, @"[^0-9a-zA-Z]+", ",");

How to "fadeOut" & "remove" a div in jQuery?

Have you tried this?

$("#notification").fadeOut(300, function(){ 
    $(this).remove();
});

That is, using the current this context to target the element in the inner function and not the id. I use this pattern all the time - it should work.

Formatting numbers (decimal places, thousands separators, etc) with CSS

Not an answer, but perhpas of interest. I did send a proposal to the CSS WG a few years ago. However, nothing has happened. If indeed they (and browser vendors) would see this as a genuine developer concern, perhaps the ball could start rolling?

Exit single-user mode

To switch out of Single User mode, try:

ALTER DATABASE [my_db] SET MULTI_USER

To switch back to Single User mode, you can use:

ALTER DATABASE [my_db] SET SINGLE_USER

how to check if a file is a directory or regular file in python?

Many of the Python directory functions are in the os.path module.

import os
os.path.isdir(d)

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

If you're using the CLI with MFA, you have to set the session token in addition to setting the access and secret keys. Please refer to this article: https://aws.amazon.com/premiumsupport/knowledge-center/authenticate-mfa-cli/

How to create an 2D ArrayList in java?

The best way is to use a List within a List:

List<List<String>> listOfLists = new ArrayList<List<String>>();  

Prolog "or" operator, query

Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:

registered(X, Y) :-
    X = ct101; X = ct102; X = ct103.

For a fuller explanation:

Predicate control in Prolog

Correct way to select from two tables in SQL Server with no common field to join on

You can (should) use CROSS JOIN. Following query will be equivalent to yours:

SELECT 
   table1.columnA
 , table2.columnA
FROM table1 
CROSS JOIN table2
WHERE table1.columnA = 'Some value'

or you can even use INNER JOIN with some always true conditon:

FROM table1 
INNER JOIN table2 ON 1=1

How to check whether a Button is clicked by using JavaScript

if(button.clicked==true) {
    console.log("Button Clicked");
} ==> // This Code Doesn't Work Properly So Please Use Below One // 


function check() { 
    console.log("Button Clicked");
}; // This Code Works Fine // 

var button= document.querySelector("button"); // Accessing The Button // 
button.addEventListener("click", check); // Adding event to call function when clicked // 

How to use Apple's new .p8 certificate for APNs in firebase console

Firebase console is now accepting .p8 file, in fact, it's recommending to upload .p8 file.

You can see in below-attached screenshot

How do I do multiple CASE WHEN conditions using SQL Server 2008?

Its just that you need multiple When for a single case to behave it like if.. Elseif else..

   Case when 1=1       //if
   Then
    When 1=1              //else if
     Then.... 
    When .....              //else if
    Then 
    Else                      //else
   ....... 
     End

SQL UPDATE all values in a field with appended string CONCAT not working

UPDATE 
    myTable
SET 
    col = CONCAT( col , "string" )

Could not work it out. The request syntax was correct, but "0 line affected" when executed.

The solution was :

UPDATE 
    myTable 
SET 
    col = CONCAT( myTable.col , "string" )

That one worked.

How to query DATETIME field using only date in Microsoft SQL Server?

Try this

 select * from test where Convert(varchar, date,111)= '03/19/2014'

Regex for Mobile Number Validation

Try this regex:

^(\+?\d{1,4}[\s-])?(?!0+\s+,?$)\d{10}\s*,?$

Explanation of the regex using Perl's YAPE is as below:

NODE                     EXPLANATION
----------------------------------------------------------------------
(?-imsx:                 group, but do not capture (case-sensitive)
                         (with ^ and $ matching normally) (with . not
                         matching \n) (matching whitespace and #
                         normally):
----------------------------------------------------------------------
  ^                        the beginning of the string
----------------------------------------------------------------------
  (                        group and capture to \1 (optional
                           (matching the most amount possible)):
----------------------------------------------------------------------
    \+?                      '+' (optional (matching the most amount
                             possible))
----------------------------------------------------------------------
    \d{1,4}                  digits (0-9) (between 1 and 4 times
                             (matching the most amount possible))
----------------------------------------------------------------------
    [\s-]                    any character of: whitespace (\n, \r,
                             \t, \f, and " "), '-'
----------------------------------------------------------------------
  )?                       end of \1 (NOTE: because you are using a
                           quantifier on this capture, only the LAST
                           repetition of the captured pattern will be
                           stored in \1)
----------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
----------------------------------------------------------------------
    0+                       '0' (1 or more times (matching the most
                             amount possible))
----------------------------------------------------------------------
    \s+                      whitespace (\n, \r, \t, \f, and " ") (1
                             or more times (matching the most amount
                             possible))
----------------------------------------------------------------------
    ,?                       ',' (optional (matching the most amount
                             possible))
----------------------------------------------------------------------
    $                        before an optional \n, and the end of
                             the string
----------------------------------------------------------------------
  )                        end of look-ahead
----------------------------------------------------------------------
  \d{10}                   digits (0-9) (10 times)
----------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
----------------------------------------------------------------------
  ,?                       ',' (optional (matching the most amount
                           possible))
----------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------

Python Loop: List Index Out of Range

You are accessing the list elements and then using them to attempt to index your list. This is not a good idea. You already have an answer showing how you could use indexing to get your sum list, but another option would be to zip the list with a slice of itself such that you can sum the pairs.

b = [i + j for i, j in zip(a, a[1:])]

List of Python format characters

In docs.python.org Topic = 5.6.2. String Formatting Operations http://docs.python.org/library/stdtypes.html#string-formatting then further down to the chart (text above chart is "The conversion types are:")

The chart lists 16 types and some following notes.

My comment: help does not include attitude which is a bonus. The attitude post enabled me to search further and find the info.

Java system properties and environment variables

I think the difference between the two boils down to access. Environment variables are accessible by any process and Java system properties are only accessible by the process they are added to.

Also as Bohemian stated, env variables are set in the OS (however they 'can' be set through Java) and system properties are passed as command line options or set via setProperty().

What is an opaque response, and what purpose does it serve?

javascript is a bit tricky getting the answer, I fixed it by getting the api from the backend and then calling it to the frontend.

public function get_typechange () {

    $ url = "https://........";
    $ json = file_get_contents ($url);
    $ data = json_decode ($ json, true);
    $ resp = json_encode ($data);
    $ error = json_last_error_msg ();
    return $ resp;

}

issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

The error message will include the name of the constraint that was violated (there may be more than one unique constraint on a table). You can use that constraint name to identify the column(s) that the unique constraint is declared on

SELECT column_name, position
  FROM all_cons_columns
 WHERE constraint_name = <<name of constraint from the error message>>
   AND owner           = <<owner of the table>>
   AND table_name      = <<name of the table>>

Once you know what column(s) are affected, you can compare the data you're trying to INSERT or UPDATE against the data already in the table to determine why the constraint is being violated.

React setState not updating state

setState is asynchronous. You can use callback method to get updated state.

changeHandler(event) {
    this.setState({ yourName: event.target.value }, () => 
    console.log(this.state.yourName));
 }

Reading a UTF8 CSV file with Python

Using codecs.open as Alex Martelli suggested proved to be useful to me.

import codecs

delimiter = ';'
reader = codecs.open("your_filename.csv", 'r', encoding='utf-8')
for line in reader:
    row = line.split(delimiter)
    # do something with your row ...

Iterating through a list to render multiple widgets in Flutter?

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

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

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

JQuery Ajax Post results in 500 Internal Server Error

I just face this problem today. with this kind of error, you won't get any responses from server, therefore, it's very hard to locate the problem.

But I can tell you "500 internal server error" is error with server not client, you got an error in server side script. Comment out the code closure by closure and try to run it again, you'll soon find out you miss a character somewhere.

How do I delete a local repository in git?

To piggyback on rkj's answer, to avoid endless prompts (and force the command recursively), enter the following into the command line, within the project folder:

$ rm -rf .git

Or to delete .gitignore and .gitmodules if any (via @aragaer):

$ rm -rf .git*

Then from the same ex-repository folder, to see if hidden folder .git is still there:

$ ls -lah

If it's not, then congratulations, you've deleted your local git repo, but not a remote one if you had it. You can delete GitHub repo on their site (github.com).

To view hidden folders in Finder (Mac OS X) execute these two commands in your terminal window:

defaults write com.apple.finder AppleShowAllFiles TRUE
killall Finder

Source: http://lifehacker.com/188892/show-hidden-files-in-finder.

How to pass multiple parameters in a querystring

Try like this.It should work

Response.Redirect(String.Format("yourpage.aspx?strId={0}&strName={1}&strDate{2}", Server.UrlEncode(strId), Server.UrlEncode(strName),Server.UrlEncode(strDate)));

How To change the column order of An Existing Table in SQL Server 2008

This can be an issue when using Source Control and automated deployments to a shared development environment. Where I work we have a very large sample DB on our development tier to work with (a subset of our production data).

Recently I did some work to remove one column from a table and then add some extra ones on the end. I then had to undo my column removal so I re-added it on the end which means the table and all references are correct in the environment but the Source Control automated deployment will no longer work because it complains about the table definition changing.

The real problem here is that the table + indexes are ~120GB and the environment only has ~60GB free so I'll need to either:

a) Rename the existing columns which are in the wrong order, add new columns in the right order, update the data then drop the old columns

OR

b) Rename the table, create a new table with the correct order, insert to the new table from the old and delete from the old as I go along

The SSMS/TFS Schema compare option of using a temp table won't work because there isn't enough room on disc to do it.

I'm not trying to say this is the best way to go about things or that column order really matters, just that I have a scenario where it is an issue and I'm sharing the options I've thought of to fix the issue

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

Which version of SQL Server?

For SQL Server 2005 and later, you can obtain the SQL script used to create the view like this:

select definition
from sys.objects     o
join sys.sql_modules m on m.object_id = o.object_id
where o.object_id = object_id( 'dbo.MyView')
  and o.type      = 'V'

This returns a single row containing the script used to create/alter the view.

Other columns in the table tell about about options in place at the time the view was compiled.

Caveats

  • If the view was last modified with ALTER VIEW, then the script will be an ALTER VIEW statement rather than a CREATE VIEW statement.

  • The script reflects the name as it was created. The only time it gets updated is if you execute ALTER VIEW, or drop and recreate the view with CREATE VIEW. If the view has been renamed (e.g., via sp_rename) or ownership has been transferred to a different schema, the script you get back will reflect the original CREATE/ALTER VIEW statement: it will not reflect the objects current name.

  • Some tools truncate the output. For example, the MS-SQL command line tool sqlcmd.exe truncates the data at 255 chars. You can pass the parameter -y N to get the result with N chars.

how to open Jupyter notebook in chrome on windows

If you haven't already, create a notebook config file by running

jupyter notebook --generate-config

Then, edit the file jupyter_notebook_config.py found in the .jupyter folder of your home directory.

You need to change the line # c.NotebookApp.browser = '' to c.NotebookApp.browser = 'C:/path/to/your/chrome.exe %s'

On windows 10, Chrome should be located C:/Program Files (x86)/Google/Chrome/Application/chrome.exe but check on your system to be sure.

Boxplot show the value of mean

First, you can calculate the group means with aggregate:

means <- aggregate(weight ~  group, PlantGrowth, mean)

This dataset can be used with geom_text:

library(ggplot2)
ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() +
  stat_summary(fun.y=mean, colour="darkred", geom="point", 
               shape=18, size=3,show_guide = FALSE) + 
  geom_text(data = means, aes(label = weight, y = weight + 0.08))

Here, + 0.08 is used to place the label above the point representing the mean.

enter image description here


An alternative version without ggplot2:

means <- aggregate(weight ~  group, PlantGrowth, mean)

boxplot(weight ~ group, PlantGrowth)
points(1:3, means$weight, col = "red")
text(1:3, means$weight + 0.08, labels = means$weight)

enter image description here

ORA-00907: missing right parenthesis

Firstly, in histories_T, you are referencing table T_customer (should be T_customers) and secondly, you are missing the FOREIGN KEY clause that REFERENCES orders; which is not being created (or dropped) with the code you provided.

There may be additional errors as well, and I admit Oracle has never been very good at describing the cause of errors - "Mutating Tables" is a case in point.

Let me know if there additional problems you are missing.

Oracle PL/SQL - Are NO_DATA_FOUND Exceptions bad for stored procedure performance?

Yes, you're missing using cursors

DECLARE
  CURSOR foo_cur IS 
    SELECT NEEDED_FIELD WHERE condition ;
BEGIN
  OPEN foo_cur;
  FETCH foo_cur INTO foo_rec;
  IF foo_cur%FOUND THEN
     ...
  END IF;
  CLOSE foo_cur;
EXCEPTION
  WHEN OTHERS THEN
    CLOSE foo_cur;
    RAISE;
END ;

admittedly this is more code, but it doesn't use EXCEPTIONs as flow-control which, having learnt most of my PL/SQL from Steve Feuerstein's PL/SQL Programming book, I believe to be a good thing.

Whether this is faster or not I don't know (I do very little PL/SQL nowadays).

What's a Good Javascript Time Picker?

CSS Gallery has variety of Time Pickers. Have a look.

Perifer Design's time picker is similar to google one

Android device chooser - My device seems offline

Updated the Android SDK platform tools using SDK Manager (in Eclipse). Works for me.

How do I change db schema to dbo

Use this code if you want to change all tables, views, and procedures at once.

BEGIN
DECLARE @name NVARCHAR(MAX)
        , @sql NVARCHAR(MAX)
        , @oldSchema NVARCHAR(MAX) = 'MyOldSchema'
        , @newSchema NVARCHAR(MAX) = 'dbo'
        
DECLARE objCursor CURSOR FOR
        SELECT  o.name
        FROM    sys.objects o
        WHERE   type IN ('P', 'U', 'V')

OPEN    objCursor
        FETCH NEXT FROM objCursor INTO @name
        WHILE   @@FETCH_STATUS = 0
        BEGIN
            SET @sql = 'ALTER SCHEMA '+ @newSchema +' TRANSFER '+ @oldSchema + '.' +  @name         
            BEGIN TRY
                exec(@sql)
                PRINT 'Success: ' + @sql
            END TRY
            BEGIN CATCH
                PRINT 'Error executing: ' + @sql
            END CATCH
            FETCH NEXT FROM objCursor INTO @name
        END
CLOSE   objCursor
DEALLOCATE  objCursor

END

It will execute a code like this

ALTER SCHEMA dbo TRANSFER MyOldSchema.xx_GetUserInformation

Best way to generate xml?

I would use the yattag library. I think it's the most pythonic way:

from yattag import Doc

doc, tag, text = Doc().tagtext()

with tag('food'):
    with tag('name'):
        text('French Breakfast')
    with tag('price', currency='USD'):
        text('6.95')
    with tag('ingredients'):
        for ingredient in ('baguettes', 'jam', 'butter', 'croissants'):
            with tag('ingredient'):
                text(ingredient)


print(doc.getvalue())

Extract matrix column values by matrix column name

> myMatrix <- matrix(1:10, nrow=2)
> rownames(myMatrix) <- c("A", "B")
> colnames(myMatrix) <- c("A", "B", "C", "D", "E")

> myMatrix
  A B C D  E
A 1 3 5 7  9
B 2 4 6 8 10

> myMatrix["A", "A"]
[1] 1

> myMatrix["A", ]
A B C D E 
1 3 5 7 9 

> myMatrix[, "A"]
A B 
1 2 

How to run SQL in shell script

Maybe it's too late for answering but, there's a working code:

sqlplus -s "/ as sysdba" << EOF
    SET HEADING OFF
    SET FEEDBACK OFF
    SET LINESIZE 3800
    SET TRIMSPOOL ON
    SET TERMOUT OFF
    SET SPACE 0
    SET PAGESIZE 0
    select (select instance_name from v\$instance) as DB_NAME,
           file_name
      from dba_data_files
     order by 2;

How to make use of ng-if , ng-else in angularJS

<span ng-if="verifyName.indicator == 1"><i class="fa fa-check"></i></span>
<span ng-if="verifyName.indicator == 0"><i class="fa fa-times"></i></span>

try this code. here verifyName.indicator value is coming from controller. this works for me.

error: src refspec master does not match any

This should help you

git init
git add .
git commit -m 'Initial Commit'
git push -u origin master

Same Navigation Drawer in different Activities

My suggestion is: do not use activities at all, instead use fragments, and replace them in the container (Linear Layout for example) where you show your first fragment.

The code is available in Android Developer Tutorials, you just have to customize.

http://developer.android.com/training/implementing-navigation/nav-drawer.html

It is advisable that you should use more and more fragments in your application, and there should be only four basic activities local to your application, that you mention in your AndroidManifest.xml apart from the external ones (FacebookActivity for example):

  1. SplashActivity: uses no fragment, and uses FullScreen theme.

  2. LoginSignUpActivity: Do not require NavigationDrawer at all, and no back button as well, so simply use the normal toolbar, but at the least, 3 or 4 fragments will be required. Uses no-action-bar theme

  3. HomeActivity or DashBoard Activity: Uses no-action-bar theme. Here you require Navigation drawer, also all the screens that follow will be fragments or nested fragments, till the leaf view, with the shared drawer. All the settings, user profile and etc. will be here as fragments, in this activity. The fragments here will not be added to the back stack and will be opened from the drawer menu items. In the case of fragments that require back button instead of the drawer, there is a fourth kind of activity below.

  4. Activity without drawer. This activity has a back button on top and the fragments inside will be sharing the same action-bar. These fragments will be added to the back-stack, as there will be a navigation history.

[ For further guidance see: https://stackoverflow.com/a/51100507/787399 ]

Happy Coding !!

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

I'm going to assume that your lack of quotes around the selector is just a transcription error, but you should check it anyway. Also, I don't see where you are actually giving the form an id. Usually you do this with the htmlAttributes parameter. I don't see you using the signature that has it. Again, though, if the form is submitting at all, this could be a transcription error.

If the selector and the id aren't the problem I'm suspicious that it might be because the click handler is added via markup when you use the Ajax BeginForm extension. You might try using $('form').trigger('submit') or in the worst case, have the click handler on the anchor create a hidden submit button in the form and click it. Or even create your own ajax submission using pure jQuery (which is probably what I would do).

Lastly, you should realize that by replacing the submit button, you're going to totally break this for people who don't have javascript enabled. The way around this is to also have a button hidden using a noscript tag and handle both AJAX and non-AJAX posts on the server.

BTW, it's consider standard practice, Microsoft not withstanding, to add the handlers via javascript not via markup. This keeps your javascript organized in one place so you can more easily see what's going on on the form. Here's an example of how I would use the trigger mechanism.

  $(function() {
      $('form#ajaxForm').find('a.submit-link').click( function() {
           $('form#ajaxForm').trigger('submit');
      }).show();
  }

<% using (Ajax.BeginForm("Update", "Description", new { id = Model.Id },
     new AjaxOptions
     {
       UpdateTargetId = "DescriptionDiv",
       HttpMethod = "post"
     }, new { id = "ajaxForm" } )) {%>
   Description:
   <%= Html.TextBox("Description", Model.Description) %><br />
   <a href="#" class="submit-link" style="display: none;">Save</a>
   <noscript>
       <input type="submit" value="Save" />
   </noscript>
<% } %>

Oracle date to string conversion

Try this. Oracle has this feature to distinguish the millennium years..

As you mentioned, if your column is a varchar, then the below query will yield you 1989..

select to_date(column_name,'dd/mm/rr') from table1;

When the format rr is used in year, the following would be done by oracle.

if rr->00 to 49 ---> result will be 2000 - 2049, if rr->50 to 99 ---> result will be 1950 - 1999

Char array declaration and initialization in C

That's because your first code snippet is not performing initialization, but assignment:

char myarray[4] = "abc";  // Initialization.

myarray = "abc";          // Assignment.

And arrays are not directly assignable in C.

The name myarray actually resolves to the address of its first element (&myarray[0]), which is not an lvalue, and as such cannot be the target of an assignment.

StringBuilder vs String concatenation in toString() in Java

In Java 9 the version 1 should be faster because it is converted to invokedynamic call. More details can be found in JEP-280:

The idea is to replace the entire StringBuilder append dance with a simple invokedynamic call to java.lang.invoke.StringConcatFactory, that will accept the values in the need of concatenation.

Is it possible to use argsort in descending order?

As @Kanmani hinted, an easier to interpret implementation may use numpy.flip, as in the following:

import numpy as np

avgDists = np.array([1, 8, 6, 9, 4])
ids = np.flip(np.argsort(avgDists))
print(ids)

By using the visitor pattern rather than member functions, it is easier to read the order of operations.

Could not establish secure channel for SSL/TLS with authority '*'

Problem

I was running into the same error message while calling a third party API from my ASP.NET Core MVC project.

Could not establish secure channel for SSL/TLS with authority '{base_url_of_WS}'.

Solution

It turned out that the third party API's server required TLS 1.2. To resolve this issue, I added the following line of code to my controller's constructor:

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

How do I modify a MySQL column to allow NULL?

Under some circumstances (if you get "ERROR 1064 (42000): You have an error in your SQL syntax;...") you need to do

ALTER TABLE mytable MODIFY mytable.mycolumn varchar(255);

One line if in VB .NET

You can use the IIf function too:

CheckIt = IIf(TestMe > 1000, "Large", "Small")

How do I compile a .cpp file on Linux?

You'll need to compile it using:

g++ inputfile.cpp -o outputbinary

The file you are referring has a missing #include <cstdlib> directive, if you also include that in your file, everything shall compile fine.

How do you POST to a page using the PHP header() function?

There is a good class that does what you want. It can be downloaded at: http://sourceforge.net/projects/snoopy/

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

some problem, but I find the solution, this is :


2 February Feb 28 (29 in leap years)

this is my code

 public string GetCountArchiveByMonth(int iii)
        {
// iii: is number of months, use any number other than (**2**)

            con.Open();

            SqlCommand cmd10 = con.CreateCommand();
            cmd10.CommandType = CommandType.Text;
            cmd10.CommandText = "select count(id_post) from posts where dateadded between CONVERT(VARCHAR, @start, 103) and CONVERT(VARCHAR, @end, 103)";
            cmd10.Parameters.AddWithValue("@start", "" + iii + "/01/2019");
            cmd10.Parameters.AddWithValue("@end", "" + iii + "/30/2019");
            string result = cmd10.ExecuteScalar().ToString();

            con.Close();

            return result;
        }

now for test

 lbl1.Text = GetCountArchiveByMonth(**7**).ToString();  // here use any number other than (**2**)

**

because of check **February** is maxed 28 days,

**

Select unique or distinct values from a list in UNIX shell script

./script.sh | sort -u

This is the same as monoxide's answer, but a bit more concise.

how do I get eclipse to use a different compiler version for Java?

Eclipse uses it's own internal compiler that can compile to several Java versions.

From Eclipse Help > Java development user guide > Concepts > Java Builder

The Java builder builds Java programs using its own compiler (the Eclipse Compiler for Java) that implements the Java Language Specification.

For Eclipse Mars.1 Release (4.5.1), this can target 1.3 to 1.8 inclusive.

When you configure a project:

[project-name] > Properties > Java Compiler > Compiler compliance level

This configures the Eclipse Java compiler to compile code to the specified Java version, typically 1.8 today.

Host environment variables, eg JAVA_HOME etc, are not used.

The Oracle/Sun JDK compiler is not used.

Does MySQL foreign_key_checks affect the entire database?

In case of using Mysql query browser, SET FOREIGN_KEY_CHECKS=0; does not have any impact in version 1.1.20. However, it works fine on Mysql query browser 1.2.17

Can a table have two foreign keys?

The foreign keys in your schema (on Account_Name and Account_Type) do not require any special treatment or syntax. Just declare two separate foreign keys on the Customer table. They certainly don't constitute a composite key in any meaningful sense of the word.

There are numerous other problems with this schema, but I'll just point out that it isn't generally a good idea to build a primary key out of multiple unique columns, or columns in which one is functionally dependent on another. It appears that at least one of these cases applies to the ID and Name columns in the Customer table. This allows you to create two rows with the same ID (different name), which I'm guessing you don't want to allow.

String Concatenation using '+' operator

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

How to get last inserted id?

After this:

INSERT INTO aspnet_GameProfiles(UserId, GameId) OUTPUT INSERTED.ID VALUES(@UserId, @GameId)

Execute this

int id = (int)command.ExecuteScalar;

It will work

How to encode a string in JavaScript for displaying in HTML?

The only character that needs escaping is <. (> is meaningless outside of a tag).

Therefore, your "magic" code is:

safestring = unsafestring.replace(/</g,'&lt;');

Format certain floating dataframe columns into percentage in pandas

You could also set the default format for float :

pd.options.display.float_format = '{:.2%}'.format

Use '{:.2%}' instead of '{:.2f}%' - The former converts 0.41 to 41.00% (correctly), the latter to 0.41% (incorrectly)

Alter a SQL server function to accept new optional parameter

I have found the EXECUTE command as suggested here T-SQL - function with default parameters to work well. With this approach there is no 'DEFAULT' needed when calling the function, you just omit the parameter as you would with a stored procedure.

SQL Query - Change date format in query to DD/MM/YYYY

If DB is SQL Server then

select Convert(varchar(10),CONVERT(date,YourDateColumn,106),103)

Html table with button on each row

Pretty sure this solves what you're looking for:

HTML:

<table>
    <tr><td><button class="editbtn">edit</button></td></tr>
    <tr><td><button class="editbtn">edit</button></td></tr>
    <tr><td><button class="editbtn">edit</button></td></tr>
    <tr><td><button class="editbtn">edit</button></td></tr>
</table>

Javascript (using jQuery):

$(document).ready(function(){
    $('.editbtn').click(function(){
        $(this).html($(this).html() == 'edit' ? 'modify' : 'edit');
    });
});

Edit:

Apparently I should have looked at your sample code first ;)

You need to change (at least) the ID attribute of each element. The ID is the unique identifier for each element on the page, meaning that if you have multiple items with the same ID, you'll get conflicts.

By using classes, you can apply the same logic to multiple elements without any conflicts.

JSFiddle sample

How can I group data with an Angular filter?

You can use groupBy of angular.filter module.
so you can do something like this:

JS:

$scope.players = [
  {name: 'Gene', team: 'alpha'},
  {name: 'George', team: 'beta'},
  {name: 'Steve', team: 'gamma'},
  {name: 'Paula', team: 'beta'},
  {name: 'Scruath', team: 'gamma'}
];

HTML:

<ul ng-repeat="(key, value) in players | groupBy: 'team'">
  Group name: {{ key }}
  <li ng-repeat="player in value">
    player: {{ player.name }} 
  </li>
</ul>

RESULT:
Group name: alpha
* player: Gene
Group name: beta
* player: George
* player: Paula
Group name: gamma
* player: Steve
* player: Scruath

UPDATE: jsbin Remember the basic requirements to use angular.filter, specifically note you must add it to your module's dependencies:

(1) You can install angular-filter using 4 different methods:

  1. clone & build this repository
  2. via Bower: by running $ bower install angular-filter from your terminal
  3. via npm: by running $ npm install angular-filter from your terminal
  4. via cdnjs http://www.cdnjs.com/libraries/angular-filter

(2) Include angular-filter.js (or angular-filter.min.js) in your index.html, after including Angular itself.

(3) Add 'angular.filter' to your main module's list of dependencies.

How can I convert a Unix timestamp to DateTime and vice versa?

DateTime to UNIX timestamp:

public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
    return (TimeZoneInfo.ConvertTimeToUtc(dateTime) - 
           new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
}

I need to learn Web Services in Java. What are the different types in it?

If your application often uses http protocol then REST is best because of its light weight, and knowing that your application uses only http protocol choosing SOAP is not so good because it heavy,Better to make decision on web service selection based on the protocols we use in our applications.

Add A Year To Today's Date

In case you want to add years to specific date besides today's date using either years, or months, or days. You can do the following

var christmas2000 = new Date(2000, 12, 25); 
christmas2000.setFullYear(christmas2000.getFullYear() + 5); // using year: next 5 years
christmas2000.setFullYear(christmas2000.getMonth() + 24); // using months: next 24 months
christmas2000.setFullYear(christmas2000.getDay() + 365); // using days: next 365 months

Add CSS or JavaScript files to layout head from views or partial views

Layout:

<html>
    <head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title</title>
        <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
        <script src="@Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/modernizr-2.0.6-development-only.js")" type="text/javascript"></script>
        @if (IsSectionDefined("AddToHead"))
        {
            @RenderSection("AddToHead", required: false)
        }

        @RenderSection("AddToHeadAnotherWay", required: false)
    </head>

View:

@model ProjectsExt.Models.DirectoryObject

@section AddToHead{
    <link href="@Url.Content("~/Content/Upload.css")" rel="stylesheet" type="text/css" />
}

bootstrap initially collapsed element

If removing the in class doesn't work for you, such was my case, you can force the collapsed initial state using the CSS display property:

...
<div id="collapseOne" class="accordion-body collapse" style="display: none;">
...

OR condition in Regex

I think what you need might be simply:

\d( \w)?

Note that your regex would have worked too if it was written as \d \w|\d instead of \d|\d \w.

This is because in your case, once the regex matches the first option, \d, it ceases to search for a new match, so to speak.

How to set up gradle and android studio to do release build?

To activate the installRelease task, you simply need a signingConfig. That is all.

From http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Android-tasks:

Finally, the plugin creates install/uninstall tasks for all build types (debug, release, test), as long as they can be installed (which requires signing).

Here is what you want:

Install tasks
-------------
installDebug - Installs the Debug build
installDebugTest - Installs the Test build for the Debug build
installRelease - Installs the Release build
uninstallAll - Uninstall all applications.
uninstallDebug - Uninstalls the Debug build
uninstallDebugTest - Uninstalls the Test build for the Debug build
uninstallRelease - Uninstalls the Release build   <--- release

Here is how to obtain the installRelease task:

Example build.gradle:

buildscript {
    repositories {
        jcenter()
    }

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

apply plugin: 'com.android.application'

android {
  compileSdkVersion 22
  buildToolsVersion '22.0.1'

  defaultConfig {
    applicationId 'demo'
    minSdkVersion 15
    targetSdkVersion 22
    versionCode 1
    versionName '1.0'
  }

  signingConfigs {
      release {
          storeFile <file>
          storePassword <password>
          keyAlias <alias>
          keyPassword <password>
      }
  }

  buildTypes {
    release {
        signingConfig signingConfigs.release
    }
  }
}

Which .NET Dependency Injection frameworks are worth looking into?

I'm a huge fan of Castle. I love the facilities it also provides beyond the IoC Container story. It really simplfies using NHibernate, logging, AOP, etc. I also use Binsor for configuration with Boo and have really fallen in love with Boo as a language because of it.

How can I compare time in SQL Server?

if (cast('2012-06-20 23:49:14.363' as time) between 
    cast('2012-06-20 23:49:14.363' as time) and 
    cast('2012-06-20 23:49:14.363' as time))

Best way to do multi-row insert in Oracle?

In Oracle, to insert multiple rows into table t with columns col1, col2 and col3 you can use the following syntax:

INSERT ALL
   INTO t (col1, col2, col3) VALUES ('val1_1', 'val1_2', 'val1_3')
   INTO t (col1, col2, col3) VALUES ('val2_1', 'val2_2', 'val2_3')
   INTO t (col1, col2, col3) VALUES ('val3_1', 'val3_2', 'val3_3')
   .
   .
   .
SELECT 1 FROM DUAL;

Prevent overwriting a file using cmd if exist

As in the answer of Escobar Ceaser, I suggest to use quotes arround the whole path. It's the common way to wrap the whole path in "", not only separate directory names within the path.

I had a similar issue that it didn't work for me. But it was no option to use "" within the path for separate directory names because the path contained environment variables, which theirself cover more than one directory hierarchies. The conclusion was that I missed the space between the closing " and the (

The correct version, with the space before the bracket, would be

If NOT exist "C:\Documents and Settings\John\Start Menu\Programs\Software Folder" (
 start "\\filer\repo\lab\software\myapp\setup.exe"
 pause
) 

How to sort alphabetically while ignoring case sensitive?

In your comparator factory class, do something like this:

 private static final Comparator<String> MYSTRING_COMPARATOR = new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
      return s1.compareToIgnoreCase(s2);
    }
  };

  public static Comparator<String> getMyStringComparator() {
    return MYSTRING_COMPARATOR;

This uses the compare to method which is case insensitive (why write your own). This way you can use Collections sort like this:

List<String> myArray = new ArrayList<String>();
//fill your array here    
Collections.sort(MyArray, MyComparators. getMyStringComparator());

How to parse XML and count instances of a particular node attribute?

Just to add another possibility, you can use untangle, as it is a simple xml-to-python-object library. Here you have an example:

Installation:

pip install untangle

Usage:

Your XML file (a little bit changed):

<foo>
   <bar name="bar_name">
      <type foobar="1"/>
   </bar>
</foo>

Accessing the attributes with untangle:

import untangle

obj = untangle.parse('/path_to_xml_file/file.xml')

print obj.foo.bar['name']
print obj.foo.bar.type['foobar']

The output will be:

bar_name
1

More information about untangle can be found in "untangle".

Also, if you are curious, you can find a list of tools for working with XML and Python in "Python and XML". You will also see that the most common ones were mentioned by previous answers.

How do I select and store columns greater than a number in pandas?

Sample DF:

In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))

In [80]: df
Out[80]:
    a   b   c
0   6  11  11
1  14   7   8
2  13   5  11
3  13   7  11
4  13   5   9
5   5  11   9
6   9   8   6
7   5  11  10
8   8  10  14
9   7  14  13

present only those rows where b > 10

In [81]: df[df.b > 10]
Out[81]:
   a   b   c
0  6  11  11
5  5  11   9
7  5  11  10
9  7  14  13

Minimums (for all columns) for the rows satisfying b > 10 condition

In [82]: df[df.b > 10].min()
Out[82]:
a     5
b    11
c     9
dtype: int32

Minimum (for the b column) for the rows satisfying b > 10 condition

In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11

UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

How to get a value of an element by name instead of ID

What element is used for the part with a green background? Just type the name of the element without "<" and ">" characters. For example type P, not <P> if the answer is the <P> element.

Regex to remove all special characters from string?

Depending on your definition of "special character", I think "[^a-zA-Z0-9]" would probably do the trick. That would find anything that is not a small letter, a capital letter, or a digit.

Tomcat 8 is not able to handle get request with '|' in query parameters?

Adding "relaxedQueryChars" attribute to the server.xml worked for me :

<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="443" URIEncoding="UTF-8" relaxedQueryChars="[]|{}^&#x5c;&#x60;&quot;&lt;&gt;"/>

How to use JavaScript to change the form action

I wanted to use JavaScript to change a form's action, so I could have different submit inputs within the same form linking to different pages.

I also had the added complication of using Apache rewrite to change example.com/page-name into example.com/index.pl?page=page-name. I found that changing the form's action caused example.com/index.pl (with no page parameter) to be rendered, even though the expected URL (example.com/page-name) was displayed in the address bar.

To get around this, I used JavaScript to insert a hidden field to set the page parameter. I still changed the form's action, just so the address bar displayed the correct URL.

function setAction (element, page)
{
  if(checkCondition(page))
  {
    /* Insert a hidden input into the form to set the page as a parameter.
     */
    var input = document.createElement("input");
    input.setAttribute("type","hidden");
    input.setAttribute("name","page");
    input.setAttribute("value",page);
    element.form.appendChild(input);

    /* Change the form's action. This doesn't chage which page is displayed,
     * it just make the URL look right.
     */
    element.form.action = '/' + page;
    element.form.submit();
  }
}

In the form:

<input type="submit" onclick='setAction(this,"my-page")' value="Click Me!" />

Here are my Apache rewrite rules:

RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^/(.*)$ %{DOCUMENT_ROOT}/index.pl?page=$1&%{QUERY_STRING}

I'd be interested in any explanation as to why just setting the action didn't work.

What is more efficient? Using pow to square or just multiply it with itself?

I was also wondering about the performance issue, and was hoping this would be optimised out by the compiler, based on the answer from @EmileCormier. However, I was worried that the test code he showed would still allow the compiler to optimise away the std::pow() call, since the same values were used in the call every time, which would allow the compiler to store the results and re-use it in the loop - this would explain the almost identical run-times for all cases. So I had a look into it too.

Here's the code I used (test_pow.cpp):

#include <iostream>                                                                                                                                                                                                                       
#include <cmath>
#include <chrono>

class Timer {
  public:
    explicit Timer () : from (std::chrono::high_resolution_clock::now()) { }

    void start () {
      from = std::chrono::high_resolution_clock::now();
    }

    double elapsed() const {
      return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - from).count() * 1.0e-6;
    }

  private:
    std::chrono::high_resolution_clock::time_point from;
};

int main (int argc, char* argv[])
{
  double total;
  Timer timer;



  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += std::pow (i,2);
  std::cout << "std::pow(i,2): " << timer.elapsed() << "s (result = " << total << ")\n";

  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += i*i;
  std::cout << "i*i: " << timer.elapsed() << "s (result = " << total << ")\n";

  std::cout << "\n";

  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += std::pow (i,3);
  std::cout << "std::pow(i,3): " << timer.elapsed() << "s (result = " << total << ")\n";

  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += i*i*i;
  std::cout << "i*i*i: " << timer.elapsed() << "s (result = " << total << ")\n";


  return 0;
}

This was compiled using:

g++ -std=c++11 [-O2] test_pow.cpp -o test_pow

Basically, the difference is the argument to std::pow() is the loop counter. As I feared, the difference in performance is pronounced. Without the -O2 flag, the results on my system (Arch Linux 64-bit, g++ 4.9.1, Intel i7-4930) were:

std::pow(i,2): 0.001105s (result = 3.33333e+07)
i*i: 0.000352s (result = 3.33333e+07)

std::pow(i,3): 0.006034s (result = 2.5e+07)
i*i*i: 0.000328s (result = 2.5e+07)

With optimisation, the results were equally striking:

std::pow(i,2): 0.000155s (result = 3.33333e+07)
i*i: 0.000106s (result = 3.33333e+07)

std::pow(i,3): 0.006066s (result = 2.5e+07)
i*i*i: 9.7e-05s (result = 2.5e+07)

So it looks like the compiler does at least try to optimise the std::pow(x,2) case, but not the std::pow(x,3) case (it takes ~40 times longer than the std::pow(x,2) case). In all cases, manual expansion performed better - but particularly for the power 3 case (60 times quicker). This is definitely worth bearing in mind if running std::pow() with integer powers greater than 2 in a tight loop...

Setting environment variables in Linux using Bash

The reason people often suggest writing

VAR=value
export VAR

instead of the shorter

export VAR=value

is that the longer form works in more different shells than the short form. If you know you're dealing with bash, either works fine, of course.

Convert xlsx to csv in Linux with command line

If you already have a Desktop environment then I'm sure Gnumeric / LibreOffice would work well, but on a headless server (such as Amazon Web Services), they require dozens of dependencies that you also need to install.

I found this Python alternative:

https://github.com/dilshod/xlsx2csv

$ easy_install xlsx2csv
$ xlsx2csv file.xlsx > newfile.csv

Took 2 seconds to install and works like a charm.

If you have multiple sheets you can export all at once, or one at a time:

$ xlsx2csv file.xlsx --all > all.csv
$ xlsx2csv file.xlsx --all -p '' > all-no-delimiter.csv
$ xlsx2csv file.xlsx -s 1 > sheet1.csv

He also links to several alternatives built in Bash, Python, Ruby, and Java.

Facebook Javascript SDK Problem: "FB is not defined"

I saw a case where Chrome had installed WidgetBlock which was blocking the Facebook script. The result was exactly this error message. Make sure you disable any extensions that may interfere.

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

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

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

Everything needs to be loaded in the correct order (:

Bootstrap onClick button event

There is no show event in js - you need to bind your button either to the click event:

$('#id').on('click', function (e) {

     //your awesome code here

})

Mind that if your button is inside a form, you may prefer to bind the whole form to the submit event.

How to write a cron that will run a script every day at midnight?

Here's a good tutorial on what crontab is and how to use it on Ubuntu. Your crontab line will look something like this:

00 00 * * * ruby path/to/your/script.rb

(00 00 indicates midnight--0 minutes and 0 hours--and the *s mean every day of every month.)

Syntax: 
  mm hh dd mt wd  command

  mm minute 0-59
  hh hour 0-23
  dd day of month 1-31
  mt month 1-12
  wd day of week 0-7 (Sunday = 0 or 7)
  command: what you want to run
  all numeric values can be replaced by * which means all

Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP

You could convert your recursive code into an iterative code, which simulates the recursion. This means that you have to push the current status (url, document, position in document etc.) into an array, when you reach a link, and pop it out of the array, when this link has finished.

button image as form input submit button?

This might be helpful

<form action="myform.cgi"> 
 <input type="file" name="fileupload" value="fileupload" id="fileupload">
 <label for="fileupload"> Select a file to upload</label> 
 <br>
 <input type="image" src="/wp-content/uploads/sendform.png" alt="Submit" width="100"> </form>

Read more: https://html.com/input-type-image/#ixzz5KD3sJxSp

Wait Until File Is Completely Written

Well you already give the answer yourself; you have to wait for the creation of the file to finish. One way to do this is via checking if the file is still in use. An example of this can be found here: Is there a way to check if a file is in use?

Note that you will have to modify this code for it to work in your situation. You might want to have something like (pseudocode):

public static void listener_Created()
{
   while CheckFileInUse()
      wait 1000 milliseconds

   CopyFile()
}

Obviously you should protect yourself from an infinite while just in case the owner application never releases the lock. Also, it might be worth checking out the other events from FileSystemWatcher you can subscribe to. There might be an event which you can use to circumvent this whole problem.

Restart pods when configmap updates in Kubernetes?

You can update a metadata annotation that is not relevant for your deployment. it will trigger a rolling-update

for example:

    spec:
      template:
        metadata:
          annotations:
            configmap-version: 1

Determine the size of an InputStream

I would read into a ByteArrayOutputStream and then call toByteArray() to get the resultant byte array. You don't need to define the size in advance (although it's possibly an optimisation if you know it. In many cases you won't)

C++ Matrix Class

For a matrix class, you want to stay away from overloading the [] operator.
See C++ FAQ 13.10

Also, search the web for some freeware Matrix classes. Worst case, they can give you guidance. Best case, less software that you have to write and debug.

CSS Transition doesn't work with top, bottom, left, right

I ran into this issue today. Here is my hacky solution.

I needed a fixed position element to transition up by 100 pixels as it loaded.

var delay = (ms) => new Promise(res => setTimeout(res, ms));
async function animateView(startPosition,elm){
  for(var i=0; i<101; i++){
    elm.style.top = `${(startPosition-i)}px`;
    await delay(1);
  }
}

Can I dynamically add HTML within a div tag from C# on load event?

You want to put code in the master page code behind that inserts HTML into the contents of a page that is using that master page?

I would not search for the control via FindControl as this is a fragile solution that could easily be broken if the name of the control changed.

Your best bet is to declare an event in the master page that any child page could handle. The event could pass the HTML as an EventArg.

jQuery: How to get the event object in an event handler function without passing it as an argument?

If you call your event handler on markup, as you're doing now, you can't (x-browser). But if you bind the click event with jquery, it's possible the following way:

Markup:

  <a href="#" id="link1" >click</a>

Javascript:

  $(document).ready(function(){
      $("#link1").click(clickWithEvent);  //Bind the click event to the link
  });
  function clickWithEvent(evt){
     myFunc('p1', 'p2', 'p3');
     function myFunc(p1,p2,p3){  //Defined as local function, but has access to evt
        alert(evt.type);        
     }
  }

Since the event ob

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

Yes, you can use Yarn or NPM to edit your package.json.

yarn upgrade [package | package@tag | package@version | @scope/]... [--ignore-engines] [--pattern]

Something like:

yarn upgrade react@^16.0.0

Then I'd see what warns or errors out and then run yarn upgrade [package]. No need to edit the file manually. Can do everything from the CLI.

Or just run yarn upgrade to update all packages to latest, probably a bad idea for a large project. APIs may change, things may break.

Alternatively, with NPM run npm outdated to see what packages will be affected. Then

npm update

https://yarnpkg.com/lang/en/docs/cli/upgrade/

https://docs.npmjs.com/getting-started/updating-local-packages

Letsencrypt add domain to existing certificate

this worked for me

 sudo letsencrypt certonly -a webroot --webroot-path=/var/www/html -d
 domain.com -d www.domain.com

How to write super-fast file-streaming code in C#?

(For future reference.)

Quite possibly the fastest way to do this would be to use memory mapped files (so primarily copying memory, and the OS handling the file reads/writes via its paging/memory management).

Memory Mapped files are supported in managed code in .NET 4.0.

But as noted, you need to profile, and expect to switch to native code for maximum performance.

How do I strip all spaces out of a string in PHP?

str_replace will do the trick thusly

$new_str = str_replace(' ', '', $old_str);

C char array initialization

This is not how you initialize an array, but for:

  1. The first declaration:

    char buf[10] = "";
    

    is equivalent to

    char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    
  2. The second declaration:

    char buf[10] = " ";
    

    is equivalent to

    char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};
    
  3. The third declaration:

    char buf[10] = "a";
    

    is equivalent to

    char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};
    

As you can see, no random content: if there are fewer initializers, the remaining of the array is initialized with 0. This the case even if the array is declared inside a function.

Exception: Can't bind to 'ngFor' since it isn't a known native property

In my case, the module containing the component using the *ngFor resulting in this error, was not included in the app.module.ts. Including it there in the imports array resolved the issue for me.

iOS: set font size of UILabel Programmatically

For iOS 8

  static NSString *_myCustomFontName;

 + (NSString *)myCustomFontName:(NSString*)fontName
  {
 if ( !_myCustomFontName )
  {
   NSArray *arr = [UIFont fontNamesForFamilyName:fontName];
    // I know I only have one font in this family
    if ( [arr count] > 0 )
       _myCustomFontName = arr[0];
  }

 return _myCustomFontName;

 }

Use string in switch case in java

Java (before version 7) does not support String in switch/case. But you can achieve the desired result by using an enum.

private enum Fruit {
    apple, carrot, mango, orange;
}

String value; // assume input
Fruit fruit = Fruit.valueOf(value); // surround with try/catch

switch(fruit) {
    case apple:
        method1;
        break;
    case carrot:
        method2;
        break;
    // etc...
}