Programs & Examples On #Lepl

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

run gradle assembleDebug --scan in Android studio Terminal, in my case I removed an element in XML and forgotten to remove it from code, but the compiler couldn't compile and show Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details to me.

enter image description here

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

it works for me Swift 3:

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }

and in ViewDidLoad:

    self.navigationController?.interactivePopGestureRecognizer?.delegate = self
    self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true

Cannot install signed apk to device manually, got error "App not installed"

Removing android:testOnly="true" attribute from the AndroidManifest.xml worked. link

How to set up a Web API controller for multipart/form-data

5 years later on and .NET Core 3.1 allows you to do specify the media type like this:

[HttpPost]
[Consumes("multipart/form-data")]
public IActionResult UploadLogo()
{
    return Ok();
}

java.util.zip.ZipException: duplicate entry during packageAllDebugClassesForMultiDex

In my case exact error was below

':android:transformClassesWithJarMergingForDebug'.

com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/android/gms/internal/zzqx.class

I was using another version of google apis i.e. in one modules gradle file

if (!project.hasProperty('gms_library_version')) {
        ext.gms_library_version = '8.6.0'
   }

however in other modules version 11.6.0 as below

   compile "com.google.android.gms:play-services-ads:11.6.0"
    compile "com.google.android.gms:play-services-games:11.6.0"
    compile "com.google.android.gms:play-services-auth:11.6.0"

However to find this i did a ctrl + n in android studio and entered class name zzqx.class and then it displayed 2 jar files being pulled for this class and then i understood that somewhere i am using version 8.6.0 . On changing 8.6.0 to 11.6.0 and rebuilding the project the issue was fixed .

Hope this helps .

More on this here https://www.versionpb.com/tutorials/step-step-tutorials-libgdx-basic-setup-libgdx/implementing-google-play-services-leaderboards-in-libgdx/

This Activity already has an action bar supplied by the window decor

You need to change

  <activity
        android:name=".YOUR ACTIVITY"
        android:theme="@style/AppTheme.NoActionBar" />
</application>`

these lines in the manifest.It will perfectly work for me.

Android Studio: “Execution failed for task ':app:mergeDebugResources'” if project is created on drive C:

Dont make name with capital letters . Always use lowercase for naming . This will work fine . like companyLogo.png will raise error but company_logo.png will work fine.

Import Google Play Services library in Android Studio

//gradle.properties

systemProp.http.proxyHost=www.somehost.org

systemProp.http.proxyPort=8080

systemProp.http.proxyUser=userid

systemProp.http.proxyPassword=password

systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

This is an annoying problem, that can take some time to find out the root case. The way you should proceed is @CommonsWare answer.

I faced this problem recently and found it hard to resolve.

My problem was i was including a library by "+" version in build.gradle. Latest version of library contained one of older dex and bang.

I reverted to older version of library and solved it.

It is good to run your androidDependencies and see what is really happening. Its also good to search in your build folder.

Above all Android Studio 2.2 provide in build features to track this problem.

Happy Coding Guys

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

If JDK installed but still not working.

In Eclipse follow below steps:- Window --> Preference --> Installed JREs -->Change path of JRE to JDK(add).

Removing the title text of an iOS UIBarButtonItem

Hide Back Button Title of Navigation Bar

UIBarButtonItem *barButton = [[UIBarButtonItem alloc] init];
barButton.title = @""; // blank or any other title
self.navigationController.navigationBar.topItem.backBarButtonItem = barButton;

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

While using grouped TableView use this to avoid border cutting in viewWillAppear

self.tableView.contentInset = UIEdgeInsetsMake(-35, 0, 0, 0);

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

I had the same issue here. As Magnus said above, for me it was happening due to an SDK update to version 22.0.5.

After performing a full update in my Android SDK (including Google Play Services) and Android plugins in Eclipse, I was able to use play services lib in my application.

Refused to apply inline style because it violates the following Content Security Policy directive

Well, I think it is too late and many others have the solution so far.

But I hope this can Help:

I'm using react for an identity server so 'unsafe-inline' is not an option at all. If you look at your console and actually read the CSP docs, you might find that there are three options for solving the issue:

  1. 'unsafe-inline' as it says is unsafe if your project is using CSPs is for one reason and it is like throwing out the complete policy, will be the same to no have CSP policy at all

    1. 'sha-XXXCODE' this is good, safe but not optimal because there is a lot of manual work and every compilation the SHA might change so it will become easily a nightmare, use only when the script or style is unlikely to change and there are few references

    2. Nonce. This is the winner!

Nonce works in the similar way as scripts

CSP HEADER ///csp stuff nonce-12331

<script nonce="12331">
   //script content
</script>

Because the nonce in the csp is the same that the tag, the script will be executed

In the case of inline styles, the nonce also came in the form of attribute so the same rules apply.

so generate the nonce and put it on your inline scritps

If you are using webpack maybe you are using the style-loader

the following code will do the trick


module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          {
            loader: 'style-loader',
            options: {
              attributes: {
                nonce: '12345678',
              },
            },
          },
          'css-loader',
        ],
      },
    ],
  },
};

How does it work - requestLocationUpdates() + LocationRequest/Listener

I use this one:

LocationManager.requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)

For example, using a 1s interval:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);

the time is in milliseconds, the distance is in meters.

This automatically calls:

public void onLocationChanged(Location location) {
    //Code here, location.getAccuracy(), location.getLongitude() etc...
}

I also had these included in the script but didnt actually use them:

public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}

In short:

public class GPSClass implements LocationListener {

    public void onLocationChanged(Location location) {
        // Called when a new location is found by the network location provider.
        Log.i("Message: ","Location changed, " + location.getAccuracy() + " , " + location.getLatitude()+ "," + location.getLongitude());
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}
    public void onProviderEnabled(String provider) {}
    public void onProviderDisabled(String provider) {}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
    }
}

Building and running app via Gradle and Android Studio is slower than via Eclipse

USE this sudo dpkg --add-architecture i386 sudo apt-get update sudo apt-get install libncurses5:i386 libstdc++6:i386 zlib1g:i386

Android Studio fails to build new project, timed out while wating for slave aapt process

Creating a UITableView Programmatically

- (void)viewDidLoad {
     [super viewDidLoad];
     arr=[[NSArray alloc]initWithObjects:@"ABC",@"XYZ", nil];
     tableview = [[UITableView alloc]initWithFrame:tableFrame style:UITableViewStylePlain];   
     tableview.delegate = self;
     tableview.dataSource = self;
     [self.view addSubview:tableview];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];

    if(cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyCell"];
    }

    cell.textLabel.text=[arr objectAtIndex:indexPath.row];

    return cell;
}

Change UITableView height dynamically

Rob's solution is very nice, only thing that in his -(void)adjustHeightOfTableview method the calling of

[self.view needsUpdateConstraints]

does nothing, it just returns a flag, instead calling

[self.view setNeedsUpdateConstraints]

will make the desired effect.

This app won't run unless you update Google Play Services (via Bazaar)

I'm answering this question for the second time, because the solution I've tried that didn't work at first now works, and I can recreate the steps to make it work :)

I also had a feeling that lack of Google Play Store is a culprit here, so I've tried to install Google Play Store to the emulator by advice on this link and this link combined. I've had some difficulties, but at the end I've succeeded in installing Google Play Store and tested it by downloading some random app. But the maps activity kept displaying the message with the "Update" button. That button would take me to the store, but there I would get a message about "item not found" and maps still didn't work. At that point I gave up.

Yesterday, I've fired up the same test app by accident and it worked! I was very confused, but quickly I've made a diff from the emulator where it's working and new clean one and I've determined two apps on the working one in /data/app/ directory: com.android.vending-1.apk and com.google.android.gms-1.apk. This is strange since, when I were installing Google Play Store by instructions from those sites, I was pushing Phonesky.apk, GoogleServicesFramework.apk and GoogleLoginService.apk and to a different folder /system/app.

Anyway, now the Android Google Maps API v2 is working on my emulator. These are the steps to do this:


Create a new emulator

  • For device, choose "5.1'' WVGA (480 x 800: mdpi)"
  • For target, choose "Android 4.1.2 - API level 16"
  • For "CPU/ABI", choose "ARM"
  • Leave the rest to defaults

These are the settings that are working for me. I don't know for different ones.


Start the emulator


install com.android.vending-1.apk and com.google.android.gms-1.apk via ADB install command


Google Maps should work now in your emulator.

Screenshot sizes for publishing android app on Google Play

It has to be any one of the given sizes and a minimum of 2 but up to 8 screenshots are accepted in Google Playstore.

Saving data to a file in C#

I think you might want something like this

// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";

// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);

file.Close();

Add button to navigationbar programmatically

Use following code:

UIBarButtonItem *customBtn=[[UIBarButtonItem alloc] initWithTitle:@"Custom" style:UIBarButtonItemStylePlain target:self action:@selector(customBtnPressed)];
[self.navigationItem setRightBarButtonItem:customBtn];

Find package name for Android apps to use Intent to launch Market app from web

It depends where exactly you want to get the information from. You have a bunch of options:

  • If you have a copy of the .apk, it's just a case of opening it as a zip file and looking at the AndroidManifest.xml file. The top level <manifest> element will have a package attribute.
  • If you have the app installed on a device and can connect using adb, you can launch adb shell and execute pm list packages -f, which shows the package name for each installed apk.
  • If you just want to manually find a couple of package names, you can search for the app on http://www.cyrket.com/m/android/, and the package name is shown in the URL
  • You can also do it progmatically from an Android app using the PackageManager

Once you've got the package name, you simply link to market://search?q=pname:<package_name> or http://market.android.com/search?q=pname:<package_name>. Both will open the market on an Android device; the latter obviously has the potential to work on other hardware as well (it doesn't at the minute).

How to store custom objects in NSUserDefaults

Swift 3

class MyObject: NSObject, NSCoding  {
    let name : String
    let url : String
    let desc : String

    init(tuple : (String,String,String)){
        self.name = tuple.0
        self.url = tuple.1
        self.desc = tuple.2
    }
    func getName() -> String {
        return name
    }
    func getURL() -> String{
        return url
    }
    func getDescription() -> String {
        return desc
    }
    func getTuple() -> (String, String, String) {
        return (self.name,self.url,self.desc)
    }

    required init(coder aDecoder: NSCoder) {
        self.name = aDecoder.decodeObject(forKey: "name") as? String ?? ""
        self.url = aDecoder.decodeObject(forKey: "url") as? String ?? ""
        self.desc = aDecoder.decodeObject(forKey: "desc") as? String ?? ""
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.name, forKey: "name")
        aCoder.encode(self.url, forKey: "url")
        aCoder.encode(self.desc, forKey: "desc")
    }
    }

to store and retrieve:

func save() {
            let data  = NSKeyedArchiver.archivedData(withRootObject: object)
            UserDefaults.standard.set(data, forKey:"customData" )
        }
        func get() -> MyObject? {
            guard let data = UserDefaults.standard.object(forKey: "customData") as? Data else { return nil }
            return NSKeyedUnarchiver.unarchiveObject(with: data) as? MyObject
        }

How to add a right button to a UINavigationController?

This issue can occur if we delete the view controller or try to add new view controller inside the interface builder(main.storyboard). To fix this issue, it requires to add "Navigation Item" inside new view controller. Sometimes it happens that we create new view controller screen and it does not connect to "Navigation Item" automatically.

  1. Go to the main.storyboard.
  2. Select that new view Controller.
  3. Go to the document outline.
  4. Check view Controller contents.
  5. If new view controller does not have a Navigation item then, copy Navigation item from previous View Controller and paste it into the new view controller.
  6. save and clean the project.

Setting action for back button in navigation controller

Using Swift:

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    if self.navigationController?.topViewController != self {
        print("back button tapped")
    }
}

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

Ignore XAK. Do not explore any private methods if you want your app to have the chance of being accepted by apple.

This is easiest if you are using Interface Builder. You would add a UIView at the top of the view (where the images will go), then add your tableview below that. IB should size it accordingly; that is, the top of the tableview touches the bottom of the UIView you've just added and it's height covers the rest of the screen.

The thinking here is that if that UIView is not actually part of the table view, it will not scroll with the tableview. i.e. ignore the tableview header.

If you're not using interface builder, it's a little more complicated because you've got to get the positioning and height correct for the tableview.

Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

Suppose I have the following table T:

a   b
--------
1   abc
1   def
1   ghi
2   jkl
2   mno
2   pqr

And I do the following query:

SELECT a, b
FROM T
GROUP BY a

The output should have two rows, one row where a=1 and a second row where a=2.

But what should the value of b show on each of these two rows? There are three possibilities in each case, and nothing in the query makes it clear which value to choose for b in each group. It's ambiguous.

This demonstrates the single-value rule, which prohibits the undefined results you get when you run a GROUP BY query, and you include any columns in the select-list that are neither part of the grouping criteria, nor appear in aggregate functions (SUM, MIN, MAX, etc.).

Fixing it might look like this:

SELECT a, MAX(b) AS x
FROM T
GROUP BY a

Now it's clear that you want the following result:

a   x
--------
1   ghi
2   pqr

python's re: return True if string contains regex pattern

You can do something like this:

Using search will return a SRE_match object, if it matches your search string.

>>> import re
>>> m = re.search(u'ba[r|z|d]', 'bar')
>>> m
<_sre.SRE_Match object at 0x02027288>
>>> m.group()
'bar'
>>> n = re.search(u'ba[r|z|d]', 'bas')
>>> n.group()

If not, it will return None

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    n.group()
AttributeError: 'NoneType' object has no attribute 'group'

And just to print it to demonstrate again:

>>> print n
None

Iterate over model instance field names and values in template

In light of Django 1.8's release (and the formalization of the Model _meta API, I figured I would update this with a more recent answer.

Assuming the same model:

class Client(Model):
    name = CharField(max_length=150)
    email = EmailField(max_length=100, verbose_name="E-mail")

Django <= 1.7

fields = [(f.verbose_name, f.name) for f in Client._meta.fields]
>>> fields
[(u'ID', u'id'), (u'name', u'name'), (u'E-mail', u'email')]

Django 1.8+ (formalized Model _meta API)

Changed in Django 1.8:

The Model _meta API has always existed as a Django internal, but wasn’t formally documented and supported. As part of the effort to make this API public, some of the already existing API entry points have changed slightly. A migration guide has been provided to assist in converting your code to use the new, official API.

In the below example, we will utilize the formalized method for retrieving all field instances of a model via Client._meta.get_fields():

fields = [(f.verbose_name, f.name) for f in Client._meta.get_fields()]
>>> fields
[(u'ID', u'id'), (u'name', u'name'), (u'E-mail', u'email')]

Actually, it has been brought to my attention that the above is slightly overboard for what was needed (I agree!). Simple is better than complex. I am leaving the above for reference. However, to display in the template, the best method would be to use a ModelForm and pass in an instance. You can iterate over the form (equivalent of iterating over each of the form's fields) and use the label attribute to retrieve the verbose_name of the model field, and use the value method to retrieve the value:

from django.forms import ModelForm
from django.shortcuts import get_object_or_404, render
from .models import Client

def my_view(request, pk):
    instance = get_object_or_404(Client, pk=pk)
    
    class ClientForm(ModelForm):
        class Meta:
            model = Client
            fields = ('name', 'email')

    form = ClientForm(instance=instance)

    return render(
        request, 
        template_name='template.html',
        {'form': form}
    )

Now, we render the fields in the template:

<table>
    <thead>
        {% for field in form %}
            <th>{{ field.label }}</th>
        {% endfor %}
    </thead>
    <tbody>
        <tr>
            {% for field in form %}
                <td>{{ field.value|default_if_none:'' }}</td>
            {% endfor %}
        </tr>
    </tbody>
</table>
 

Read file from line 2 or skip header row

f = open(fname,'r')
lines = f.readlines()[1:]
f.close()

Deploying just HTML, CSS webpage to Tomcat

There is no real need to create a war to run it from Tomcat. You can follow these steps

  1. Create a folder in webapps folder e.g. MyApp

  2. Put your html and css in that folder and name the html file, which you want to be the starting page for your application, index.html

  3. Start tomcat and point your browser to url "http://localhost:8080/MyApp". Your index.html page will pop up in the browser

Failed to find target with hash string 'android-25'

You don't need to update anything. Just download the SDK for API 25 from Android SDK Manager or by launching Android standalone SDK manager. The error is for missing platform and not for missing tool.Android SDK Manager Android Studio 2.2.2

How to setup virtual environment for Python in VS Code?

For Mac users, note this bug: when you click "Enter interpreter path", you have two options: (1) manually enter the path; (2) select the venv file from Finder.

It only works if I manually enter the path. Selecting with Finder yields some strange path like Library/Developer/CommandTools/... which I understand.

Two Page Login with Spring Security 3.2.x

There should be three pages here:

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

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

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

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

How do I open a URL from C++?

For linux environments, you can use xdg-open. It is installed by default on most distributions. The benefit over the accepted answer is that it opens the user's preferred browser.

$ xdg-open https://google.com
$ xdg-open steam://run/10

Of course you can wrap this in a system() call.

elasticsearch bool query combine must with OR

I recently had to solve this problem too, and after a LOT of trial and error I came up with this (in PHP, but maps directly to the DSL):

'query' => [
    'bool' => [
        'should' => [
            ['prefix' => ['name_first' => $query]],
            ['prefix' => ['name_last' => $query]],
            ['prefix' => ['phone' => $query]],
            ['prefix' => ['email' => $query]],
            [
                'multi_match' => [
                    'query' => $query,
                    'type' => 'cross_fields',
                    'operator' => 'and',
                    'fields' => ['name_first', 'name_last']
                ]
            ]
        ],
        'minimum_should_match' => 1,
        'filter' => [
            ['term' => ['state' => 'active']],
            ['term' => ['company_id' => $companyId]]
        ]
    ]
]

Which maps to something like this in SQL:

SELECT * from <index> 
WHERE (
    name_first LIKE '<query>%' OR
    name_last LIKE '<query>%' OR
    phone LIKE  '<query>%' OR
    email LIKE '<query>%'
)
AND state = 'active'
AND company_id = <query>

The key in all this is the minimum_should_match setting. Without this the filter totally overrides the should.

Hope this helps someone!

What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

The first, curly braces. Otherwise, you run into consistency issues with keys that have odd characters in them, like =.

# Works fine.
a = {
    'a': 'value',
    'b=c': 'value',
}

# Eeep! Breaks if trying to be consistent.
b = dict( 
    a='value',
    b=c='value',
)

How to find rows that have a value that contains a lowercase letter

This is how I did it for utf8 encoded table and utf8_unicode_ci column, which doesn't seem to have been posted exactly:

SELECT *
FROM table
WHERE UPPER(column) != BINARY(column)

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

IE.Document.getElementById("dgTime").getElementsByTagName("a")(0).Click

EDIT: to loop through the collection (items should appear in the same order as they are in the source document)

Dim links, link 

Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")

'For Each loop
For Each link in links
    link.Click
Next link

'For Next loop
Dim n, i
n = links.length
For i = 0 to n-1 Step 2
    links(i).click
Next I

How to submit a form with JavaScript by clicking a link?

HTML & CSS - No Javascript Solution

Make your button appear like a Bootstrap link

HTML:

<form>
    <button class="btn-link">Submit</button>
</form>

CSS:

.btn-link {

    background: none;
    border: none;
    padding: 0px;
    color: #3097D1;
    font: inherit;

}

.btn-link:hover {

    color: #216a94;
    text-decoration: underline;

}

What is the difference between C++ and Visual C++?

C++ is a programming language and Visual C++ is an IDE for developing with languages such as C and C++.

VC++ contains tools for, amongst others, developing against the .net framework and the Windows API.

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

You could convert it to an array and then print that out with Arrays.toString(Object[]):

System.out.println(Arrays.toString(stack.toArray()));

How to use GNU Make on Windows?

While make itself is available as a standalone executable (gnuwin32.sourceforge.net package make), using it in a proper development environment means using msys2.

Git 2.24 (Q4 2019) illustrates that:

See commit 4668931, commit b35304b, commit ab7d854, commit be5d88e, commit 5d65ad1, commit 030a628, commit 61d1d92, commit e4347c9, commit ed712ef, commit 5b8f9e2, commit 41616ef, commit c097b95 (04 Oct 2019), and commit dbcd970 (30 Sep 2019) by Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit 6d5291b, 15 Oct 2019)

test-tool run-command: learn to run (parts of) the testsuite

Signed-off-by: Johannes Schindelin

Git for Windows jumps through hoops to provide a development environment that allows to build Git and to run its test suite.

To that end, an entire MSYS2 system, including GNU make and GCC is offered as "the Git for Windows SDK".
It does come at a price: an initial download of said SDK weighs in with several hundreds of megabytes, and the unpacked SDK occupies ~2GB of disk space.

A much more native development environment on Windows is Visual Studio. To help contributors use that environment, we already have a Makefile target vcxproj that generates a commit with project files (and other generated files), and Git for Windows' vs/master branch is continuously re-generated using that target.

The idea is to allow building Git in Visual Studio, and to run individual tests using a Portable Git.

Correct way to synchronize ArrayList in java

Let's take a normal list (implemented by the ArrayList class) and make it synchronized. This is shown in the SynchronizedListExample class. We pass the Collections.synchronizedList method a new ArrayList of Strings. The method returns a synchronized List of Strings. //Here is SynchronizedArrayList class

package com.mnas.technology.automation.utility;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
/**
* 
* @author manoj.kumar
* @email [email protected]
* 
*/
public class SynchronizedArrayList {
    static Logger log = Logger.getLogger(SynchronizedArrayList.class.getName());
    public static void main(String[] args) {    
        List<String> synchronizedList = Collections.synchronizedList(new ArrayList<String>());
        synchronizedList.add("Aditya");
        synchronizedList.add("Siddharth");
        synchronizedList.add("Manoj");
        // when iterating over a synchronized list, we need to synchronize access to the synchronized list
        synchronized (synchronizedList) {
            Iterator<String> iterator = synchronizedList.iterator();
            while (iterator.hasNext()) {
                log.info("Synchronized Array List Items: " + iterator.next());
            }
        }    
    }
}

Notice that when iterating over the list, this access is still done using a synchronized block that locks on the synchronizedList object. In general, iterating over a synchronized collection should be done in a synchronized block

IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

Alternatively, you can apply maven-compiler-plugin with appropriate java version by adding this to your pom.xml:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Difference between the Apache HTTP Server and Apache Tomcat?

an apache server is an http server which can serve any simple http requests, where tomcat server is actually a servlet container which can serve java servlet requests.

Web server [apache] process web client (web browsers) requests and forwards it to servlet container [tomcat] and container process the requests and sends response which gets forwarded by web server to the web client [browser].

Also you can check this link for more clarification:-

https://sites.google.com/site/sureshdevang/servlet-architecture

Also check this answer for further researching :-

https://softwareengineering.stackexchange.com/a/221092

2D cross-platform game engine for Android and iOS?

I've tried AppGameKit, It's both c++ and Basic. It's very easy to code 2d games in the Basic varient, with physics, collision and heaps more. It's also in active development, and really cheap (65$). The main problem is that it's really hard to compile for Android (you need to download heaps of files and follow difficult guides and things like that) My opinion is that it isn't yet good enough for commercial use, but is good for indie programmers It's got a medium size community

What is a monad?

Mathematial thinking

For short: An Algebraic Structure for Combining Computations.

return data: create a computation who just simply generate a data in monad world.

(return data) >>= (return func): The second parameter accept first parameter as a data generator and create a new computations which concatenate them.

You can think that (>>=) and return won't do any computation itself. They just simply combine and create computations.

Any monad computation will be compute if and only if main trigs it.

how do I get a new line, after using float:left?

you can also use

<br style="clear:both" />

How to wait for a JavaScript Promise to resolve before resuming function?

If using ES2016 you can use async and await and do something like:

(async () => {
  const data = await fetch(url)
  myFunc(data)
}())

If using ES2015 you can use Generators. If you don't like the syntax you can abstract it away using an async utility function as explained here.

If using ES5 you'll probably want a library like Bluebird to give you more control.

Finally, if your runtime supports ES2015 already execution order may be preserved with parallelism using Fetch Injection.

Compare cell contents against string in Excel

You can use the EXACT Function for exact string comparisons.

=IF(EXACT(A1, "ENG"), 1, 0)

How do you use variables in a simple PostgreSQL script?

For the official CLI client "psql" see here. And "pgAdmin3" 1.10 (still in beta) has "pgScript".

'True' and 'False' in Python

is compares identity. A string will never be identical to a not-string.

== is equality. But a string will never be equal to either True or False.

You want neither.

path = '/bla/bla/bla'

if path:
    print "True"
else:
    print "False"

How to fix a header on scroll

Or just simply add a span tag with the height of the fixed header set as its height then insert it next to the sticky header:

$(function() {
  var $span_height = $('.fixed-header').height;
  var $span_tag = '<span style="display:block; height:' + $span_height + 'px"></span>';

  $('.fixed-header').after($span_tag);
});

JavaScript moving element in the DOM

var swap = function () {
    var divs = document.getElementsByTagName('div');
    var div1 = divs[0];
    var div2 = divs[1];
    var div3 = divs[2];

    div3.parentNode.insertBefore(div1, div3);
    div1.parentNode.insertBefore(div3, div2);
};

This function may seem strange, but it heavily relies on standards in order to function properly. In fact, it may seem to function better than the jQuery version that tvanfosson posted which seems to do the swap only twice.

What standards peculiarities does it rely on?

insertBefore Inserts the node newChild before the existing child node refChild. If refChild is null, insert newChild at the end of the list of children. If newChild is a DocumentFragment object, all of its children are inserted, in the same order, before refChild. If the newChild is already in the tree, it is first removed.

I need to convert an int variable to double

Converting to double can be done by casting an int to a double:

You can convert an int to a double by using this mechnism like so:

int i = 3; // i is 3
double d = (double) i; // d = 3.0

Alternative (using Java's automatic type recognition):

double d = 1.0 * i; // d = 3.0

Implementing this in your code would be something like:

double firstSolution = ((double)(b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21));
double secondSolution = ((double)(b2 * a11 - b1 * a21) / (double)(a11 * a22 - a12 * a21));

Alternatively you can use a hard-parameter of type double (1.0) to have java to the work for you, like so:

double firstSolution = ((1.0 * (b1 * a22 - b2 * a12)) / (1.0 * (a11 * a22 - a12 * a21)));
double secondSolution = ((1.0 * (b2 * a11 - b1 * a21)) / (1.0 * (a11 * a22 - a12 * a21)));

Good luck.

Create Directory if it doesn't exist with Ruby

How about just Dir.mkdir('dir') rescue nil ?

Want to make Font Awesome icons clickable

You can wrap those elements in anchor tag

like this

<a href="your link here"> <i class="fa fa-dribbble fa-4x"></i></a>
<a href="your link here"> <i class="fa fa-behance-square fa-4x"></i></a>
<a href="your link here"> <i class="fa fa-linkedin-square fa-4x"></i></a>
<a href="your link here"> <i class="fa fa-twitter-square fa-4x"></i></a>
<a href="your link here"> <i class="fa fa-facebook-square fa-4x"></i></a>

Note: Replace href="your link here" with your desired link e.g. href="https://www.stackoverflow.com".

How to change the default collation of a table?

MySQL has 4 levels of collation: server, database, table, column. If you change the collation of the server, database or table, you don't change the setting for each column, but you change the default collations.

E.g if you change the default collation of a database, each new table you create in that database will use that collation, and if you change the default collation of a table, each column you create in that table will get that collation.

How to read and write to a text file in C++?

Default c++ mechanism for file IO is called streams. Streams can be of three flavors: input, output and inputoutput. Input streams act like sources of data. To read data from an input stream you use >> operator:

istream >> my_variable; //This code will read a value from stream into your variable.

Operator >> acts different for different types. If in the example above my_variable was an int, then a number will be read from the strem, if my_variable was a string, then a word would be read, etc. You can read more then one value from the stream by writing istream >> a >> b >> c; where a, b and c would be your variables.

Output streams act like sink to which you can write your data. To write your data to a stream, use << operator.

ostream << my_variable; //This code will write a value from your variable into stream.

As with input streams, you can write several values to the stream by writing something like this:

ostream << a << b << c;

Obviously inputoutput streams can act as both.

In your code sample you use cout and cin stream objects. cout stands for console-output and cin for console-input. Those are predefined streams for interacting with default console.

To interact with files, you need to use ifstream and ofstream types. Similar to cin and cout, ifstream stands for input-file-stream and ofstream stands for output-file-stream.

Your code might look like this:

#include <iostream>
#include <fstream>

using namespace std;

int start()
{
    cout << "Welcome...";

    // do fancy stuff

    return 0;
}

int main ()
{
    string usreq, usr, yn, usrenter;

    cout << "Is this your first time using TEST" << endl;
    cin >> yn;
    if (yn == "y")
    {
        ifstream iusrfile;
        ofstream ousrfile;
        iusrfile.open("usrfile.txt");
        iusrfile >> usr;
        cout << iusrfile; // I'm not sure what are you trying to do here, perhaps print iusrfile contents?
        iusrfile.close();
        cout << "Please type your Username. \n";
        cin >> usrenter;
        if (usrenter == usr)
        {
            start ();
        }
    }
    else
    {
        cout << "THAT IS NOT A REGISTERED USERNAME.";
    }

    return 0;
}

For further reading you might want to look at c++ I/O reference

Migration: Cannot add foreign key constraint

Laravel ^5.8

As of Laravel 5.8, migration stubs use the bigIncrements method on ID columns by default. Previously, ID columns were created using the increments method.

This will not affect any existing code in your project; however, be aware that foreign key columns must be of the same type. Therefore, a column created using the increments method can not reference a column created using the bigIncrements method.

Source: Migrations & bigIncrements


Example

Let's imagine you are building a simple role-based application, and you need to references user_id in the PIVOT table "role_user".

2019_05_05_112458_create_users_table.php

// ...

public function up()
{
    Schema::create('users', function (Blueprint $table) {

        $table->bigIncrements('id');

        $table->string('full_name');
        $table->string('email');
        $table->timestamps();
    });
}

2019_05_05_120634_create_role_user_pivot_table.php

// ...

public function up()
{
    Schema::create('role_user', function (Blueprint $table) {

        // this line throw QueryException "SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint..."
        // $table->integer('user_id')->unsigned()->index();

        $table->bigInteger('user_id')->unsigned()->index(); // this is working
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

As you can see, the commented line will throw a query exception, because, as mentioned in the upgrade notes, foreign key columns must be of the same type, therefore you need to either change the foreing key (in this example it's user_id) to bigInteger in role_user table or change bigIncrements method to increments method in users table and use the commented line in the pivot table, it's up to you.


I hope i was able to clarify this issue to you.

if, elif, else statement issues in Bash

I would recommend you having a look at the basics of conditioning in bash.

The symbol "[" is a command and must have a whitespace prior to it. If you don't give whitespace after your elif, the system interprets elif[ as a a particular command which is definitely not what you'd want at this time.

Usage:

elif(A COMPULSORY WHITESPACE WITHOUT PARENTHESIS)[(A WHITE SPACE WITHOUT PARENTHESIS)conditions(A WHITESPACE WITHOUT PARENTHESIS)]

In short, edit your code segment to:

elif [ "$seconds" -gt 0 ]

You'd be fine with no compilation errors. Your final code segment should look like this:

#!/bin/sh    
if [ "$seconds" -eq 0 ];then
       $timezone_string="Z"
    elif [ "$seconds" -gt 0 ]
    then
       $timezone_string=`printf "%02d:%02d" $seconds/3600 ($seconds/60)%60`
    else
       echo "Unknown parameter"
    fi

PHP foreach loop through multidimensional array

$last = count($arr_nav) - 1;

foreach ($arr_nav as $i => $row)
{
    $isFirst = ($i == 0);
    $isLast = ($i == $last);

    echo ... $row['name'] ... $row['url'] ...;
}

Why am I seeing "TypeError: string indices must be integers"?

item is most likely a string in your code; the string indices are the ones in the square brackets, e.g., gravatar_id. So I'd first check your data variable to see what you received there; I guess that data is a list of strings (or at least a list containing at least one string) while it should be a list of dictionaries.

How do you set up use HttpOnly cookies in PHP

You can use this in a header file.

// setup session enviroment
ini_set('session.cookie_httponly',1);
ini_set('session.use_only_cookies',1);

This way all future session cookies will use httponly.

  • Updated.

Rails: Can't verify CSRF token authenticity when making a POST request

Since Rails 5 you can also create a new class with ::API instead of ::Base:

class ApiController < ActionController::API
end

Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine

you can do update the User path as inside _JAVA_OPTIONS : -Xmx512M Path : C:\Program Files (x86)\Java\jdk1.8.0_231\bin;C:\Program Files(x86)\Java\jdk1.8.0_231\jre\bin for now it is working / /

How do the major C# DI/IoC frameworks compare?

See for a comparison of net-ioc-frameworks on google code including linfu and spring.net that are not on your list while i write this text.

I worked with spring.net: It has many features (aop, libraries , docu, ...) and there is a lot of experience with it in the dotnet and the java-world. The features are modularized so you donot have to take all features. The features are abstractions of common issues like databaseabstraction, loggingabstraction. however it is difficuilt to do and debug the IoC-configuration.

From what i have read so far: If i had to chooseh for a small or medium project i would use ninject since ioc-configuration is done and debuggable in c#. But i havent worked with it yet. for large modular system i would stay with spring.net because of abstraction-libraries.

Resizing Images in VB.NET

Here is an article with full details on how to do this.

Private Sub btnScale_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnScale.Click
    ' Get the scale factor.
    Dim scale_factor As Single = Single.Parse(txtScale.Text)

    ' Get the source bitmap.
    Dim bm_source As New Bitmap(picSource.Image)

    ' Make a bitmap for the result.
    Dim bm_dest As New Bitmap( _
        CInt(bm_source.Width * scale_factor), _
        CInt(bm_source.Height * scale_factor))

    ' Make a Graphics object for the result Bitmap.
    Dim gr_dest As Graphics = Graphics.FromImage(bm_dest)

    ' Copy the source image into the destination bitmap.
    gr_dest.DrawImage(bm_source, 0, 0, _
        bm_dest.Width + 1, _
        bm_dest.Height + 1)

    ' Display the result.
    picDest.Image = bm_dest
End Sub

[Edit]
One more on the similar lines.

How to change the session timeout in PHP?

No. If you don't have access to the php.ini, you can't guarantee that changes would have any effect.

I doubt you need to extend your sessions time though.
It has pretty sensible timeout at the moment and there are no reasons to extend it.

Why is 1/1/1970 the "epoch time"?

Early versions of unix measured system time in 1/60 s intervals. This meant that a 32-bit unsigned integer could only represent a span of time less than 829 days. For this reason, the time represented by the number 0 (called the epoch) had to be set in the very recent past. As this was in the early 1970s, the epoch was set to 1971-1-1.

Later, the system time was changed to increment every second, which increased the span of time that could be represented by a 32-bit unsigned integer to around 136 years. As it was no longer so important to squeeze every second out of the counter, the epoch was rounded down to the nearest decade, thus becoming 1970-1-1. One must assume that this was considered a bit neater than 1971-1-1.

Note that a 32-bit signed integer using 1970-1-1 as its epoch can represent dates up to 2038-1-19, on which date it will wrap around to 1901-12-13.

What does T&& (double ampersand) mean in C++11?

An rvalue reference is a type that behaves much like the ordinary reference X&, with several exceptions. The most important one is that when it comes to function overload resolution, lvalues prefer old-style lvalue references, whereas rvalues prefer the new rvalue references:

void foo(X& x);  // lvalue reference overload
void foo(X&& x); // rvalue reference overload

X x;
X foobar();

foo(x);        // argument is lvalue: calls foo(X&)
foo(foobar()); // argument is rvalue: calls foo(X&&)

So what is an rvalue? Anything that is not an lvalue. An lvalue being an expression that refers to a memory location and allows us to take the address of that memory location via the & operator.

It is almost easier to understand first what rvalues accomplish with an example:

 #include <cstring>
 class Sample {
  int *ptr; // large block of memory
  int size;
 public:
  Sample(int sz=0) : ptr{sz != 0 ? new int[sz] : nullptr}, size{sz} 
  {
     if (ptr != nullptr) memset(ptr, 0, sz);
  }
  // copy constructor that takes lvalue 
  Sample(const Sample& s) : ptr{s.size != 0 ? new int[s.size] :\
      nullptr}, size{s.size}
  {
     if (ptr != nullptr) memcpy(ptr, s.ptr, s.size);
     std::cout << "copy constructor called on lvalue\n";
  }

  // move constructor that take rvalue
  Sample(Sample&& s) 
  {  // steal s's resources
     ptr = s.ptr;
     size = s.size;        
     s.ptr = nullptr; // destructive write
     s.size = 0;
     cout << "Move constructor called on rvalue." << std::endl;
  }    
  // normal copy assignment operator taking lvalue
  Sample& operator=(const Sample& s)
  {
   if(this != &s) {
      delete [] ptr; // free current pointer
      size = s.size;

      if (size != 0) {
        ptr = new int[s.size];
        memcpy(ptr, s.ptr, s.size);
      } else 
         ptr = nullptr;
     }
     cout << "Copy Assignment called on lvalue." << std::endl;
     return *this;
  }    
 // overloaded move assignment operator taking rvalue
 Sample& operator=(Sample&& lhs)
 {
   if(this != &s) {
      delete [] ptr; //don't let ptr be orphaned 
      ptr = lhs.ptr;   //but now "steal" lhs, don't clone it.
      size = lhs.size; 
      lhs.ptr = nullptr; // lhs's new "stolen" state
      lhs.size = 0;
   }
   cout << "Move Assignment called on rvalue" << std::endl;
   return *this;
 }
//...snip
};     

The constructor and assignment operators have been overloaded with versions that take rvalue references. Rvalue references allow a function to branch at compile time (via overload resolution) on the condition "Am I being called on an lvalue or an rvalue?". This allowed us to create more efficient constructor and assignment operators above that move resources rather copy them.

The compiler automatically branches at compile time (depending on the whether it is being invoked for an lvalue or an rvalue) choosing whether the move constructor or move assignment operator should be called.

Summing up: rvalue references allow move semantics (and perfect forwarding, discussed in the article link below).

One practical easy-to-understand example is the class template std::unique_ptr. Since a unique_ptr maintains exclusive ownership of its underlying raw pointer, unique_ptr's can't be copied. That would violate their invariant of exclusive ownership. So they do not have copy constructors. But they do have move constructors:

template<class T> class unique_ptr {
  //...snip
 unique_ptr(unique_ptr&& __u) noexcept; // move constructor
};

 std::unique_ptr<int[] pt1{new int[10]};  
 std::unique_ptr<int[]> ptr2{ptr1};// compile error: no copy ctor.  

 // So we must first cast ptr1 to an rvalue 
 std::unique_ptr<int[]> ptr2{std::move(ptr1)};  

std::unique_ptr<int[]> TakeOwnershipAndAlter(std::unique_ptr<int[]> param,\
 int size)      
{
  for (auto i = 0; i < size; ++i) {
     param[i] += 10;
  }
  return param; // implicitly calls unique_ptr(unique_ptr&&)
}

// Now use function     
unique_ptr<int[]> ptr{new int[10]};

// first cast ptr from lvalue to rvalue
unique_ptr<int[]> new_owner = TakeOwnershipAndAlter(\
           static_cast<unique_ptr<int[]>&&>(ptr), 10);

cout << "output:\n";

for(auto i = 0; i< 10; ++i) {
   cout << new_owner[i] << ", ";
}

output:
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 

static_cast<unique_ptr<int[]>&&>(ptr) is usually done using std::move

// first cast ptr from lvalue to rvalue
unique_ptr<int[]> new_owner = TakeOwnershipAndAlter(std::move(ptr),0);

An excellent article explaining all this and more (like how rvalues allow perfect forwarding and what that means) with lots of good examples is Thomas Becker's C++ Rvalue References Explained. This post relied heavily on his article.

A shorter introduction is A Brief Introduction to Rvalue References by Stroutrup, et. al

How can I initialize C++ object member variables in the constructor?

I know this is 5 years later, but the replies above don't address what was wrong with your software. (Well, Yuushi's does, but I didn't realise until I had typed this - doh!). They answer the question in the title How can I initialize C++ object member variables in the constructor? This is about the other questions: Am I using the right approach but the wrong syntax? Or should I be coming at this from a different direction?

Programming style is largely a matter of opinion, but an alternative view to doing as much as possible in a constructor is to keep constructors down to a bare minimum, often having a separate initialization function. There is no need to try to cram all initialization into a constructor, never mind trying to force things at times into the constructors initialization list.

So, to the point, what was wrong with your software?

private:
    ThingOne* ThingOne;
    ThingTwo* ThingTwo;

Note that after these lines, ThingOne (and ThingTwo) now have two meanings, depending on context.

Outside of BigMommaClass, ThingOne is the class you created with #include "ThingOne.h"

Inside BigMommaClass, ThingOne is a pointer.

That is assuming the compiler can even make sense of the lines and doesn't get stuck in a loop thinking that ThingOne is a pointer to something which is itself a pointer to something which is a pointer to ...

Later, when you write

this->ThingOne = ThingOne(100);
this->ThingTwo = ThingTwo(numba1, numba2);

bear in mind that inside of BigMommaClass your ThingOne is a pointer.

If you change the declarations of the pointers to include a prefix (p)

private:
    ThingOne* pThingOne;
    ThingTwo* pThingTwo;

Then ThingOne will always refer to the class and pThingOne to the pointer.

It is then possible to rewrite

this->ThingOne = ThingOne(100);
this->ThingTwo = ThingTwo(numba1, numba2);

as

pThingOne = new ThingOne(100);
pThingTwo = new ThingTwo(numba1, numba2);

which corrects two problems: the double meaning problem, and the missing new. (You can leave this-> if you like!)

With that in place, I can add the following lines to a C++ program of mine and it compiles nicely.

class ThingOne{public:ThingOne(int n){};};
class ThingTwo{public:ThingTwo(int x, int y){};};

class BigMommaClass {

    public:
            BigMommaClass(int numba1, int numba2);

    private:
            ThingOne* pThingOne;
            ThingTwo* pThingTwo;
};

BigMommaClass::BigMommaClass(int numba1, int numba2)
{
    pThingOne = new ThingOne(numba1 + numba2);
    pThingTwo = new ThingTwo(numba1, numba2);
};

When you wrote

this->ThingOne = ThingOne(100);
this->ThingTwo = ThingTwo(numba1, numba2);

the use of this-> tells the compiler that the left hand side ThingOne is intended to mean the pointer. However we are inside BigMommaClass at the time and it's not necessary.

The problem is with the right hand side of the equals where ThingOne is intended to mean the class. So another way to rectify your problems would have been to write

this->ThingOne = new ::ThingOne(100);
this->ThingTwo = new ::ThingTwo(numba1, numba2);

or simply

ThingOne = new ::ThingOne(100);
ThingTwo = new ::ThingTwo(numba1, numba2);

using :: to change the compiler's interpretation of the identifier.

CodeIgniter removing index.php from url

Solved it with 2 steps.

  1. Update 2 parameters in the config file application/config/config.php
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';
  1. Update the file .htaccess in the root folder
<IfModule mod_rewrite.c>
    RewriteEngine On
      RewriteBase /
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

Python 3: UnboundLocalError: local variable referenced before assignment

Why not simply return your calculated value and let the caller modify the global variable. It's not a good idea to manipulate a global variable within a function, as below:

Var1 = 1
Var2 = 0

def function(): 
    if Var2 == 0 and Var1 > 0:
        print("Result One")
    elif Var2 == 1 and Var1 > 0:
        print("Result Two")
    elif Var1 < 1:
        print("Result Three")
    return Var1 - 1

Var1 = function()

or even make local copies of the global variables and work with them and return the results which the caller can then assign appropriately

def function():
v1, v2 = Var1, Var2
# calculate using the local variables v1 & v2
return v1 - 1

Var1 = function()

React JS - Uncaught TypeError: this.props.data.map is not a function

You don't need an array to do it.

var ItemNode = this.state.data.map(function(itemData) {
return (
   <ComponentName title={itemData.title} key={itemData.id} number={itemData.id}/>
 );
});

Why es6 react component works only with "export default"?

Exporting without default means it's a "named export". You can have multiple named exports in a single file. So if you do this,

class Template {}
class AnotherTemplate {}

export { Template, AnotherTemplate }

then you have to import these exports using their exact names. So to use these components in another file you'd have to do,

import {Template, AnotherTemplate} from './components/templates'

Alternatively if you export as the default export like this,

export default class Template {}

Then in another file you import the default export without using the {}, like this,

import Template from './components/templates'

There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.

You're free to rename the default export as you import it,

import TheTemplate from './components/templates'

And you can import default and named exports at the same time,

import Template,{AnotherTemplate} from './components/templates'

Change EditText hint color when using TextInputLayout

 <android.support.design.widget.TextInputLayout
        android:id="@+id/input_layout_passdword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColorHint="#d3d3d3">
        <EditText
            android:id="@+id/etaddrfess_ciwty"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            android:bottomLeftRadius="10dp"
            android:bottomRightRadius="50dp"
            android:fontFamily="@font/frutiger"
            android:gravity="start"
            android:hint="@string/address_city"
            android:padding="10dp"
            android:textColor="#000000"
            android:textColorHint="#000000"
            android:textSize="14sp"
            android:topLeftRadius="10dp"
            android:topRightRadius="10dp" />
    </android.support.design.widget.TextInputLayout>``

Matlab: Running an m-file from command-line

Here is what I would use instead, to gracefully handle errors from the script:

"C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "try, run('C:\<a long path here>\mfile.m'), catch, exit, end, exit"

If you want more verbosity:

"C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "try, run('C:\<a long path here>\mfile.m'), catch me, fprintf('%s / %s\n',me.identifier,me.message), end, exit"

I found the original reference here. Since original link is now gone, here is the link to an alternate newreader still alive today:

How to copy a file from remote server to local machine?

When you use scp you have to tell the host name and ip address from where you want to copy the file. For instance, if you are at the remote host and you want to transfer the file to your pc you may use something like this:

scp -P[portnumber] myfile_at_remote_host [user]@[your_ip_address]:/your/path/

Example:

scp -P22 table [email protected]:/home/me/Desktop/

On the other hand, if you are at your are actually on your machine you may use something like this:

scp -P[portnumber] [remote_login]@[remote's_ip_address]:/remote/path/myfile_at_remote_host /your/path/

Example:

scp -P22 [fake_user]@222.222.222.222:/remote/path/table /home/me/Desktop/

How do I create a file at a specific path?

The file path "c:\Test\blah" will have a tab character for the `\T'. You need to use either:

"C:\\Test"

or

r"C:\Test"

Xcode build failure "Undefined symbols for architecture x86_64"

I am late to the party but thought of sharing one more scenario where this could happen. I was working on a framework and was distributing it over cocoapods. The framework had both objective c and swift classes and protocols and it was building successfully. While using pod in another framework or project it was giving this error as I forgot to include .m files in podspec. Please include .swtift,.h and .m files in your podspec sources as below: s.source_files = "Projectname/Projectname/**/*.{swift,h,m}"

I hope it saves someone else's time.

How to permanently export a variable in Linux?

A particular example: I have Java 7 and Java 6 installed, I need to run some builds with 6, others with 7. Therefore I need to dynamically alter JAVA_HOME so that maven picks up what I want for each build. I did the following:

  • created j6.sh script which simply does export JAVA_HOME=... path to j6 install...
  • then, as suggested by one of the comments above, whenever I need J6 for a build, I run source j6.sh in that respective command terminal. By default, my JAVA_HOME is set to J7.

Hope this helps.

Web API Put Request generates an Http 405 Method Not Allowed error

Decorating one of the action params with [FromBody] solved the issue for me:

public async Task<IHttpActionResult> SetAmountOnEntry(string id, [FromBody]int amount)

However ASP.NET would infer it correctly if complex object was used in the method parameter:

public async Task<IHttpActionResult> UpdateEntry(string id, MyEntry entry)

keytool error Keystore was tampered with, or password was incorrect

Works on Windows

open command prompt (press Windows Key + R then type "cmd" without quotations in the appearing dialogue box and then press Enter Key).

then type the code sniff below :

  1. cd C:\Program Files\Java\jdk1.7.0_25\bin

then type following command

  1. keytool -list -keystore "C:/Documents and Settings/Your Name/.android/debug.keystore"

Then it will ask for Keystore password now. The default password is "android" type and enter or just hit enter "DONT TYPE ANY PASSWORD".

How do I make a new line in swift

You should be able to use \n inside a Swift string, and it should work as expected, creating a newline character. You will want to remove the space after the \n for proper formatting like so:

var example: String = "Hello World \nThis is a new line"

Which, if printed to the console, should become:

Hello World
This is a new line

However, there are some other considerations to make depending on how you will be using this string, such as:

  • If you are setting it to a UILabel's text property, make sure that the UILabel's numberOfLines = 0, which allows for infinite lines.
  • In some networking use cases, use \r\n instead, which is the Windows newline.

Edit: You said you're using a UITextField, but it does not support multiple lines. You must use a UITextView.

Java 8: How do I work with exception throwing methods in streams?

This question may be a little old, but because I think the "right" answer here is only one way which can lead to some issues hidden Issues later in your code. Even if there is a little Controversy, Checked Exceptions exist for a reason.

The most elegant way in my opinion can you find was given by Misha here Aggregate runtime exceptions in Java 8 streams by just performing the actions in "futures". So you can run all the working parts and collect not working Exceptions as a single one. Otherwise you could collect them all in a List and process them later.

A similar approach comes from Benji Weber. He suggests to create an own type to collect working and not working parts.

Depending on what you really want to achieve a simple mapping between the input values and Output Values occurred Exceptions may also work for you.

If you don't like any of these ways consider using (depending on the Original Exception) at least an own exception.

Convert PDF to image with high resolution

The following python script will work on any Mac (Snow Leopard and upward). It can be used on the command line with successive PDF files as arguments, or you can put in into a Run Shell Script action in Automator, and make a Service (Quick Action in Mojave).

You can set the resolution of the output image in the script.

The script and a Quick Action can be downloaded from github.

#!/usr/bin/python
# coding: utf-8

import os, sys
import Quartz as Quartz
from LaunchServices import (kUTTypeJPEG, kUTTypeTIFF, kUTTypePNG, kCFAllocatorDefault) 

resolution = 300.0 #dpi
scale = resolution/72.0

cs = Quartz.CGColorSpaceCreateWithName(Quartz.kCGColorSpaceSRGB)
whiteColor = Quartz.CGColorCreate(cs, (1, 1, 1, 1))
# Options: kCGImageAlphaNoneSkipLast (no trans), kCGImageAlphaPremultipliedLast 
transparency = Quartz.kCGImageAlphaNoneSkipLast

#Save image to file
def writeImage (image, url, type, options):
    destination = Quartz.CGImageDestinationCreateWithURL(url, type, 1, None)
    Quartz.CGImageDestinationAddImage(destination, image, options)
    Quartz.CGImageDestinationFinalize(destination)
    return

def getFilename(filepath):
    i=0
    newName = filepath
    while os.path.exists(newName):
        i += 1
        newName = filepath + " %02d"%i
    return newName

if __name__ == '__main__':

    for filename in sys.argv[1:]:
        pdf = Quartz.CGPDFDocumentCreateWithProvider(Quartz.CGDataProviderCreateWithFilename(filename))
        numPages = Quartz.CGPDFDocumentGetNumberOfPages(pdf)
        shortName = os.path.splitext(filename)[0]
        prefix = os.path.splitext(os.path.basename(filename))[0]
        folderName = getFilename(shortName)
        try:
            os.mkdir(folderName)
        except:
            print "Can't create directory '%s'"%(folderName)
            sys.exit()

        # For each page, create a file
        for i in range (1, numPages+1):
            page = Quartz.CGPDFDocumentGetPage(pdf, i)
            if page:
        #Get mediabox
                mediaBox = Quartz.CGPDFPageGetBoxRect(page, Quartz.kCGPDFMediaBox)
                x = Quartz.CGRectGetWidth(mediaBox)
                y = Quartz.CGRectGetHeight(mediaBox)
                x *= scale
                y *= scale
                r = Quartz.CGRectMake(0,0,x, y)
        # Create a Bitmap Context, draw a white background and add the PDF
                writeContext = Quartz.CGBitmapContextCreate(None, int(x), int(y), 8, 0, cs, transparency)
                Quartz.CGContextSaveGState (writeContext)
                Quartz.CGContextScaleCTM(writeContext, scale,scale)
                Quartz.CGContextSetFillColorWithColor(writeContext, whiteColor)
                Quartz.CGContextFillRect(writeContext, r)
                Quartz.CGContextDrawPDFPage(writeContext, page)
                Quartz.CGContextRestoreGState(writeContext)
        # Convert to an "Image"
                image = Quartz.CGBitmapContextCreateImage(writeContext) 
        # Create unique filename per page
                outFile = folderName +"/" + prefix + " %03d.png"%i
                url = Quartz.CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, outFile, len(outFile), False)
        # kUTTypeJPEG, kUTTypeTIFF, kUTTypePNG
                type = kUTTypePNG
        # See the full range of image properties on Apple's developer pages.
                options = {
                    Quartz.kCGImagePropertyDPIHeight: resolution,
                    Quartz.kCGImagePropertyDPIWidth: resolution
                    }
                writeImage (image, url, type, options)
                del page

Installation of VB6 on Windows 7 / 8 / 10

VB6 Installs just fine on Windows 7 (and Windows 8 / Windows 10) with a few caveats.

Here is how to install it:

  • Before proceeding with the installation process below, create a zero-byte file in C:\Windows called MSJAVA.DLL. The setup process will look for this file, and if it doesn't find it, will force an installation of old, old Java, and require a reboot. By creating the zero-byte file, the installation of moldy Java is bypassed, and no reboot will be required.
  • Turn off UAC.
  • Insert Visual Studio 6 CD.
  • Exit from the Autorun setup.
  • Browse to the root folder of the VS6 CD.
  • Right-click SETUP.EXE, select Run As Administrator.
  • On this and other Program Compatibility Assistant warnings, click Run Program.
  • Click Next.
  • Click "I accept agreement", then Next.
  • Enter name and company information, click Next.
  • Select Custom Setup, click Next.
  • Click Continue, then Ok.
  • Setup will "think to itself" for about 2 minutes. Processing can be verified by starting Task Manager, and checking the CPU usage of ACMSETUP.EXE.
  • On the options list, select the following:
    • Microsoft Visual Basic 6.0
    • ActiveX
    • Data Access
    • Graphics
    • All other options should be unchecked.
  • Click Continue, setup will continue.
  • Finally, a successful completion dialog will appear, at which click Ok. At this point, Visual Basic 6 is installed.
  • If you do not have the MSDN CD, clear the checkbox on the next dialog, and click next. You'll be warned of the lack of MSDN, but just click Yes to accept.
  • Click Next to skip the installation of Installshield. This is a really old version you don't want anyway.
  • Click Next again to skip the installation of BackOffice, VSS, and SNA Server. Not needed!
  • On the next dialog, clear the checkbox for "Register Now", and click Finish.
  • The wizard will exit, and you're done. You can find VB6 under Start, All Programs, Microsoft Visual Studio 6. Enjoy!
  • Turn On UAC again

  • You might notice after successfully installing VB6 on Windows 7 that working in the IDE is a bit, well, sluggish. For example, resizing objects on a form is a real pain.
  • After installing VB6, you'll want to change the compatibility settings for the IDE executable.
  • Using Windows Explorer, browse the location where you installed VB6. By default, the path is C:\Program Files\Microsoft Visual Studio\VB98\
  • Right click the VB6.exe program file, and select properties from the context menu.
  • Click on the Compatibility tab.
  • Place a check in each of these checkboxes:
  • Run this program in compatibility mode for Windows XP (Service Pack 3)
    • Disable Visual Themes
    • Disable Desktop Composition
    • Disable display scaling on high DPI settings
    • If you have UAC turned on, it is probably advisable to check the 'Run this program as an Administrator' box

After changing these settings, fire up the IDE, and things should be back to normal, and the IDE is no longer sluggish.

Edit: Updated dead link to point to a different page with the same instructions

Edit: Updated the answer with the actual instructions in the post as the link kept dying

asp.net mvc3 return raw html to view

Simply create a property in your view model of type MvcHtmlString. You won't need to Html.Raw it then either.

How to remove &quot; from my Json in javascript?

var data = $('<div>').html('[{&quot;Id&quot;:1,&quot;Name&quot;:&quot;Name}]')[0].textContent;

that should parse all the encoded values you need.

Query a parameter (postgresql.conf setting) like "max_connections"

You can use SHOW:

SHOW max_connections;

This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf in your current session:

RESET max_connections;

However, not applicable to this particular setting. The manual:

This parameter can only be set at server start.

To see all settings:

SHOW ALL;

There is also pg_settings:

The view pg_settings provides access to run-time parameters of the server. It is essentially an alternative interface to the SHOW and SET commands. It also provides access to some facts about each parameter that are not directly available from SHOW, such as minimum and maximum values.

For your original request:

SELECT *
FROM   pg_settings
WHERE  name = 'max_connections';

Finally, there is current_setting(), which can be nested in DML statements:

SELECT current_setting('max_connections');

Related:

Maven Out of Memory Build Failure

Someone has already mentioned the problem with the 32 bit OS. In my case the problem was that I was compiling with 32 bit JDK.

How to avoid .pyc files?

Solution for ipython 6.2.1 using python 3.5.2 (Tested on Ubuntu 16.04 and Windows 10):

Ipython doesn’t respect %env PYTHONDONTWRITEBYTECODE =1 if set in the ipython interpretor or during startup in ~/.ipython/profile-default/startup/00-startup.ipy. Instead using the following in your ~.ipython/profile-default/startup/00-startup.py

import sys
sys.dont_write_bytecode=True

How to get Map data using JDBCTemplate.queryForMap

queryForMap is appropriate if you want to get a single row. You are selecting without a where clause, so you probably want to queryForList. The error is probably indicative of the fact that queryForMap wants one row, but you query is retrieving many rows.

Check out the docs. There is a queryForList that takes just sql; the return type is a

List<Map<String,Object>>.

So once you have the results, you can do what you are doing. I would do something like

List results = template.queryForList(sql);

for (Map m : results){
   m.get('userid');
   m.get('username');
} 

I'll let you fill in the details, but I would not iterate over keys in this case. I like to explicit about what I am expecting.

If you have a User object, and you actually want to load User instances, you can use the queryForList that takes sql and a class type

queryForList(String sql, Class<T> elementType)

(wow Spring has changed a lot since I left Javaland.)

ASP.NET Web API session or something?

In WebApi 2 you can add this to global.asax

protected void Application_PostAuthorizeRequest() 
{
    System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}

Then you could access the session through:

HttpContext.Current.Session

MongoDB: Server has startup warnings ''Access control is not enabled for the database''

You need to delete your old db folder and recreate new one. It will resolve your issue.

UICollectionView current visible cell index

In this thread, There are so many solutions that work fine if cell takes full screen but they use collection view bounds and midpoints of Visible rect However there is a simple solution to this problem

    DispatchQueue.main.async {
        let visibleCell = self.collImages.visibleCells.first
        print(self.collImages.indexPath(for: visibleCell))
    }

by this, you can get indexPath of the visible cell. I have added DispatchQueue because when you swipe faster and if for a brief moment the next cell is shown then without dispactchQueue you'll get indexPath of briefly shown cell not the cell that is being displayed on the screen.

Postgresql SQL: How check boolean field with null and True,False Value?

There are 3 states for boolean in PG: true, false and unknown (null). Explained here: Postgres boolean datatype

Therefore you need only query for NOT TRUE:

SELECT * from table_name WHERE boolean_column IS NOT TRUE;

Is there any sed like utility for cmd.exe?

You could try powershell. There are get-content and set-content commandlets build in that you could use.

How to customize <input type="file">?

Here is one way which I like because it makes the input fill out the whole container. The trick is the "font-size: 100px", and it need to go with the "overflow: hidden" and the relative position.

<div id="upload-file-container" >
   <input type="file" />
</div>

#upload-file-container {
   width: 200px;
   height: 50px;
   position: relative;
   border: dashed 1px black;
   overflow: hidden;
}

#upload-file-container input[type="file"]
{
   margin: 0;
   opacity: 0;   
   font-size: 100px;
}

How can I escape a double quote inside double quotes?

Bash allows you to place strings adjacently, and they'll just end up being glued together.

So this:

$ echo "Hello"', world!'

produces

Hello, world!

The trick is to alternate between single and double-quoted strings as required. Unfortunately, it quickly gets very messy. For example:

$ echo "I like to use" '"double quotes"' "sometimes"

produces

I like to use "double quotes" sometimes

In your example, I would do it something like this:

$ dbtable=example
$ dbload='load data local infile "'"'gfpoint.csv'"'" into '"table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '"'"'"' LINES "'TERMINATED BY "'"'\n'"'" IGNORE 1 LINES'
$ echo $dbload

which produces the following output:

load data local infile "'gfpoint.csv'" into table example FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY "'\n'" IGNORE 1 LINES

It's difficult to see what's going on here, but I can annotate it using Unicode quotes. The following won't work in bash – it's just for illustration:

dbload=load data local infile "’“'gfpoint.csv'”‘" into’“table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '”‘"’“' LINES”‘TERMINATED BY "’“'\n'”‘" IGNORE 1 LINES

The quotes like “ ‘ ’ ” in the above will be interpreted by bash. The quotes like " ' will end up in the resulting variable.

If I give the same treatment to the earlier example, it looks like this:

$ echoI like to use"double quotes"sometimes

Angular 4 Pipe Filter

Pipes in Angular 2+ are a great way to transform and format data right from your templates.

Pipes allow us to change data inside of a template; i.e. filtering, ordering, formatting dates, numbers, currencies, etc. A quick example is you can transfer a string to lowercase by applying a simple filter in the template code.

List of Built-in Pipes from API List Examples

{{ user.name | uppercase }}

Example of Angular version 4.4.7. ng version


Custom Pipes which accepts multiple arguments.

HTML « *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] "
TS   « transform(json: any[], args: any[]) : any[] { ... }

Filtering the content using a Pipe « json-filter-by.pipe.ts

import { Pipe, PipeTransform, Injectable } from '@angular/core';

@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {

  transform(json: any[], args: any[]) : any[] {
    var searchText = args[0];
    var jsonKey = args[1];

    // json = undefined, args = (2) [undefined, "name"]
    if(searchText == null || searchText == 'undefined') return json;
    if(jsonKey    == null || jsonKey    == 'undefined') return json;

    // Copy all objects of original array into new Array.
    var returnObjects = json;
    json.forEach( function ( filterObjectEntery ) {

      if( filterObjectEntery.hasOwnProperty( jsonKey ) ) {
        console.log('Search key is available in JSON object.');

        if ( typeof filterObjectEntery[jsonKey] != "undefined" && 
        filterObjectEntery[jsonKey].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
            // object value contains the user provided text.
        } else {
            // object didn't match a filter value so remove it from array via filter
            returnObjects = returnObjects.filter(obj => obj !== filterObjectEntery);
        }
      } else {
        console.log('Search key is not available in JSON object.');
      }

    })
    return returnObjects;
  }
}

Add to @NgModule « Add JsonFilterByPipe to your declarations list in your module; if you forget to do this you'll get an error no provider for jsonFilterBy. If you add to module then it is available to all the component's of that module.

@NgModule({
  imports: [
    CommonModule,
    RouterModule,
    FormsModule, ReactiveFormsModule,
  ],
  providers: [ StudentDetailsService ],
  declarations: [
    UsersComponent, UserComponent,

    JsonFilterByPipe,
  ],
  exports : [UsersComponent, UserComponent]
})
export class UsersModule {
    // ...
}

File Name: users.component.ts and StudentDetailsService is created from this link.

import { MyStudents } from './../../services/student/my-students';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { StudentDetailsService } from '../../services/student/student-details.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: [ './users.component.css' ],

  providers:[StudentDetailsService]
})
export class UsersComponent implements OnInit, OnDestroy  {

  students: MyStudents[];
  selectedStudent: MyStudents;

  constructor(private studentService: StudentDetailsService) { }

  ngOnInit(): void {
    this.loadAllUsers();
  }
  ngOnDestroy(): void {
    // ONDestroy to prevent memory leaks
  }

  loadAllUsers(): void {
    this.studentService.getStudentsList().then(students => this.students = students);
  }

  onSelect(student: MyStudents): void {
    this.selectedStudent = student;
  }

}

File Name: users.component.html

<div>
    <br />
    <div class="form-group">
        <div class="col-md-6" >
            Filter by Name: 
            <input type="text" [(ngModel)]="searchText" 
                   class="form-control" placeholder="Search By Category" />
        </div>
    </div>

    <h2>Present are Students</h2>
    <ul class="students">
    <li *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] " >
        <a *ngIf="student" routerLink="/users/update/{{student.id}}">
            <span class="badge">{{student.id}}</span> {{student.name | uppercase}}
        </a>
    </li>
    </ul>
</div>

ggplot legends - change labels, order and title

You need to do two things:

  1. Rename and re-order the factor levels before the plot
  2. Rename the title of each legend to the same title

The code:

dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))

library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha = 0.35, linetype=0)+ 
  geom_line(aes(linetype=model), size = 1) +       
  geom_point(aes(shape=model), size=4)  +      
  theme(legend.position=c(.6,0.8)) +
  theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
  scale_linetype_discrete("Model 1") +
  scale_shape_discrete("Model 1") +
  scale_colour_discrete("Model 1")

enter image description here

However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:

ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha=0.2, colour=NA)+ 
  geom_line() +       
  geom_point()  +      
  facet_wrap(~model)

enter image description here

Check if string contains \n Java

I'd rather trust JDK over System property. Following is a working snippet.

    private boolean checkIfStringContainsNewLineCharacters(String str){
        if(!StringUtils.isEmpty(str)){
            Scanner scanner = new Scanner(str);
            scanner.nextLine();
            boolean hasNextLine =  scanner.hasNextLine();
            scanner.close();
            return hasNextLine;
        }
        return false;
    }

ReactJS map through Object

Map over the keys of the object using Object.keys():

{Object.keys(yourObject).map(function(key) {
  return <div>Key: {key}, Value: {yourObject[key]}</div>;
})}

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

Another possible problem is a missing builder (it will prevent from your .class file from being built).

Check that your .project file has the following lines

<buildSpec>
  <buildCommand>
    <name>org.eclipse.jdt.core.javabuilder</name>
    <arguments>
    </arguments>
  </buildCommand>
</buildSpec>
<natures>
  <nature>org.eclipse.jdt.core.javanature</nature>
</natures>

How to create a custom navigation drawer in android

I used below layout and able to achieve custom layout in Navigation View.

<android.support.design.widget.NavigationView
        android:id="@+id/navi_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start|top"
        android:background="@color/navigation_view_bg_color"
        app:theme="@style/NavDrawerTextStyle">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <include layout="@layout/drawer_header" />

            <include layout="@layout/navigation_drawer_menu" />
        </LinearLayout>
</android.support.design.widget.NavigationView> 

Get average color of image via Javascript

I would say via the HTML canvas tag.

You can find here a post by @Georg talking about a small code by the Opera dev :

// Get the CanvasPixelArray from the given coordinates and dimensions.
var imgd = context.getImageData(x, y, width, height);
var pix = imgd.data;

// Loop over each pixel and invert the color.
for (var i = 0, n = pix.length; i < n; i += 4) {
    pix[i  ] = 255 - pix[i  ]; // red
    pix[i+1] = 255 - pix[i+1]; // green
    pix[i+2] = 255 - pix[i+2]; // blue
    // i+3 is alpha (the fourth element)
}

// Draw the ImageData at the given (x,y) coordinates.
context.putImageData(imgd, x, y);

This invert the image by using the R, G and B value of each pixel. You could easily store the RGB values, then round up the Red, Green and Blue arrays, and finally converting them back into an HEX code.

Decreasing height of bootstrap 3.0 navbar

I got the same problem, the height of my menu bar provided by bootstrap was too big, actually i downloaded some wrong bootstrap, finally get rid of it by downloading the orignal bootstrap from this site.. http://getbootstrap.com/2.3.2/ want to use bootstrap in yii( netbeans) follow this tutorial, https://www.youtube.com/watch?v=XH_qG8gphaw... The voice is not present but the steps are slow you can easily understand and implement them. Thanks

node.js: cannot find module 'request'

I was running into the same problem, here is how I got it working..

open terminal:

mkdir testExpress
cd testExpress
npm install request

or

sudo npm install -g request // If you would like to globally install.

now don't use

node app.js or node test.js, you will run into this problem doing so. You can also print the problem that is being cause by using this command.. "node -p app.js"

The above command to start nodeJs has been deprecated. Instead use

npm start

You should see this..

[email protected] start /Users/{username}/testExpress
node ./bin/www

Open your web browser and check for localhost:3000

You should see Express install (Welcome to Express)

Normalizing images in OpenCV

When you normalize a matrix using NORM_L1, you are dividing every pixel value by the sum of absolute values of all the pixels in the image. As a result, all pixel values become much less than 1 and you get a black image. Try NORM_MINMAX instead of NORM_L1.

Python display text with font & color?

I have some code in my game that displays live score. It is in a function for quick access.

def texts(score):
   font=pygame.font.Font(None,30)
   scoretext=font.render("Score:"+str(score), 1,(255,255,255))
   screen.blit(scoretext, (500, 457))

and I call it using this in my while loop:

texts(score)

Pass table as parameter into sql server UDF

To obtain the column count on a table, use this:

select count(id) from syscolumns where id = object_id('tablename')

and to pass a table to a function, try XML as show here:

create function dbo.ReadXml (@xmlMatrix xml)
returns table
as
return
( select
t.value('./@Salary', 'integer') as Salary,
t.value('./@Age', 'integer') as Age
from @xmlMatrix.nodes('//row') x(t)
)
go

declare @source table
( Salary integer,
age tinyint
)
insert into @source
select 10000, 25 union all
select 15000, 27 union all
select 12000, 18 union all
select 15000, 36 union all
select 16000, 57 union all
select 17000, 44 union all
select 18000, 32 union all
select 19000, 56 union all
select 25000, 34 union all
select 7500, 29
--select * from @source

declare @functionArgument xml

select @functionArgument =
( select
Salary as [row/@Salary],
Age as [row/@Age]
from @source
for xml path('')
)
--select @functionArgument as [@functionArgument]

select * from readXml(@functionArgument)

/* -------- Sample Output: --------
Salary Age
----------- -----------
10000 25
15000 27
12000 18
15000 36
16000 57
17000 44
18000 32
19000 56
25000 34
7500 29
*/

Implementation difference between Aggregation and Composition in Java

I would use a nice UML example.

Take a university that has 1 to 20 different departments and each department has 1 to 5 professors. There is a composition link between a University and its' departments. There is an aggregation link between a department and its' professors.

Composition is just a STRONG aggregation, if the university is destroyed then the departments should also be destroyed. But we shouldn't kill the professors even if their respective departments disappear.

In java :

public class University {

     private List<Department> departments;

     public void destroy(){
         //it's composition, when I destroy a university I also destroy the departments. they cant live outside my university instance
         if(departments!=null)
             for(Department d : departments) d.destroy();
         departments.clean();
         departments = null;
     }
}

public class Department {

     private List<Professor> professors;
     private University university;

     Department(University univ){
         this.university = univ;
         //check here univ not null throw whatever depending on your needs
     }

     public void destroy(){
         //It's aggregation here, we just tell the professor they are fired but they can still keep living
         for(Professor p:professors)
             p.fire(this);
         professors.clean();
         professors = null;
     }
}

public class Professor {

     private String name;
     private List<Department> attachedDepartments;

     public void destroy(){

     }

     public void fire(Department d){
         attachedDepartments.remove(d);
     }
}

Something around this.

EDIT: an example as requested

public class Test
{
    public static void main(String[] args)
    {
        University university = new University();
        //the department only exists in the university
        Department dep = university.createDepartment();
        // the professor exists outside the university
        Professor prof = new Professor("Raoul");
        System.out.println(university.toString());
        System.out.println(prof.toString());

        dep.assign(prof);
        System.out.println(university.toString());
        System.out.println(prof.toString());
        dep.destroy();

        System.out.println(university.toString());
        System.out.println(prof.toString());

    }


}

University class

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

public class University {

    private List<Department> departments = new ArrayList<>();

    public Department createDepartment() {
        final Department dep = new Department(this, "Math");
        departments.add(dep);
        return dep;
    }

    public void destroy() {
        System.out.println("Destroying university");
        //it's composition, when I destroy a university I also destroy the departments. they cant live outside my university instance
        if (departments != null)
            departments.forEach(Department::destroy);
        departments = null;
    }

    @Override
    public String toString() {
        return "University{\n" +
                "departments=\n" + departments.stream().map(Department::toString).collect(Collectors.joining("\n")) +
                "\n}";
    }
}

Department class

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

public class Department {

    private final String name;
    private List<Professor> professors = new ArrayList<>();
    private final University university;

    public Department(University univ, String name) {
        this.university = univ;
        this.name = name;
        //check here univ not null throw whatever depending on your needs
    }

    public void assign(Professor p) {
        //maybe use a Set here
        System.out.println("Department hiring " + p.getName());
        professors.add(p);
        p.join(this);
    }

    public void fire(Professor p) {
        //maybe use a Set here
        System.out.println("Department firing " + p.getName());
        professors.remove(p);
        p.quit(this);
    }

    public void destroy() {
        //It's aggregation here, we just tell the professor they are fired but they can still keep living
        System.out.println("Destroying department");
        professors.forEach(professor -> professor.quit(this));
        professors = null;
    }

    @Override
    public String toString() {
        return professors == null
                ? "Department " + name + " doesn't exists anymore"
                : "Department " + name + "{\n" +
                "professors=" + professors.stream().map(Professor::toString).collect(Collectors.joining("\n")) +
                "\n}";
    }
}

Professor class

import java.util.ArrayList;
import java.util.List;

public class Professor {

    private final String name;
    private final List<Department> attachedDepartments = new ArrayList<>();

    public Professor(String name) {
        this.name = name;
    }

    public void destroy() {

    }

    public void join(Department d) {
        attachedDepartments.add(d);
    }

    public void quit(Department d) {
        attachedDepartments.remove(d);
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Professor " + name + " working for " + attachedDepartments.size() + " department(s)\n";
    }
}

The implementation is debatable as it depends on how you need to handle creation, hiring deletion etc. Unrelevant for the OP

How to reverse an std::string?

I'm not sure what you mean by a string that contains binary numbers. But for reversing a string (or any STL-compatible container), you can use std::reverse(). std::reverse() operates in place, so you may want to make a copy of the string first:

#include <algorithm>
#include <iostream>
#include <string>

int main()
{
    std::string foo("foo");
    std::string copy(foo);
    std::cout << foo << '\n' << copy << '\n';

    std::reverse(copy.begin(), copy.end());
    std::cout << foo << '\n' << copy << '\n';
}

Add horizontal scrollbar to html table

With bootstrap

 <div class="table-responsive">
   <table class="table">
     ...
   </table>
 </div>

jQuery dialog popup

It's quite simple, first HTML must be added:

<div id="dialog"></div>

Then, it must be initialized:

<script type="text/javascript">
  jQuery( document ).ready( function() {
    jQuery( '#dialog' ).dialog( { 'autoOpen': false } );
  });
</script>

After this you can show it by code:

jQuery( '#dialog' ).dialog( 'open' );

In oracle, how do I change my session to display UTF8?

Therefore, before starting '$ sqlplus' on OS, run the followings:

  • On Windows

    set NLS_LANG=AMERICAN_AMERICA.UTF8

  • On Unix (Solaris and Linux, centos etc)

    export NLS_LANG=AMERICAN_AMERICA.UTF8

It would also be advisable to set env variable in your '.bash_profile' [on start up script]

This is the place where other ORACLE env variables (ORACLE_SID, ORACLE_HOME) are usually set.

just fyi - SQL Developer is good at displaying/handling non-English UTF8 characters.

How can I import data into mysql database via mysql workbench?

For MySQL Workbench 6.1: in the home window click on the server instance(connection)/ or create a new one. In the thus opened 'connection' tab click on 'server' -> 'data import'. The rest of the steps remain as in Vishy's answer.

jQuery 1.9 .live() is not a function

.live was removed in 1.9, please see the upgrade guide: http://jquery.com/upgrade-guide/1.9/#live-removed

Configuration System Failed to Initialize

I know this has already been answered but I had exactly the same problem in my unit tests. I was tearing my hair out - adding an appSettings section, and then declaring the configuration section as per the answer. Finally found out that I had already declared an appSettings section further up my config file. Both sections pointed to my external settings file "appSettings.config" but the first appSettings element using the attribute file whilst the other used the attribute configSource. I know the question was about the connectionStrings. Sure enough, this happens if the appSettings element is the connectionStrings element being duplicated with different attributes.

Hopefully, this can provide someone else with the solution before they go down the path I did which leads to wasting an hour or two. sigh oh the life of us developers. We waste more hours some days debugging than we spend developing!

Mount current directory as a volume in Docker on Windows 10

In Windows Command Line (cmd), you can mount the current directory like so:

docker run --rm -it -v %cd%:/usr/src/project gcc:4.9

In PowerShell, you use ${PWD}, which gives you the current directory:

docker run --rm -it -v ${PWD}:/usr/src/project gcc:4.9

On Linux:

docker run --rm -it -v $(pwd):/usr/src/project gcc:4.9

Cross Platform

The following options will work on both PowerShell and on Linux (at least Ubuntu):

docker run --rm -it -v ${PWD}:/usr/src/project gcc:4.9
docker run --rm -it -v $(pwd):/usr/src/project gcc:4.9

Changing plot scale by a factor in matplotlib

To set the range of the x-axis, you can use set_xlim(left, right), here are the docs

Update:

It looks like you want an identical plot, but only change the 'tick values', you can do that by getting the tick values and then just changing them to whatever you want. So for your need it would be like this:

ticks = your_plot.get_xticks()*10**9
your_plot.set_xticklabels(ticks)

Aligning two divs side-by-side

The HTML code is for three div align side by side and can be used for two also by some changes

<div id="wrapper">
  <div id="first">first</div>
  <div id="second">second</div>
  <div id="third">third</div>
</div>

The CSS will be

#wrapper {
  display:table;
  width:100%;
}
#row {
  display:table-row;
}
#first {
  display:table-cell;
  background-color:red;
  width:33%;
}
#second {
  display:table-cell;
  background-color:blue;
  width:33%;
}
#third {
  display:table-cell;
  background-color:#bada55;
  width:34%;
}

This code will workup towards responsive layout as it will resize the

<div> 

according to device width. Even one can silent anyone

<div>

as

<!--<div id="third">third</div> --> 

and can use rest two for two

<div> 

side by side.

make script execution to unlimited

You'll have to set it to zero. Zero means the script can run forever. Add the following at the start of your script:

ini_set('max_execution_time', 0);

Refer to the PHP documentation of max_execution_time

Note that:

set_time_limit(0);

will have the same effect.

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

puttygen supports exporting your private key to an OpenSSH compatible format. You can then use OpenSSH tools to recreate the public key.

  1. Open PuttyGen
  2. Click Load
  3. Load your private key
  4. Go to Conversions->Export OpenSSH and export your private key
  5. Copy your private key to ~/.ssh/id_dsa (or id_rsa).
  6. Create the RFC 4716 version of the public key using ssh-keygen

    ssh-keygen -e -f ~/.ssh/id_dsa > ~/.ssh/id_dsa_com.pub
    
  7. Convert the RFC 4716 version of the public key to the OpenSSH format:

    ssh-keygen -i -f ~/.ssh/id_dsa_com.pub > ~/.ssh/id_dsa.pub
    

See this and this for more information.

How to extract an assembly from the GAC?

I think the easiest way is to do it through the command line like David mentions. The only trick is that the .dll isn't simply located at C:\Windows\Assembly. You have to navigate to C:\Windows\Assembly\GAC\[ASSEMBLY_NAME]\[VERSION_NUMBER]_[PUBLIC KEY]. You can then do a copy using:

copy [ASSEMBLY_NAME].dll c:\ (or whatever location you want)

Hope that helps.

Basic HTTP and Bearer Token Authentication

curl --anyauth

Tells curl to figure out authentication method by itself, and use the most secure one the remote site claims to support. This is done by first doing a request and checking the response- headers, thus possibly inducing an extra network round-trip. This is used instead of setting a specific authentication method, which you can do with --basic, --digest, --ntlm, and --negotiate.

Automatic confirmation of deletion in powershell

Add -recurse after the remove-item, also the -force parameter helps remove hidden files e.g.:

gci C:\temp\ -exclude *.svn-base,".svn" -recurse | %{ri $_ -force -recurse}

Easiest way to read from and write to files

     class Program
    { 
         public static void Main()
        { 
            //To write in a txt file
             File.WriteAllText("C:\\Users\\HP\\Desktop\\c#file.txt", "Hello and Welcome");

           //To Read from a txt file & print on console
             string  copyTxt = File.ReadAllText("C:\\Users\\HP\\Desktop\\c#file.txt");
             Console.Out.WriteLine("{0}",copyTxt);
        }      
    }

How to turn off INFO logging in Spark?

The way I do it is:

in the location I run the spark-submit script do

$ cp /etc/spark/conf/log4j.properties .
$ nano log4j.properties

change INFO to what ever level of logging you want and then run your spark-submit

How to put an image next to each other

Instead of using position:relative in #icons, you could just take that away and maybe add a z-index or something so the picture won't get covered up. Hope this helps.

Convert UTC/GMT time to local time

I'd look into using the System.TimeZoneInfo class if you are in .NET 3.5. See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx. This should take into account the daylight savings changes correctly.

// Coordinated Universal Time string from 
// DateTime.Now.ToUniversalTime().ToString("u");
string date = "2009-02-25 16:13:00Z"; 
// Local .NET timeZone.
DateTime localDateTime = DateTime.Parse(date); 
DateTime utcDateTime = localDateTime.ToUniversalTime();

// ID from: 
// "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Time Zone"
// See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.id.aspx
string nzTimeZoneKey = "New Zealand Standard Time";
TimeZoneInfo nzTimeZone = TimeZoneInfo.FindSystemTimeZoneById(nzTimeZoneKey);
DateTime nzDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, nzTimeZone);

Sort columns of a dataframe by column name

  test[,sort(names(test))]

sort on names of columns can work easily.

Java - JPA - @Version annotation

Every time an entity is updated in the database the version field will be increased by one. Every operation that updates the entity in the database will have appended WHERE version = VERSION_THAT_WAS_LOADED_FROM_DATABASE to its query.

In checking affected rows of your operation the jpa framework can make sure there was no concurrent modification between loading and persisting your entity because the query would not find your entity in the database when it's version number has been increased between load and persist.

How to set selectedIndex of select element using display text?

Try this:

function SelectAnimal()
{
    var animals = document.getElementById('Animals');
    var animalsToFind = document.getElementById('AnimalToFind');
    // get the options length
    var len = animals.options.length;
    for(i = 0; i < len; i++)
    {
      // check the current option's text if it's the same with the input box
      if (animals.options[i].innerHTML == animalsToFind.value)
      {
         animals.selectedIndex = i;
         break;
      }     
    }
}

How to delete all records from table in sqlite with Android?

Can be usefull.

public boolean deleteAllFood() {
            SQLiteDatabase db = dbHelper.getReadableDatabase();
            int affectedRows = db.delete(DBHelper.TABLE_NAME_FOOD, null, null);
            return affectedRows > 0;
        }



public class DBProgram {
    private static DBProgram INSTANCE;
    private Context context;
    private DBHelper dbHelper;

    private DBProgram(Context context) {
        // burda bu methodu kullanan activity ile eilestiriyoruz
        this.dbHelper = new DBHelper(context);
    }

    public static synchronized DBProgram getInstance(Context context) {
        if (INSTANCE == null) {
            INSTANCE = new DBProgram(context);
        }
        return INSTANCE;
    }

    //**********************************************
    public boolean updateById(ProgramModel program) {
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(DBHelper.COLUM_NAME_P, program.getProgName());
        contentValues.put(DBHelper.COLUM_DAY_P, program.getDay());
        contentValues.put(DBHelper.COLUMN_WEIGHT_P, program.getWeight());
        contentValues.put(DBHelper.COLUMN_SET_P, program.getSet());
        contentValues.put(DBHelper.COLUMN_REPETITION_P, program.getRepetition());
        int affectedRows = database.update(DBHelper.TABLE_NAME_PROGRAM, contentValues, "PROG_ID_P = ?", new String[]{String.valueOf(program.getId())});
        return affectedRows > 0;
    }
    //**********************************************


    //**********************************************
    // TODO
    public boolean deleteProgramById(int id) {
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        int affectedRows = database.delete(DBHelper.TABLE_NAME_PROGRAM, DBHelper.COLUMN_ID_P + "= ?", new String[]{String.valueOf(id)});
        // return bize etkilenen sira sayisiniini temsil eder
        return affectedRows > 0;
    }
    //**********************************************


    //***************************************************
    public boolean deleteProgramByName(String progName) {
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        final String whereClause = DBHelper.COLUM_NAME_P + "=?";
        final String whereArgs[] = {progName};
        int affectedRows = database.delete(DBHelper.TABLE_NAME_PROGRAM, whereClause, whereArgs);
        return affectedRows > 0;
    }
    //***************************************************


    //************************************** get Meal
    // TODO  WEB Get All  Meals
    public List<ProgramModel> getAllProgram(String name) {
        List<ProgramModel> foodList = new ArrayList<>();
        ProgramModel food;
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        final String kolonlar[] = {DBHelper.COLUMN_ID_P,
                DBHelper.COLUM_NAME_P,
                DBHelper.COLUM_DAY_P,
                DBHelper.COLUMN_WEIGHT_P,
                DBHelper.COLUMN_SET_P,
                DBHelper.COLUMN_REPETITION_P};

        final String whereClause = DBHelper.COLUM_DAY_P + "=?";
        final String whereArgs[] = {name};
        Cursor cursor = database.query(DBHelper.TABLE_NAME_PROGRAM, kolonlar, whereClause, whereArgs, null, null, null);
        while (cursor.moveToNext()) {

            food = new ProgramModel();
            food.setId(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_ID_P)));
            food.setProgName(cursor.getString(cursor.getColumnIndex(DBHelper.COLUM_NAME_P)));
            food.setDay(cursor.getString(cursor.getColumnIndex(DBHelper.COLUM_DAY_P)));
            food.setWeight(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_WEIGHT_P)));
            food.setSet(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_SET_P)));
            food.setRepetition(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_REPETITION_P)));
            foodList.add(food);
        }
        database.close();
        cursor.close();
        return foodList;
    }
    //**************************************


    //**************************************insert FOOD
    //TODO LOCAL insert Foods
    public boolean insertProgram(ProgramModel favorite) {
        boolean result = false;
        ContentValues contentValues = new ContentValues();
        contentValues.put(DBHelper.COLUM_NAME_P, favorite.getProgName());
        contentValues.put(DBHelper.COLUM_DAY_P, favorite.getDay());
        contentValues.put(DBHelper.COLUMN_WEIGHT_P, favorite.getWeight());
        contentValues.put(DBHelper.COLUMN_SET_P, favorite.getSet());
        contentValues.put(DBHelper.COLUMN_REPETITION_P, favorite.getRepetition());
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        long id = database.insert(DBHelper.TABLE_NAME_PROGRAM, null, contentValues);
        if (id != 1) {
            result = true;
        }
        database.close();

        return result;
    }
    //***************************************************

    // *******************************  SQLITE HELPER CLASS ******************
    private class DBHelper extends SQLiteOpenHelper {
        private final Context context;
        private static final String DATABASE_NAME = "PROGRAM_INFO";
        private static final String TABLE_NAME_PROGRAM = "PROGRAM";
        private static final int DATABASE_VERSION = 2;

        // FOOD
        private static final String COLUMN_ID_P = "PROG_ID_P";
        private static final String COLUM_NAME_P = "PROG_NAME_P";
        private static final String COLUM_DAY_P = "PROG_DAY_P";
        private static final String COLUMN_WEIGHT_P = "PROG_WEIGHT_P";
        private static final String COLUMN_SET_P = "PROG_SET_P";
        private static final String COLUMN_REPETITION_P = "PROG_REPETITION_P";

        private final String CREATE_TABLE_PROGRAM = "CREATE TABLE " + TABLE_NAME_PROGRAM +
                " (" + COLUMN_ID_P + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + COLUM_NAME_P + " TEXT, "
                + COLUM_DAY_P + " TEXT, "
                + COLUMN_WEIGHT_P + " INTEGER, "
                + COLUMN_SET_P + " INTEGER, "
                + COLUMN_REPETITION_P + " INTEGER)";

        private static final String DROP_TABLE_PROGRAM = "DROP TABLE IF EXIST " + TABLE_NAME_PROGRAM;

        public DBHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            this.context = context;
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_TABLE_PROGRAM);

            Util.showMessage(context, "Database Created");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL(DROP_TABLE_PROGRAM);
            Util.showMessage(context, "Database Upgrated");
            onCreate(db);
        }

        @Override
        public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            super.onDowngrade(db, oldVersion, newVersion);
        }
    }


}

Insert a background image in CSS (Twitter Bootstrap)

isn't the problem the following line is incorrect as the statement for background-repeat isn't closed before the next statement for display...

background-repeat:no-repeatdisplay: compact;

Shouldn't this be

background-repeat:no-repeat;
display: compact;

adding or removing quotes (in my experience) makes no difference if the URL is correct. Is the path to the image correct? If you give a relative path to a resource in a CSS it's relative to the CSS file, not the file including the CSS.

MySQL Database won't start in XAMPP Manager-osx

Minimal Guide

1. sudo killall mysqld

2. manager-osx > start mysql


If that didn't work...

sudo /Applications/XAMPP/xamppfiles/bin/mysql.server start

Google the error...


Examples:

Error:

ERROR! The server quit without updating PID file (/Applications/XAMPP/xamppfiles/var/mysql/<computername>.local.pid)

My Solution:

In /Applications/XAMPP/xamppfiles/etc/my.cnf change user = <uid> s that <uid> is uid from id command.

$ id
uid=...

$ vim /Applications/XAMPP/xamppfiles/etc/my.cnf
...

Collectors.toMap() keyMapper -- more succinct expression?

We can use an optional merger function also in case of same key collision. For example, If two or more persons have the same getLast() value, we can specify how to merge the values. If we not do this, we could get IllegalStateException. Here is the example to achieve this...

Map<String, Person> map = 
roster
    .stream()
    .collect(
        Collectors.toMap(p -> p.getLast(),
                         p -> p,
                         (person1, person2) -> person1+";"+person2)
    );

laravel the requested url was not found on this server

In addition to all the answers if you still encounter some variation of the problem, edit the .env file and set APP_URL to your domain name as in:

 APP_URL=similar_to_my_avatar_link 

How to use ES6 Fat Arrow to .filter() an array of objects

Here is my solution for those who use hook; If you are listing items in your grid and want to remove the selected item, you can use this solution.

var list = data.filter(form => form.id !== selectedRowDataId);
setData(list);

java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused)

Why this might have happened:

  1. The server couldn't send a response: Ensure that the backend is working properly at IP and port mentioned.
  2. SSL connections are being blocked: Fix this by importing SSL certificates

Less likely:

  1. Cookies not being sent
  2. Request timeout: Change request timeout

What is the http-header "X-XSS-Protection"?

X-XSS-Protection is a HTTP header understood by Internet Explorer 8 (and newer versions). This header lets domains toggle on and off the "XSS Filter" of IE8, which prevents some categories of XSS attacks. IE8 has the filter activated by default, but servers can switch if off by setting

   X-XSS-Protection: 0

See also http://blogs.msdn.com/b/ieinternals/archive/2011/01/31/controlling-the-internet-explorer-xss-filter-with-the-x-xss-protection-http-header.aspx

How to test for $null array in PowerShell

It's an array, so you're looking for Count to test for contents.

I'd recommend

$foo.count -gt 0

The "why" of this is related to how PSH handles comparison of collection objects

Python 3 Online Interpreter / Shell

I recently came across Python 3 interpreter at CompileOnline.

Possible to view PHP code of a website?

By using exploits or on badly configured servers it could be possible to download your PHP source. You could however either obfuscate and/or encrypt your code (using Zend Guard, Ioncube or a similar app) if you want to make sure your source will not be readable (to be accurate, obfuscation by itself could be reversed given enough time/resources, but I haven't found an IonCube or Zend Guard decryptor yet...).

Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'

Unfortunately, no approached mentioned here worked for me. I have to register couple PFX in a docker container and I need to pass the password via command line.

So I re-developed the sn.exe -i <infile> <container> command in C# using the RSACryptoServiceProvider. The source and the app are on GitHub in the SnInstallPfx project.

The SnInstallPfx app accepts a PFX key and its password. It computes the key container name (VS_KEY_*) automatically (borrowed from MSBuild source code) and installs it to the strong name CSP.

Usage:

SnInstallPfx.exe <pfx_infile> <pfx_password>
// or pass a container name if the default is not what you need (e.g. C++)
SnInstallPfx.exe <pfx_infile> <pfx_password> <container_name>

How can I do SELECT UNIQUE with LINQ?

Using query comprehension syntax you could achieve the orderby as follows:

var uniqueColors = (from dbo in database.MainTable
                    where dbo.Property
                    orderby dbo.Color.Name ascending
                    select dbo.Color.Name).Distinct();

Bootstrap date time picker

Try This:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
  <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>_x000D_
  <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.js"></script>_x000D_
  <script src="//cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/e8bddc60e73c1ec2475f827be36e1957af72e2ea/src/js/bootstrap-datetimepicker.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
_x000D_
<body>_x000D_
_x000D_
  <div class="container">_x000D_
    <div class="row">_x000D_
      <div class='col-sm-6'>_x000D_
        <div class="form-group">_x000D_
          <div class='input-group date' id='datetimepicker1'>_x000D_
            <input type='text' class="form-control" />_x000D_
            <span class="input-group-addon">_x000D_
                        <span class="glyphicon glyphicon-calendar"></span>_x000D_
            </span>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
      <script type="text/javascript">_x000D_
        $(function() {_x000D_
          $('#datetimepicker1').datetimepicker();_x000D_
        });_x000D_
      </script>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

PHP "php://input" vs $_POST

php://input can give you the raw bytes of the data. This is useful if the POSTed data is a JSON encoded structure, which is often the case for an AJAX POST request.

Here's a function to do just that:

  /**
   * Returns the JSON encoded POST data, if any, as an object.
   * 
   * @return Object|null
   */
  private function retrieveJsonPostData()
  {
    // get the raw POST data
    $rawData = file_get_contents("php://input");

    // this returns null if not valid json
    return json_decode($rawData);
  }

The $_POST array is more useful when you're handling key-value data from a form, submitted by a traditional POST. This only works if the POSTed data is in a recognised format, usually application/x-www-form-urlencoded (see http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4 for details).

Clear a terminal screen for real

Use the following command to do a clear screen instead of merely adding new lines ...

printf "\033c"

yes that's a 'printf' on the bash prompt.

You will probably want to define an alias though...

alias cls='printf "\033c"'

Explanation

\033 == \x1B == 27 == ESC

So this becomes <ESC>c which is the VT100 escape code for resetting the terminal. Here is some more information on terminal escape codes.

Edit

Here are a few other ways of doing it...

printf "\ec" #\e is ESC in bash
echo -en "\ec" #thanks @Jonathon Reinhart.
# -e    Enable interpretation of of backslash escapes
# -n    Do not output a new line

KDE

The above does not work on the KDE console (called Konsole) but there is hope! Use the following sequence of commands to clear the screen and the scroll-back buffer...

clear && echo -en "\e[3J"

Or perhaps use the following alias on KDE...

alias cls='clear && echo -en "\e[3J"'

I got the scroll-back clearing command from here.

Convert interface{} to int

You need to do type assertion for converting your interface{} to int value.

iAreaId := val.(int)
iAreaId, ok := val.(int)

More information is available.

How do I remove a comma off the end of a string?

have a look at the rtrim function

rtrim ($string , ",");

the above line will remove a char if the last char is a comma

How to install VS2015 Community Edition offline

You can download visual studio community edition with /layout switch.

But I prefer to use /layout with /NoRefresh for my low-speed internet connection that downloading long more than a day.

vs_community.exe /layout /NoRefresh

Every time that you run the installer it searches for new updates and if it finds updates, start downloading them and consume more time and more bandwidth!

Using iFrames In ASP.NET

try this

<iframe name="myIframe" id="myIframe" width="400px" height="400px" runat="server"></iframe>

Expose this iframe in the master page's codebehind:

public HtmlControl iframe
{
get
{
return this.myIframe;
}
}

Add the MasterType directive for the content page to strongly typed Master Page.

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits=_Default" Title="Untitled Page" %>
<%@ MasterType VirtualPath="~/MasterPage.master" %>

In code behind

protected void Page_Load(object sender, EventArgs e)
{
this.Master.iframe.Attributes.Add("src", "some.aspx");
}

How to declare an array of strings in C++?

One possiblity is to use a NULL pointer as a flag value:

const char *list[] = {"dog", "cat", NULL};
for (char **iList = list; *iList != NULL; ++iList)
{
    cout << *iList;
}

Overriding interface property type defined in Typescript d.ts file

NOTE: Not sure if the syntax I'm using in this answer was available when the older answers were written, but I think that this is a better approach on how to solve the example mentioned in this question.


I've had some issues related to this topic (overwriting interface properties), and this is how I'm handling it:

  1. First create a generic interface, with the possible types you'd like to use.

You can even use choose a default value for the generic parameter as you can see in <T extends number | SOME_OBJECT = number>

type SOME_OBJECT = { foo: "bar" }

interface INTERFACE_A <T extends number | SOME_OBJECT = number> {
  property: T;
}
  1. Then you can create new types based on that contract, by passing a value to the generic parameter (or omit it and use the default):
type A_NUMBER = INTERFACE_A;                   // USES THE default = number TYPE. SAME AS INTERFACE_A<number>
type A_SOME_OBJECT = INTERFACE_A<SOME_OBJECT>  // MAKES { property: SOME_OBJECT }

And this is the result:

const aNumber: A_NUMBER = {
    property: 111  // THIS EXPECTS A NUMBER
}

const anObject: A_SOME_OBJECT = {
    property: {   // THIS EXPECTS SOME_OBJECT
        foo: "bar"
    }
}

Typescript playground

How to enable external request in IIS Express?

As a sidenote to this:

netsh http add urlacl url=http://vaidesg:8080/ user=everyone

This will only work on English versions of Windows. If you are using a localized version you have to replace "everyone" with something else, for example:

  • "Iedereen" when using a Dutch version
  • "Jeder" when using a German version
  • "Mindenki" when using a Hungarian version

Otherwise you will get an error (Create SDDL failed, Error: 1332)

How to get the full URL of a Drupal page?

For Drupal 8 you can do this :

$url = 'YOUR_URL';
$url = \Drupal\Core\Url::fromUserInput('/' . $url,  array('absolute' => 'true'))->toString();

determine DB2 text string length

Mostly we write below statement select * from table where length(ltrim(rtrim(field)))=10;

How can I "disable" zoom on a mobile web page?

For those of you late to the party, kgutteridge's answer doesn't work for me and Benny Neugebauer's answer includes target-densitydpi (a feature that is being deprecated).

This however does work for me:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

Share application "link" in Android

Kotlin extension for share action. You can share whatever you want e.g. link

fun Context.share(text: String) =
    this.startActivity(Intent().apply {
        action = Intent.ACTION_SEND
        putExtra(Intent.EXTRA_TEXT, text)
        type = "text/plain"
    })

Usage

context.share("Check https://stackoverflow.com")

0xC0000005: Access violation reading location 0x00000000

This line looks suspicious:

invaders[i] = inv;

You're never incrementing i, so you keep assigning to invaders[0]. If this is just an error you made when reducing your code to the example, check how you calculate i in the real code; you could be exceeding the size of invaders.

If as your comment suggests, you're creating 55 invaders, then check that invaders has been initialised correctly to handle this number.

Difference between links and depends_on in docker_compose.yml

The post needs an update after the links option is deprecated.

Basically, links is no longer needed because its main purpose, making container reachable by another by adding environment variable, is included implicitly with network. When containers are placed in the same network, they are reachable by each other using their container name and other alias as host.

For docker run, --link is also deprecated and should be replaced by a custom network.

docker network create mynet
docker run -d --net mynet --name container1 my_image
docker run -it --net mynet --name container1 another_image

depends_on expresses start order (and implicitly image pulling order), which was a good side effect of links.

Two decimal places using printf( )

Use: "%.2f" or variations on that.

See the POSIX spec for an authoritative specification of the printf() format strings. Note that it separates POSIX extras from the core C99 specification. There are some C++ sites which show up in a Google search, but some at least have a dubious reputation, judging from comments seen elsewhere on SO.

Since you're coding in C++, you should probably be avoiding printf() and its relatives.

Efficient way to insert a number into a sorted array of numbers?

Very good and remarkable question with a very interesting discussion! I also was using the Array.sort() function after pushing a single element in an array with some thousands of objects.

I had to extend your locationOf function for my purpose because of having complex objects and therefore the need for a compare function like in Array.sort():

function locationOf(element, array, comparer, start, end) {
    if (array.length === 0)
        return -1;

    start = start || 0;
    end = end || array.length;
    var pivot = (start + end) >> 1;  // should be faster than dividing by 2

    var c = comparer(element, array[pivot]);
    if (end - start <= 1) return c == -1 ? pivot - 1 : pivot;

    switch (c) {
        case -1: return locationOf(element, array, comparer, start, pivot);
        case 0: return pivot;
        case 1: return locationOf(element, array, comparer, pivot, end);
    };
};

// sample for objects like {lastName: 'Miller', ...}
var patientCompare = function (a, b) {
    if (a.lastName < b.lastName) return -1;
    if (a.lastName > b.lastName) return 1;
    return 0;
};

Count all duplicates of each value

SELECT   col,
         COUNT(dupe_col) AS dupe_cnt
FROM     TABLE
GROUP BY col
HAVING   COUNT(dupe_col) > 1
ORDER BY COUNT(dupe_col) DESC

How can I work with command line on synology?

You can use your favourite telnet (not recommended) or ssh (recommended) application to connect to your Synology box and use it as a terminal.

  1. Enable the command line interface (CLI) from the Network Services
  2. Define the protocol and the user and make sure the user has password set
  3. Access the CLI

If you need more detailed instruction read https://www.synology.com/en-global/knowledgebase/DSM/help/DSM/AdminCenter/system_terminal

How to create an installer for a .net Windows Service using Visual Studio

In the service project do the following:

  1. In the solution explorer double click your services .cs file. It should bring up a screen that is all gray and talks about dragging stuff from the toolbox.
  2. Then right click on the gray area and select add installer. This will add an installer project file to your project.
  3. Then you will have 2 components on the design view of the ProjectInstaller.cs (serviceProcessInstaller1 and serviceInstaller1). You should then setup the properties as you need such as service name and user that it should run as.

Now you need to make a setup project. The best thing to do is use the setup wizard.

  1. Right click on your solution and add a new project: Add > New Project > Setup and Deployment Projects > Setup Wizard

    a. This could vary slightly for different versions of Visual Studio. b. Visual Studio 2010 it is located in: Install Templates > Other Project Types > Setup and Deployment > Visual Studio Installer

  2. On the second step select "Create a Setup for a Windows Application."

  3. On the 3rd step, select "Primary output from..."

  4. Click through to Finish.

Next edit your installer to make sure the correct output is included.

  1. Right click on the setup project in your Solution Explorer.
  2. Select View > Custom Actions. (In VS2008 it might be View > Editor > Custom Actions)
  3. Right-click on the Install action in the Custom Actions tree and select 'Add Custom Action...'
  4. In the "Select Item in Project" dialog, select Application Folder and click OK.
  5. Click OK to select "Primary output from..." option. A new node should be created.
  6. Repeat steps 4 - 5 for commit, rollback and uninstall actions.

You can edit the installer output name by right clicking the Installer project in your solution and select Properties. Change the 'Output file name:' to whatever you want. By selecting the installer project as well and looking at the properties windows, you can edit the Product Name, Title, Manufacturer, etc...

Next build your installer and it will produce an MSI and a setup.exe. Choose whichever you want to use to deploy your service.

How many threads is too many?

As many threads as the CPU cores is what I've heard very often.

How to fluently build JSON in Java?

See the Java EE 7 Json specification. This is the right way:

String json = Json.createObjectBuilder()
            .add("key1", "value1")
            .add("key2", "value2")
            .build()
            .toString();

How Do I Uninstall Yarn

Try this, it works well on macOS:

$ brew uninstall --force yarn
$ npm uninstall -g yarn
$ yarn -v

v0.24.5 (or your current version)

$ which yarn

/usr/local/bin/yarn

$ rm -rf /usr/local/bin/yarn
$ rm -rf /usr/local/bin/yarnpkg
$ which yarn

yarn not found

$ brew install yarn 
$ brew link yarn
$ yarn -v

v1.17.3 (latest version)

String isNullOrEmpty in Java?

For new projects, I've started having every class I write extend the same base class where I can put all the utility methods that are annoyingly missing from Java like this one, the equivalent for collections (tired of writing list != null && ! list.isEmpty()), null-safe equals, etc. I still use Apache Commons for the implementation but this saves a small amount of typing and I haven't seen any negative effects.

Calculate time difference in Windows batch file

@echo off

rem Get start time:
for /F "tokens=1-4 delims=:.," %%a in ("%time%") do (
   set /A "start=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)

rem Any process here...

rem Get end time:
for /F "tokens=1-4 delims=:.," %%a in ("%time%") do (
   set /A "end=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)

rem Get elapsed time:
set /A elapsed=end-start

rem Show elapsed time:
set /A hh=elapsed/(60*60*100), rest=elapsed%%(60*60*100), mm=rest/(60*100), rest%%=60*100, ss=rest/100, cc=rest%%100
if %mm% lss 10 set mm=0%mm%
if %ss% lss 10 set ss=0%ss%
if %cc% lss 10 set cc=0%cc%
echo %hh%:%mm%:%ss%,%cc%

EDIT 2017-05-09: Shorter method added

I developed a shorter method to get the same result, so I couldn't resist to post it here. The two for commands used to separate time parts and the three if commands used to insert leading zeros in the result are replaced by two long arithmetic expressions, that could even be combined into a single longer line.

The method consists in directly convert a variable with a time in "HH:MM:SS.CC" format into the formula needed to convert the time to centiseconds, accordingly to the mapping scheme given below:

       HH        :      MM        :      SS        .       CC

(((10  HH  %%100)*60+1  MM  %%100)*60+1  SS  %%100)*100+1  CC  %%100

That is, insert (((10 at beginning, replace the colons by %%100)*60+1, replace the point by %%100)*100+1 and insert %%100 at end; finally, evaluate the resulting string as an arithmetic expression. In the time variable there are two different substrings that needs to be replaced, so the conversion must be completed in two lines. To get an elapsed time, use (endTime)-(startTime) expression and replace both time strings in the same line.

EDIT 2017/06/14: Locale independent adjustment added

EDIT 2020/06/05: Pass-over-midnight adjustment added

@echo off
setlocal EnableDelayedExpansion

set "startTime=%time: =0%"

set /P "=Any process here..."

set "endTime=%time: =0%"



rem Get elapsed time:
set "end=!endTime:%time:~8,1%=%%100)*100+1!"  &  set "start=!startTime:%time:~8,1%=%%100)*100+1!"
set /A "elap=((((10!end:%time:~2,1%=%%100)*60+1!%%100)-((((10!start:%time:~2,1%=%%100)*60+1!%%100), elap-=(elap>>31)*24*60*60*100"

rem Convert elapsed time to HH:MM:SS:CC format:
set /A "cc=elap%%100+100,elap/=100,ss=elap%%60+100,elap/=60,mm=elap%%60+100,hh=elap/60+100"

echo Start:    %startTime%
echo End:      %endTime%
echo Elapsed:  %hh:~1%%time:~2,1%%mm:~1%%time:~2,1%%ss:~1%%time:~8,1%%cc:~1%

You may review a detailed explanation of this method at this answer.

rsync: difference between --size-only and --ignore-times

You are missing that rsync can also compare files by checksum.

--size-only means that rsync will skip files that match in size, even if the timestamps differ. This means it will synchronise fewer files than the default behaviour. It will miss any file with changes that don't affect the overall file size. If you have something that changes the dates on files without changing the files, and you don't want rsync to spend lots of time checksumming those files to discover they haven't changed, this is the option to use.

--ignore-times means that rsync will checksum every file, even if the timestamps and file sizes match. This means it will synchronise more files than the default behaviour. It will include changes to files even where the file size is the same and the modification date/time has been reset to the original value. Checksumming every file means it has to be entirely read from disk, which may be slow. Some build pipelines will reset timestamps to a specific date (like 1970-01-01) to ensure that the final build file is reproducible bit for bit, e.g. when packed into a tar file that saves the timestamps.

How to compare two List<String> to each other?

I discovered that SequenceEqual is not the most efficient way to compare two lists of strings (initially from http://www.dotnetperls.com/sequenceequal).

I wanted to test this myself so I created two methods:

    /// <summary>
    /// Compares two string lists using LINQ's SequenceEqual.
    /// </summary>
    public bool CompareLists1(List<string> list1, List<string> list2)
    {
        return list1.SequenceEqual(list2);
    }

    /// <summary>
    /// Compares two string lists using a loop.
    /// </summary>
    public bool CompareLists2(List<string> list1, List<string> list2)
    {
        if (list1.Count != list2.Count)
            return false;

        for (int i = 0; i < list1.Count; i++)
        {
            if (list1[i] != list2[i])
                return false;
        }

        return true;
    }

The second method is a bit of code I encountered and wondered if it could be refactored to be "easier to read." (And also wondered if LINQ optimization would be faster.)

As it turns out, with two lists containing 32k strings, over 100 executions:

  • Method 1 took an average of 6761.8 ticks
  • Method 2 took an average of 3268.4 ticks

I usually prefer LINQ for brevity, performance, and code readability; but in this case I think a loop-based method is preferred.

Edit:

I recompiled using optimized code, and ran the test for 1000 iterations. The results still favor the loop (even more so):

  • Method 1 took an average of 4227.2 ticks
  • Method 2 took an average of 1831.9 ticks

Tested using Visual Studio 2010, C# .NET 4 Client Profile on a Core i7-920

node.js - how to write an array to file

We can simply write the array data to the filesystem but this will raise one error in which ',' will be appended to the end of the file. To handle this below code can be used:

var fs = require('fs');

var file = fs.createWriteStream('hello.txt');
file.on('error', function(err) { Console.log(err) });
data.forEach(value => file.write(`${value}\r\n`));
file.end();

\r\n

is used for the new Line.

\n

won't help. Please refer this

Algorithm to randomly generate an aesthetically-pleasing color palette

Here is something I wrote for a site I made. It will auto-generate a random flat background-color for any div with the class .flat-color-gen. Jquery is only required for the purposes of adding css to the page; it's not required for the main part of this, which is the generateFlatColorWithOrder() method.

JsFiddle Link

(function($) {
    function generateFlatColorWithOrder(num, rr, rg, rb) {
        var colorBase = 256;
        var red = 0;
        var green = 0;
        var blue = 0;
        num = Math.round(num);
        num = num + 1;
        if (num != null) {

            red = (num*rr) % 256;
            green = (num*rg) % 256;
            blue = (num*rb) % 256;
        }
        var redString = Math.round((red + colorBase) / 2).toString();
        var greenString = Math.round((green + colorBase) / 2).toString();
        var blueString = Math.round((blue + colorBase) / 2).toString();
        return "rgb("+redString+", "+greenString+", "+blueString+")";
        //return '#' + redString + greenString + blueString;
    }

    function generateRandomFlatColor() {
        return generateFlatColorWithOrder(Math.round(Math.random()*127));
    }

    var rr = Math.round(Math.random()*1000);
    var rg = Math.round(Math.random()*1000);
    var rb = Math.round(Math.random()*1000);
    console.log("random red: "+ rr);
    console.log("random green: "+ rg);
    console.log("random blue: "+ rb);
    console.log("----------------------------------------------------");
    $('.flat-color-gen').each(function(i, obj) {
        console.log(generateFlatColorWithOrder(i));
        $(this).css("background-color",generateFlatColorWithOrder(i, rr, rg, rb).toString());
    });
})(window.jQuery);

How to programmatically move, copy and delete files and directories on SD?

Moving file using kotlin. App has to have permission to write a file in destination directory.

@Throws(FileNotFoundException::class, IOError::class)
private fun moveTo(source: File, dest: File, destDirectory: File? = null) {

    if (destDirectory?.exists() == false) {
        destDirectory.mkdir()
    }

    val fis = FileInputStream(source)
    val bufferLength = 1024
    val buffer = ByteArray(bufferLength)
    val fos = FileOutputStream(dest)
    val bos = BufferedOutputStream(fos, bufferLength)
    var read = fis.read(buffer, 0, read)
    while (read != -1) {
        bos.write(buffer, 0, read)
        read = fis.read(buffer) // if read value is -1, it escapes loop.
    }
    fis.close()
    bos.flush()
    bos.close()

    if (!source.delete()) {
        HLog.w(TAG, klass, "failed to delete ${source.name}")
    }
}

How to insert a value that contains an apostrophe (single quote)?

eduffy had a good idea. He just got it backwards in his code example. Either in JavaScript or in SQLite you can replace the apostrophe with the accent symbol.

He (accidentally I am sure) placed the accent symbol as the delimiter for the string instead of replacing the apostrophe in O'Brian. This is in fact a terrifically simple solution for most cases.

Boolean vs boolean in Java

Boolean is threadsafe, so you can consider this factor as well along with all other listed in answers

Default argument values in JavaScript functions

You have to check if the argument is undefined:

function func(a, b) {
    if (a === undefined) a = "default value";
    if (b === undefined) b = "default value";
}

Also note that this question has been answered before.

How to keep the header static, always on top while scrolling?

Use position: fixed on the div that contains your header, with something like

#header {
  position: fixed;
}

#content {
  margin-top: 100px;
}

In this example, when #content starts off 100px below #header, but as the user scrolls, #header stays in place. Of course it goes without saying that you'll want to make sure #header has a background so that its content will actually be visible when the two divs overlap. Have a look at the position property here: http://reference.sitepoint.com/css/position

C# - How to convert string to char?

Your question is a bit unclear, but I think you want (requires using System.Linq;):

var result = yourArrayOfStrings.SelectMany(s => s).ToArray();

Another solution is:

var result = string.Concat(yourArrayOfStrings).ToCharArray();

How do I get the current year using SQL on Oracle?

Yet another option would be:

SELECT * FROM mytable
 WHERE TRUNC(mydate, 'YEAR') = TRUNC(SYSDATE, 'YEAR');

socket connect() vs bind()

The one liner : bind() to own address, connect() to remote address.

Quoting from the man page of bind()

bind() assigns the address specified by addr to the socket referred to by the file descriptor sockfd. addrlen specifies the size, in bytes, of the address structure pointed to by addr. Traditionally, this operation is called "assigning a name to a socket".

and, from the same for connect()

The connect() system call connects the socket referred to by the file descriptor sockfd to the address specified by addr.

To clarify,

  • bind() associates the socket with its local address [that's why server side binds, so that clients can use that address to connect to server.]
  • connect() is used to connect to a remote [server] address, that's why is client side, connect [read as: connect to server] is used.

Is it still valid to use IE=edge,chrome=1?

It's still valid to use IE=edge,chrome=1.

But, since the chrome frame project has been wound down the chrome=1 part is redundant for browsers that don't already have the chrome frame plug in installed.

I use the following for correctness nowadays

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

Remove element by id

Shortest

I improve Sai Sunder answer because OP uses ID which allows to avoid getElementById:

elementId.remove();

_x000D_
_x000D_
box2.remove();          // remove BOX 2_x000D_
_x000D_
this["box-3"].remove(); // remove BOX 3 (for Id with 'minus' character)
_x000D_
<div id="box1">My BOX 1</div>_x000D_
<div id="box2">My BOX 2</div>_x000D_
<div id="box-3">My BOX 3</div>_x000D_
<div id="box4">My BOX 4</div>
_x000D_
_x000D_
_x000D_

How to revert a "git rm -r ."?

git reset HEAD

Should do it. If you don't have any uncommitted changes that you care about, then

git reset --hard HEAD

should forcibly reset everything to your last commit. If you do have uncommitted changes, but the first command doesn't work, then save your uncommitted changes with git stash:

git stash
git reset --hard HEAD
git stash pop

Convert PEM to PPK file format

  1. Save YourPEMFILE.pem to your .ssh directory
  2. Run puttygen from Command Prompt

    a. Click “Load” button to “Load an existing private key file”
    b. Change the file filter to “All Files (.)
    c. Select the YourPEMFILE.pem
    d. Click Open
    e. Puttygen shows a notice saying that it Successfully imported foreign key. Click OK.
    f. Click “Save private key” button
    g. When asked if you are sure that you want to save without a passphrase entered, answer “Yes”.
    h. Enter the file name YourPEMFILE.ppk
    i. Click “Save”

JSON Java 8 LocalDateTime format in Spring Boot

I found another solution which you can convert it to whatever format you want and apply to all LocalDateTime datatype and you do not have to specify @JsonFormat above every LocalDateTime datatype. first add the dependency :

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

Add the following bean :

@Configuration
public class Java8DateTimeConfiguration {
    /**
     * Customizing
     * http://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html
     *
     * Defining a @Bean of type Jackson2ObjectMapperBuilder will allow you to customize both default ObjectMapper and XmlMapper (used in MappingJackson2HttpMessageConverter and MappingJackson2XmlHttpMessageConverter respectively).
     */
    @Bean
    public Module jsonMapperJava8DateTimeModule() {
        val bean = new SimpleModule();

        bean.addDeserializer (ZonedDateTime.class, new JsonDeserializer<ZonedDateTime>() {
            @Override
            public ZonedDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
                return ZonedDateTime.parse(jsonParser.getValueAsString(), DateTimeFormatter.ISO_ZONED_DATE_TIME);
            }
        });

        bean.addDeserializer(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
            @Override
            public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
                return LocalDateTime.parse(jsonParser.getValueAsString(), DateTimeFormatter.ISO_LOCAL_DATE_TIME);
            }
        });

        bean.addSerializer(ZonedDateTime.class, new JsonSerializer<ZonedDateTime>() {
            @Override
            public void serialize(
                    ZonedDateTime zonedDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
                    throws IOException {
                jsonGenerator.writeString(DateTimeFormatter.ISO_ZONED_DATE_TIME.format(zonedDateTime));
            }
        });

        bean.addSerializer(LocalDateTime.class, new JsonSerializer<LocalDateTime>() {
            @Override
            public void serialize(
                    LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
                    throws IOException {
                jsonGenerator.writeString(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(localDateTime));
            }
        });

        return bean;
    }
}

in your config file add the following :

@Import(Java8DateTimeConfiguration.class)

This will serialize and de-serialize all properties LocalDateTime and ZonedDateTime as long as you are using objectMapper created by spring.

The format that you got for ZonedDateTime is : "2017-12-27T08:55:17.317+02:00[Asia/Jerusalem]" for LocalDateTime is : "2017-12-27T09:05:30.523"

jQuery 'input' event

As claustrofob said, oninput is supported for IE9+.

However, "The oninput event is buggy in Internet Explorer 9. It is not fired when characters are deleted from a text field through the user interface only when characters are inserted. Although the onpropertychange event is supported in Internet Explorer 9, but similarly to the oninput event, it is also buggy, it is not fired on deletion.

Since characters can be deleted in several ways (Backspace and Delete keys, CTRL + X, Cut and Delete command in context menu), there is no good solution to detect all changes. If characters are deleted by the Delete command of the context menu, the modification cannot be detected in JavaScript in Internet Explorer 9."

I have good results binding to both input and keyup (and keydown, if you want it to fire in IE while holding down the Backspace key).

Rails 4 - passing variable to partial

ou are able to create local variables once you call the render function on a partial, therefore if you want to customize a partial you can for example render the partial _form.html.erb by:

<%= render 'form', button_label: "Create New Event", url: new_event_url %>
<%= render 'form', button_label: "Update Event", url: edit_event_url %>

this way you can access in the partial to the label for the button and the URL, those are different if you try to create or update a record. finally, for accessing to this local variables you have to put in your code local_assigns[:button_label] (local_assigns[:name_of_your_variable])

<%=form_for(@event, url: local_assigns[:url]) do |f|  %>
<%= render 'shared/error_messages_events' %>
<%= f.label :title ,"Title"%>
  <%= f.text_field :title, class: 'form-control'%>
  <%=f.label :date, "Date"%>
  <%=f.date_field :date, class: 'form-control'  %>
  <%=f.label :description, "Description"%>
  <%=f.text_area :description, class: 'form-control'  %>
  <%= f.submit local_assigns[:button_label], class:"btn btn-primary"%>
<%end%>

Generate a random point within a circle (uniformly)

1) Choose a random X between -1 and 1.

var X:Number = Math.random() * 2 - 1;

2) Using the circle formula, calculate the maximum and minimum values of Y given that X and a radius of 1:

var YMin:Number = -Math.sqrt(1 - X * X);
var YMax:Number = Math.sqrt(1 - X * X);

3) Choose a random Y between those extremes:

var Y:Number = Math.random() * (YMax - YMin) + YMin;

4) Incorporate your location and radius values in the final value:

var finalX:Number = X * radius + pos.x;
var finalY:Number = Y * radois + pos.y;

How to write text in ipython notebook?

Change the cell type to Markdown in the menu bar, from Code to Markdown. Currently in Notebook 4.x, the keyboard shortcut for such an action is: Esc (for command mode), then m (for markdown).

What HTTP traffic monitor would you recommend for Windows?

Fiddler is great when you are only interested in the http(s) side of the communications. It is also very useful when you are trying to inspect inside a https stream.

Make page to tell browser not to cache/preserve input values

Basically, there are two ways to clear the cache:

<form autocomplete="off"></form>

or

$('#Textfiledid').attr('autocomplete', 'off');

How do I change the default library path for R packages

Windows 10 on a Network

Having your packages stored on the network drive can slow down the performance of R / R Studio considerably, and you spend a lot of time waiting for the libraries to load/install, due to the bottlenecks of having to retrieve and push data over the server back to your local host. See the following for instructions on how to create an .RProfile on your local machine:

  1. Create a directory called C:\Users\xxxxxx\Documents\R\3.4 (or whatever R version you are using, and where you will store your local R packages- your directory location may be different than mine)
  2. On R Console, type Sys.getenv("HOME") to get your home directory (this is where your .RProfile will be stored and R will always check there for packages- and this is on the network if packages are stored there)
  3. Create a file called .Rprofile and place it in :\YOUR\HOME\DIRECTORY\ON_NETWORK (the directory you get after typing Sys.getenv("HOME") in R Console)
  4. File contents of .Rprofile should be like this:

#search 2 places for packages- install new packages to first directory- load built-in packages from the second (this is from your base R package- will be different for some)

.libPaths(c("C:\Users\xxxxxx\Documents\R\3.4", "C:/Program Files/Microsoft/R Client/R_SERVER/library"))

message("*** Setting libPath to local hard drive ***")

#insert a sleep command at line 12 of the unpackPkgZip function. So, just after the package is unzipped.

trace(utils:::unpackPkgZip, quote(Sys.sleep(2)), at=12L, print=TRUE)

message("*** Add 2 second delay when installing packages, to accommodate virus scanner for R 3.4 (fixed in R 3.5+)***")

# fix problem with tcltk for sqldf package: https://github.com/ggrothendieck/sqldf#problem-involvling-tcltk

options(gsubfn.engine = "R")

message("*** Successfully loaded .Rprofile ***")
  1. Restart R Studio and verify that you see that the messages above are displayed.

Now you can enjoy faster performance of your application on local host, vs. storing the packages on the network and slowing everything down.

Determine a string's encoding in C#

Note: this was an experiment to see how UTF-8 encoding worked internally. The solution offered by vilicvane, to use a UTF8Encoding object that is initialised to throw an exception on decoding failure, is much simpler, and basically does the same thing.


I wrote this piece of code to differentiate between UTF-8 and Windows-1252. It shouldn't be used for gigantic text files though, since it loads the entire thing into memory and scans it completely. I used it for .srt subtitle files, just to be able to save them back in the encoding in which they were loaded.

The encoding given to the function as ref should be the 8-bit fallback encoding to use in case the file is detected as not being valid UTF-8; generally, on Windows systems, this will be Windows-1252. This doesn't do anything fancy like checking actual valid ascii ranges though, and doesn't detect UTF-16 even on byte order mark.

The theory behind the bitwise detection can be found here: https://ianthehenry.com/2015/1/17/decoding-utf-8/

Basically, the bit range of the first byte determines how many after it are part of the UTF-8 entity. These bytes after it are always in the same bit range.

/// <summary>
/// Reads a text file, and detects whether its encoding is valid UTF-8 or ascii.
/// If not, decodes the text using the given fallback encoding.
/// Bit-wise mechanism for detecting valid UTF-8 based on
/// https://ianthehenry.com/2015/1/17/decoding-utf-8/
/// </summary>
/// <param name="docBytes">The bytes read from the file.</param>
/// <param name="encoding">The default encoding to use as fallback if the text is detected not to be pure ascii or UTF-8 compliant. This ref parameter is changed to the detected encoding.</param>
/// <returns>The contents of the read file, as String.</returns>
public static String ReadFileAndGetEncoding(Byte[] docBytes, ref Encoding encoding)
{
    if (encoding == null)
        encoding = Encoding.GetEncoding(1252);
    Int32 len = docBytes.Length;
    // byte order mark for utf-8. Easiest way of detecting encoding.
    if (len > 3 && docBytes[0] == 0xEF && docBytes[1] == 0xBB && docBytes[2] == 0xBF)
    {
        encoding = new UTF8Encoding(true);
        // Note that even when initialising an encoding to have
        // a BOM, it does not cut it off the front of the input.
        return encoding.GetString(docBytes, 3, len - 3);
    }
    Boolean isPureAscii = true;
    Boolean isUtf8Valid = true;
    for (Int32 i = 0; i < len; ++i)
    {
        Int32 skip = TestUtf8(docBytes, i);
        if (skip == 0)
            continue;
        if (isPureAscii)
            isPureAscii = false;
        if (skip < 0)
        {
            isUtf8Valid = false;
            // if invalid utf8 is detected, there's no sense in going on.
            break;
        }
        i += skip;
    }
    if (isPureAscii)
        encoding = new ASCIIEncoding(); // pure 7-bit ascii.
    else if (isUtf8Valid)
        encoding = new UTF8Encoding(false);
    // else, retain given encoding. This should be an 8-bit encoding like Windows-1252.
    return encoding.GetString(docBytes);
}

/// <summary>
/// Tests if the bytes following the given offset are UTF-8 valid, and
/// returns the amount of bytes to skip ahead to do the next read if it is.
/// If the text is not UTF-8 valid it returns -1.
/// </summary>
/// <param name="binFile">Byte array to test</param>
/// <param name="offset">Offset in the byte array to test.</param>
/// <returns>The amount of bytes to skip ahead for the next read, or -1 if the byte sequence wasn't valid UTF-8</returns>
public static Int32 TestUtf8(Byte[] binFile, Int32 offset)
{
    // 7 bytes (so 6 added bytes) is the maximum the UTF-8 design could support,
    // but in reality it only goes up to 3, meaning the full amount is 4.
    const Int32 maxUtf8Length = 4;
    Byte current = binFile[offset];
    if ((current & 0x80) == 0)
        return 0; // valid 7-bit ascii. Added length is 0 bytes.
    Int32 len = binFile.Length;
    for (Int32 addedlength = 1; addedlength < maxUtf8Length; ++addedlength)
    {
        Int32 fullmask = 0x80;
        Int32 testmask = 0;
        // This code adds shifted bits to get the desired full mask.
        // If the full mask is [111]0 0000, then test mask will be [110]0 0000. Since this is
        // effectively always the previous step in the iteration I just store it each time.
        for (Int32 i = 0; i <= addedlength; ++i)
        {
            testmask = fullmask;
            fullmask += (0x80 >> (i+1));
        }
        // figure out bit masks from level
        if ((current & fullmask) == testmask)
        {
            if (offset + addedlength >= len)
                return -1;
            // Lookahead. Pattern of any following bytes is always 10xxxxxx
            for (Int32 i = 1; i <= addedlength; ++i)
            {
                if ((binFile[offset + i] & 0xC0) != 0x80)
                    return -1;
            }
            return addedlength;
        }
    }
    // Value is greater than the maximum allowed for utf8. Deemed invalid.
    return -1;
}

JavaScript single line 'if' statement - best syntax, this alternative?

As a lot of people have said, if you're looking for an actual 1 line if then:

    if (Boolean_expression) do.something();

is preferred. However, if you're looking to do an if/else then ternary is your friend (and also super cool):

    (Boolean_expression) ? do.somethingForTrue() : do.somethingForFalse();

ALSO:

    var something = (Boolean_expression) ? trueValueHardware : falseATRON;

However, I saw one very cool example. Shouts to @Peter-Oslson for &&

    (Boolean_expression) && do.something();

Lastly, it's not an if statement but executing things in a loop with either a map/reduce or Promise.resolve() is fun too. Shouts to @brunettdan

Increasing the maximum post size

; Maximum allowed size for uploaded files.
upload_max_filesize = 40M

; Must be greater than or equal to upload_max_filesize
post_max_size = 40M

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

In my case updating buildToolsVersion in app level build.gradle worked perfectly. If you don't know which to use you can create new project and copy buildToolsVersion from that into existing one.

Difference between <context:annotation-config> and <context:component-scan>

<context:annotation-config>: Scanning and activating annotations for already registered beans in spring config xml.

<context:component-scan>: Bean registration + <context:annotation-config>


@Autowired and @Required are targets property level so bean should register in spring IOC before use these annotations. To enable these annotations either have to register respective beans or include <context:annotation-config />. i.e. <context:annotation-config /> works with registered beans only.

@Required enables RequiredAnnotationBeanPostProcessor processing tool
@Autowired enables AutowiredAnnotationBeanPostProcessor processing tool

Note: Annotation itself nothing to do, we need a Processing Tool, which is a class underneath, responsible for the core process.


@Repository, @Service and @Controller are @Component, and they targets class level.

<context:component-scan> it scans the package and find and register the beans, and it includes the work done by <context:annotation-config />.

Migrating XML to Annotations

Docker: Container keeps on restarting again on again

Check the partition where you have installed docker. In most cases, the partition is at 100% capacity so you may need to look into that.

Global keyboard capture in C# application

Here's my code that works:

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace SnagFree.TrayApp.Core
{
    class GlobalKeyboardHookEventArgs : HandledEventArgs
    {
        public GlobalKeyboardHook.KeyboardState KeyboardState { get; private set; }
        public GlobalKeyboardHook.LowLevelKeyboardInputEvent KeyboardData { get; private set; }

        public GlobalKeyboardHookEventArgs(
            GlobalKeyboardHook.LowLevelKeyboardInputEvent keyboardData,
            GlobalKeyboardHook.KeyboardState keyboardState)
        {
            KeyboardData = keyboardData;
            KeyboardState = keyboardState;
        }
    }

    //Based on https://gist.github.com/Stasonix
    class GlobalKeyboardHook : IDisposable
    {
        public event EventHandler<GlobalKeyboardHookEventArgs> KeyboardPressed;

        public GlobalKeyboardHook()
        {
            _windowsHookHandle = IntPtr.Zero;
            _user32LibraryHandle = IntPtr.Zero;
            _hookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.

            _user32LibraryHandle = LoadLibrary("User32");
            if (_user32LibraryHandle == IntPtr.Zero)
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new Win32Exception(errorCode, $"Failed to load library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
            }



            _windowsHookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, _hookProc, _user32LibraryHandle, 0);
            if (_windowsHookHandle == IntPtr.Zero)
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new Win32Exception(errorCode, $"Failed to adjust keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
            }
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                // because we can unhook only in the same thread, not in garbage collector thread
                if (_windowsHookHandle != IntPtr.Zero)
                {
                    if (!UnhookWindowsHookEx(_windowsHookHandle))
                    {
                        int errorCode = Marshal.GetLastWin32Error();
                        throw new Win32Exception(errorCode, $"Failed to remove keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
                    }
                    _windowsHookHandle = IntPtr.Zero;

                    // ReSharper disable once DelegateSubtraction
                    _hookProc -= LowLevelKeyboardProc;
                }
            }

            if (_user32LibraryHandle != IntPtr.Zero)
            {
                if (!FreeLibrary(_user32LibraryHandle)) // reduces reference to library by 1.
                {
                    int errorCode = Marshal.GetLastWin32Error();
                    throw new Win32Exception(errorCode, $"Failed to unload library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
                }
                _user32LibraryHandle = IntPtr.Zero;
            }
        }

        ~GlobalKeyboardHook()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private IntPtr _windowsHookHandle;
        private IntPtr _user32LibraryHandle;
        private HookProc _hookProc;

        delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll")]
        private static extern IntPtr LoadLibrary(string lpFileName);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern bool FreeLibrary(IntPtr hModule);

        /// <summary>
        /// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
        /// You would install a hook procedure to monitor the system for certain types of events. These events are
        /// associated either with a specific thread or with all threads in the same desktop as the calling thread.
        /// </summary>
        /// <param name="idHook">hook type</param>
        /// <param name="lpfn">hook procedure</param>
        /// <param name="hMod">handle to application instance</param>
        /// <param name="dwThreadId">thread identifier</param>
        /// <returns>If the function succeeds, the return value is the handle to the hook procedure.</returns>
        [DllImport("USER32", SetLastError = true)]
        static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);

        /// <summary>
        /// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
        /// </summary>
        /// <param name="hhk">handle to hook procedure</param>
        /// <returns>If the function succeeds, the return value is true.</returns>
        [DllImport("USER32", SetLastError = true)]
        public static extern bool UnhookWindowsHookEx(IntPtr hHook);

        /// <summary>
        /// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
        /// A hook procedure can call this function either before or after processing the hook information.
        /// </summary>
        /// <param name="hHook">handle to current hook</param>
        /// <param name="code">hook code passed to hook procedure</param>
        /// <param name="wParam">value passed to hook procedure</param>
        /// <param name="lParam">value passed to hook procedure</param>
        /// <returns>If the function succeeds, the return value is true.</returns>
        [DllImport("USER32", SetLastError = true)]
        static extern IntPtr CallNextHookEx(IntPtr hHook, int code, IntPtr wParam, IntPtr lParam);

        [StructLayout(LayoutKind.Sequential)]
        public struct LowLevelKeyboardInputEvent
        {
            /// <summary>
            /// A virtual-key code. The code must be a value in the range 1 to 254.
            /// </summary>
            public int VirtualCode;

            /// <summary>
            /// A hardware scan code for the key. 
            /// </summary>
            public int HardwareScanCode;

            /// <summary>
            /// The extended-key flag, event-injected Flags, context code, and transition-state flag. This member is specified as follows. An application can use the following values to test the keystroke Flags. Testing LLKHF_INJECTED (bit 4) will tell you whether the event was injected. If it was, then testing LLKHF_LOWER_IL_INJECTED (bit 1) will tell you whether or not the event was injected from a process running at lower integrity level.
            /// </summary>
            public int Flags;

            /// <summary>
            /// The time stamp stamp for this message, equivalent to what GetMessageTime would return for this message.
            /// </summary>
            public int TimeStamp;

            /// <summary>
            /// Additional information associated with the message. 
            /// </summary>
            public IntPtr AdditionalInformation;
        }

        public const int WH_KEYBOARD_LL = 13;
        //const int HC_ACTION = 0;

        public enum KeyboardState
        {
            KeyDown = 0x0100,
            KeyUp = 0x0101,
            SysKeyDown = 0x0104,
            SysKeyUp = 0x0105
        }

        public const int VkSnapshot = 0x2c;
        //const int VkLwin = 0x5b;
        //const int VkRwin = 0x5c;
        //const int VkTab = 0x09;
        //const int VkEscape = 0x18;
        //const int VkControl = 0x11;
        const int KfAltdown = 0x2000;
        public const int LlkhfAltdown = (KfAltdown >> 8);

        public IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam)
        {
            bool fEatKeyStroke = false;

            var wparamTyped = wParam.ToInt32();
            if (Enum.IsDefined(typeof(KeyboardState), wparamTyped))
            {
                object o = Marshal.PtrToStructure(lParam, typeof(LowLevelKeyboardInputEvent));
                LowLevelKeyboardInputEvent p = (LowLevelKeyboardInputEvent)o;

                var eventArguments = new GlobalKeyboardHookEventArgs(p, (KeyboardState)wparamTyped);

                EventHandler<GlobalKeyboardHookEventArgs> handler = KeyboardPressed;
                handler?.Invoke(this, eventArguments);

                fEatKeyStroke = eventArguments.Handled;
            }

            return fEatKeyStroke ? (IntPtr)1 : CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
        }
    }
}

Usage:

using System;
using System.Windows.Forms;

namespace SnagFree.TrayApp.Core
{
    internal class Controller : IDisposable
    {
        private GlobalKeyboardHook _globalKeyboardHook;

        public void SetupKeyboardHooks()
        {
            _globalKeyboardHook = new GlobalKeyboardHook();
            _globalKeyboardHook.KeyboardPressed += OnKeyPressed;
        }

        private void OnKeyPressed(object sender, GlobalKeyboardHookEventArgs e)
        {
            //Debug.WriteLine(e.KeyboardData.VirtualCode);

            if (e.KeyboardData.VirtualCode != GlobalKeyboardHook.VkSnapshot)
                return;

            // seems, not needed in the life.
            //if (e.KeyboardState == GlobalKeyboardHook.KeyboardState.SysKeyDown &&
            //    e.KeyboardData.Flags == GlobalKeyboardHook.LlkhfAltdown)
            //{
            //    MessageBox.Show("Alt + Print Screen");
            //    e.Handled = true;
            //}
            //else

            if (e.KeyboardState == GlobalKeyboardHook.KeyboardState.KeyDown)
            {
                MessageBox.Show("Print Screen");
                e.Handled = true;
            }
        }

        public void Dispose()
        {
            _globalKeyboardHook?.Dispose();
        }
    }
}

C# Linq Group By on multiple columns

Given a list:

var list = new List<Child>()
{
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "John"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Bob", Name = "Pete"},
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "Fred"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Fred", Name = "Bob"},
};

The query would look like:

var newList = list
    .GroupBy(x => new {x.School, x.Friend, x.FavoriteColor})
    .Select(y => new ConsolidatedChild()
        {
            FavoriteColor = y.Key.FavoriteColor,
            Friend = y.Key.Friend,
            School = y.Key.School,
            Children = y.ToList()
        }
    );

Test code:

foreach(var item in newList)
{
    Console.WriteLine("School: {0} FavouriteColor: {1} Friend: {2}", item.School,item.FavoriteColor,item.Friend);
    foreach(var child in item.Children)
    {
        Console.WriteLine("\t Name: {0}", child.Name);
    }
}

Result:

School: School1 FavouriteColor: blue Friend: Bob
    Name: John
    Name: Fred
School: School2 FavouriteColor: blue Friend: Bob
    Name: Pete
School: School2 FavouriteColor: blue Friend: Fred
    Name: Bob

Creating a "Hello World" WebSocket example

WebSockets is protocol that relies on TCP streamed connection. Although WebSockets is Message based protocol.

If you want to implement your own protocol then I recommend to use latest and stable specification (for 18/04/12) RFC 6455. This specification contains all necessary information regarding handshake and framing. As well most of description on scenarios of behaving from browser side as well as from server side. It is highly recommended to follow what recommendations tells regarding server side during implementing of your code.

In few words, I would describe working with WebSockets like this:

  1. Create server Socket (System.Net.Sockets) bind it to specific port, and keep listening with asynchronous accepting of connections. Something like that:

    Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
    serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
    serverSocket.Listen(128);
    serverSocket.BeginAccept(null, 0, OnAccept, null);
  2. You should have accepting function "OnAccept" that will implement handshake. In future it has to be in another thread if system is meant to handle huge amount of connections per second.

    private void OnAccept(IAsyncResult result) {
    try {
        Socket client = null;
        if (serverSocket != null && serverSocket.IsBound) {
            client = serverSocket.EndAccept(result);
        }
        if (client != null) {
            /* Handshaking and managing ClientSocket */
        }
    } catch(SocketException exception) {
    
    } finally {
        if (serverSocket != null && serverSocket.IsBound) {
            serverSocket.BeginAccept(null, 0, OnAccept, null);
        }
    }
    }
  3. After connection established, you have to do handshake. Based on specification 1.3 Opening Handshake, after connection established you will receive basic HTTP request with some information. Example:

    GET /chat HTTP/1.1
    Host: server.example.com
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
    Origin: http://example.com
    Sec-WebSocket-Protocol: chat, superchat
    Sec-WebSocket-Version: 13

    This example is based on version of protocol 13. Bear in mind that older versions have some differences but mostly latest versions are cross-compatible. Different browsers may send you some additional data. For example Browser and OS details, cache and others.

    Based on provided handshake details, you have to generate answer lines, they are mostly same, but will contain Accpet-Key, that is based on provided Sec-WebSocket-Key. In specification 1.3 it is described clearly how to generate response key. Here is my function I've been using for V13:

    static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    private string AcceptKey(ref string key) {
        string longKey = key + guid;
        SHA1 sha1 = SHA1CryptoServiceProvider.Create();
        byte[] hashBytes = sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(longKey));
        return Convert.ToBase64String(hashBytes);
    }
    

    Handshake answer looks like that:

    HTTP/1.1 101 Switching Protocols
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

    But accept key have to be the generated one based on provided key from client and method AcceptKey I provided before. As well, make sure after last character of accept key you put two new lines "\r\n\r\n".

  4. After handshake answer is sent from server, client should trigger "onopen" function, that means you can send messages after.
  5. Messages are not sent in raw format, but they have Data Framing. And from client to server as well implement masking for data based on provided 4 bytes in message header. Although from server to client you don't need to apply masking over data. Read section 5. Data Framing in specification. Here is copy-paste from my own implementation. It is not ready-to-use code, and have to be modified, I am posting it just to give an idea and overall logic of read/write with WebSocket framing. Go to this link.
  6. After framing is implemented, make sure that you receive data right way using sockets. For example to prevent that some messages get merged into one, because TCP is still stream based protocol. That means you have to read ONLY specific amount of bytes. Length of message is always based on header and provided data length details in header it self. So when you receiving data from Socket, first receive 2 bytes, get details from header based on Framing specification, then if mask provided another 4 bytes, and then length that might be 1, 4 or 8 bytes based on length of data. And after data it self. After you read it, apply demasking and your message data is ready to use.
  7. You might want to use some Data Protocol, I recommend to use JSON due traffic economy and easy to use on client side in JavaScript. For server side you might want to check some of parsers. There is lots of them, google can be really helpful.

Implementing own WebSockets protocol definitely have some benefits and great experience you get as well as control over protocol it self. But you have to spend some time doing it, and make sure that implementation is highly reliable.

In same time you might have a look in ready to use solutions that google (again) have enough.

Extract the first word of a string in a SQL Server query

A slight tweak to the function returns the next word from a start point in the entry

    CREATE FUNCTION [dbo].[GetWord] 
    (
        @value varchar(max)
        , @startLocation int
    ) 
    RETURNS varchar(max) 
    AS 
      BEGIN 

         SET @value = LTRIM(RTRIM(@Value))  
         SELECT @startLocation = 
                CASE 
                    WHEN @startLocation > Len(@value) THEN LEN(@value) 
                    ELSE @startLocation 
                END

            SELECT @value = 
                CASE 
                    WHEN @startLocation > 1 
                        THEN LTRIM(RTRIM(RIGHT(@value, LEN(@value) - @startLocation)))
                    ELSE @value
                END

            RETURN CASE CHARINDEX(' ', @value, 1) 
                    WHEN 0 THEN @value 
                    ELSE SUBSTRING(@value, 1, CHARINDEX(' ', @value, 1) - 1) 
                END

     END 
    GO

    SELECT dbo.GetWord(NULL, 1) 
    SELECT dbo.GetWord('', 1) 
    SELECT dbo.GetWord('abc', 1) 
    SELECT dbo.GetWord('abc def', 4) 
    SELECT dbo.GetWord('abc def ghi', 20) 

TypeError: list indices must be integers or slices, not str

First, array_length should be an integer and not a string:

array_length = len(array_dates)

Second, your for loop should be constructed using range:

for i in range(array_length):  # Use `xrange` for python 2.

Third, i will increment automatically, so delete the following line:

i += 1

Note, one could also just zip the two lists given that they have the same length:

import csv

dates = ['2020-01-01', '2020-01-02', '2020-01-03']
urls = ['www.abc.com', 'www.cnn.com', 'www.nbc.com']

csv_file_patch = '/path/to/filename.csv'

with open(csv_file_patch, 'w') as fout:
    csv_file = csv.writer(fout, delimiter=';', lineterminator='\n')
    result_array = zip(dates, urls)
    csv_file.writerows(result_array)

The opposite of Intersect()

array1.NonIntersect(array2);

Nonintersect such operator is not present in Linq you should do

except -> union -> except

a.except(b).union(b.Except(a));

Using find command in bash script

You can use this:

list=$(find /home/user/Desktop -name '*.pdf' -o -name '*.txt' -o -name '*.bmp')

Besides, you might want to use -iname instead of -name to catch files with ".PDF" (upper-case) extension as well.

Submit form without page reloading

You'll need to submit an ajax request to send the email without reloading the page. Take a look at http://api.jquery.com/jQuery.ajax/

Your code should be something along the lines of:

$('#submit').click(function() {
    $.ajax({
        url: 'send_email.php',
        type: 'POST',
        data: {
            email: '[email protected]',
            message: 'hello world!'
        },
        success: function(msg) {
            alert('Email Sent');
        }               
    });
});

The form will submit in the background to the send_email.php page which will need to handle the request and send the email.

How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?

If your are using ViewPager2 you just have to use:

viewpager.setUserInputEnabled(false);

From the docs:

Enable or disable user initiated scrolling. This includes touch input (scroll and fling gestures) and accessibility input. Disabling keyboard input is not yet supported. When user initiated scrolling is disabled, programmatic scrolls through setCurrentItem still work. By default, user initiated scrolling is enabled.

Thanks to: https://stackoverflow.com/a/61685871/9026710

Sleep function in ORACLE

It would be better to implement a synchronization mechanism. The easiest is to write a file after the first file is complete. So you have a sentinel file.

So the external programs looks for the sentinel file to exist. When it does it knows that it can safely use the data in the real file.

Another way to do this, which is similar to how some browsers do it when downloading files, is to have the file named base-name_part until the file is completely downloaded and then at the end rename the file to base-name. This way the external program can't "see" the file until it is complete. This way wouldn't require rewrite of the external program. Which might make it best for this situation.

Which is the fastest algorithm to find prime numbers?

Rabin-Miller is a standard probabilistic primality test. (you run it K times and the input number is either definitely composite, or it is probably prime with probability of error 4-K. (a few hundred iterations and it's almost certainly telling you the truth)

There is a non-probabilistic (deterministic) variant of Rabin Miller.

The Great Internet Mersenne Prime Search (GIMPS) which has found the world's record for largest proven prime (274,207,281 - 1 as of June 2017), uses several algorithms, but these are primes in special forms. However the GIMPS page above does include some general deterministic primality tests. They appear to indicate that which algorithm is "fastest" depends upon the size of the number to be tested. If your number fits in 64 bits then you probably shouldn't use a method intended to work on primes of several million digits.

How to get an input text value in JavaScript

Do not use global variables in this way. Even if this could work, it's bad programming style. You can inadvertently overwrite important data in this way. Do this instead:

<script type="text/javascript">
   function kk(){
       var lol = document.getElementById('lolz').value;
       alert(lol);
   }
</script>

If you insist var lol to be set outside the function kk, then I propose this solution:

<body>
    <input type="text" name="enter" class="enter" value="" id="lolz"/>
    <input type="button" value="click" OnClick="kk()"/>
    <script type="text/javascript">
       var lol = document.getElementById('lolz');
       function kk() {
           alert(lol.value);
       }
    </script>
</body>

Note that the script element must follow the input element it refers to, because elements are only queryable with getElementById if they already have been parsed and created.

Both examples work, tested in jsfiddler.

Edit: I removed the language="javascript" attribute, because it's deprecated. See W3 HTML4 Specification, the SCRIPT element:

language = cdata [CI]

Deprecated. This attribute specifies the scripting language of the contents of this element. Its value is an identifier for the language, but since these identifiers are not standard, this attribute has been deprecated in favor of type.

and

A deprecated element or attribute is one that has been outdated by newer constructs. […] Deprecated elements may become obsolete in future versions of HTML. […] This specification includes examples that illustrate how to avoid using deprecated elements. […]

"Cannot evaluate expression because the code of the current method is optimized" in Visual Studio 2010

It sounds like you are debugging an optimised / release build, despite having the optimised box un-checked. Things you can try are:

  • Do a complete rebuild of your solution file (right click on the solution and select Rebuild all)
  • While debugging open up the modules window (Debug -> Windows -> Modules) and find your assembly in the list of loaded modules. Check that the Path listed against your loaded assembly is what you expect it to be, and that the modified timestamp of the file indicates that the assembly was actually rebuilt.
  • The modules window should also tell you whether or not the loaded module is optimised or not - make sure that the modules window indicates that it is not optimised.

If you cant't see the Modules menu item in the Debug -> Windows menu then you may need to add it in the "Customise..." menu.

integrating barcode scanner into php application?

You can use AJAX for that. Whenever you scan a barcode, your scanner will act as if it is a keyboard typing into your input type="text" components. With JavaScript, capture the corresponding event, and send HTTP REQUEST and process responses accordingly.

How to add parameters into a WebRequest?

For doing FORM posts, the best way is to use WebClient.UploadValues() with a POST method.

Attach the Source in Eclipse of a jar

I have faced same problem and resolved it by using following scenario.

1 ) First we have to determine which jar file's source code we want along with version number. For Example "Spring Core » 4.0.6.RELEASE" 2 ) open https://mvnrepository.com/ and search file with name "Spring Core » 4.0.6.RELEASE". 3 ) Now Maven repository will show the the details of that jar file. 4 ) In that details there is one option "View All" just click on that. 5 ) Then we will navigate to URL "https://repo1.maven.org/maven2/org/springframework/spring-core/4.0.6.RELEASE/".

6) there so many options so select and download "spring-core-4.0.6.RELEASE-sources.jar " in our our system and attach same jar file as a source attachment in eclipse.

Is there any way to do HTTP PUT in python

You can use the requests library, it simplifies things a lot in comparison to taking the urllib2 approach. First install it from pip:

pip install requests

More on installing requests.

Then setup the put request:

import requests
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}

# Create your header as required
headers = {"content-type": "application/json", "Authorization": "<auth-key>" }

r = requests.put(url, data=json.dumps(payload), headers=headers)

See the quickstart for requests library. I think this is a lot simpler than urllib2 but does require this additional package to be installed and imported.

Flex-box: Align last row to grid

If you want to align the last item to the grid use the following code:

Grid container

.card-grid {
  box-sizing: border-box;
  max-height: 100%;
  display: flex;
  flex-direction: row;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  justify-content: space-between;
  align-items: stretch;
  align-content: stretch;
  -webkit-box-align: stretch;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -ms-flex-flow: row wrap;
  flex-flow: row wrap;
}

.card-grid:after {
  content: "";
  flex: 1 1 100%;
  max-width: 32%;
}

Item in the grid

.card {
  flex: 1 1 100%;
  box-sizing: border-box;
  -webkit-box-flex: 1;
  max-width: 32%;
  display: block;
  position: relative;

}

The trick is to set the max-width of the item equal to the max-width of the .card-grid:after.

Live demo on Codepen