Programs & Examples On #Scientific software

Error renaming a column in MySQL

Renaming a column in MySQL :

ALTER TABLE mytable CHANGE current_column_name new_column_name DATATYPE;

Opencv - Grayscale mode Vs gray color conversion

Note: This is not a duplicate, because the OP is aware that the image from cv2.imread is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)

To illustrate, I've opened up this same color JPEG image:

enter image description here

once using the conversion

img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

and another by loading it in gray scale mode

img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom

enter image description here

I've summed up the diff too to see

import numpy as np
np.sum(diff)
# I got 6143, on a 494 x 750 image

I tried all cv2.imread() modes

Among all the IMREAD_ modes for cv2.imread(), only IMREAD_COLOR and IMREAD_ANYCOLOR can be converted using COLOR_BGR2GRAY, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE

The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)

Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.

In brief, let's not mix the versions and types in the processing pipeline.

So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Yes or No confirm box using jQuery

I had trouble getting the answer back from the dialog box but eventually came up with a solution by combining the answer from this other question display-yes-and-no-buttons-instead-of-ok-and-cancel-in-confirm-box with part of the code from the modal-confirmation dialog

This is what was suggested for the other question:

Create your own confirm box:

<div id="confirmBox">
    <div class="message"></div>
    <span class="yes">Yes</span>
    <span class="no">No</span>
</div>

Create your own confirm() method:

function doConfirm(msg, yesFn, noFn)
{
    var confirmBox = $("#confirmBox");
    confirmBox.find(".message").text(msg);
    confirmBox.find(".yes,.no").unbind().click(function()
    {
        confirmBox.hide();
    });
    confirmBox.find(".yes").click(yesFn);
    confirmBox.find(".no").click(noFn);
    confirmBox.show();
}

Call it by your code:

doConfirm("Are you sure?", function yes()
{
    form.submit();
}, function no()
{
    // do nothing
});

MY CHANGES I have tweaked the above so that instead of calling confirmBox.show() I used confirmBox.dialog({...}) like this

confirmBox.dialog
    ({
      autoOpen: true,
      modal: true,
      buttons:
        {
          'Yes': function () {
            $(this).dialog('close');
            $(this).find(".yes").click();
          },
          'No': function () {
            $(this).dialog('close');
            $(this).find(".no").click();
          }
        }
    });

The other change I made was to create the confirmBox div within the doConfirm function, like ThulasiRam did in his answer.

Display back button on action bar

I know that the above are many helpful solutions, but this time I read this article (current Android Studio 2.1.2 with sdk 23) some method above doesn't work.

Below is my solution for sub-activity is MapsActivity

First, you need to add parentActivity in

AndroidManifest.xml

like this :

<application ... >
    ...
    <!-- Main activity (which has no parent activity) -->
    <activity
        android:name="com.example.myapp.MainActivity" ...>
        ...
    </activity>
    <!-- A child of the main activity -->
    <activity
        .....
        android:parentActivityName=".MainActivity" >
        <!-- Support Parent activity for Android 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myapp.MainActivity" />
    </activity>
</application>

Second, ensure that your sub-Activity extends AppCompatActivity, not FragmentActivity.

Third, override onOptionsItemSelected() method

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // app icon action bar is clicked; go to parent activity
                this.finish();
                return true;
            case R.id.action_settings:
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

Hope this will help!

Configure Log4net to write to multiple files

Vinay is correct. In answer to your comment in his answer, one way you can do it is as follows:

<root>
    <level value="ALL" />
    <appender-ref ref="File1Appender" />
</root>
<logger name="SomeName">
    <level value="ALL" />
    <appender-ref ref="File1Appender2" />
</logger>

This is how I have done it in the past. Then something like this for the other log:

private static readonly ILog otherLog = LogManager.GetLogger("SomeName");

And you can get your normal logger as follows:

private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

Read the loggers and appenders section of the documentation to understand how this works.

How does Task<int> become an int?

No requires converting the Task to int. Simply Use The Task Result.

int taskResult = AccessTheWebAndDouble().Result;

public async Task<int> AccessTheWebAndDouble()
{
    int task = AccessTheWeb();
    return task;
}

It will return the value if available otherwise it return 0.

Normalize columns of pandas data frame

one easy way by using Pandas: (here I want to use mean normalization)

normalized_df=(df-df.mean())/df.std()

to use min-max normalization:

normalized_df=(df-df.min())/(df.max()-df.min())

Edit: To address some concerns, need to say that Pandas automatically applies colomn-wise function in the code above.

Remove trailing spaces automatically or with a shortcut

Have a look at the EditorConfig plugin.

By using the plugin you can have settings specific for various projects. Visual Studio Code also has IntelliSense built-in for .editorconfig files.

How could I create a list in c++?

I'm guessing this is a homework question, so you probably want to go here. It has a tutorial explaining linked lists, gives good pseudocode and also has a C++ implementation you can download.

I'd recommend reading through the explanation and understanding the pseudocode before blindly using the implementation. This is a topic that you really should understand in depth if you want to continue on in CS.

SSL Connection / Connection Reset with IISExpress

KASPERSKY ISSUE!! I'd tried everything, localhost with SSL worked if I ran VS2019 as Administrator, but the connection was lost after a while of debugging, and I had to re-run the app. The only worked for me was uninstall Kaspersky, unbelievable, days ago I'd tried to pause Kaspersky protection and it didn't solve the problem, so I had discarded antivirus issues, after days of trying solutions, I resumed antivirus matter, uninstalled Kaspersky V 21.1 ..., tried and worked, installed V 21.2 ... and it works fine also without running VS as Administrator

AngularJS HTTP post to PHP and undefined

It took me hours to understand that while working with Angular and PHP. Post data was not going to PHP in $_POST

in PHP code do the following. - Create a variable $angular_post_params - Then do the following $angular_http_params = (array)json_decode(trim(file_get_contents('php://input')));

now you can access your parameters like you do from $_POST

$angular_http_params["key"]

in case you were wondering about javascript....this is what i used

    var myApp = angular.module('appUsers', []);
    //var post_params = $.param({ request_type: "getListOfUsersWithRolesInfo" });
    var dataObj = {
        task_to_perform: 'getListOfUsersWithRolesInfo'
    };

    myApp.controller('ctrlListOfUsers', function ($scope, $http) {
        $http({
            method: 'POST',
            dataType: 'json',
            url: ajax_processor_url,
            headers: {
                'Content-Type': 'application/json'
            },
            data: dataObj,
            //transformRequest: function(){},
            timeout: 30000,
            cache: false
        }).
        success(function (rsp) {
            console.log("success");
            console.log(rsp);
        }).
        error(function (rsp) {
            console.log("error");
        });
    });

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

I had same issue in Angular7 when I create dynamic components. There are two components(TreatListComponent, MyTreatComponent) that needs to be loaded dynamically. I just added entryComponents array in to my app.module.ts file.

    entryComponents: [
    TreatListComponent,
    MyTreatComponent
  ],

XMLHttpRequest module not defined/found

Since the last update of the xmlhttprequest module was around 2 years ago, in some cases it does not work as expected.

So instead, you can use the xhr2 module. In other words:

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();

becomes:

var XMLHttpRequest = require('xhr2');
var xhr = new XMLHttpRequest();

But ... of course, there are more popular modules like Axios, because -for example- uses promises:

// Make a request for a user with a given ID
axios.get('/user?ID=12345').then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});

how to redirect to external url from c# controller

If you are using MVC then it would be more appropriate to use RedirectResult instead of using Response.Redirect.

public ActionResult Index() {
        return new RedirectResult("http://www.website.com");
    }

Reference - https://blogs.msdn.microsoft.com/rickandy/2012/03/01/response-redirect-and-asp-net-mvc-do-not-mix/

Get all mysql selected rows into an array

you can call mysql_fetch_array() for no_of_row time

How to leave space in HTML

Use white-space: pre:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<span style="white-space: pre">    My spaces   </span>_x000D_
<br>_x000D_
<span>     My spaces   </span>_x000D_
</html>
_x000D_
_x000D_
_x000D_

SSIS package creating Hresult: 0x80004005 Description: "Login timeout expired" error

I had a similar error..This might be due to two reasons. a) If you have used variables, re-evaluate the expressions in which variables are used and make sure the expression is evaluated without errors. b) If you are deleting the excel sheet and creating excel sheet on the fly in your package.

How to deploy a React App on Apache web server

First, add a pom.xml and make it a maven project and then build it. It will create a War file for you in the target folder after that you can deploy it wherever you want.

pom.xml http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 it.megadix create-react-app-servlet 0.0.1-SNAPSHOT war

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <npm.output.directory>build</npm.output.directory>
</properties>

<build>
    <finalName>${project.artifactId}</finalName>
    <plugins>
        <!-- Standard plugin to generate WAR -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.1.1</version>
            <configuration>
                <webResources>
                    <resource>
                        <directory>${npm.output.directory}</directory>
                    </resource>
                </webResources>
                <webXml>${basedir}/web.xml</webXml>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.3.2</version>
            <executions>
                <!-- Required: The following will ensure `npm install` is called
                     before anything else during the 'Default Lifecycle' -->
                <execution>
                    <id>npm install (initialize)</id>
                    <goals>
                        <goal>exec</goal>
                    </goals>
                    <phase>initialize</phase>
                    <configuration>
                        <executable>npm</executable>
                        <arguments>
                            <argument>install</argument>
                        </arguments>
                    </configuration>
                </execution>
                <!-- Required: The following will ensure `npm install` is called
                     before anything else during the 'Clean Lifecycle' -->
                <execution>
                    <id>npm install (clean)</id>
                    <goals>
                        <goal>exec</goal>
                    </goals>
                    <phase>pre-clean</phase>
                    <configuration>
                        <executable>npm</executable>
                        <arguments>
                            <argument>install</argument>
                        </arguments>
                    </configuration>
                </execution>

                <!-- Required: This following calls `npm run build` where 'build' is
                     the script name I used in my project, change this if yours is
                         different -->
                <execution>
                    <id>npm run build (compile)</id>
                    <goals>
                        <goal>exec</goal>
                    </goals>
                    <phase>compile</phase>
                    <configuration>
                        <executable>npm</executable>
                        <arguments>
                            <argument>run</argument>
                            <argument>build</argument>
                        </arguments>
                    </configuration>
                </execution>

            </executions>

            <configuration>
                <environmentVariables>
                    <CI>true</CI>
                    <!-- The following parameters create an NPM sandbox for CI -->
                    <NPM_CONFIG_PREFIX>${basedir}/npm</NPM_CONFIG_PREFIX>
                    <NPM_CONFIG_CACHE>${NPM_CONFIG_PREFIX}/cache</NPM_CONFIG_CACHE>
                    <NPM_CONFIG_TMP>${project.build.directory}/npmtmp</NPM_CONFIG_TMP>
                </environmentVariables>
            </configuration>
        </plugin>
    </plugins>
</build>

<profiles>
    <profile>
        <id>local</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>exec-maven-plugin</artifactId>

                    <configuration>
                        <environmentVariables>
                            <PUBLIC_URL>http://localhost:8080/${project.artifactId}</PUBLIC_URL>
                            <REACT_APP_ROUTER_BASE>/${project.artifactId}</REACT_APP_ROUTER_BASE>
                        </environmentVariables>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>

    <profile>
        <id>prod</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>exec-maven-plugin</artifactId>

                    <configuration>
                        <environmentVariables>
                            <PUBLIC_URL>http://my-awesome-production-host/${project.artifactId}</PUBLIC_URL>
                            <REACT_APP_ROUTER_BASE>/${project.artifactId}</REACT_APP_ROUTER_BASE>
                        </environmentVariables>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

Note:- If you find a blank page after running your project then clear your cache or restart your IDE.

How to generate unique ID with node.js

It's been some time since I used node.js, but I think I might be able to help.

Firstly, in node, you only have a single thread and are supposed to use callbacks. What will happen with your code, is that base.getID query will get queued up by for execution, but the while loop will continusouly run as a busy loop pointlessly.

You should be able to solve your issue with a callback as follows:

function generate(count, k) {
    var _sym = 'abcdefghijklmnopqrstuvwxyz1234567890',
    var str = '';

    for(var i = 0; i < count; i++) {
        str += _sym[parseInt(Math.random() * (_sym.length))];
    }
    base.getID(str, function(err, res) {
        if(!res.length) {
          k(str)                   // use the continuation
        } else generate(count, k)  // otherwise, recurse on generate
    });
}

And use it as such

generate(10, function(uniqueId){
  // have a uniqueId
})

I haven't coded any node/js in around 2 years and haven't tested this, but the basic idea should hold – don't use a busy loop, and use callbacks. You might want to have a look at the node async package.

How to view UTF-8 Characters in VIM or Gvim

Try to reload the document using:

:e! ++enc=utf8

If that works you should maybe change the fileencodings settings in your .vimrc.

What is the difference between Document style and RPC style communication?

Document
Document style messages can be validated against predefined schema. In document style, SOAP message is sent as a single document. Example of schema:

  <types>  
   <xsd:schema> <xsd:import namespace="http://example.com/" 
    schemaLocation="http://localhost:8080/ws/hello?xsd=1"/>  
   </xsd:schema>  
  </types>

Example of document style soap body message

  <message name="getHelloWorldAsString">   
     <part name="parameters" element="tns:getHelloWorldAsString"/>   
  </message> 
  <message name="getHelloWorldAsStringResponse">  
     <part name="parameters"> element="tns:getHelloWorldAsStringResponse"/>   
  </message>

Document style message is loosely coupled.

RPC RPC style messages use method name and parameters to generate XML structure. messages are difficult to be validated against schema. In RPC style, SOAP message is sent as many elements.

  <message name="getHelloWorldAsString">
    <part name="arg0"> type="xsd:string"/>   
   </message> 
  <message name="getHelloWorldAsStringResponse">   
    <part name="return"
   > type="xsd:string"/>   
  </message>

Here each parameters are discretely specified, RPC style message is tightly coupled, is typically static, requiring changes to the client when the method signature changes The rpc style is limited to very simple XSD types such as String and Integer, and the resulting WSDL will not even have a types section to define and constrain the parameters

Literal By default style. Data is serialized according to a schema, data type not specified in messages but a reference to schema(namespace) is used to build soap messages.

   <soap:body>
     <myMethod>
        <x>5</x>
        <y>5.0</y>
     </myMethod>
   </soap:body>

Encoded Datatype specified in each parameter

   <soap:body>
     <myMethod>
         <x xsi:type="xsd:int">5</x>
         <y xsi:type="xsd:float">5.0</y>
     </myMethod>
   </soap:body>

Schema free

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

To use aliases on eloquent models modify your code like this:

Item
    ::from( 'items as items_alias' )
    ->join( 'attachments as att', DB::raw( 'att.item_id' ), '=', DB::raw( 'items_alias.id' ) )
    ->select( DB::raw( 'items_alias.*' ) )
    ->get();

This will automatically add table prefix to table names and returns an instance of Items model. not a bare query result. Adding DB::raw prevents laravel from adding table prefixes to aliases.

jquery AJAX and json format

Currently you are sending the data as typical POST values, which look like this:

first_name=somename&last_name=somesurname

If you want to send data as json you need to create an object with data and stringify it.

data: JSON.stringify(someobject)

Setting selected option in laravel form

You can also try this for limited options:

          <select class="form-control required" id="assignedRole">
            <option id = "employeeRole" selected ="@if($employee->employee_role=='Employee'){'selected'}else{''} @endif">Employee</option>
            <option id = "adminRole" selected ="@if($employee->employee_role=='Admin'){'selected'}else{''} @endif">Admin</option>
            <option id = "employerRole" selected ="@if($employee->employee_role=='Employer'){'selected'}else{''} @endif">Employer</option>
          </select>

Bootstrap 3 Styled Select dropdown looks ugly in Firefox on OS X

I am using Chosen. Look at: http://harvesthq.github.io/chosen/

It works on Firefox, Chrome, IE and Safari with the same style. But not on Mobile Devices.

IE Enable/Disable Proxy Settings via Registry

modifying the proxy value under

[HKEY_USERS\<your SID>\Software\Microsoft\Windows\CurrentVersion\Internet Settings]

doesnt need to restart ie

How to detect if CMD is running as Administrator/has elevated privileges?

ADDENDUM: For Windows 8 this will not work; see this excellent answer instead.


Found this solution here: http://www.robvanderwoude.com/clevertricks.php

AT > NUL
IF %ERRORLEVEL% EQU 0 (
    ECHO you are Administrator
) ELSE (
    ECHO you are NOT Administrator. Exiting...
    PING 127.0.0.1 > NUL 2>&1
    EXIT /B 1
)

Assuming that doesn't work and since we're talking Win7 you could use the following in Powershell if that's suitable:

$principal = new-object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())
$principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)

If not (and probably not, since you explicitly proposed batch files) then you could write the above in .NET and return an exit code from an exe based on the result for your batch file to use.

How to uncommit my last commit in Git

Just a note - if you're using ZSH and see the error

zsh: no matches found: HEAD^

You need to escape the ^

git reset --soft HEAD\^

Why is JavaFX is not included in OpenJDK 8 on Ubuntu Wily (15.10)?

According to the packages list in Ubuntu Wily Xenial Bionic there is a package named openjfx. This should be a candidate for what you're looking for:

JavaFX/OpenJFX 8 - Rich client application platform for Java

You can install it via:

sudo apt-get install openjfx

It provides the following JAR files to the OpenJDK installation on Ubuntu systems:

/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/jfxrt.jar
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/jfxswt.jar
/usr/lib/jvm/java-8-openjdk-amd64/lib/ant-javafx.jar
/usr/lib/jvm/java-8-openjdk-amd64/lib/javafx-mx.jar

If you want to have sources available, for example for debugging, you can additionally install:

sudo apt-get install openjfx-source

Difference between two numpy arrays in python

This is pretty simple with numpy, just subtract the arrays:

diffs = array1 - array2

I get:

diffs == array([ 0.1,  0.2,  0.3])

Can regular JavaScript be mixed with jQuery?

Of course you can, but why do this? You have to include a <script></script>pair of tags that link to the jQuery web page, i.e.: <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> . Then you will load the whole jQuery object just to use one single function, and because jQuery is a JavaScript library which will take time for the computer to upload, it will execute slower than just JavaScript.

How to run .APK file on emulator

Step-by-Step way to do this:

  1. Install Android SDK
  2. Start the emulator by going to $SDK_root/emulator.exe
  3. Go to command prompt and go to the directory $SDK_root/platform-tools (or else add the path to windows environment)
  4. Type in the command adb install
  5. Bingo. Your app should be up and running on the emulator

Run AVD Emulator without Android Studio

This is the commands on Mac

cd ~/Library/Android/Sdk/tools/bin && ./avdmanager list avd

then

cd ~/Library/Android/Sdk/tools && ./emulator -avd NAME_OF_YOUR_DEVICE

MVC controller : get JSON object from HTTP body?

It seems that if

  • Content-Type: application/json and
  • if POST body isn't tightly bound to controller's input object class

Then MVC doesn't really bind the POST body to any particular class. Nor can you just fetch the POST body as a param of the ActionResult (suggested in another answer). Fair enough. You need to fetch it from the request stream yourself and process it.

[HttpPost]
public ActionResult Index(int? id)
{
    Stream req = Request.InputStream;
    req.Seek(0, System.IO.SeekOrigin.Begin);
    string json = new StreamReader(req).ReadToEnd();

    InputClass input = null;
    try
    {
        // assuming JSON.net/Newtonsoft library from http://json.codeplex.com/
        input = JsonConvert.DeserializeObject<InputClass>(json)
    }

    catch (Exception ex)
    {
        // Try and handle malformed POST body
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    //do stuff

}

Update:

for Asp.Net Core, you have to add [FromBody] attrib beside your param name in your controller action for complex JSON data types:

[HttpPost]
public ActionResult JsonAction([FromBody]Customer c)

Also, if you want to access the request body as string to parse it yourself, you shall use Request.Body instead of Request.InputStream:

Stream req = Request.Body;
req.Seek(0, System.IO.SeekOrigin.Begin);
string json = new StreamReader(req).ReadToEnd();

How can I calculate the difference between two dates?

With Swift 5 and iOS 12, according to your needs, you may use one of the two following ways to find the difference between two dates in days.


#1. Using Calendar's dateComponents(_:from:to:) method

import Foundation

let calendar = Calendar.current

let startDate = calendar.date(from: DateComponents(year: 2010, month: 11, day: 22))!
let endDate = calendar.date(from: DateComponents(year: 2015, month: 5, day: 1))!

let dateComponents = calendar.dateComponents([Calendar.Component.day], from: startDate, to: endDate)

print(dateComponents) // prints: day: 1621 isLeapMonth: false
print(String(describing: dateComponents.day)) // prints: Optional(1621)

#2. Using DateComponentsFormatter's string(from:to:) method

import Foundation

let calendar = Calendar.current

let startDate = calendar.date(from: DateComponents(year: 2010, month: 11, day: 22))!
let endDate = calendar.date(from: DateComponents(year: 2015, month: 5, day: 1))!

let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.allowedUnits = [NSCalendar.Unit.day]

let elapsedTime = formatter.string(from: startDate, to: endDate)
print(String(describing: elapsedTime)) // prints: Optional("1,621 days")

Why is 22 the default port number for SFTP?

Why is 21 the default port for FTP? Or 80 the default for HTTP? It is a convention.

How do you append to a file?

if you want to append to a file

with open("test.txt", "a") as myfile:
    myfile.write("append me")

We declared the variable myfile to open a file named test.txt. Open takes 2 arguments, the file that we want to open and a string that represents the kinds of permission or operation we want to do on the file

here is file mode options

Mode    Description

'r' This is the default mode. It Opens file for reading.
'w' This Mode Opens file for writing. 
If file does not exist, it creates a new file.
If file exists it truncates the file.
'x' Creates a new file. If file already exists, the operation fails.
'a' Open file in append mode. 
If file does not exist, it creates a new file.
't' This is the default mode. It opens in text mode.
'b' This opens in binary mode.
'+' This will open a file for reading and writing (updating)

Link to download apache http server for 64bit windows.

you can find multiple options listed at http://httpd.apache.org/docs/current/platform/windows.html#down

ApacheHaus Apache Lounge BitNami WAMP Stack WampServer XAMPP

IntelliJ cannot find any declarations

Came across the same issue and in my case (Java project), I had to include all the dependent jars in the project's libraries section.

File -> Project Structure -> Libraries

I had to add my project dependent jars in the above section (for example; project/web/lib/). After doing so, all resolved fine. I hope this will help someone.

How can I convert a string to boolean in JavaScript?

You need to separate (in your thinking) the value of your selections and the representation of that value.

Pick a point in the JavaScript logic where they need to transition from string sentinels to native type and do a comparison there, preferably where it only gets done once for each value that needs to be converted. Remember to address what needs to happen if the string sentinel is not one the script knows (i.e. do you default to true or to false?)

In other words, yes, you need to depend on the string's value. :-)

How to decode HTML entities using jQuery?

Like Mike Samuel said, don't use jQuery.html().text() to decode html entities as it's unsafe.

Instead, use a template renderer like Mustache.js or decodeEntities from @VyvIT's comment.

Underscore.js utility-belt library comes with escape and unescape methods, but they are not safe for user input:

_.escape(string)

_.unescape(string)

How to add a set path only for that batch file executing?

Just like any other environment variable, with SET:

SET PATH=%PATH%;c:\whatever\else

If you want to have a little safety check built in first, check to see if the new path exists first:

IF EXIST c:\whatever\else SET PATH=%PATH%;c:\whatever\else

If you want that to be local to that batch file, use setlocal:

setlocal
set PATH=...
set OTHERTHING=...

@REM Rest of your script

Read the docs carefully for setlocal/endlocal , and have a look at the other references on that site - Functions is pretty interesting too and the syntax is tricky.

The Syntax page should get you started with the basics.

How do I get the current time zone of MySQL?

To anyone come to find timezone of mysql db.

With this query you can get current timezone :

mysql> SELECT @@system_time_zone as tz;
+-------+
|  tz   |
+-------+
|  CET  |
+-------+

Difference between "process.stdout.write" and "console.log" in node.js?

I know this is a very old question but I didn't see anybody talking about the main difference between process.stdout.write and console.log and I just want to mention it.

As Mauvis Leford and TK-421 pointed out, the console.log adds a line-break character at the end of the line (\n) but that's not all what it does.

The code has not changed since at least 0.10.X version and now we have a a 5.X version.

Here is the code:

Console.prototype.log = function() {
  this._stdout.write(util.format.apply(this, arguments) + '\n');
};

As you can see, there is a part that says .apply(this, arguments) and that makes a big difference on functionality. It is easier to explain that with examples:

process.stdout.write has a very basic functionality, you can just write something in there, like this:

process.stdout.write("Hello World\n"); 

If you don't put the break line at the end you will get a weird character after your string, something like this:

process.stdout.write("Hello World"); //Hello World% 

(I think that means something like "the end of the program", so you will see it only if you process.stdout.write was used at the end of your file and you didn't add the break line)

On the other hand, console.log can do more.

  1. You can use it in the same way

    console.log("Hello World"); //You don't need the break line here because it was already formated and also that weird character did disappear

  2. You can write more than one string

    console.log("Hello", "World");

  3. You can make associations

    console.log("Hello %s", "World") //Useful when "World" is inside a variable

An that's it, that added functionality is given thanks to the util.format.apply part (I could talk a lot about what exactly this does but you get my point, you can read more here).

I hope somebody find this information useful.

What is the difference between .text, .value, and .value2?

.Text is the formatted cell's displayed value; .Value is the value of the cell possibly augmented with date or currency indicators; .Value2 is the raw underlying value stripped of any extraneous information.

range("A1") = Date
range("A1").numberformat = "yyyy-mm-dd"
debug.print range("A1").text
debug.print range("A1").value
debug.print range("A1").value2

'results from Immediate window
2018-06-14
6/14/2018 
43265 

range("A1") = "abc"
range("A1").numberformat = "_(_(_(@"
debug.print range("A1").text
debug.print range("A1").value
debug.print range("A1").value2

'results from Immediate window
   abc
abc
abc

range("A1") = 12
range("A1").numberformat = "0 \m\m"
debug.print range("A1").text
debug.print range("A1").value
debug.print range("A1").value2

'results from Immediate window
12 mm
12
12

If you are processing the cell's value then reading the raw .Value2 is marginally faster than .Value or .Text. If you are locating errors then .Text will return something like #N/A as text and can be compared to a string while .Value and .Value2 will choke comparing their returned value to a string. If you have some custom cell formatting applied to your data then .Text may be the better choice when building a report.

How to generate and manually insert a uniqueidentifier in sql server?

Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .

*Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument..*

So error is raised..

Please refere sample script:

DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)

insert into #temp1 values(@id)

Select * from #temp1

Drop Table #temp1

What is best tool to compare two SQL Server databases (schema and data)?

I've used Red Gate's tools and they are superb. However, if you can't spend any money you could try Open DBDiff to compare schemas.

Calculate date/time difference in java

I would prefer to use suggested java.util.concurrent.TimeUnit class.

long diff = d2.getTime() - d1.getTime();//as given

long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff); 

Rounding numbers to 2 digits after comma

Though we have many answers here with plenty of useful suggestions, each of them still misses some steps.
So here is a complete solution wrapped into small function:

function roundToTwoDigitsAfterComma(floatNumber) {
    return parseFloat((Math.round(floatNumber * 100) / 100).toFixed(2));
}

Just in case you are interested how this works:

  1. Multiple with 100 and then do round to keep precision of 2 digits after comma
  2. Divide back into 100 and use toFixed(2) to keep 2 digits after comma and throw other unuseful part
  3. Convert it back to float by using parseFloat() function as toFixed(2) returns string instead

Note: If you keep last 2 digits after comma because of working with monetary values, and doing financial calculations keep in mind that it's not a good idea and you'd better use integer values instead.

Not an enclosing class error Android Studio

you are calling the context of not existing activity...so just replace your code in onClick(View v) as Intent intent=new Intent(this,Katra_home.class); startActivity(intent); it will definitely works....

Concatenate a NumPy array to another NumPy array

Actually one can always create an ordinary list of numpy arrays and convert it later.

In [1]: import numpy as np

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

In [3]: b = np.array([[1,2],[3,4]])

In [4]: l = [a]

In [5]: l.append(b)

In [6]: l = np.array(l)

In [7]: l.shape
Out[7]: (2, 2, 2)

In [8]: l
Out[8]: 
array([[[1, 2],
        [3, 4]],

       [[1, 2],
        [3, 4]]])

Error to run Android Studio

in OpenSuSE 13.1 and some 13.2 versions you also need to:

  • install java-1_7_0-openjdk-devel package
  • change the JAVA_HOME path when starting the studio:

For x86: JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk-1.7.0/ sh studio.sh

For x64: JAVA_HOME=/usr/lib64/jvm/java-1.7.0-openjdk-1.7.0/ sh studio.sh

PowerShell script to return members of multiple security groups

This will give you a list of a single group, and the members of each group.

param
(   
    [Parameter(Mandatory=$true,position=0)]
    [String]$GroupName
)

import-module activedirectory

# optional, add a wild card..
# $groups = $groups + "*"

$Groups = Get-ADGroup -filter {Name -like $GroupName} | Select-Object Name

ForEach ($Group in $Groups)
   {write-host " "
    write-host "$($group.name)"
    write-host "----------------------------"

    Get-ADGroupMember -identity $($groupname) -recursive | Select-Object samaccountname

 }
write-host "Export Complete"

If you want the friendly name, or other details, add them to the end of the select-object query.

gem install: Failed to build gem native extension (can't find header files)

sudo apt-get install ruby-dev

This command solved the problem for me!

Executing <script> elements inserted with .innerHTML

@phidah... Here is a very interesting solution to your problem: http://24ways.org/2005/have-your-dom-and-script-it-too

So it would look like this instead:

<img src="empty.gif" onload="alert('test');this.parentNode.removeChild(this);" />

Creating a .p12 file

The openssl documentation says that file supplied as the -in argument must be in PEM format.

Turns out that, contrary to the CA's manual, the certificate returned by the CA which I stored in myCert.cer is not PEM format rather it is PKCS7.

In order to create my .p12, I had to first convert the certificate to PEM:

openssl pkcs7 -in myCert.cer -print_certs -out certs.pem

and then execute

openssl pkcs12 -export -out keyStore.p12 -inkey myKey.pem -in certs.pem

Secure FTP using Windows batch script

First, make sure you understand, if you need to use Secure FTP (=FTPS, as per your text) or SFTP (as per tag you have used).

Neither is supported by Windows command-line ftp.exe. As you have suggested, you can use WinSCP. It supports both FTPS and SFTP.

Using WinSCP, your batch file would look like (for SFTP):

echo open sftp://ftp_user:[email protected] -hostkey="server's hostkey" >> ftpcmd.dat
echo put c:\directory\%1-export-%date%.csv >> ftpcmd.dat
echo exit >> ftpcmd.dat
winscp.com /script=ftpcmd.dat
del ftpcmd.dat

And the batch file:

winscp.com /log=ftpcmd.log /script=ftpcmd.dat /parameter %1 %date%

Though using all capabilities of WinSCP (particularly providing commands directly on command-line and the %TIMESTAMP% syntax), the batch file simplifies to:

winscp.com /log=ftpcmd.log /command ^
    "open sftp://ftp_user:[email protected] -hostkey=""server's hostkey""" ^
    "put c:\directory\%1-export-%%TIMESTAMP#yyyymmdd%%.csv" ^
    "exit"

For the purpose of -hostkey switch, see verifying the host key in script.

Easier than assembling the script/batch file manually is to setup and test the connection settings in WinSCP GUI and then have it generate the script or batch file for you:

Generate batch file

All you need to tweak is the source file name (use the %TIMESTAMP% syntax as shown previously) and the path to the log file.


For FTPS, replace the sftp:// in the open command with ftpes:// (explicit TLS/SSL) or ftps:// (implicit TLS/SSL). Remove the -hostkey switch.

winscp.com /log=ftpcmd.log /command ^
    "open ftps://ftp_user:[email protected] -explicit" ^
    "put c:\directory\%1-export-%%TIMESTAMP#yyyymmdd%%.csv" ^
    "exit"

You may need to add the -certificate switch, if your server's certificate is not issued by a trusted authority.

Again, as with the SFTP, easier is to setup and test the connection settings in WinSCP GUI and then have it generate the script or batch file for you.


See a complete conversion guide from ftp.exe to WinSCP.

You should also read the Guide to automating file transfers to FTP server or SFTP server.


Note to using %TIMESTAMP#yyyymmdd% instead of %date%: A format of %date% variable value is locale-specific. So make sure you test the script on the same locale you are actually going to use the script on. For example on my Czech locale the %date% resolves to ct 06. 11. 2014, what might be problematic when used as a part of a file name.

For this reason WinSCP supports (locale-neutral) timestamp formatting natively. For example %TIMESTAMP#yyyymmdd% resolves to 20170515 on any locale.

(I'm the author of WinSCP)

Reference to non-static member function must be called

You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?

Spring cron expression for every day 1:01:am

You can use annotate your method with @Scheduled(cron ="0 1 1 * * ?").

0 - is for seconds

1- 1 minute

1 - hour of the day.

How to create a vector of user defined size but with no predefined values?

With the constructor:

// create a vector with 20 integer elements
std::vector<int> arr(20);

for(int x = 0; x < 20; ++x)
   arr[x] = x;

Retaining file permissions with Git

In case you are coming into this right now, I've just been through it today and can summarize where this stands. If you did not try this yet, some details here might help.

I think @Omid Ariyan's approach is the best way. Add the pre-commit and post-checkout scripts. DON'T forget to name them exactly the way Omid does and DON'T forget to make them executable. If you forget either of those, they have no effect and you run "git commit" over and over wondering why nothing happens :) Also, if you cut and paste out of the web browser, be careful that the quotation marks and ticks are not altered.

If you run the pre-commit script once (by running a git commit), then the file .permissions will be created. You can add it to the repository and I think it is unnecessary to add it over and over at the end of the pre-commit script. But it does not hurt, I think (hope).

There are a few little issues about the directory name and the existence of spaces in the file names in Omid's scripts. The spaces were a problem here and I had some trouble with the IFS fix. For the record, this pre-commit script did work correctly for me:

#!/bin/bash  

SELF_DIR=`git rev-parse --show-toplevel`
DATABASE=$SELF_DIR/.permissions

# Clear the permissions database file
> $DATABASE

echo -n "Backing-up file permissions..."

IFSold=$IFS
IFS=$'\n'
for FILE  in `git ls-files`
do
   # Save the permissions of all the files in the index
   echo $FILE";"`stat -c "%a;%U;%G" $FILE` >> $DATABASE
done
IFS=${IFSold}
# Add the permissions database file to the index
git add $DATABASE

echo "OK"

Now, what do we get out of this?

The .permissions file is in the top level of the git repo. It has one line per file, here is the top of my example:

$ cat .permissions
.gitignore;660;pauljohn;pauljohn
05.WhatToReport/05.WhatToReport.doc;664;pauljohn;pauljohn
05.WhatToReport/05.WhatToReport.pdf;664;pauljohn;pauljohn

As you can see, we have

filepath;perms;owner;group

In the comments about this approach, one of the posters complains that it only works with same username, and that is technically true, but it is very easy to fix it. Note the post-checkout script has 2 action pieces,

# Set the file permissions
chmod $PERMISSIONS $FILE
# Set the file owner and groups
chown $USER:$GROUP $FILE

So I am only keeping the first one, that's all I need. My user name on the Web server is indeed different, but more importantly you can't run chown unless you are root. Can run "chgrp", however. It is plain enough how to put that to use.

In the first answer in this post, the one that is most widely accepted, the suggestion is so use git-cache-meta, a script that is doing the same work that the pre/post hook scripts here are doing (parsing output from git ls-files). These scripts are easier for me to understand, the git-cache-meta code is rather more elaborate. It is possible to keep git-cache-meta in the path and write pre-commit and post-checkout scripts that would use it.

Spaces in file names are a problem with both of Omid's scripts. In the post-checkout script, you'll know you have the spaces in file names if you see errors like this

$ git checkout -- upload.sh
Restoring file permissions...chmod: cannot access  '04.StartingValuesInLISREL/Open': No such file or directory
chmod: cannot access 'Notebook.onetoc2': No such file or directory
chown: cannot access '04.StartingValuesInLISREL/Open': No such file or directory
chown: cannot access 'Notebook.onetoc2': No such file or directory

I'm checking on solutions for that. Here's something that seems to work, but I've only tested in one case

#!/bin/bash

SELF_DIR=`git rev-parse --show-toplevel`
DATABASE=$SELF_DIR/.permissions

echo -n "Restoring file permissions..."
IFSold=${IFS}
IFS=$
while read -r LINE || [[ -n "$LINE" ]];
do
   FILE=`echo $LINE | cut -d ";" -f 1`
   PERMISSIONS=`echo $LINE | cut -d ";" -f 2`
   USER=`echo $LINE | cut -d ";" -f 3`
   GROUP=`echo $LINE | cut -d ";" -f 4`

   # Set the file permissions
   chmod $PERMISSIONS $FILE
   # Set the file owner and groups
   chown $USER:$GROUP $FILE
done < $DATABASE
IFS=${IFSold}
echo "OK"

exit 0

Since the permissions information is one line at a time, I set IFS to $, so only line breaks are seen as new things.

I read that it is VERY IMPORTANT to set the IFS environment variable back the way it was! You can see why a shell session might go badly if you leave $ as the only separator.

How can I query for null values in entity framework?

If it is a nullable type, maybe try use the HasValue property?

var result = from entry in table
                 where !entry.something.HasValue
                 select entry;

Don't have any EF to test on here though... just a suggestion =)

Getting a File's MD5 Checksum in Java

Here is a simple function that wraps around Sunil's code so that it takes a File as a parameter. The function does not need any external libraries, but it does require Java 7.

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.xml.bind.DatatypeConverter;

public class Checksum {

    /**
     * Generates an MD5 checksum as a String.
     * @param file The file that is being checksummed.
     * @return Hex string of the checksum value.
     * @throws NoSuchAlgorithmException
     * @throws IOException
     */
    public static String generate(File file) throws NoSuchAlgorithmException,IOException {

        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.update(Files.readAllBytes(file.toPath()));
        byte[] hash = messageDigest.digest();

        return DatatypeConverter.printHexBinary(hash).toUpperCase();
    }

    public static void main(String argv[]) throws NoSuchAlgorithmException, IOException {
        File file = new File("/Users/foo.bar/Documents/file.jar");          
        String hex = Checksum.generate(file);
        System.out.printf("hex=%s\n", hex);            
    }


}

Example output:

hex=B117DD0C3CBBD009AC4EF65B6D75C97B

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

If your targetSdkVersion >= 24, then we have to use FileProvider class to give access to the particular file or folder to make them accessible for other apps. We create our own class inheriting FileProvider in order to make sure our FileProvider doesn't conflict with FileProviders declared in imported dependencies as described here.

Steps to replace file:// URI with content:// URI:

  • Add a FileProvider <provider> tag in AndroidManifest.xml under <application> tag. Specify a unique authority for the android:authorities attribute to avoid conflicts, imported dependencies might specify ${applicationId}.provider and other commonly used authorities.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    <application
        ...
        <provider
            android:name="androidx.core.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>
    </application>
</manifest>
  • Then create a provider_paths.xml file in res/xml folder. A folder may be needed to be created if it doesn't exist yet. The content of the file is shown below. It describes that we would like to share access to the External Storage at root folder (path=".") with the name external_files.
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external_files" path="."/>
</paths>
  • The final step is to change the line of code below in

     Uri photoURI = Uri.fromFile(createImageFile());
    

    to

     Uri photoURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", createImageFile());
    
  • Edit: If you're using an intent to make the system open your file, you may need to add the following line of code:

     intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    

Please refer to the full code and solution that have been explained here.

Custom domain for GitHub project pages

I just discovered, after a bit of frustration, that if you're using PairNIC, all you have to do is enable the "Web Forwarding" setting under "Custom DNS" and supply the username.github.io/project address and it will automatically set up both the apex and subdomain records for you. It appears to do exactly what's suggested in the accepted answer. However, it won't let you do the exact same thing by manually adding records. Very strange. Anyway, it took me a while to figure that out, so I thought I'd share to save everyone else the trouble.

Get an OutputStream into a String

This worked nicely

OutputStream output = new OutputStream() {
    private StringBuilder string = new StringBuilder();

    @Override
    public void write(int b) throws IOException {
        this.string.append((char) b );
    }

    //Netbeans IDE automatically overrides this toString()
    public String toString() {
        return this.string.toString();
    }
};

method call =>> marshaller.marshal( (Object) toWrite , (OutputStream) output);

then to print the string or get it just reference the "output" stream itself As an example, to print the string out to console =>> System.out.println(output);

FYI: my method call marshaller.marshal(Object,Outputstream) is for working with XML. It is irrelevant to this topic.

This is highly wasteful for productional use, there is a way too many conversion and it is a bit loose. This was just coded to prove to you that it is totally possible to create a custom OuputStream and output a string. But just go Horcrux7 way and all is good with merely two method calls.

And the world lives on another day....

How can I select all children of an element except the last child?

Nick Craver's solution gave me what I needed but to make it explicit for those using CSS-in-JS:

const styles = {
  yourClass: {
    /* Styles for all elements with this class */
    '&:not(:last-child)': {
      /* Styles for all EXCEPT the last element with this class */
    },
  },
};

Try-catch-finally-return clarification

Here is some code that show how it works.

class Test
{
    public static void main(String args[]) 
    { 
        System.out.println(Test.test()); 
    }

    public static String test()
    {
        try {
            System.out.println("try");
            throw new Exception();
        } catch(Exception e) {
            System.out.println("catch");
            return "return"; 
        } finally {  
            System.out.println("finally");
            return "return in finally"; 
        }
    }
}

The results is:

try
catch
finally
return in finally

Resolve Git merge conflicts in favor of their changes during a pull

from https://git-scm.com/book/en/v2/Git-Tools-Advanced-Merging

This will basically do a fake merge. It will record a new merge commit with both branches as parents, but it will not even look at the branch you’re merging in. It will simply record as the result of the merge the exact code in your current branch.

$ git merge -s ours mundo

Merge made by the 'ours' strategy.

$ git diff HEAD HEAD~

You can see that there is no difference between the branch we were on and the result of the merge.

This can often be useful to basically trick Git into thinking that a branch is already merged when doing a merge later on. For example, say you branched off a release branch and have done some work on it that you will want to merge back into your master branch at some point. In the meantime some bugfix on master needs to be backported into your release branch. You can merge the bugfix branch into the release branch and also merge -s ours the same branch into your master branch (even though the fix is already there) so when you later merge the release branch again, there are no conflicts from the bugfix.

A situation I've found to be useful if I want master to reflect the changes of a new topic branch. I've noticed that -Xtheirs doesn't merge without conflicts in some circumstances... e.g.

$ git merge -Xtheirs topicFoo 

CONFLICT (modify/delete): js/search.js deleted in HEAD and modified in topicFoo. Version topicFoo of js/search.js left in tree.

In this case the solution I found was

$ git checkout topicFoo

from topicFoo, first merge in master using the -s ours strategy, this will create the fake commit that is just the state of topicFoo. $ git merge -s ours master

check the created merge commit

$ git log

now checkout the master branch

$ git checkout master

merge the topic branch back but this time use the -Xtheirs recursive strategy, this will now present you with a master branch with the state of topicFoo.

$ git merge -X theirs topicFoo

Mockito. Verify method arguments

An alternative to ArgumentMatcher is ArgumentCaptor.

Official example:

ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
verify(mock).doSomething(argument.capture());
assertEquals("John", argument.getValue().getName());

A captor can also be defined using the @Captor annotation:

@Captor ArgumentCaptor<Person> captor;
//... MockitoAnnotations.initMocks(this);
@Test public void test() {
    //...
    verify(mock).doSomething(captor.capture());
    assertEquals("John", captor.getValue().getName());
}

File content into unix variable with newlines

Bash -ge 4 has the mapfile builtin to read lines from the standard input into an array variable.

help mapfile 

mapfile < file.txt lines
printf "%s" "${lines[@]}"

mapfile -t < file.txt lines    # strip trailing newlines
printf "%s\n" "${lines[@]}" 

See also:

http://bash-hackers.org/wiki/doku.php/commands/builtin/mapfile

How to get file path in iPhone app

Since it is your files in your app bundle, I think you can use pathForResource:ofType: to get the full pathname of your file.

Here is an example:

NSString* filePath = [[NSBundle mainBundle] pathForResource:@"your_file_name" 
                                            ofType:@"the_file_extension"];

Post form data using HttpWebRequest

Use this code:

internal void SomeFunction() {
    Dictionary<string, string> formField = new Dictionary<string, string>();
    
    formField.Add("Name", "Henry");
    formField.Add("Age", "21");
    
    string body = GetBodyStringFromDictionary(formField);
    // output : Name=Henry&Age=21
}

internal string GetBodyStringFromDictionary(Dictionary<string, string> formField)
{
    string body = string.Empty;
    foreach (var pair in formField)
    {
        body += $"{pair.Key}={pair.Value}&";   
    }

    // delete last "&"
    body = body.Substring(0, body.Length - 1);

    return body;
}

Abort trap 6 error in C

Try this:

void drawInitialNim(int num1, int num2, int num3){
    int board[3][50] = {0}; // This is a local variable. It is not possible to use it after returning from this function. 

    int i, j, k;

    for(i=0; i<num1; i++)
        board[0][i] = 'O';
    for(i=0; i<num2; i++)
        board[1][i] = 'O';
    for(i=0; i<num3; i++)
        board[2][i] = 'O';

    for (j=0; j<3;j++) {
        for (k=0; k<50; k++) {
            if(board[j][k] != 0)
                printf("%c", board[j][k]);
        }
        printf("\n");
    }
}

Confirm button before running deleting routine from website

You have 2 options

1) Use javascript to confirm deletion (use onsubmit event handler), however if the client has JS disabled, you're in trouble.

2) Use PHP to echo out a confirmation message, along with the contents of the form (hidden if you like) as well as a submit button called "confirmation", in PHP check if $_POST["confirmation"] is set.

How do I get which JRadioButton is selected from a ButtonGroup

You could use getSelectedObjects() of ItemSelectable (superinterface of ButtonModel) which returns the list of selected items. In case of a radio button group it can only be one or none at all.

echo that outputs to stderr

Since 1 is the standard output, you do not have to explicitly name it in front of an output redirection like >. Instead, you can simply type:

echo This message goes to stderr >&2

Since you seem to be worried that 1>&2 will be difficult for you to reliably type, the elimination of the redundant 1 might be a slight encouragement to you!

For loop for HTMLCollection elements

Alternative to Array.from is to use Array.prototype.forEach.call

forEach: Array.prototype.forEach.call(htmlCollection, i => { console.log(i) });

map: Array.prototype.map.call(htmlCollection, i => { console.log(i) });

ect...

How do you clear the console screen in C?

Well, C doesn't understand the concept of screen. So any code would fail to be portable. Maybe take a look at conio.h or curses, according to your needs?

Portability is an issue, no matter what library is used.

Android 6.0 multiple permissions

Simple way to ask multiple permission,

https://github.com/sachinvarma/EasyPermission

How to add :

repositories {
        maven { url "https://jitpack.io" }
    }

implementation 'com.github.sachinvarma:EasyPermission:1.0.1'

How to ask permission:

 List<String> permission = new ArrayList<>();
 permission.add(EasyPermissionList.READ_EXTERNAL_STORAGE);
 permission.add(EasyPermissionList.ACCESS_FINE_LOCATION);

 new EasyPermissionInit(MainActivity.this, permission);

For more Details - >

https://github.com/sachinvarma/EasyPermission/blob/master/app/src/main/java/com/sachinvarma/easypermissionsample/MainActivity.java

It may help someone in future.

How can I count the number of elements with same class?

document.getElementsByClassName("classstringhere").length

The document.getElementsByClassName("classstringhere") method returns an array of all the elements with that class name, so .length gives you the amount of them.

gnuplot - adjust size of key/legend

To adjust the length of the samples:

set key samplen X

(default is 4)

To adjust the vertical spacing of the samples:

set key spacing X

(default is 1.25)

and (for completeness), to adjust the fontsize:

set key font "<face>,<size>"

(default depends on the terminal)

And of course, all these can be combined into one line:

set key samplen 2 spacing .5 font ",8"

Note that you can also change the position of the key using set key at <position> or any one of the pre-defined positions (which I'll just defer to help key at this point)

How to remove white space characters from a string in SQL Server

There may be 2 spaces after the text, please confirm. You can use LTRIM and RTRIM functions also right?

LTRIM(RTRIM(ProductAlternateKey))

Maybe the extra space isn't ordinary spaces (ASCII 32, soft space)? Maybe they are "hard space", ASCII 160?

ltrim(rtrim(replace(ProductAlternateKey, char(160), char(32))))

What are libtool's .la file for?

According to http://blog.flameeyes.eu/2008/04/14/what-about-those-la-files, they're needed to handle dependencies. But using pkg-config may be a better option:

In a perfect world, every static library needing dependencies would have its own .pc file for pkg-config, and every package trying to statically link to that library would be using pkg-config --static to get the libraries to link to.

How to create a MySQL hierarchical recursive query?

Simple query to list child's of first recursion:

select @pv:=id as id, name, parent_id
from products
join (select @pv:=19)tmp
where parent_id=@pv

Result:

id  name        parent_id
20  category2   19
21  category3   20
22  category4   21
26  category24  22

... with left join:

select
    @pv:=p1.id as id
  , p2.name as parent_name
  , p1.name name
  , p1.parent_id
from products p1
join (select @pv:=19)tmp
left join products p2 on p2.id=p1.parent_id -- optional join to get parent name
where p1.parent_id=@pv

The solution of @tincot to list all child's:

select  id,
        name,
        parent_id 
from    (select * from products
         order by parent_id, id) products_sorted,
        (select @pv := '19') initialisation
where   find_in_set(parent_id, @pv) > 0
and     @pv := concat(@pv, ',', id)

Test it online with Sql Fiddle and see all results.

http://sqlfiddle.com/#!9/a318e3/4/0

Setting an int to Infinity in C++

int is inherently finite; there's no value that satisfies your requirements.

If you're willing to change the type of b, though, you can do this with operator overrides:

class infinitytype {};

template<typename T>
bool operator>(const T &, const infinitytype &) {
  return false;
}

template<typename T>
bool operator<(const T &, const infinitytype &) {
  return true;
}

bool operator<(const infinitytype &, const infinitytype &) {
  return false;
}


bool operator>(const infinitytype &, const infinitytype &) {
  return false;
}

// add operator==, operator!=, operator>=, operator<=...

int main() {
  std::cout << ( INT_MAX < infinitytype() ); // true
}

How do I set the selenium webdriver get timeout?

Used below code in similar situation

driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);

and embedded driver.get code in a try catch, which solved the issue of loading pages which were taking more than 1 minute.

find without recursion

If you look for POSIX compliant solution:

cd DirsRoot && find . -type f -print -o -name . -o -prune

-maxdepth is not POSIX compliant option.

Cannot connect to Database server (mysql workbench)

My problem was that the MySQL server wasn't actually installed. I had run the MySQL Installer, but it didn't install the MySQL server.

I reran the installer, click "Add", and then added MySQL server to the list. Now it works fine.

How to change DatePicker dialog color for Android 5.0

Kotlin, 2021

// set date as button text if pressed
btnDate.setOnClickListener(View.OnClickListener {

    val dpd = DatePickerDialog(
        this,
        { view, year, monthOfYear, dayOfMonth ->
            val selectDate = Calendar.getInstance()
            selectDate.set(Calendar.YEAR, year)
            selectDate.set(Calendar.MONTH, monthOfYear)
            selectDate.set(Calendar.DAY_OF_MONTH, dayOfMonth)

            var formatDate = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
            val date = formatDate.format(selectDate.time)
            Toast.makeText(this, date, Toast.LENGTH_SHORT).show()
            btnDate.text = date
        }, 1990, 6, 6
    )

    val calendar = Calendar.getInstance()
    val year = calendar[Calendar.YEAR]
    val month = calendar[Calendar.MONTH]
    val day = calendar[Calendar.DAY_OF_MONTH]
    dpd.datePicker.minDate = GregorianCalendar(year - 90, month, day, 0, 0).timeInMillis
    dpd.datePicker.maxDate = GregorianCalendar(year - 10, month, day, 0, 0).timeInMillis
    dpd.show()
})

Styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- This is main Theme Style for your application! -->
    <item name="android:datePickerDialogTheme">@style/MyDatePickerDialogTheme</item>
</style>

<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Dialog">
    <item name="android:datePickerStyle">@style/MyDatePickerStyle</item>
</style>

<style name="MyDatePickerStyle" parent="@android:style/Widget.Material.DatePicker">
    <item name="android:headerBackground">#A500FF</item>
</style>

enter image description here

SQL join on multiple columns in same tables

You want to join on condition 1 AND condition 2, so simply use the AND keyword as below

ON a.userid = b.sourceid AND a.listid = b.destinationid;

getting integer values from textfield

You need to use Integer.parseInt(String)

private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
        if(evt.getSource()==jTextField2){
            int jml = Integer.parseInt(jTextField3.getText());
            jTextField1.setText(numberToWord(jml));

        }
    }

How do I set a value in CKEditor with Javascript?

Use the CKEditor method setData():

CKEDITOR.instances[**fieldname**].setData(**your data**)

How to use jQuery Plugin with Angular 4?

Install jQuery using NPM Jquery NPM

npm install jquery

Install the jQuery declaration file

npm install -D @types/jquery

Import jQuery inside .ts

import * as $ from 'jquery';

call inside class

export class JqueryComponent implements OnInit {

constructor() {
}

ngOnInit() {
    $(window).click(function () {
        alert('ok');
        });
    }

}

How do I run a class in a WAR from the command line?

Well, according to Wikipedia, with a WAR file, the classes that get loaded into the classpath are in the "/WEB-INF/classes" and "/WEB-INF/lib" directory.

You could try simply putting a copy of the classes on the root file system of the zip file (which is what a war/jar is). I'm not sure if that would work though.

You can always just create two separate files.

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

How to return value from function which has Observable subscription inside?

In the single-threaded,asynchronous,promise-oriented,reactive-trending world of javascript async/await is the imperative-style programmer's best friend:

(async()=>{

    const store = of("someValue");
    function getValueFromObservable () {
        return store.toPromise();
    }
    console.log(await getValueFromObservable())

})();

And in case store is a sequence of multiple values:

  const aiFrom = require('ix/asynciterable').from;
  (async function() {

     const store = from(["someValue","someOtherValue"]);
     function getValuesFromObservable () {
        return aiFrom(store);
     }
     for await (let num of getValuesFromObservable()) {
       console.log(num);
     }
  })();

How to set Status Bar Style in Swift 3

Swift 3

In Info.plist add a row called "View controller-based status bar appearance" and set its value to No.

class YourViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        UIApplication.shared.statusBarStyle = .lightContent //or .default
        setNeedsStatusBarAppearanceUpdate()

    }

}

iOS app 'The application could not be verified' only on one device

I resolved this issue by changing the Build System to legacy in xcode.

I had the same problem but the mentioned solutions above didn't work for me. Even I had no previous app on device, I got this error when deploying on my device.

How to do:

Simply, go to menu File > Project Setting, inside Share Project Settings, change Build System from "New Build System (default)" to "Lagacy Build System".

Add a summary row with totals

If you want to display more column values without an aggregation function use GROUPING SETS instead of ROLLUP:

SELECT
  Type = ISNULL(Type, 'Total'),
  SomeIntColumn = ISNULL(SomeIntColumn, 0),
  TotalSales = SUM(TotalSales)
FROM atable
GROUP BY GROUPING SETS ((Type, SomeIntColumn ), ())
ORDER BY SomeIntColumn --Displays summary row as the first row in query result

Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

Using Accept header is really easy to get the format json or xml from the REST service.

This is my Controller, take a look produces section.

@RequestMapping(value = "properties", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, method = RequestMethod.GET)
    public UIProperty getProperties() {
        return uiProperty;
    }

In order to consume the REST service we can use the code below where header can be MediaType.APPLICATION_JSON_VALUE or MediaType.APPLICATION_XML_VALUE

HttpHeaders headers = new HttpHeaders();
headers.add("Accept", header);

HttpEntity entity = new HttpEntity(headers);

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/properties", HttpMethod.GET, entity,String.class);
return response.getBody();

Edit 01:

In order to work with application/xml, add this dependency

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

How does strcmp() work?

Here is the BSD implementation:

int
strcmp(s1, s2)
    register const char *s1, *s2;
{
    while (*s1 == *s2++)
        if (*s1++ == 0)
            return (0);
    return (*(const unsigned char *)s1 - *(const unsigned char *)(s2 - 1));
}

Once there is a mismatch between two characters, it just returns the difference between those two characters.

How to set enum to null

Color? color = null;

or you can use

Color? color = new Color?();

example where assigning null wont work

color = x == 5 ? Color.Red : x == 9 ? Color.Black : null ; 

so you can use :

 color = x == 5 ? Color.Red : x == 9 ? Color.Black : new Color?(); 

Get the full URL in PHP

$base_dir = __DIR__; // Absolute path to your installation, ex: /var/www/mywebsite
$doc_root = preg_replace("!{$_SERVER['SCRIPT_NAME']}$!", '', $_SERVER['SCRIPT_FILENAME']); # ex: /var/www
$base_url = preg_replace("!^{$doc_root}!", '', $base_dir); # ex: '' or '/mywebsite'
$base_url = str_replace('\\', '/', $base_url);//On Windows
$base_url = str_replace($doc_root, '', $base_url);//On Windows
$protocol = empty($_SERVER['HTTPS']) ? 'http' : 'https';
$port = $_SERVER['SERVER_PORT'];
$disp_port = ($protocol == 'http' && $port == 80 || $protocol == 'https' && $port == 443) ? '' : ":$port";
$domain = $_SERVER['SERVER_NAME'];
$full_url = "$protocol://{$domain}{$disp_port}{$base_url}"; # Ex: 'http://example.com', 'https://example.com/mywebsite', etc. 

source: http://blog.lavoie.sl/2013/02/php-document-root-path-and-url-detection.html

C# Get a control's position on a form

You could walk up through the parents, noting their position within their parent, until you arrive at the Form.

Edit: Something like (untested):

public Point GetPositionInForm(Control ctrl)
{
   Point p = ctrl.Location;
   Control parent = ctrl.Parent;
   while (! (parent is Form))
   {
      p.Offset(parent.Location.X, parent.Location.Y);
      parent = parent.Parent;
   }
   return p;
}

Log4j, configuring a Web App to use a relative path

My solution is similar to Iker Jimenez's solution, but instead of using System.setProperty(...) I use org.apache.log4j.PropertyConfigurator.configure(Properties). For that I also need log4j to be unable to find its configuration on its own and I load it manually (both points described in Wolfgang Liebich's answer).

This works for Jetty and Tomcat, standalone or run from IDE, requires zero configuration, allows to put each app's logs in their own folder, no matter how many apps inside the container (which is the problem with the System-based solution). This way one can also put the log4j config file anywhere inside the web app (e.g. in one project we had all config files inside WEB-INF/).

Details:

  1. I have my properties in the log4j-no-autoload.properties file in the classpath (e.g. in my Maven project it's originally in src/main/resources, gets packaged into WEB-INF/classes),
  2. It has the file appender configured as e.g.:

    log4j.appender.MyAppFileAppender = org.apache.log4j.FileAppender
    log4j.appender.MyAppFileAppender.file = ${webAppRoot}/WEB-INF/logs/my-app.log
    ...
    
  3. And I have a context listener like this (gets much shorter with Java 7's "try-with-resource" syntax):

    @WebListener
    public class ContextListener implements ServletContextListener {
        @Override
        public void contextInitialized(final ServletContextEvent event) {
            Properties props = new Properties();
            InputStream strm =
                ContextListener.class.getClassLoader()
                    .getResourceAsStream("log4j-no-autoload.properties");
            try {
                props.load(strm);
            } catch (IOException propsLoadIOE) {
                throw new Error("can't load logging config file", propsLoadIOE);
            } finally {
                try {
                    strm.close();
                } catch (IOException configCloseIOE) {
                    throw new Error("error closing logging config file", configCloseIOE);
                }
            }
            props.put("webAppRoot", event.getServletContext().getRealPath("/"));
            PropertyConfigurator.configure(props);
            // from now on, I can use LoggerFactory.getLogger(...)
        }
        ...
    }
    

How to iterate for loop in reverse order in swift?

You can consider using the C-Style while loop instead. This works just fine in Swift 3:

var i = 5 
while i > 0 { 
    print(i)
    i -= 1
}

Call an activity method from a fragment

I have been looking for the best way to do that since not every method we want to call is located in Fragment with same Activity Parent.

In your Fragment

public void methodExemple(View view){

        // your code here

        Toast.makeText(view.getContext(), "Clicked clicked",Toast.LENGTH_LONG).show();
    }

In your Activity

new ExempleFragment().methodExemple(context); 

How to make circular background using css?

Maybe you should use a display inline-block too:

.circle {
    display: inline-block;
    height: 25px;
    width: 25px;
    background-color: #bbb;
    border-radius: 50%;
    z-index: -1;
}

Android: failed to convert @drawable/picture into a drawable

This is because your Image name contains "-" symbol . the only allowed characters are [a-zA-Z0-9_.]

Thanks

how to display data values on Chart.js

Following this good answer, I'd use these options for a bar chart:

var chartOptions = {
    animation: false,
    responsive : true,
    tooltipTemplate: "<%= value %>",
    tooltipFillColor: "rgba(0,0,0,0)",
    tooltipFontColor: "#444",
    tooltipEvents: [],
    tooltipCaretSize: 0,
    onAnimationComplete: function()
    {
        this.showTooltip(this.datasets[0].bars, true);
    }
};

window.myBar = new Chart(ctx1).Bar(chartData, chartOptions);

Bar Chart

This still uses the tooltip system and his advantages (automatic positionning, templating, ...) but hiding the decorations (background color, caret, ...)

The object 'DF__*' is dependent on column '*' - Changing int to double

When we try to drop a column which is depended upon then we see this kind of error:

The object 'DF__*' is dependent on column ''.

drop the constraint which is dependent on that column with:

ALTER TABLE TableName DROP CONSTRAINT dependent_constraint;

Example:

Msg 5074, Level 16, State 1, Line 1

The object 'DF__Employees__Colf__1273C1CD' is dependent on column 'Colf'.

Msg 4922, Level 16, State 9, Line 1

ALTER TABLE DROP COLUMN Colf failed because one or more objects access this column.

Drop Constraint(DF__Employees__Colf__1273C1CD):

ALTER TABLE Employees DROP CONSTRAINT DF__Employees__Colf__1273C1CD;

Then you can Drop Column:

Alter Table TableName Drop column ColumnName

Can't find how to use HttpContent

To take 6footunder's comment and turn it into an answer, HttpContent is abstract so you need to use one of the derived classes:

enter image description here

What is 'PermSize' in Java?

lace to store your loaded class definition and metadata. If a large code-base project is loaded, the insufficient Perm Gen size will cause the popular Java.Lang.OutOfMemoryError: PermGen.

html select scroll bar

One options will be to show the selected option above (or below) the select list like following:

HTML

<div id="selText"><span>&nbsp;</span></div><br/>
<select size="4" id="mySelect" style="width:65px;color:#f98ad3;">
    <option value="1" selected>option 1 The Long Option</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
    <option value="4">option 4</option>
    <option value="5">option 5 Another Longer than the Long Option ;)</option>
    <option value="6">option 6</option>
</select>

JavaScript

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"   
  type="text/javascript"></script> 
<script type="text/javascript">
$(document).ready(function(){        
    $("select#mySelect").change(function(){
      //$("#selText").html($($(this).children("option:selected")[0]).text());
       var txt = $($(this).children("option:selected")[0]).text();
       $("<span>" + txt + "<br/></span>").appendTo($("#selText span:last"));
    });
});
</script>

PS:- Set height of div#selText otherwise it will keep shifting select list downward.

Select distinct values from a large DataTable column

Try this:

var idColumn="id";
var list = dt.DefaultView
    .ToTable(true, idColumn)
    .Rows
    .Cast<DataRow>()
    .Select(row => row[idColumn])
    .ToList();

javascript - pass selected value from popup window to parent window input box

If you want a popup window rather than a <div />, I would suggest the following approach.

In your parent page, you call a small helper method to show the popup window:

<input type="button" name="choice" onClick="selectValue('sku1')" value="?">

Add the following JS methods:

function selectValue(id)
{
    // open popup window and pass field id
    window.open('sku.php?id=' + encodeURIComponent(id),'popuppage',
      'width=400,toolbar=1,resizable=1,scrollbars=yes,height=400,top=100,left=100');
}

function updateValue(id, value)
{
    // this gets called from the popup window and updates the field with a new value
    document.getElementById(id).value = value;
}

Your sku.php receives the selected field via $_GET['id'] and uses it to construct the parent callback function:

?>
<script type="text/javascript">
function sendValue(value)
{
    var parentId = <?php echo json_encode($_GET['id']); ?>;
    window.opener.updateValue(parentId, value);
    window.close();
}
</script>

For each row in your popup, change code to this:

<td><input type=button value="Select" onClick="sendValue('<?php echo $rows['packcode']; ?>')" /></td>

Following this approach, the popup window doesn't need to know how to update fields in the parent form.

PHP DOMDocument loadHTML not encoding UTF-8 correctly

The problem is that when you add a parameter to DOMDocument::saveHTML() function, you lose the encoding. In a few cases, you'll need to avoid the use of the parameter and use old string function to find what your are looking for.

I think the previous answer works for you, but since this workaround didn't work for me, I'm adding that answer to help people who may be in my case.

java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver

Following is a simple code to read from SQL database. Database names is "database1". Table name is "table1". It contain two columns "uname" and "pass". Dont forget to add "sqljdbc4.jar" to your project. Download sqljdbc4.jar

public class NewClass {

    public static void main(String[] args) {

        Connection conn = null;
        String dbName = "database1";
        String serverip="192.168.100.100";
        String serverport="1433";
        String url = "jdbc:sqlserver://"+serverip+"\\SQLEXPRESS:"+serverport+";databaseName="+dbName+"";
        Statement stmt = null;
        ResultSet result = null;
        String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        String databaseUserName = "admin";
        String databasePassword = "root";
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url, databaseUserName, databasePassword);
            stmt = conn.createStatement();
            result = null;
            String pa,us;
            result = stmt.executeQuery("select * from table1 ");

            while (result.next()) {
                us=result.getString("uname");
                pa = result.getString("pass");              
                System.out.println(us+"  "+pa);
            }

            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

What is a race condition?

A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data.

Problems often occur when one thread does a "check-then-act" (e.g. "check" if the value is X, then "act" to do something that depends on the value being X) and another thread does something to the value in between the "check" and the "act". E.g:

if (x == 5) // The "Check"
{
   y = x * 2; // The "Act"

   // If another thread changed x in between "if (x == 5)" and "y = x * 2" above,
   // y will not be equal to 10.
}

The point being, y could be 10, or it could be anything, depending on whether another thread changed x in between the check and act. You have no real way of knowing.

In order to prevent race conditions from occurring, you would typically put a lock around the shared data to ensure only one thread can access the data at a time. This would mean something like this:

// Obtain lock for x
if (x == 5)
{
   y = x * 2; // Now, nothing can change x until the lock is released. 
              // Therefore y = 10
}
// release lock for x

How SQL query result insert in temp table?

Look at SELECT INTO. This will create a new table for you, which can be temporary if you want by prefixing the table name with a pound sign (#).

For example, you can do:

SELECT * 
INTO #YourTempTable
FROM YourReportQuery

String concatenation in Jinja

If you can't just use filter join but need to perform some operations on the array's entry:

{% for entry in array %}
User {{ entry.attribute1 }} has id {{ entry.attribute2 }}
{% if not loop.last %}, {% endif %}
{% endfor %}

How to open .SQLite files

I would suggest using R and the package RSQLite

#install.packages("RSQLite") #perhaps needed
library("RSQLite")

# connect to the sqlite file
sqlite    <- dbDriver("SQLite")
exampledb <- dbConnect(sqlite,"database.sqlite")

dbListTables(exampledb)

Correct way to create rounded corners in Twitter Bootstrap

If you're using Bootstrap Sass, here's another way that avoids having to add extra classes to your element markup:

@import "bootstrap/mixins/_border-radius";
@import "bootstrap/_variables";

.your-class {
  $r: $border-radius-base; // or $border-radius-large, $border-radius-small, ...
  @include border-top-radius($r);
  @include border-bottom-radius($r);
}

why $(window).load() is not working in jQuery?

<script type="text/javascript">
   $(window).ready(function () {
      alert("Window Loaded");
   });
</script>

WorksheetFunction.CountA - not working post upgrade to Office 2010

It may be obvious but, by stating the Range and not including which workbook or worksheet then it may be trying to CountA() on a different sheet entirely. I find to fully address these things saves a lot of headaches.

What's the simplest way to list conflicted files in Git?

git status displays "both modified" next to files that have conflicts instead of "modified" or "new file", etc

Removing duplicate elements from an array in Swift

Inspired by https://www.swiftbysundell.com/posts/the-power-of-key-paths-in-swift, we can declare a more powerful tool that is able to filter for unicity on any keyPath. Thanks to Alexander comments on various answers regarding complexity, the below solutions should be near optimal.

Non-mutating solution

We extend with a function that is able to filter for unicity on any keyPath:

extension RangeReplaceableCollection {
    /// Returns a collection containing, in order, the first instances of
    /// elements of the sequence that compare equally for the keyPath.
    func unique<T: Hashable>(for keyPath: KeyPath<Element, T>) -> Self {
        var unique = Set<T>()
        return filter { unique.insert($0[keyPath: keyPath]).inserted }
    }
}

Note: in the case where your object doesn't conform to RangeReplaceableCollection, but does conform to Sequence, you can have this additional extension, but the return type will always be an Array:

extension Sequence {
    /// Returns an array containing, in order, the first instances of
    /// elements of the sequence that compare equally for the keyPath.
    func unique<T: Hashable>(for keyPath: KeyPath<Element, T>) -> [Element] {
        var unique = Set<T>()
        return filter { unique.insert($0[keyPath: keyPath]).inserted }
    }
}

Usage

If we want unicity for elements themselves, as in the question, we use the keyPath \.self:

let a = [1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]
let b = a.unique(for: \.self)
/* b is [1, 4, 2, 6, 24, 15, 60] */

If we want unicity for something else (like for the id of a collection of objects) then we use the keyPath of our choice:

let a = [CGPoint(x: 1, y: 1), CGPoint(x: 2, y: 1), CGPoint(x: 1, y: 2)]
let b = a.unique(for: \.y)
/* b is [{x 1 y 1}, {x 1 y 2}] */

Mutating solution

We extend with a mutating function that is able to filter for unicity on any keyPath:

extension RangeReplaceableCollection {
    /// Keeps only, in order, the first instances of
    /// elements of the collection that compare equally for the keyPath.
    mutating func uniqueInPlace<T: Hashable>(for keyPath: KeyPath<Element, T>) {
        var unique = Set<T>()
        removeAll { !unique.insert($0[keyPath: keyPath]).inserted }
    }
}

Usage

If we want unicity for elements themselves, as in the question, we use the keyPath \.self:

var a = [1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]
a.uniqueInPlace(for: \.self)
/* a is [1, 4, 2, 6, 24, 15, 60] */

If we want unicity for something else (like for the id of a collection of objects) then we use the keyPath of our choice:

var a = [CGPoint(x: 1, y: 1), CGPoint(x: 2, y: 1), CGPoint(x: 1, y: 2)]
a.uniqueInPlace(for: \.y)
/* a is [{x 1 y 1}, {x 1 y 2}] */

How to return PDF to browser in MVC?

FileStreamResult certainly works. But if you look at the Microsoft Docs, it inherits from ActionResult -> FileResult, which has another derived class FileContentResult. It "sends the contents of a binary file to the response". So if you already have the byte[], you should just use FileContentResult instead.

public ActionResult DisplayPDF()
{
    byte[] byteArray = GetPdfFromWhatever();

    return new FileContentResult(byteArray, "application/pdf");
}

Better way to remove specific characters from a Perl string

With a character class this big it is easier to say what you want to keep. A caret in the first position of a character class inverts its sense, so you can write

$varTemp =~ s/[^"%'+\-0-9<=>a-z_{|}]+//gi

or, using the more efficient tr

$varTemp =~ tr/"%'+\-0-9<=>A-Z_a-z{|}//cd

tr docs

Git Bash: Could not open a connection to your authentication agent

Situation: MVS2017 App - Using 'Git Bash' on Windows 10 - Trying to connect to a BitBucket repository.

To be clear, when you install Git for Windows (https://git-scm.com/download/win), it comes with an utility called Git Bash.

enter image description here

So, I am in 'Git Bash', as follows:

Mike@DUBLIN MINGW64 ~/source/repos/DoubleIrish (master)
$ git remote add origin [email protected]:Guiness/DoubleIrish.git
$ git remote -v
origin  [email protected]:Guiness/DoubleIrish.git (fetch)
origin  [email protected]:Guiness/DoubleIrish.git (push)
Mike@DUBLIN MINGW64 ~/source/repos/DoubleIrish (master)
$ git push -u origin master
[...]
[email protected]: Permission denied (publickey).
fatal: Could not read from remote repository.

Is the private key set up?

$ ssh -V
OpenSSH_7.7p1, OpenSSL 1.0.2p  14 Aug 2018
$ ls -a ~/.ssh
./  ../  known_hosts

I can see that, at this point, my private key file (id_rsa) is missing. So I add it: (note: generating a pair of private-public keys is out of scope of my reply, but I can say that in Linux, you can use ssh-keygen for that.)

$ ls -a ~/.ssh
./  ../  id_rsa  known_hosts

OK, let's proceed:

$ ssh-agent
SSH_AUTH_SOCK=/tmp/ssh-KhQwFLAgWGYC/agent.18320; export SSH_AUTH_SOCK;
SSH_AGENT_PID=17996; export SSH_AGENT_PID;
echo Agent pid 17996;

$ ssh-add ~/.ssh/id_rsa
Could not open a connection to your authentication agent.

To solve this, I run:

$ ssh-agent bash

And then, again:

$ ssh-add ~/.ssh/id_rsa
Identity added: /c/Users/Mike.CORP/.ssh/id_rsa (/c/Users/Mike.CORP/.ssh/id_rsa)

It worked for me. Hope this helps

How to remove only 0 (Zero) values from column in excel 2010

Easiest way for me was to create an extra column with an if statement to essentially use as a copy past clipboard.

=IF(desired cell = 0, "", desired cell)

That should return a corrected column which then you can copy and paste back over the original column AS TEXT--if you just copy paste a circular reference occurs and all the data is "erased" from both columns. Don't fret if you didn't read this carefully Ctrl+Z is your best friend...

Understanding INADDR_ANY for socket programming

INADDR_ANY instructs listening socket to bind to all available interfaces. It's the same as trying to bind to inet_addr("0.0.0.0"). For completeness I'll also mention that there is also IN6ADDR_ANY_INIT for IPv6 and it's the same as trying to bind to :: address for IPv6 socket.

#include <netinet/in.h>

struct in6_addr addr = IN6ADDR_ANY_INIT;

Also, note that when you bind IPv6 socket to to IN6ADDR_ANY_INIT your socket will bind to all IPv6 interfaces, and should be able to accept connections from IPv4 clients as well (though IPv6-mapped addresses).

Absolute positioning ignoring padding of parent

Here is my best shot at it. I added another Div and made it red and changed you parent's height to 200px just to test it. The idea is the the child now becomes the grandchild and the parent becomes the grandparent. So the parent respects its parent. Hope you get my idea.

<html>
  <body>
    <div style="background-color: blue; padding: 10px; position: relative; height: 200px;">
     <div style="background-color: red;  position: relative; height: 100%;">    
        <div style="background-color: gray; position: absolute; left: 0px; right: 0px;bottom: 0px;">css sux</div>
     </div>
    </div>
  </body>
</html>

Edit:

I think what you are trying to do can't be done. Absolute position means that you are going to give it co-ordinates it must honor. What if the parent has a padding of 5px. And you absolutely position the child at top: -5px; left: -5px. How is it suppose to honor the parent and you at the same time??

My solution

If you want it to honor the parent, don't absolutely position it then.

Passing enum or object through an intent (the best solution)

This is an old question, but everybody fails to mention that Enums are actually Serializable and therefore can perfectly be added to an Intent as an extra. Like this:

public enum AwesomeEnum {
  SOMETHING, OTHER;
}

intent.putExtra("AwesomeEnum", AwesomeEnum.SOMETHING);

AwesomeEnum result = (AwesomeEnum) intent.getSerializableExtra("AwesomeEnum");

The suggestion to use static or application-wide variables is a really bad idea. This really couples your activities to a state managing system, and it is hard to maintain, debug and problem bound.


ALTERNATIVES:

A good point was noted by tedzyc about the fact that the solution provided by Oderik gives you an error. However, the alternative offered is a bit cumbersome to use (even using generics).

If you are really worried about the performance of adding the enum to an Intent I propose these alternatives instead:

OPTION 1:

public enum AwesomeEnum {
  SOMETHING, OTHER;
  private static final String name = AwesomeEnum.class.getName();
  public void attachTo(Intent intent) {
    intent.putExtra(name, ordinal());
  }
  public static AwesomeEnum detachFrom(Intent intent) {
    if(!intent.hasExtra(name)) throw new IllegalStateException();
    return values()[intent.getIntExtra(name, -1)];
  }
}

Usage:

// Sender usage
AwesomeEnum.SOMETHING.attachTo(intent);
// Receiver usage
AwesomeEnum result = AwesomeEnum.detachFrom(intent);

OPTION 2: (generic, reusable and decoupled from the enum)

public final class EnumUtil {
    public static class Serializer<T extends Enum<T>> extends Deserializer<T> {
        private T victim;
        @SuppressWarnings("unchecked") 
        public Serializer(T victim) {
            super((Class<T>) victim.getClass());
            this.victim = victim;
        }
        public void to(Intent intent) {
            intent.putExtra(name, victim.ordinal());
        }
    }
    public static class Deserializer<T extends Enum<T>> {
        protected Class<T> victimType;
        protected String name;
        public Deserializer(Class<T> victimType) {
            this.victimType = victimType;
            this.name = victimType.getName();
        }
        public T from(Intent intent) {
            if (!intent.hasExtra(name)) throw new IllegalStateException();
            return victimType.getEnumConstants()[intent.getIntExtra(name, -1)];
        }
    }
    public static <T extends Enum<T>> Deserializer<T> deserialize(Class<T> victim) {
        return new Deserializer<T>(victim);
    }
    public static <T extends Enum<T>> Serializer<T> serialize(T victim) {
        return new Serializer<T>(victim);
    }
}

Usage:

// Sender usage
EnumUtil.serialize(AwesomeEnum.Something).to(intent);
// Receiver usage
AwesomeEnum result = 
EnumUtil.deserialize(AwesomeEnum.class).from(intent);

OPTION 3 (with Kotlin):

It's been a while, but since now we have Kotlin, I thought I would add another option for the new paradigm. Here we can make use of extension functions and reified types (which retains the type when compiling).

inline fun <reified T : Enum<T>> Intent.putExtra(victim: T): Intent =
    putExtra(T::class.java.name, victim.ordinal)

inline fun <reified T: Enum<T>> Intent.getEnumExtra(): T? =
    getIntExtra(T::class.java.name, -1)
        .takeUnless { it == -1 }
        ?.let { T::class.java.enumConstants[it] }

There are a few benefits of doing it this way.

  • We don't require the "overhead" of an intermediary object to do the serialization as it's all done in place thanks to inline which will replace the calls with the code inside the function.
  • The functions are more familiar as they are similar to the SDK ones.
  • The IDE will autocomplete these functions which means there is no need to have previous knowledge of the utility class.

One of the downsides is that, if we change the order of the Emums, then any old reference will not work. This can be an issue with things like Intents inside pending intents as they may survive updates. However, for the rest of the time, it should be ok.

It's important to note that other solutions, like using the name instead of the position, will also fail if we rename any of the values. Although, in those cases, we get an exception instead of the incorrect Enum value.

Usage:

// Sender usage
intent.putExtra(AwesomeEnum.SOMETHING)
// Receiver usage
val result = intent.getEnumExtra<AwesomeEnum>()

How to get First and Last record from a sql query?

SELECT <rows> FROM TABLE_NAME WHERE ROWID=(SELECT MIN(ROWID) FROM TABLE_NAME) 
UNION
SELECT <rows> FROM TABLE_NAME WHERE ROWID=(SELECT MAX(ROWID) FROM TABLE_NAME)

or

SELECT * FROM TABLE_NAME WHERE ROWID=(SELECT MIN(ROWID) FROM TABLE_NAME) 
                            OR ROWID=(SELECT MAX(ROWID) FROM TABLE_NAME)

How to run python script in webpage

If you are using your own computer, install a software called XAMPP (or WAMPP either works). This is basically a website server that only runs on your computer. Then, once it is installed, go to xampp folder and double click the htdocs folder. Now what you need to do is create an html file (I'm gonna call it runpython.html). (Remember to move the python file to htdocs as well)

Add in this to your html body (and inputs as necessary)

<form action = "file_name.py" method = "POST">
   <input type = "submit" value = "Run the Program!!!">
</form>

Now, in the python file, we are basically going to be printing out HTML code.

#We will need a comment here depending on your server. It is basically telling the server where your python.exe is in order to interpret the language. The server is too lazy to do it itself.

    import cgitb
    import cgi

    cgitb.enable() #This will show any errors on your webpage

    inputs = cgi.FieldStorage() #REMEMBER: We do not have inputs, simply a button to run the program. In order to get inputs, give each one a name and call it by inputs['insert_name']

    print "Content-type: text/html" #We are using HTML, so we need to tell the server

    print #Just do it because it is in the tutorial :P

    print "<title> MyPythonWebpage </title>"

    print "Whatever you would like to print goes here, preferably in between tags to make it look nice"

What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

Spring 2 introduced ResponseStatusException using this you can return String, different HTTP status code, DTO at the same time.

@PostMapping("/save")
public ResponseEntity<UserDto> saveUser(@RequestBody UserDto userDto) {
    if(userDto.getId() != null) {
        throw new ResponseStatusException(HttpStatus.NOT_ACCEPTABLE,"A new user cannot already have an ID");
    }
    return ResponseEntity.ok(userService.saveUser(userDto));
}

Detect all Firefox versions in JS

This will detect any version of Firefox:

var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;

more specifically:

if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1){
     // Do Firefox-related activities
}

You may want to consider using feature-detection ala Modernizr, or a related tool, to accomplish what you need.

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

multipart/form-data

Note. Please consult RFC2388 for additional information about file uploads, including backwards compatibility issues, the relationship between "multipart/form-data" and other content types, performance issues, etc.

Please consult the appendix for information about security issues for forms.

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

The content type "multipart/form-data" follows the rules of all multipart MIME data streams as outlined in RFC2045. The definition of "multipart/form-data" is available at the [IANA] registry.

A "multipart/form-data" message contains a series of parts, each representing a successful control. The parts are sent to the processing agent in the same order the corresponding controls appear in the document stream. Part boundaries should not occur in any of the data; how this is done lies outside the scope of this specification.

As with all multipart MIME types, each part has an optional "Content-Type" header that defaults to "text/plain". User agents should supply the "Content-Type" header, accompanied by a "charset" parameter.

application/x-www-form-urlencoded

This is the default content type. Forms submitted with this content type must be encoded as follows:

Control names and values are escaped. Space characters are replaced by +', and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., %0D%0A'). The control names/values are listed in the order they appear in the document. The name is separated from the value by=' and name/value pairs are separated from each other by `&'.

application/x-www-form-urlencoded the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be:

MyVariableOne=ValueOne&MyVariableTwo=ValueTwo

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

How do I check (at runtime) if one class is a subclass of another?

issubclass minimal runnable example

Here is a more complete example with some assertions:

#!/usr/bin/env python3

class Base:
    pass

class Derived(Base):
    pass

base = Base()
derived = Derived()

# Basic usage.
assert issubclass(Derived, Base)
assert not issubclass(Base, Derived)

# True for same object.
assert issubclass(Base, Base)

# Cannot use object of class.
try:
    issubclass(derived, Base)
except TypeError:
    pass
else:
    assert False

# Do this instead.
assert isinstance(derived, Base)

GitHub upstream.

Tested in Python 3.5.2.

indexOf method in an object array?

Brief

myArray.indexOf('stevie','hello')

Use Cases :

  /*****NORMAL****/  
[2,4,5].indexOf(4) ;//OUTPUT 1
 /****COMPLEX*****/
 [{slm:2},{slm:4},{slm:5}].indexOf(4,'slm');//OUTPUT 1
 //OR
 [{slm:2},{slm:4},{slm:5}].indexOf(4,function(e,i){
   return e.slm;
});//OUTPUT 1
/***MORE Complex**/
[{slm:{salat:2}},{slm:{salat:4}},{slm:{salat:5}}].indexOf(4,function(e,i){
   return e.slm.salat;
});//OUTPUT 1

API :

    Array.prototype.indexOfOld=Array.prototype.indexOf

    Array.prototype.indexOf=function(e,fn){
      if(!fn){return this.indexOfOld(e)}
      else{ 
       if(typeof fn ==='string'){var att=fn;fn=function(e){return e[att];}}
        return this.map(fn).indexOfOld(e);
      }
    };

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

Where can I find jenkins restful api reference?

Additional Solution: use Restul api wrapper libraries written in Java / python / Ruby - An object oriented wrappers which aim to provide a more conventionally way of controlling a Jenkins server.

For documentation and links: Remote Access API

Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue

For non-preemptive system,

waitingTime = startTime - arrivalTime

turnaroundTime = burstTime + waitingTime = finishTime- arrivalTime

startTime = Time at which the process started executing

finishTime = Time at which the process finished executing

You can keep track of the current time elapsed in the system(timeElapsed). Assign all processors to a process in the beginning, and execute until the shortest process is done executing. Then assign this processor which is free to the next process in the queue. Do this until the queue is empty and all processes are done executing. Also, whenever a process starts executing, recored its startTime, when finishes, record its finishTime (both same as timeElapsed). That way you can calculate what you need.

Check if number is prime number

Here is a version without the "clutter" of other answers and simply does the trick.

static void Main(string[] args)
{

    Console.WriteLine("Enter your number: ");
    int num = Convert.ToInt32(Console.ReadLine());
    bool isPrime = true;
    for (int i = 2; i < num/2; i++)
    {
        if (num % i == 0)
        {
            isPrime = false;
            break;
        }
    }
    if (isPrime)
        Console.WriteLine("It is Prime");
    else
        Console.WriteLine("It is not Prime");
    Console.ReadLine();
}

How to pretty-print a numpy.array without scientific notation and with given precision?

And here is what I use, and it's pretty uncomplicated:

print(np.vectorize("%.2f".__mod__)(sparse))

What does a circled plus mean?

I used the logic in the replies by rampion and schnaader. I will summarise how I confirmed the results. I changed the numbers to binary and then used the XOR-operation. Alternatively, you can use the Hexadecimal tables: Click here!

Java: Find .txt files in specified folder

I made my solution based on the posts I found here with Google. And I thought there is no harm to post mine as well even if it is an old thread.

The only plus this code gives is that it can iterate through sub-directories as well.

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;

Method is as follows:

List <File> exploreThis(String dirPath){

    File topDir = new File(dirPath);

    List<File> directories = new ArrayList<>();
    directories.add(topDir);

    List<File> textFiles = new ArrayList<>();

    List<String> filterWildcards = new ArrayList<>();
    filterWildcards.add("*.txt");
    filterWildcards.add("*.doc");

    FileFilter typeFilter = new WildcardFileFilter(filterWildcards);

    while (directories.isEmpty() == false)
    {
        List<File> subDirectories = new ArrayList();

        for(File f : directories)
        {
            subDirectories.addAll(Arrays.asList(f.listFiles((FileFilter)DirectoryFileFilter.INSTANCE)));
            textFiles.addAll(Arrays.asList(f.listFiles(typeFilter)));
        }

        directories.clear();
        directories.addAll(subDirectories);
    }

    return textFiles;
}

How to View Oracle Stored Procedure using SQLPlus?

check your casing, the name is typically stored in upper case

SELECT * FROM all_source WHERE name = 'DAILY_UPDATE' ORDER BY TYPE, LINE;

Disabled form inputs do not appear in the request

I find this works easier. readonly the input field, then style it so the end user knows it's read only. inputs placed here (from AJAX for example) can still submit, without extra code.

<input readonly style="color: Grey; opacity: 1; ">

Passing an array as parameter in JavaScript

It is possible to pass arrays to functions, and there are no special requirements for dealing with them. Are you sure that the array you are passing to to your function actually has an element at [0]?

Reshape an array in NumPy

There are two possible result rearrangements (following example by @eumiro). Einops package provides a powerful notation to describe such operations non-ambigously

>> a = np.arange(18).reshape(9,2)

# this version corresponds to eumiro's answer
>> einops.rearrange(a, '(x y) z -> z y x', x=3)

array([[[ 0,  6, 12],
        [ 2,  8, 14],
        [ 4, 10, 16]],

       [[ 1,  7, 13],
        [ 3,  9, 15],
        [ 5, 11, 17]]])

# this has the same shape, but order of elements is different (note that each paer was trasnposed)
>> einops.rearrange(a, '(x y) z -> z x y', x=3)

array([[[ 0,  2,  4],
        [ 6,  8, 10],
        [12, 14, 16]],

       [[ 1,  3,  5],
        [ 7,  9, 11],
        [13, 15, 17]]])

What is the total amount of public IPv4 addresses?

Public IP Addresses

https://github.com/stephenlb/geo-ip will generate a list of Valid IP Public Addresses including Localities.

'1.0.0.0/8' to '191.0.0.0/8' are the valid public IP Address range exclusive of the reserved Private IP Addresses as follows:

import iptools
## Private IP Addresses
private_ips = iptools.IpRangeList(
    '0.0.0.0/8',      '10.0.0.0/8',     '100.64.0.0/10', '127.0.0.0/8',
    '169.254.0.0/16', '172.16.0.0/12',  '192.0.0.0/24',  '192.0.2.0/24',
    '192.88.99.0/24', '192.168.0.0/16', '198.18.0.0/15', '198.51.100.0/24',
    '203.0.113.0/24', '224.0.0.0/4',    '240.0.0.0/4',   '255.255.255.255/32'
)

IP Generator

Generates a JSON dump of IP Addresses and associated Geo information. Note that the valid public IP Address range is from '1.0.0.0/8' to '191.0.0.0/8' excluding the reserved Private IP Address ranges shown lower down in this readme.

docker build -t geo-ip .
docker run -e IPRANGE='54.0.0.0/30' geo-ip               ## a few IPs
docker run -e IPRANGE='54.0.0.0/26' geo-ip               ## a few more IPs
docker run -e IPRANGE='54.0.0.0/16' geo-ip               ## a lot more IPs
docker run -e IPRANGE='0.0.0.0/0'   geo-ip               ## ALL IPs ( slooooowwwwww )
docker run -e IPRANGE='0.0.0.0/0'   geo-ip > geo-ip.json ## ALL IPs saved to JSON File
docker run geo-ip 

A little faster option for scanning all valid public addresses:

for i in $(seq 1 191); do \
    docker run -e IPRANGE="$i.0.0.0/8" geo-ip; \
    sleep 1; \ 
done

This prints less than 4,228,250,625 JSON lines to STDOUT. Here is an example of one of the lines:

{"city": "Palo Alto", "ip": "0.0.0.0", "longitude": -122.1274,
 "continent": "North America", "continent_code": "NA",
 "state": "California", "country": "United States", "latitude": 37.418,
 "iso_code": "US", "state_code": "CA", "aso": "PubNub",
 "asn": "11404", "zip_code": "94107"}

Private and Reserved IP Range

The dockerfile in the repo above will exclude non-usable IP addresses following the guide from the wikipedia article: https://en.wikipedia.org/wiki/Reserved_IP_addresses

MaxMind Geo IP

The dockerfile imports a free public Database provided by https://www.maxmind.com/en/home

How to test the `Mosquitto` server?

The OP has not defined the scope of testing, however, simple (gross) 'smoke testing' an install should be performed before any time is invested with functionality testing.

How to test if application is installed ('smoke-test')

Log into the mosquitto server's command line and type:

mosquitto

If mosquitto is installed the machine will return:

 mosquitto version 1.4.8 (build date Wed, date of installation) starting
 Using default config.
 Opening ipv4 listen socket on port 1883

Jquery get input array field

use map method we can get input values that stored in array.

var values = $("input[name='pages_title[]']").map(function(){return $(this).val();}).get();

How to exclude particular class name in CSS selector?

In modern browsers you can do:

.reMode_hover:not(.reMode_selected):hover{}

Consult http://caniuse.com/css-sel3 for compatibility information.

adb is not recognized as internal or external command on windows

You have two ways:

First go to the particular path of Android SDK:

1) Open your command prompt and traverse to the platform-tools directory through it such as

$ cd Frameworks\Android-Sdk\platform-tools

2) Run your adb commands now such as to know that your adb is working properly :

$ adb devices OR adb logcat OR simply adb

Second way is :

1) Right click on your My Computer.

2) Open Environment variables.

3) Add new variable to your System PATH variable(Add if not exist otherwise no need to add new variable if already exist).

4) Add path of platform-tools directory to as value of this variable such as C:\Program Files\android-sdk\platform-tools.

5) Restart your computer once.

6) Now run the above adb commands such adb devices or other adb commands from anywhere in command prompt.

Also on you can fire a command on terminal setx PATH "%PATH%;C:\Program Files\android-sdk\platform-tools"

How to concatenate a std::string and an int?

#include <string>
#include <sstream>
using namespace std;
string concatenate(std::string const& name, int i)
{
    stringstream s;
    s << name << i;
    return s.str();
}

undefined reference to `std::ios_base::Init::Init()'

Most of these linker errors occur because of missing libraries.

I added the libstdc++.6.dylib in my Project->Targets->Build Phases-> Link Binary With Libraries.

That solved it for me on Xcode 6.3.2 for iOS 8.3

Cheers!

Converting a String array into an int Array in java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class array_test {

public static void main(String args[]) throws IOException{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();

String[] s_array = line.split(" ");

/* Splitting the array of number separated by space into string array.*/

Integer [] a = new Integer[s_array.length];

/Creating the int array of size equals to string array./

    for(int i =0; i<a.length;i++)
    {
        a[i]= Integer.parseInt(s_array[i]);// Parsing from string to int

        System.out.println(a[i]);
    }

    // your integer array is ready to use.

}

}

How can I add an item to a SelectList in ASP.net MVC

The .ToList().Insert(..) method puts an element into your List. Any position can be specified. After ToList just add .Insert(0, "- - First Item - -")

Your code

SelectList list = new SelectList(repository.func.ToList());

New Code

SelectList list = new SelectList(repository.func.ToList().Insert(0, "- - First Item - -"));

Error message "Linter pylint is not installed"

A similar issue happened to me after I a completely reinstalled Python. Opening the settings.json by Ctrl+ ? Shift+P:

                             

and I saw that I had set the default linter to

"python.linting.pylintPath": "pylint_django"

so opening a terminal (e.g., Ctrl + ?Shift + ~) and the installing

pip install pylint_django

solved the problem.

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

<context:component-scan base-package="" /> 

tells Spring to scan those packages for Annotations.

<mvc:annotation-driven> 

registers a RequestMappingHanderMapping, a RequestMappingHandlerAdapter, and an ExceptionHandlerExceptionResolver to support the annotated controller methods like @RequestMapping, @ExceptionHandler, etc. that come with MVC.

This also enables a ConversionService that supports Annotation driven formatting of outputs as well as Annotation driven validation for inputs. It also enables support for @ResponseBody which you can use to return JSON data.

You can accomplish the same things using Java-based Configuration using @ComponentScan(basePackages={"...", "..."} and @EnableWebMvc in a @Configuration class.

Check out the 3.1 documentation to learn more.

http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-config

Nuget connection attempt failed "Unable to load the service index for source"

I had this error and then I realized I was logged in with my personal Microsoft account instead of my work account.

Hope this helps.

Remove trailing zeros

This is simple.

decimal decNumber = Convert.ToDecimal(value);
        return decNumber.ToString("0.####");

Tested.

Cheers :)

Converting Dictionary to List?

 >>> a = {'foo': 'bar', 'baz': 'quux', 'hello': 'world'}
 >>> list(reduce(lambda x, y: x + y, a.items()))
 ['foo', 'bar', 'baz', 'quux', 'hello', 'world']

To explain: a.items() returns a list of tuples. Adding two tuples together makes one tuple containing all elements. Thus the reduction creates one tuple containing all keys and values and then the list(...) makes a list from that.

Prevent flex items from stretching

You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.

To affect all flex-items of the container, choose this:
You have to set align-items: flex-start; to div and all flex-items of this container get the height of their content.

_x000D_
_x000D_
div {_x000D_
  align-items: flex-start;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}
_x000D_
<div>_x000D_
  <span>This is some text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start; to this flex-item. All other flex-items of the container aren't affected.

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
  background: tan;_x000D_
}_x000D_
span.only {_x000D_
  background: red;_x000D_
  align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
    background:green;_x000D_
}
_x000D_
<div>_x000D_
  <span class="only">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why is this happening to the span?
The default value of the property align-items is stretch. This is the reason why the span fill the height of the div.

Difference between baseline and flex-start?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start the flex-item will be set to the top of the container (without space).

_x000D_
_x000D_
div {_x000D_
  align-items: baseline;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
  font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
  <span class="fontsize">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can find more information about the difference between baseline and flex-start here:
What's the difference between flex-start and baseline?

How to transform currentTimeMillis to a readable date format?

It will work.

long yourmilliseconds = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");    
Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate));

how to show progress bar(circle) in an activity having a listview before loading the listview with data

Please use the sample at tutorialspoint.com. The whole implementation only needs a few lines of code without changing your xml file. Hope this helps.

STEP 1: Import library

import android.app.ProgressDialog;

STEP 2: Declare ProgressDialog global variable

ProgressDialog loading = null;

STEP 3: Start new ProgressDialog and use the following properties (please be informed that this sample only covers the basic circle loading bar without the real time progress status).

loading = new ProgressDialog(v.getContext());
loading.setCancelable(true);
loading.setMessage(Constant.Message.AuthenticatingUser);
loading.setProgressStyle(ProgressDialog.STYLE_SPINNER);

STEP 4: If you are using AsyncTasks, you can start showing the dialog in onPreExecute method. Otherwise, just place the code in the beginning of your button onClick event.

loading.show();

STEP 5: If you are using AsyncTasks, you can close the progress dialog by placing the code in onPostExecute method. Otherwise, just place the code before closing your button onClick event.

loading.dismiss();

Tested it with my Nexus 5 android v4.0.3. Good luck!

Add placeholder text inside UITextView in Swift?

Swift Answer

Here is the custom class, that animates placeholder.

class CustomTextView: UITextView {
    
    //   MARK: - public
    
    public var placeHolderText: String? = "Enter Reason.."
    
    public lazy var placeHolderLabel: UILabel! = {
        let placeHolderLabel = UILabel(frame: .zero)
        placeHolderLabel.numberOfLines = 0
        placeHolderLabel.backgroundColor = .clear
        placeHolderLabel.alpha = 0.5
        return placeHolderLabel
    }()
    
    //   MARK: - Init
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        enableNotifications()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        enableNotifications()
    }
    
    func setup() {
        placeHolderLabel.frame = CGRect(x: 8, y: 8, width: self.bounds.size.width - 16, height: 15)
        placeHolderLabel.sizeToFit()
    }
    
    //   MARK: - Cycle
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        textContainerInset = UIEdgeInsets(top: 8, left: 5, bottom: 8, right: 8)
        returnKeyType = .done
        addSubview(placeHolderLabel)
        placeHolderLabel.frame = CGRect(x: 8, y: 8, width: self.bounds.size.width - 16, height: 15)
        placeHolderLabel.textColor = textColor
        placeHolderLabel.font = font
        placeHolderLabel.text = placeHolderText
        bringSubviewToFront(placeHolderLabel)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        setup()
    }
    
    //   MARK: - Notifications
    
    private func enableNotifications() {
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChangeNotification(_:)), name: UITextView.textDidChangeNotification , object: nil)
    }
    
    @objc func textDidChangeNotification(_ notify: Notification) {
        guard self == notify.object as? UITextView else { return }
        guard placeHolderText != nil else { return }
        
        UIView.animate(withDuration: 0.25, animations: {
            self.placeHolderLabel.alpha = (self.text.count == 0) ? 0.5 : 0
        }, completion: nil)
    }
    
}

How can I combine hashes in Perl?

Quick Answer (TL;DR)


    %hash1 = (%hash1, %hash2)

    ## or else ...

    @hash1{keys %hash2} = values %hash2;

    ## or with references ...

    $hash_ref1 = { %$hash_ref1, %$hash_ref2 };

Overview

  • Context: Perl 5.x
  • Problem: The user wishes to merge two hashes1 into a single variable

Solution

  • use the syntax above for simple variables
  • use Hash::Merge for complex nested variables

Pitfalls

See also


Footnotes

1 * (aka associative-array, aka dictionary)

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

In my case, where nothing else helped, i did the following:

  1. change the AppID to a new one
  2. XCode automatically generated new provisioning profiles
  3. run the app on real device -> now it has worked
  4. change back the AppID to the original id
  5. works

Before this i have tried out every step that was mentioned here. But only this helped.

How to use WebRequest to POST some data and read response?

From MSDN

// Create a request using a URL that can receive a post. 
WebRequest request = WebRequest.Create ("http://contoso.com/PostAccepter.aspx ");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();

Take into account that the information must be sent in the format key1=value1&key2=value2

How to have the formatter wrap code with IntelliJ?

You can create a macro for Ctrl +Shift + S (for example) that do all this things:

Edit > Macros > Start Macro Recording (the recording will start). Click where you need.

For example:

Code > Reformat Code
Code > Auto-Indent Lines
Code > Optimize Imports
Code > Rearrange Code
File > Save All
... (all that you want)

Then, click on red button in bottom-right of the IDE to stop the Macro recording.

Set a macro name.

Go to File > Settings > Macros > YOUR MACRO NAME.

Right Click > Add Keyboard Shortcut, and type Ctrl + Shift + S.

How to square or raise to a power (elementwise) a 2D numpy array?

The fastest way is to do a*a or a**2 or np.square(a) whereas np.power(a, 2) showed to be considerably slower.

np.power() allows you to use different exponents for each element if instead of 2 you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2 or a*a, which become important in cases where you have small tolerances.

I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:

In [29]: a = np.random.random((1000, 1000))

In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop

In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop

In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop

A CSS selector to get last visible div

You could select and style this with JavaScript or jQuery, but CSS alone can't do this.

For example, if you have jQuery implemented on the site, you could just do:

var last_visible_element = $('div:visible:last');

Although hopefully you'll have a class/ID wrapped around the divs you're selecting, in which case your code would look like:

var last_visible_element = $('#some-wrapper div:visible:last');

Best solution to protect PHP code without encryption

I have not looked at the VBulletin source code in some time, but the way they used to do it around 2003 was to embed a call to their server inside the code. IIRC, it was on a really long code line (like 200-300+ chars long) and was broken up over several string concatenations and such.

It did nothing "bad" if you pirated it - the forum still worked 100%. But your server's IP was logged along with other info and they used that to investigate and take legal action.

Your license number was embedded in this call, so they could easily track how many IPs/websites a given licensed copy was running on.

A field initializer cannot reference the nonstatic field, method, or property

private dynamic defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)]; is a field initializer and executes first (before any field without an initializer is set to its default value and before the invoked instance constructor is executed). Instance fields that have no initializer will only have a legal (default) value after all instance field initializers are completed. Due to the initialization order, instance constructors are executed last, which is why the instance is not created yet the moment the initializers are executed. Therefore the compiler cannot allow any instance property (or field) to be referenced before the class instance is fully constructed. This is because any access to an instance variable like reminder implicitly references the instance (this) to tell the compiler the concrete memory location of the instance to use.

This is also the reason why this is not allowed in an instance field initializer.

A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-time error to reference this in a variable initializer, as it is a compile-time error for a variable initializer to reference any instance member through a simple_name.

The only type members that are guaranteed to be initialized before instance field initializers are executed are class (static) field initializers and class (static) constructors and class methods. Since static members are instance independent, they can be referenced at any time:

class SomeOtherClass
{
  private static Reminders reminder = new Reminders();

  // This operation is allowed,
  // since the compiler can guarantee that the referenced class member is already initialized
  // when this instance field initializer executes
  private dynamic defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
}

That's why instance field initializers are only allowed to reference a class member (static member). This compiler initialization rules will ensure a deterministic type instantiation.

For more details I recommend this document: Microsoft Docs: Class declarations.

This means that an instance field that references another instance member to initialize its value, must be initialized from the instance constructor or the referenced member must be declared static.

How to select a single column with Entity Framework?

If you're fetching a single item only then, you need use select before your FirstOrDefault()/SingleOrDefault(). And you can use anonymous object of the required properties.

var name = dbContext.MyTable.Select(x => new { x.UserId, x.Name }).FirstOrDefault(x => x.UserId == 1)?.Name;

Above query will be converted to this:

Select Top (1) UserId, Name from MyTable where UserId = 1;

For multiple items you can simply chain Select after Where:

var names = dbContext.MyTable.Where(x => x.UserId > 10).Select(x => x.Name);

Use anonymous object inside Select if you need more than one properties.

How to abort a Task like aborting a Thread (Thread.Abort method)?

While it's possible to abort a thread, in practice it's almost always a very bad idea to do so. Aborthing a thread means the thread is not given a chance to clean up after itself, leaving resources undeleted, and things in unknown states.

In practice, if you abort a thread, you should only do so in conjunction with killing the process. Sadly, all too many people think ThreadAbort is a viable way of stopping something and continuing on, it's not.

Since Tasks run as threads, you can call ThreadAbort on them, but as with generic threads you almost never want to do this, except as a last resort.

How to get Django and ReactJS to work together?

I don't have experience with Django but the concepts from front-end to back-end and front-end framework to framework are the same.

  1. React will consume your Django REST API. Front-ends and back-ends aren't connected in any way. React will make HTTP requests to your REST API in order to fetch and set data.
  2. React, with the help of Webpack (module bundler) & Babel (transpiler), will bundle and transpile your Javascript into single or multiple files that will be placed in the entry HTML page. Learn Webpack, Babel, Javascript and React and Redux (a state container). I believe you won't use Django templating but instead allow React to render the front-end.
  3. As this page is rendered, React will consume the API to fetch data so React can render it. Your understanding of HTTP requests, Javascript (ES6), Promises, Middleware and React is essential here.

Here are a few things I've found on the web that should help (based on a quick Google search):

Hope this steers you in the right direction! Good luck! Hopefully others who specialize in Django can add to my response.

How do you split a list into evenly sized chunks?

You could use numpy's array_split function e.g., np.array_split(np.array(data), 20) to split into 20 nearly equal size chunks.

To make sure chunks are exactly equal in size use np.split.

Show a message box from a class in c#?

using System.Windows.Forms;
...
MessageBox.Show("Hello World!");

How do I get the path to the current script with Node.js?

If you want something more like $0 in a shell script, try this:

var path = require('path');

var command = getCurrentScriptPath();

console.log(`Usage: ${command} <foo> <bar>`);

function getCurrentScriptPath () {
    // Relative path from current working directory to the location of this script
    var pathToScript = path.relative(process.cwd(), __filename);

    // Check if current working dir is the same as the script
    if (process.cwd() === __dirname) {
        // E.g. "./foobar.js"
        return '.' + path.sep + pathToScript;
    } else {
        // E.g. "foo/bar/baz.js"
        return pathToScript;
    }
}

Browser: Identifier X has already been declared

Remember that window is the global namespace. These two lines attempt to declare the same variable:

window.APP = { ... }
const APP = window.APP

The second definition is not allowed in strict mode (enabled with 'use strict' at the top of your file).

To fix the problem, simply remove the const APP = declaration. The variable will still be accessible, as it belongs to the global namespace.

How to generate gcc debug symbol outside the build target?

NOTE: Programs compiled with high-optimization levels (-O3, -O4) cannot generate many debugging symbols for optimized variables, in-lined functions and unrolled loops, regardless of the symbols being embedded (-g) or extracted (objcopy) into a '.debug' file.

Alternate approaches are

  1. Embed the versioning (VCS, git, svn) data into the program, for compiler optimized executables (-O3, -O4).
  2. Build a 2nd non-optimized version of the executable.

The first option provides a means to rebuild the production code with full debugging and symbols at a later date. Being able to re-build the original production code with no optimizations is a tremendous help for debugging. (NOTE: This assumes testing was done with the optimized version of the program).

Your build system can create a .c file loaded with the compile date, commit, and other VCS details. Here is a 'make + git' example:

program: program.o version.o 

program.o: program.cpp program.h 

build_version.o: build_version.c    

build_version.c: 
    @echo "const char *build1=\"VCS: Commit: $(shell git log -1 --pretty=%H)\";" > "$@"
    @echo "const char *build2=\"VCS: Date: $(shell git log -1 --pretty=%cd)\";" >> "$@"
    @echo "const char *build3=\"VCS: Author: $(shell git log -1 --pretty="%an %ae")\";" >> "$@"
    @echo "const char *build4=\"VCS: Branch: $(shell git symbolic-ref HEAD)\";" >> "$@"
    # TODO: Add compiler options and other build details

.TEMPORARY: build_version.c

After the program is compiled you can locate the original 'commit' for your code by using the command: strings -a my_program | grep VCS

VCS: PROGRAM_NAME=my_program
VCS: Commit=190aa9cace3b12e2b58b692f068d4f5cf22b0145
VCS: BRANCH=refs/heads/PRJ123_feature_desc
VCS: AUTHOR=Joe Developer  [email protected]
VCS: COMMIT_DATE=2013-12-19

All that is left is to check-out the original code, re-compile without optimizations, and start debugging.

How to do a recursive find/replace of a string with awk or sed?

An one nice oneliner as an extra. Using git grep.

git grep -lz 'subdomainA.example.com' | xargs -0 perl -i'' -pE "s/subdomainA.example.com/subdomainB.example.com/g"

How to replace a character with a newline in Emacs?

More explicitly:

To replace the semi colon character (;) with a newline, follow these exact steps.

  1. locate cursor at upper left of buffer containing text you want to change
  2. Type m-x replace-string and hit RETURN
  3. the mini-buffer will display something like this: Replace string (default ^ -> ):
  4. Type in the character you want to replace. In this case, ; and hit RETURN
  5. the mini-buffer will display something like this: string ; with:
  6. Now execute C-q C-j
  7. All instances of semi-colon will be replaced a newline (from the cursor location to the end of the buffer will now appear)

Bit more to it than the original explanation says.

Pandas (python): How to add column to dataframe for index?

How about this:

from pandas import *

idx = Int64Index([171, 174, 173])
df = DataFrame(index = idx, data =([1,2,3]))
print df

It gives me:

     0
171  1
174  2
173  3

Is this what you are looking for?

Implement a loading indicator for a jQuery AJAX call

There is a global configuration using jQuery. This code runs on every global ajax request.

<div id='ajax_loader' style="position: fixed; left: 50%; top: 50%; display: none;">
    <img src="themes/img/ajax-loader.gif"></img>
</div>

<script type="text/javascript">
    jQuery(function ($){
        $(document).ajaxStop(function(){
            $("#ajax_loader").hide();
         });
         $(document).ajaxStart(function(){
             $("#ajax_loader").show();
         });    
    });    
</script>

Here is a demo: http://jsfiddle.net/sd01fdcm/

OSError: [Errno 2] No such file or directory while using python subprocess in Django

Use shell=True if you're passing a string to subprocess.call.

From docs:

If passing a single string, either shell must be True or else the string must simply name the program to be executed without specifying any arguments.

subprocess.call(crop, shell=True)

or:

import shlex
subprocess.call(shlex.split(crop))

Elegant way to create empty pandas DataFrame with NaN of type float

You could specify the dtype directly when constructing the DataFrame:

>>> df = pd.DataFrame(index=range(0,4),columns=['A'], dtype='float')
>>> df.dtypes
A    float64
dtype: object

Specifying the dtype forces Pandas to try creating the DataFrame with that type, rather than trying to infer it.

TypeError: unhashable type: 'list' when using built-in set function

Definitely not the ideal solution, but it's easier for me to understand if I convert the list into tuples and then sort it.

mylist = [[1,2,3,4],[4,5,6,7]]
mylist2 = []
for thing in mylist:
    thing = tuple(thing)
    mylist2.append(thing)
set(mylist2)

Child inside parent with min-height: 100% not inheriting height

after trying for ours! chrome understands that I want the child element to be 100% height when I set the display value to inline block. btw setting float will causing it.

display:inline-block

update

this is not working. the solution is to get the parentnode offsetheight and use it at the and of the page with javascript.

<script>
    SomedivElement = document.getElementById('mydiv');
    SomedivElement.style.height = String(nvleft.parentNode.offsetHeight) + 'px';    
</script>

turn typescript object into json string

If you're using fs-extra, you can skip the JSON.stringify part with the writeJson function:

const fsExtra = require('fs-extra');

fsExtra.writeJson('./package.json', {name: 'fs-extra'})
.then(() => {
  console.log('success!')
})
.catch(err => {
  console.error(err)
})

How to validate domain credentials?

C# in .NET 3.5 using System.DirectoryServices.AccountManagement.

 bool valid = false;
 using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
 {
     valid = context.ValidateCredentials( username, password );
 }

This will validate against the current domain. Check out the parameterized PrincipalContext constructor for other options.

Android: Remove all the previous activities from the back stack

Use the following for activity

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);

remove CLEAR_TASK flag for fragment use.

I hope this may use for some people.

How to add new column to MYSQL table?

Something like:

$db = mysqli_connect("localhost", "user", "password", "database");
$name = $db->mysqli_real_escape_string($name);
$query = 'ALTER TABLE assesment ADD ' . $name . ' TINYINT NOT NULL DEFAULT \'0\'';
if($db->query($query)) {
    echo "It worked";
}

Haven't tested it but should work.