Programs & Examples On #Vsewss

AttributeError: Can only use .dt accessor with datetimelike values

First you need to define the format of date column.

df['Date'] = pd.to_datetime(df.Date, format='%Y-%m-%d %H:%M:%S')

For your case base format can be set to;

df['Date'] = pd.to_datetime(df.Date, format='%Y-%m-%d')

After that you can set/change your desired output as follows;

df['Date'] = df['Date'].dt.strftime('%Y-%m-%d')

What is the difference between smoke testing and sanity testing?

Smoke testing

Smoke testing came from the hardware environment where testing should be done to check whether the development of a new piece of hardware causes no fire and smoke for the first time.

In the software environment, smoke testing is done to verify whether we can consider for further testing the functionality which is newly built.

Sanity testing

A subset of regression test cases are executed after receiving a functionality or code with small or minor changes in the functionality or code, to check whether it resolved the issues or software bugs and no other software bug is introduced by the new changes.


Difference between smoke testing and sanity testing

Smoke testing

  • Smoke testing is used to test all areas of the application without going into too deep.

  • A smoke test always use an automated test or a written set of tests. It is always scripted.

  • Smoke testing is designed to include every part of the application in a not thorough or detailed way.

  • Smoke testing always ensures whether the most crucial functions of a program are working, but not bothering with finer details.

Sanity testing

  • Sanity testing is a narrow test that focuses on one or a few areas of functionality, but not thoroughly or in-depth.

  • A sanity test is usually unscripted.

  • Sanity testing is used to ensure that after a minor change a small part of the application is still working.

  • Sanity testing is a cursory testing, which is performed to prove that the application is functioning according to the specifications. This level of testing is a subset of regression testing.

Hope these points help you to understand the difference between smoke testing and sanity testing.


References

JWT refresh token flow

Based in this implementation with Node.js of JWT with refresh token:

1) In this case they use a uid and it's not a JWT. When they refresh the token they send the refresh token and the user. If you implement it as a JWT, you don't need to send the user, because it would inside the JWT.

2) They implement this in a separated document (table). It has sense to me because a user can be logged in in different client applications and it could have a refresh token by app. If the user lose a device with one app installed, the refresh token of that device could be invalidated without affecting the other logged in devices.

3) In this implementation it response to the log in method with both, access token and refresh token. It seams correct to me.

How can I add a .npmrc file?

In MacOS Catalina 10.15.5 the .npmrc file path can be found at

/Users/<user-name>/.npmrc

Open in it in (for first time users, create a new file) any editor and copy-paste your token. Save it.

You are ready to go.

Note: As mentioned by @oligofren, the command npm config ls -l will npm configurations. You will get the .npmrc file from config parameter userconfig

VBA Convert String to Date

Looks like it could be throwing the error on the empty data row, have you tried to just make sure itemDate isn't empty before you run the CDate() function? I think this might be your problem.

Deserialize JSON into C# dynamic object?

You can do this using System.Web.Helpers.Json - its Decode method returns a dynamic object which you can traverse as you like.

It's included in the System.Web.Helpers assembly (.NET 4.0).

var dynamicObject = Json.Decode(jsonString);

How to execute INSERT statement using JdbcTemplate class from Spring Framework

Use jdbcTemplate.update(String sql, Object... args) method:

jdbcTemplate.update(
    "INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)",
    var1, var2
);

or jdbcTemplate.update(String sql, Object[] args, int[] argTypes), if you need to map arguments to SQL types manually:

jdbcTemplate.update(
    "INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)",
    new Object[]{var1, var2}, new Object[]{Types.TYPE_OF_VAR1, Types.TYPE_OF_VAR2}
);

An item with the same key has already been added

I found the answer.It was because of the variables. Like int a and string a. there were two variables with the same name.

Powershell get ipv4 address into a variable

tldr;

I used this command to get the ip address of my Ethernet network adapter into a variable called IP.

for /f "tokens=3 delims=: " %i  in ('netsh interface ip show config name^="Ethernet" ^| findstr "IP Address"') do set IP=%i

For those who are curious to know what all that means, read on

Most commands using ipconfig for example just print out all your IP addresses and I needed a specific one which in my case was for my Ethernet network adapter.

You can see your list of network adapters by using the netsh interface ipv4 show interfaces command. Most people need Wi-Fi or Ethernet.

You'll see a table like so in the output to the command prompt:

Idx     Met         MTU          State                Name
---  ----------  ----------  ------------  ---------------------------
  1          75  4294967295  connected     Loopback Pseudo-Interface 1
 15          25        1500  connected     Ethernet
 17        5000        1500  connected     vEthernet (Default Switch)
 32          15        1500  connected     vEthernet (DockerNAT)

In the name column you should find the network adapter you want (i.e. Ethernet, Wi-Fi etc.).

As mentioned, I was interested in Ethernet in my case.

To get the IP for that adapter we can use the netsh command:

netsh interface ip show config name="Ethernet"

This gives us this output:

Configuration for interface "Ethernet"
    DHCP enabled:                         Yes
    IP Address:                           169.252.27.59
    Subnet Prefix:                        169.252.0.0/16 (mask 255.255.0.0)
    InterfaceMetric:                      25
    DNS servers configured through DHCP:  None
    Register with which suffix:           Primary only
    WINS servers configured through DHCP: None

(I faked the actual IP number above for security reasons )

I can further specify which line I want using the findstr command in the ms-dos command prompt. Here I want the line containing the string IP Address.

netsh interface ip show config name="Ethernet" | findstr "IP Address"

This gives the following output:

 IP Address:                           169.252.27.59

I can then use the for command that allows me to parse files (or multiline strings in this case) and split out the strings' contents based on a delimiter and the item number that I'm interested in.

Note that I am looking for the third item (tokens=3) and that I am using the space character and : as my delimiters (delims=: ).

for /f "tokens=3 delims=: " %i  in ('netsh interface ip show config name^="Ethernet" ^| findstr "IP Address"') do set IP=%i

Each value or token in the loop is printed off as the variable %i but I'm only interested in the third "token" or item (hence tokens=3). Note that I had to escape the | and = using a ^

At the end of the for command you can specify a command to run with the content that is returned. In this case I am using set to assign the value to an environment variable called IP. If you want you could also just echo the value or what ever you like.

With that you get an environment variable with the IP Address of your preferred network adapter assigned to an environment variable. Pretty neat, huh?

If you have any ideas for improving please leave a comment.

Checking if a variable exists in javascript

if (variable) can be used if variable is guaranteed to be an object, or if false, 0, etc. are considered "default" values (hence equivalent to undefined or null).

typeof variable == 'undefined' can be used in cases where a specified null has a distinct meaning to an uninitialised variable or property. This check will not throw and error is variable is not declared.

How can I quickly sum all numbers in a file?

I prefer to use GNU datamash for such tasks because it's more succinct and legible than perl or awk. For example

datamash sum 1 < myfile

where 1 denotes the first column of data.

GCC fatal error: stdio.h: No such file or directory

I know my case is rare, but I'll still add it here for someone who troubleshoots it later. I had a Linux Kernel module target in my Makefile and I tried to compile my user space program together with the kernel module that doesn't have stdio. Making it a separate target solved the problem.

How to connect Bitbucket to Jenkins properly

I am not familiar with this plugin, but we quite successfully use Bitbucket and Jenkins together, however we poll for changes instead of having them pushed from BitBucket (due to the fact our build server is hidden behind a company firewall). This approach may work for you if you are still having problems with the current approach.

This document on Setting up SSH for Git & Mercurial on Linux covers the details of what you need to do to be able to communicate between your build server and Bitbucket over SSH. Once this is done, with the Git Plugin installed, go to your build configuration and select 'Git' under Source Code Management, and enter the ssh URL of your repository as the repository URL. Finally, in the Build Triggers section, select Poll SCM and set the poll frequency to whatever you require.

Google Maps Android API v2 Authorization failure

I had the same issue. After about two hours of googling, retries, regenerating API Key many times, etc. i discovered that i enabled the wrong service in the Google APis Console. I enabled Google Maps API v2 Service, but for Android Apps you have to use Google Maps Android API v2. After enabling the right service all started working.

Get string after character

This should work:

your_str='GenFiltEff=7.092200e-01'
echo $your_str | cut -d "=" -f2

https with WCF error: "Could not find base address that matches scheme https"

In my case i am setting security mode to "TransportCredentialOnly" instead of "Transport" in binding. Changing it resolved the issue

<bindings>
  <webHttpBinding>
    <binding name="webHttpSecure">
      <security mode="Transport">
        <transport clientCredentialType="Windows" ></transport>
      </security>
      </binding>
  </webHttpBinding>
</bindings>

Concatenate multiple result rows of one column into one, group by another column

You can use array_agg function for that:

SELECT "Movie",
array_to_string(array_agg(distinct "Actor"),',') AS Actor
FROM Table1
GROUP BY "Movie";

Result:

MOVIE ACTOR
A 1,2,3
B 4

See this SQLFiddle

For more See 9.18. Aggregate Functions

Get values from other sheet using VBA

That will be (for you very specific example)

ActiveWorkbook.worksheets("Sheet2").cells(aRow,aCol).Value=someval

OR

someVal=ActiveWorkbook.worksheets("Sheet2").cells(aRow,aCol).Value

So get a F1 click and read about Worksheets collection, which contains Worksheet objects, which in turn has a Cells collection, holding Cell objects...

Scheduled run of stored procedure on SQL server

Yes, in MS SQL Server, you can create scheduled jobs. In SQL Management Studio, navigate to the server, then expand the SQL Server Agent item, and finally the Jobs folder to view, edit, add scheduled jobs.

Java: Instanceof and Generics

Two options for runtime type checking with generics:

Option 1 - Corrupt your constructor

Let's assume you are overriding indexOf(...), and you want to check the type just for performance, to save yourself iterating the entire collection.

Make a filthy constructor like this:

public MyCollection<T>(Class<T> t) {

    this.t = t;
}

Then you can use isAssignableFrom to check the type.

public int indexOf(Object o) {

    if (
        o != null &&

        !t.isAssignableFrom(o.getClass())

    ) return -1;

//...

Each time you instantiate your object you would have to repeat yourself:

new MyCollection<Apples>(Apples.class);

You might decide it isn't worth it. In the implementation of ArrayList.indexOf(...), they do not check that the type matches.

Option 2 - Let it fail

If you need to use an abstract method that requires your unknown type, then all you really want is for the compiler to stop crying about instanceof. If you have a method like this:

protected abstract void abstractMethod(T element);

You can use it like this:

public int indexOf(Object o) {

    try {

        abstractMethod((T) o);

    } catch (ClassCastException e) {

//...

You are casting the object to T (your generic type), just to fool the compiler. Your cast does nothing at runtime, but you will still get a ClassCastException when you try to pass the wrong type of object into your abstract method.

NOTE 1: If you are doing additional unchecked casts in your abstract method, your ClassCastExceptions will get caught here. That could be good or bad, so think it through.

NOTE 2: You get a free null check when you use instanceof. Since you can't use it, you may need to check for null with your bare hands.

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

I had been experiencing the same problem, in my ASP.NET MVC 4 application.

The way I solved it, was in the DatabaseContext. By passing down the name of the connection string I wanted to use through the base constructor.

public class DatabaseContext : DbContext
{ 
    public DatabaseContext()
        : base("DefaultConnection") // <-- this is what i added.
    {
    }

    public DbSet<SomeModel> SomeModels { get; set; }
}

how to set imageview src?

What you are looking for is probably this:

ImageView myImageView;
myImageView = mDialog.findViewById(R.id.image_id);
String src = "imageFileName"

int drawableId = this.getResources().getIdentifier(src, "drawable", context.getPackageName())
popupImageView.setImageResource(drawableId);

Let me know if this was helpful :)

How can I loop through a List<T> and grab each item?

The low level iterator manipulate code:

List<Money> myMoney = new List<Money>
{
    new Money{amount = 10, type = "US"},
    new Money{amount = 20, type = "US"}
};
using (var enumerator = myMoney.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        var element = enumerator.Current;
        Console.WriteLine(element.amount);
    }
}

How do I make a text input non-editable?

you just need to add disabled at the end

<input type="text" value="3" class="field left" disabled>

Getter and Setter?

Validating + Formatting/Deriving Values

Setters let you to validate data and getters let you format or derive data. Objects allow you to encapsulate data and its validation and formatting code into a neat package that encourages DRY.

For example, consider the following simple class that contains a birth date.

class BirthDate {

    private $birth_date;

    public function getBirthDate($format='Y-m-d') {
        //format $birth_date ...
        //$birth_date = ...
        return $birth_date;
    }

    public function setBirthDate($birth_date) {                   
        //if($birth_date is not valid) throw an exception ...          
        $this->birth_date = $birth_date;
    }

    public function getAge() {
        //calculate age ...
        return $age;
    }

    public function getDaysUntilBirthday() {
        //calculate days until birth days
        return $days;
    }
}

You'll want to validate that the value being set is

  • A valid date
  • Not in the future

And you don't want to do this validation all over your application (or over multiple applications for that matter). Instead, it's easier to make the member variable protected or private (in order to make the setter the only access point) and to validate in the setter because then you'll know that the object contains a valid birth date no matter which part of the application the object came from and if you want to add more validation then you can add it in a single place.

You might want to add multiple formatters that operate on the same member variable i.e. getAge() and getDaysUntilBirthday() and you might want to enforce a configurable format in getBirthDate() depending on locale. Therefore I prefer consistently accessing values via getters as opposed to mixing $date->getAge() with $date->birth_date.

getters and setters are also useful when you extend objects. For example, suppose your application needed to allow 150+ year birth dates in some places but not in others. One way to solve the problem without repeating any code would be to extend the BirthDate object and put the additional validation in the setter.

class LivingBirthDate extends BirthDate {

    public function setBirthDate($birth_date) {
        //if $birth_date is greater than 150 years throw an exception
        //else pass to parent's setter
        return parent::setBirthDate($birth_date);
    }
}

Android: How to programmatically access the device serial number shown in the AVD manager (API Version 8)

Build.SERIAL can be empty or sometimes return a different value (proof 1, proof 2) than what you can see in your device's settings.

If you want a more complete and robust solution, I've compiled every possible solution I could found in a single gist. Here's a simplified version of it :

public static String getSerialNumber() {
    String serialNumber;

    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class);

        serialNumber = (String) get.invoke(c, "gsm.sn1");
        if (serialNumber.equals(""))
            serialNumber = (String) get.invoke(c, "ril.serialnumber");
        if (serialNumber.equals(""))
            serialNumber = (String) get.invoke(c, "ro.serialno");
        if (serialNumber.equals(""))
            serialNumber = (String) get.invoke(c, "sys.serialnumber");
        if (serialNumber.equals(""))
            serialNumber = Build.SERIAL;

        // If none of the methods above worked
        if (serialNumber.equals(""))
            serialNumber = null;
    } catch (Exception e) {
        e.printStackTrace();
        serialNumber = null;
    }

    return serialNumber;
}

I try to update the gist regularly whenever I can test on a new device or Android version. Contributions are welcome too.

Regex for checking if a string is strictly alphanumeric

Considering you want to check for ASCII Alphanumeric characters, Try this: "^[a-zA-Z0-9]*$". Use this RegEx in String.matches(Regex), it will return true if the string is alphanumeric, else it will return false.

public boolean isAlphaNumeric(String s){
    String pattern= "^[a-zA-Z0-9]*$";
    return s.matches(pattern);
}

If it will help, read this for more details about regex: http://www.vogella.com/articles/JavaRegularExpressions/article.html

How to loop over a Class attributes in Java?

Simple way to iterate over class fields and obtain values from object:

 Class<?> c = obj.getClass();
 Field[] fields = c.getDeclaredFields();
 Map<String, Object> temp = new HashMap<String, Object>();

 for( Field field : fields ){
      try {
           temp.put(field.getName().toString(), field.get(obj));
      } catch (IllegalArgumentException e1) {
      } catch (IllegalAccessException e1) {
      }
 }

How to Get a Sublist in C#

Use the Where clause from LINQ:

List<object> x = new List<object>();
x.Add("A");
x.Add("B");
x.Add("C");
x.Add("D");
x.Add("B");

var z = x.Where(p => p == "A");
z = x.Where(p => p == "B");

In the statements above "p" is the object that is in the list. So if you used a data object, i.e.:

public class Client
{
    public string Name { get; set; }
}

then your linq would look like this:

List<Client> x = new List<Client>();
x.Add(new Client() { Name = "A" });
x.Add(new Client() { Name = "B" });
x.Add(new Client() { Name = "C" });
x.Add(new Client() { Name = "D" });
x.Add(new Client() { Name = "B" });

var z = x.Where(p => p.Name == "A");
z = x.Where(p => p.Name == "B");

Git status shows files as changed even though contents are the same

i had the same problem. after win->lin copy i've got all files modified.
i used fromdos to fix line endings
and then

git add -uv 

to add changes.
it added 3 files (not all of them), which i actually modified. and after that git status shows only 3 modified files. after git commit everything is ok with git status

MYSQL query between two timestamps

@Amaynut Thanks

SELECT * 
FROM eventList 
WHERE date BETWEEN UNIX_TIMESTAMP('2017-08-01') AND UNIX_TIMESTAMP('2017/08/01');

above mention, code works and my problem solved.

Can I run Keras model on gpu?

I'm using Anaconda on Windows 10, with a GTX 1660 Super. I first installed the CUDA environment following this step-by-step. However there is now a keras-gpu metapackage available on Anaconda which apparently doesn't require installing CUDA and cuDNN libraries beforehand (mine were already installed anyway).

This is what worked for me to create a dedicated environment named keras_gpu:

# need to downgrade from tensorflow 2.1 for my particular setup
conda create --name keras_gpu keras-gpu=2.3.1 tensorflow-gpu=2.0

To add on @johncasey 's answer but for TensorFlow 2.0, adding this block works for me:

import tensorflow as tf
from tensorflow.python.keras import backend as K

# adjust values to your needs
config = tf.compat.v1.ConfigProto( device_count = {'GPU': 1 , 'CPU': 8} )
sess = tf.compat.v1.Session(config=config) 
K.set_session(sess)

This post solved the set_session error I got: you need to use the keras backend from the tensorflow path instead of keras itself.

Git pull after forced update

To receive the new commits

git fetch

Reset

You can reset the commit for a local branch using git reset.

To change the commit of a local branch:

git reset origin/master --hard

Be careful though, as the documentation puts it:

Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.

If you want to actually keep whatever changes you've got locally - do a --soft reset instead. Which will update the commit history for the branch, but not change any files in the working directory (and you can then commit them).

Rebase

You can replay your local commits on top of any other commit/branch using git rebase:

git rebase -i origin/master

This will invoke rebase in interactive mode where you can choose how to apply each individual commit that isn't in the history you are rebasing on top of.

If the commits you removed (with git push -f) have already been pulled into the local history, they will be listed as commits that will be reapplied - they would need to be deleted as part of the rebase or they will simply be re-included into the history for the branch - and reappear in the remote history on the next push.

Use the help git command --help for more details and examples on any of the above (or other) commands.

Call external javascript functions from java code

Use ScriptEngine.eval(java.io.Reader) to read the script

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// read script file
engine.eval(Files.newBufferedReader(Paths.get("C:/Scripts/Jsfunctions.js"), StandardCharsets.UTF_8));

Invocable inv = (Invocable) engine;
// call function from script file
inv.invokeFunction("yourFunction", "param");

How to manage startActivityForResult on Android?

First you use startActivityForResult() with parameters in first Activity and if you want to send data from second Activity to first Activity then pass value using Intent with setResult() method and get that data inside onActivityResult() method in first Activity.

curl -GET and -X GET

By default you use curl without explicitly saying which request method to use. If you just pass in a HTTP URL like curl http://example.com it will use GET. If you use -d or -F curl will use POST, -I will cause a HEAD and -T will make it a PUT.

If for whatever reason you're not happy with these default choices that curl does for you, you can override those request methods by specifying -X [WHATEVER]. This way you can for example send a DELETE by doing curl -X DELETE [URL].

It is thus pointless to do curl -X GET [URL] as GET would be used anyway. In the same vein it is pointless to do curl -X POST -d data [URL]... But you can make a fun and somewhat rare request that sends a request-body in a GET request with something like curl -X GET -d data [URL].

Digging deeper

curl -GET (using a single dash) is just wrong for this purpose. That's the equivalent of specifying the -G, -E and -T options and that will do something completely different.

There's also a curl option called --get to not confuse matters with either. It is the long form of -G, which is used to convert data specified with -d into a GET request instead of a POST.

(I subsequently used my own answer here to populate the curl FAQ to cover this.)

Warnings

Modern versions of curl will inform users about this unnecessary and potentially harmful use of -X when verbose mode is enabled (-v) - to make users aware. Further explained and motivated in this blog post.

-G converts a POST + body to a GET + query

You can ask curl to convert a set of -d options and instead of sending them in the request body with POST, put them at the end of the URL's query string and issue a GET, with the use of `-G. Like this:

curl -d name=daniel -d grumpy=yes -G https://example.com/

Can I set up HTML/Email Templates with ASP.NET?

Mail.dll email component includes email template engine:

Here's the syntax overview:

<html>
<body>
Hi {FirstName} {LastName},

Here are your orders: 
{foreach Orders}
    Order '{Name}' sent to <strong>{Street}</strong>. 
{end}

</body>
</html>

And the code that loads the template, fills data from c# object and sends an email:

Mail.Html(Template
              .FromFile("template.txt")
              .DataFrom(_contact)
              .Render())
    .Text("This is text version of the message.")
    .From(new MailBox("[email protected]", "Alice"))
    .To(new MailBox("[email protected]", "Bob"))
    .Subject("Your order")
    .UsingNewSmtp()
    .WithCredentials("[email protected]", "password")
    .Server("mail.com")
    .WithSSL()
    .Send();

You can get more info on email template engine blog post.

Or just download Mail.dll email component and give it a try.

Please note that this is a commercial product I've created.

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

You need to handle two scenarios:

  1. When you're pushing a new view onto the stack
  2. When you're showing the root view controller

If you just need a base class you can use, here's a Swift 3 version:

import UIKit

final class SwipeNavigationController: UINavigationController {
    
    // MARK: - Lifecycle
    
    override init(rootViewController: UIViewController) {
        super.init(rootViewController: rootViewController)

         delegate = self
    }
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        
        delegate = self
    }

    required init?(coder aDecoder: NSCoder) { 
        super.init(coder: aDecoder) 

        delegate = self 
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // This needs to be in here, not in init
        interactivePopGestureRecognizer?.delegate = self
    }
    
    deinit {
        delegate = nil
        interactivePopGestureRecognizer?.delegate = nil
    }
    
    // MARK: - Overrides
    
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        duringPushAnimation = true
        
        super.pushViewController(viewController, animated: animated)
    }
    
    // MARK: - Private Properties
    
    fileprivate var duringPushAnimation = false

}

// MARK: - UINavigationControllerDelegate

extension SwipeNavigationController: UINavigationControllerDelegate {
    
    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        guard let swipeNavigationController = navigationController as? SwipeNavigationController else { return }
        
        swipeNavigationController.duringPushAnimation = false
    }
    
}

// MARK: - UIGestureRecognizerDelegate

extension SwipeNavigationController: UIGestureRecognizerDelegate {
    
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        guard gestureRecognizer == interactivePopGestureRecognizer else {
            return true // default value
        }
        
        // Disable pop gesture in two situations:
        // 1) when the pop animation is in progress
        // 2) when user swipes quickly a couple of times and animations don't have time to be performed
        return viewControllers.count > 1 && duringPushAnimation == false
    }
}

If you end up needing to act as a UINavigationControllerDelegate in another class, you can write a delegate forwarder similar to this answer.

Adapted from source in Objective-C: https://github.com/fastred/AHKNavigationController

Laravel 5.2 - pluck() method returns array

In the original example, why not use the select() method in your database query?

$name = DB::table('users')->where('name', 'John')->select("id");

This will be faster than using a PHP framework, for it'll utilize the SQL query to do the row selection for you. For ordinary collections, I don't believe this applies, but since you're using a database...

Larvel 5.3: Specifying a Select Clause

UITableView - scroll to the top

Use this code for UITableview implementation in swift:

var cell = tableView.dequeueReusableCellWithIdentifier(“cell”)
if cell == nil {
    cell = UITableViewCell(style: .Value1, reuseIdentifier: “cell”)
}

How to show "if" condition on a sequence diagram?

Very simple , using Alt fragment

Lets take an example of sequence diagram for an ATM machine.Let's say here you want

IF card inserted is valid then prompt "Enter Pin"....ELSE prompt "Invalid Pin"

Then here is the sequence diagram for the same

ATM machine sequence diagram

Hope this helps!

including parameters in OPENQUERY

You can execute a string with OPENQUERY once you build it up. If you go this route think about security and take care not to concatenate user-entered text into your SQL!

DECLARE @Sql VARCHAR(8000)
SET @Sql = 'SELECT * FROM Tbl WHERE Field1 < ''someVal'' AND Field2 IN '+ @valueList 
SET @Sql = 'SELECT * FROM OPENQUERY(SVRNAME, ''' + REPLACE(@Sql, '''', '''''') + ''')'
EXEC(@Sql)

How to check type of variable in Java?

Just use:

.getClass().getSimpleName();

Example:

StringBuilder randSB = new StringBuilder("just a String");
System.out.println(randSB.getClass().getSimpleName());

Output:

StringBuilder

How to position absolute inside a div?

The problem is described (among other) in this article.

#box is relatively positioned, which makes it part of the "flow" of the page. Your other divs are absolutely positioned, so they are removed from the page's "flow".

Page flow means that the positioning of an element effects other elements in the flow.

In other words, as #box now sees the dom, .a and .b are no longer "inside" #box.

To fix this, you would want to make everything relative, or everything absolute.

One way would be:

.a {
   position:relative;
   margin-top:10px;
   margin-left:10px;
   background-color:red;
   width:210px;
   padding: 5px;
}

Convert a JSON string to object in Java ME?

GSON is a good option to convert java object to json object and vise versa.
It is a tool provided by google.

for converting json to java object use: fromJson(jsonObject,javaclassname.class)
for converting java object to json object use: toJson(javaObject)
and rest will be done automatically

For more information and for download

How can I connect to a Tor hidden service using cURL in PHP?

Try to add this:

curl_setopt($ch, CURLOPT_HEADER, 1); 
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); 

R command for setting working directory to source file location in Rstudio

This answer can help:

script.dir <- dirname(sys.frame(1)$ofile)

Note: script must be sourced in order to return correct path

I found it in: https://support.rstudio.com/hc/communities/public/questions/200895567-can-user-obtain-the-path-of-current-Project-s-directory-

The BumbleBee´s answer (with parent.frame instead sys.frame) didn´t work to me, I always get an error.

What is a practical use for a closure in JavaScript?

JavaScript closures can be used to implement throttle and debounce functionality in your application.

Throttling

Throttling puts a limit on as a maximum number of times a function can be called over time. As in "execute this function at most once every 100 milliseconds."

Code:

const throttle = (func, limit) => {
  let isThrottling
  return function() {
    const args = arguments
    const context = this
    if (!isThrottling) {
      func.apply(context, args)
      isThrottling = true
      setTimeout(() => isThrottling = false, limit)
    }
  }
}

Debouncing

Debouncing puts a limit on a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called."

Code:

const debounce = (func, delay) => {
  let debouncing
  return function() {
    const context = this
    const args = arguments
    clearTimeout(debouncing)
    debouncing = setTimeout(() => func.apply(context, args), delay)
  }
}

As you can see closures helped in implementing two beautiful features which every web application should have to provide smooth UI experience functionality.

Where is Python language used?

Python started as a scripting language for Linux like Perl but less cryptic. Now it is used for both web and desktop applications and is available on Windows too. Desktop GUI APIs like GTK have their Python implementations and Python based web frameworks like Django are preferred by many over PHP et al. for web applications.

And by the way,

  • What can you do with PHP that you can't do with ASP or JSP?
  • What can you do with Java that you can't do with C++?

delete all record from table in mysql

truncate tableName

That is what you are looking for.

Truncate will delete all records in the table, emptying it.

Adding POST parameters before submit

PURE JavaScript:

Creating the XMLHttpRequest:

function getHTTPObject() {
    /* Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, 
       por lo que se puede copiar tal como esta aqui */
    var xmlhttp = false;
    /* No mas soporte para Internet Explorer
    try { // Creacion del objeto AJAX para navegadores no IE
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(nIE) {
        try { // Creacion del objet AJAX para IE
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(IE) {
            if (!xmlhttp && typeof XMLHttpRequest!='undefined') 
                xmlhttp = new XMLHttpRequest();
        }
    }
    */
    xmlhttp = new XMLHttpRequest();
    return xmlhttp; 
}

JavaScript function to Send the info via POST:

function sendInfo() {
    var URL = "somepage.html"; //depends on you
    var Params = encodeURI("var1="+val1+"var2="+val2+"var3="+val3);
    console.log(Params);
    var ajax = getHTTPObject();     
    ajax.open("POST", URL, true); //True:Sync - False:ASync
    ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    ajax.setRequestHeader("Content-length", Params.length);
    ajax.setRequestHeader("Connection", "close");
    ajax.onreadystatechange = function() { 
        if (ajax.readyState == 4 && ajax.status == 200) {
            alert(ajax.responseText);
        } 
    }
    ajax.send(Params);
}

Total width of element (including padding and border) in jQuery

same browsers may return string for border width, in this parseInt will return NaN so make sure you parse value to int properly.

        var getInt = function (string) {
            if (typeof string == "undefined" || string == "")
                return 0;
            var tempInt = parseInt(string);

            if (!(tempInt <= 0 || tempInt > 0))
                return 0;
            return tempInt;
        }

        var liWidth = $(this).width();
        liWidth += getInt($(this).css("padding-left"));
        liWidth += getInt($(this).css("padding-right"));
        liWidth += getInt($(this).css("border-left-width"));
        liWidth += getInt($(this).css("border-right-width"));

how to select rows based on distinct values of A COLUMN only

I am not sure about your DBMS. So, I created a temporary table in Redshift and from my experience, I think this query should return what you are looking for:

select min(Id), distinct MailId, EmailAddress, Name
    from yourTableName
    group by MailId, EmailAddress, Name

I see that I am using a GROUP BY clause but you still won't have two rows against any particular MailId.

Android : Capturing HTTP Requests with non-rooted android device

There is many ways to do that but one of them is fiddler

Fiddler Configuration

  1. Go to options
  2. In HTTPS tab, enable Capture HTTPS Connects and Decrypt HTTPS traffic
  3. In Connections tab, enable Allow remote computers to connect
  4. Restart fiddler

Android Configuration

  1. Connect to same network
  2. Modify network settings
  3. Add proxy for connection with your PC's IP address ( or hostname ) and default fiddler's port ( 8888 / you can change that in settings )

Now you can see full log from your device in fiddler

Also you can find a full instruction here

How to include Authorization header in cURL POST HTTP Request in PHP?

@jason-mccreary is totally right. Besides I recommend you this code to get more info in case of malfunction:

$rest = curl_exec($crl);

if ($rest === false)
{
    // throw new Exception('Curl error: ' . curl_error($crl));
    print_r('Curl error: ' . curl_error($crl));
}

curl_close($crl);
print_r($rest);

EDIT 1

To debug you can set CURLOPT_HEADER to true to check HTTP response with firebug::net or similar.

curl_setopt($crl, CURLOPT_HEADER, true);

EDIT 2

About Curl error: SSL certificate problem, verify that the CA cert is OK try adding this headers (just to debug, in a production enviroment you should keep these options in true):

curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, false);

How to dynamic filter options of <select > with jQuery?

Just a minor modification to the excellent answer above by Lessan Vaezi. I ran into a situation where I needed to include attributes in my option entries. The original implementation loses any tag attributes. This version of the above answer preserves the option tag attributes:

jQuery.fn.filterByText = function(textbox) {
  return this.each(function() {
    var select = this;
    var options = [];
    $(select).find('option').each(function() {
      options.push({
          value: $(this).val(),
          text: $(this).text(),
          attrs: this.attributes, // Preserve attributes.
      });
    });
    $(select).data('options', options);

    $(textbox).bind('change keyup', function() {
      var options = $(select).empty().data('options');
      var search = $.trim($(this).val());
      var regex = new RegExp(search, "gi");

      $.each(options, function(i) {
        var option = options[i];
        if (option.text.match(regex) !== null) { 
            var new_option = $('<option>').text(option.text).val(option.value);
            if (option.attrs) // Add old element options to new entry
            {
                $.each(option.attrs, function () {
                    $(new_option).attr(this.name, this.value);
                    });
            }
            
            $(select).append(new_option);
        }
      });
    });
  });
};

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

You must enable the transaction support (<tx:annotation-driven> or @EnableTransactionManagement) and declare the transactionManager and it should work through the SessionFactory.

You must add @Transactional into your @Repository

With @Transactional in your @Repository Spring is able to apply transactional support into your repository.

Your Student class has no the @javax.persistence.* annotations how @Entity, I am assuming the Mapping Configuration for that class has been defined through XML.

Passing Arrays to Function in C++

The syntaxes

int[]

and

int[X] // Where X is a compile-time positive integer

are exactly the same as

int*

when in a function parameter list (I left out the optional names).

Additionally, an array name decays to a pointer to the first element when passed to a function (and not passed by reference) so both int firstarray[3] and int secondarray[5] decay to int*s.

It also happens that both an array dereference and a pointer dereference with subscript syntax (subscript syntax is x[y]) yield an lvalue to the same element when you use the same index.

These three rules combine to make the code legal and work how you expect; it just passes pointers to the function, along with the length of the arrays which you cannot know after the arrays decay to pointers.

How to put/get multiple JSONObjects to JSONArray?

I found very good link for JSON: http://code.google.com/p/json-simple/wiki/EncodingExamples#Example_1-1_-_Encode_a_JSON_object

Here's code to add multiple JSONObjects to JSONArray.

JSONArray Obj = new JSONArray();
try {
    for(int i = 0; i < 3; i++) {
        // 1st object
        JSONObject list1 = new JSONObject();
        list1.put("val1",i+1);
        list1.put("val2",i+2);
        list1.put("val3",i+3);
        obj.put(list1);
    }

} catch (JSONException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}             
Toast.makeText(MainActivity.this, ""+obj, Toast.LENGTH_LONG).show();

git command to move a folder inside another

I'm sorry I don't have enough reputation to comment the "answer" of "Andres Jaan Tack".

I think my messege will be deleted (( But I just want to warn "lurscher" and others who got the same error: be carefull doing

$ mkdir include
$ mv common include
$ git rm -r common
$ git add include/common

It may cause you will not see the git history of your project in new folder.

I tryed

$ git mv oldFolderName newFolderName

got

fatal: bad source, source=oldFolderName/somepath/__init__.py, dest
ination=ESWProj_Base/ESWProj_DebugControlsMenu/somepath/__init__.py

I did

git rm -r oldFolderName

and

git add newFolderName

and I don't see old git history in my project. At least my project is not lost. Now I have my project in newFolderName, but without the history (

Just want to warn, be carefull using advice of "Andres Jaan Tack", if you dont want to lose your git hsitory.

PHP Create and Save a txt file to root directory

If you are running PHP on Apache then you can use the enviroment variable called DOCUMENT_ROOT. This means that the path is dynamic, and can be moved between servers without messing about with the code.

<?php
  $fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
  $file = fopen($fileLocation,"w");
  $content = "Your text here";
  fwrite($file,$content);
  fclose($file);
?>

Install gitk on Mac

As of macOS Catalina 10.15.6, I run:

brew install git
brew install git-gui

and it worked for me.

Select Tag Helper in ASP.NET Core MVC

You can also use IHtmlHelper.GetEnumSelectList.

    // Summary:
    //     Returns a select list for the given TEnum.
    //
    // Type parameters:
    //   TEnum:
    //     Type to generate a select list for.
    //
    // Returns:
    //     An System.Collections.Generic.IEnumerable`1 containing the select list for the
    //     given TEnum.
    //
    // Exceptions:
    //   T:System.ArgumentException:
    //     Thrown if TEnum is not an System.Enum or if it has a System.FlagsAttribute.
    IEnumerable<SelectListItem> GetEnumSelectList<TEnum>() where TEnum : struct;

Getting only 1 decimal place

>>> "{:.1f}".format(45.34531)
'45.3'

Or use the builtin round:

>>> round(45.34531, 1)
45.299999999999997

Changing the size of a column referenced by a schema-bound view in SQL Server

ALTER TABLE [table_name] ALTER COLUMN [column_name] varchar(150)

Logout button php

When you want to destroy a session completely, you need to do more then just

session_destroy();

First, you should unset any session variables. Then you should destroy the session followed by closing the write of the session. This can be done by the following:

<?php
session_start();
unset($_SESSION);
session_destroy();
session_write_close();
header('Location: /');
die;
?>

The reason you want have a separate script for a logout is so that you do not accidently execute it on the page. So make a link to your logout script, then the header will redirect to the root of your site.

Edit:

You need to remove the () from your exit code near the top of your script. it should just be

exit;

How do you share constants in NodeJS modules?

In my opinion, utilizing Object.freeze allows for a DRYer and more declarative style. My preferred pattern is:

./lib/constants.js

module.exports = Object.freeze({
    MY_CONSTANT: 'some value',
    ANOTHER_CONSTANT: 'another value'
});

./lib/some-module.js

var constants = require('./constants');

console.log(constants.MY_CONSTANT); // 'some value'

constants.MY_CONSTANT = 'some other value';

console.log(constants.MY_CONSTANT); // 'some value'

Outdated Performance Warning

The following issue was fixed in v8 in Jan 2014 and is no longer relevant to most developers:

Be aware that both setting writable to false and using Object.freeze have a massive performance penalty in v8 - https://bugs.chromium.org/p/v8/issues/detail?id=1858 and http://jsperf.com/performance-frozen-object

How to export table as CSV with headings on Postgresql?

copy (anysql query datawanttoexport) to 'fileablsoutepathwihname' delimiter ',' csv header;

Using this u can export data also.

How to use regex with find command?

on Mac OS X (BSD find): Same as accepted answer, the .*/ prefix is needed to match a complete path:

$ find -E . -regex ".*/[a-f0-9\-]{36}.jpg"

man find says -E uses extended regex support

How do I make a list of data frames?

I consider myself a complete newbie, but I think I have an extremely simple answer to one of the original subquestions that has not been stated here: accessing the data frames, or parts of it.

Let's start by creating the list with data frames as was stated above:

d1 <- data.frame(y1 = c(1, 2, 3), y2 = c(4, 5, 6))

d2 <- data.frame(y1 = c(3, 2, 1), y2 = c(6, 5, 4))

my.list <- list(d1, d2)

Then, if you want to access a specific value in one of the data frames, you can do so by using the double brackets sequentially. The first set gets you into the data frame, and the second set gets you to the specific coordinates:

my.list[[1]][[3,2]]

[1] 6

AngularJS ng-click to go to another page (with Ionic framework)

app.controller('NavCtrl', function ($scope, $location, $state, $window, Post, Auth) {
    $scope.post = {url: 'http://', title: ''};

    $scope.createVariable = function(url) {
      $window.location.href = url;
    };
    $scope.createFixed = function() {
      $window.location.href = '/tab/newpost';
    };
});

HTML

<button class="button button-icon ion-compose" ng-click="createFixed()"></button>
<button class="button button-icon ion-compose" ng-click="createVariable('/tab/newpost')"></button>

Where can I find error log files?

What OS you are using and which Webserver? On Linux and Apache you can find the apache error_log in /var/log/apache2/

How do I toggle an element's class in pure JavaScript?

2014 answer: classList.toggle() is the standard and supported by most browsers.

Older browsers can use use classlist.js for classList.toggle():

var menu = document.querySelector('.menu') // Using a class instead, see note below.
menu.classList.toggle('hidden-phone');

As an aside, you shouldn't be using IDs (they leak globals into the JS window object).

Subdomain on different host

You just need to add an "A" record in the DNS manager on Godaddy. In that "A" record put your IP from dreamhost.

I know this works since I'm doing the very same thing.

How to use MySQL dump from a remote machine

If you haven't install mysql_client yet and using Docker container instead:

sudo docker exec MySQL_CONTAINER_NAME /usr/bin/mysqldump --host=192.168.1.1 -u username --password=password db_name > dump.sql

Turn off textarea resizing

This is works for me

_x000D_
_x000D_
<textarea_x000D_
  type='text'_x000D_
  style="resize: none"_x000D_
>_x000D_
Some text_x000D_
</textarea>
_x000D_
_x000D_
_x000D_

glob exclude pattern

More generally, to exclude files that don't comply with some shell regexp, you could use module fnmatch:

import fnmatch

file_list = glob('somepath')    
for ind, ii in enumerate(file_list):
    if not fnmatch.fnmatch(ii, 'bash_regexp_with_exclude'):
        file_list.pop(ind)

The above will first generate a list from a given path and next pop out the files that won't satisfy the regular expression with the desired constraint.

Is it possible to refresh a single UITableViewCell in a UITableView?

Swift 3 :

tableView.beginUpdates()
tableView.reloadRows(at: [indexPath], with: .automatic)
tableView.endUpdates()

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

I didn't check each and every answer for this question, but after analyzing most of them I found that design fails in case of multiline data in cells or head. I used Javascript to solve this. I hope someone finds this helpful.

https://codepen.io/kushagrarora/pen/zeYaoY

_x000D_
_x000D_
var freezeTables = document.getElementsByClassName("freeze-pane");_x000D_
_x000D_
[].forEach.call(freezeTables, ftable => {_x000D_
  var wrapper = document.createElement("div");_x000D_
  wrapper.className = "freeze-pane-wrapper";_x000D_
  var scroll = document.createElement("div");_x000D_
  scroll.className = "freeze-pane-scroll";_x000D_
_x000D_
  wrapper.appendChild(scroll);_x000D_
_x000D_
  ftable.parentNode.replaceChild(wrapper, ftable);_x000D_
_x000D_
  scroll.appendChild(ftable);_x000D_
_x000D_
  var heads = ftable.querySelectorAll("th:first-child");_x000D_
_x000D_
  let maxWidth = 0;_x000D_
_x000D_
  [].forEach.call(heads, head => {_x000D_
    var w = window_x000D_
      .getComputedStyle(head)_x000D_
      .getPropertyValue("width")_x000D_
      .split("px")[0];_x000D_
    if (Number(w) > Number(maxWidth)) maxWidth = w;_x000D_
  });_x000D_
_x000D_
  ftable.parentElement.style.marginLeft = maxWidth + "px";_x000D_
  ftable.parentElement.style.width = "calc(100% - " + maxWidth + "px)";_x000D_
  [].forEach.call(heads, head => {_x000D_
    head.style.width = maxWidth + "px";_x000D_
    var restRowHeight = window_x000D_
      .getComputedStyle(head.nextElementSibling)_x000D_
      .getPropertyValue("height");_x000D_
    var headHeight = window.getComputedStyle(head).getPropertyValue("height");_x000D_
    if (headHeight > restRowHeight)_x000D_
      head.nextElementSibling.style.height = headHeight;_x000D_
    else head.style.height = restRowHeight;_x000D_
  });_x000D_
});
_x000D_
@import url("https://fonts.googleapis.com/css?family=Open+Sans");_x000D_
* {_x000D_
  font-family: "Open Sans", sans-serif;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  width: 400px;_x000D_
  height: 90vh;_x000D_
  border: 1px solid black;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
table,_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid #eee;_x000D_
}_x000D_
_x000D_
.table {_x000D_
  width: 100%;_x000D_
  margin-bottom: 1rem;_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
.freeze-pane-wrapper {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.freeze-pane-scroll {_x000D_
  overflow-x: scroll;_x000D_
  overflow-y: visible;_x000D_
}_x000D_
_x000D_
.freeze-pane th:first-child {_x000D_
  position: absolute;_x000D_
  background-color: pink;_x000D_
  left: 0;_x000D_
  top: auto;_x000D_
  max-width: 40%;_x000D_
}
_x000D_
<div class="container">_x000D_
  <table class="freeze-pane">_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <th>_x000D_
          <p>Model</p>_x000D_
        </th>_x000D_
        <th>_x000D_
          <p>Mercedes Benz AMG C43 4dr</p>_x000D_
        </th>_x000D_
        <th>_x000D_
          <p>Audi S4 Premium 4dr</p>_x000D_
        </th>_x000D_
        <th>_x000D_
          <p>BMW 440i 4dr sedan</p>_x000D_
        </th>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <th>_x000D_
          <p>Passenger capacity</p>_x000D_
        </th>_x000D_
        <td>_x000D_
          <p>5</p>_x000D_
        </td>_x000D_
        <td>_x000D_
          <p>5</p>_x000D_
        </td>_x000D_
        <td>_x000D_
          <p>5</p>_x000D_
        </td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <th>_x000D_
          <p>Front (Head/Shoulder/Leg) (In.)</p>_x000D_
        </th>_x000D_
        <td>_x000D_
          <p>37.1/55.3/41.7</p>_x000D_
        </td>_x000D_
        <td>_x000D_
          <p>38.9/55.9/41.3</p>_x000D_
        </td>_x000D_
        <td>_x000D_
          <p>39.9/54.8/42.2</p>_x000D_
        </td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <th>_x000D_
          <p>Second (Head/Shoulder/Leg) (In.)</p>_x000D_
        </th>_x000D_
        <td>_x000D_
          <p>37.1/55.5/35.2</p>_x000D_
        </td>_x000D_
        <td>_x000D_
          <p>37.4/54.5/35.7</p>_x000D_
        </td>_x000D_
        <td>_x000D_
          <p>36.9/54.3/33.7</p>_x000D_
        </td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note: the "container" div is just to demonstrate that code is compatible with mobile-view.

How to create strings containing double quotes in Excel formulas?

Concatenate " as a ceparate cell:

    A |   B   | C | D
1   " | text  | " | =CONCATENATE(A1; B1; C1);

D1 displays "text"

How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?

You need to subclass ViewPager. onTouchEvent has a lot of good things in it that you don't want to change like allowing child views to get touches. onInterceptTouchEvent is what you want to change. If you look at the code for ViewPager, you'll see the comment:

    /*
     * This method JUST determines whether we want to intercept the motion.
     * If we return true, onMotionEvent will be called and we do the actual
     * scrolling there.
     */

Here's a complete solution:

First, add this class to your src folder:

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.DecelerateInterpolator;
import android.widget.Scroller;
import java.lang.reflect.Field;

public class NonSwipeableViewPager extends ViewPager {

    public NonSwipeableViewPager(Context context) {
        super(context);
        setMyScroller();
    }

    public NonSwipeableViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        setMyScroller();
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        // Never allow swiping to switch between pages
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Never allow swiping to switch between pages
        return false;
    }

    //down one is added for smooth scrolling

    private void setMyScroller() {
        try {
            Class<?> viewpager = ViewPager.class;
            Field scroller = viewpager.getDeclaredField("mScroller");
            scroller.setAccessible(true);
            scroller.set(this, new MyScroller(getContext()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class MyScroller extends Scroller {
        public MyScroller(Context context) {
            super(context, new DecelerateInterpolator());
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy, int duration) {
            super.startScroll(startX, startY, dx, dy, 350 /*1 secs*/);
        }
    }
}

Next, make sure to use this class instead of the regular ViewPager, which you probably specified as android.support.v4.view.ViewPager. In your layout file, you'll want to specify it with something like:

<com.yourcompany.NonSwipeableViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" />

This particular example is in a LinearLayout and is meant to take up the entire screen, which is why layout_weight is 1 and layout_height is 0dp.

And setMyScroller(); method is for smooth transition

Eclipse internal error while initializing Java tooling

In my case, Eclipse tried to launch with non-existing workspace folder. Sure the folder is created at the moment, but the exception is occured durring creating the workspace. After the exception I just switched workspace to the right folder. To avoid slipping to non-existing workspace folder I deleted it from Recent workspaces.

C++ STL Vectors: Get iterator from index?

way mentioned by @dirkgently ( v.begin() + index ) nice and fast for vectors

but std::advance( v.begin(), index ) most generic way and for random access iterators works constant time too.

EDIT
differences in usage:

std::vector<>::iterator it = ( v.begin() + index );

or

std::vector<>::iterator it = v.begin();
std::advance( it, index );

added after @litb notes.

Command to escape a string in bash

You can use perl to replace various characters, for example:

$ echo "Hello\ world" | perl -pe 's/\\/\\\\/g'
Hello\\ world

Depending on the nature of your escape, you can chain multiple calls to escape the proper characters.

c++ parse int from string

You can use boost::lexical_cast:

#include <iostream>
#include <boost/lexical_cast.hpp>

int main( int argc, char* argv[] ){
std::string s1 = "10";
std::string s2 = "abc";
int i;

   try   {
      i = boost::lexical_cast<int>( s1 );
   }
   catch( boost::bad_lexical_cast & e ){
      std::cout << "Exception caught : " << e.what() << std::endl;
   }

   try   {
      i = boost::lexical_cast<int>( s2 );
   }
   catch( boost::bad_lexical_cast & e ){
      std::cout << "Exception caught : " << e.what() << std::endl;
   }

   return 0;
}

calling parent class method from child class object in java

NOTE calling parent method via super will only work on parent class, If your parent is interface, and wants to call the default methods then need to add interfaceName before super like IfscName.super.method();

interface Vehicle {
    //Non abstract method
    public default void printVehicleTypeName() { //default keyword can be used only in interface.
        System.out.println("Vehicle");
    }
}


class FordFigo extends FordImpl implements Vehicle, Ford {
    @Override
    public void printVehicleTypeName() { 
        System.out.println("Figo");
        Vehicle.super.printVehicleTypeName();
    }
}

Interface name is needed because same default methods can be available in multiple interface name that this class extends. So explicit call to a method is required.

JS regex: replace all digits in string

find the numbers and then replaced with strings which specified. It is achieved by two methods

  1. Using a regular expression literal

  2. Using keyword RegExp object

Using a regular expression literal:

<script type="text/javascript">

var string = "my contact number is 9545554545. my age is 27.";
alert(string.replace(/\d+/g, "XXX"));

</script>

**Output:**my contact number is XXX. my age is XXX.

for more details:

http://www.infinetsoft.com/Post/How-to-replace-number-with-string-in-JavaScript/1156

EF 5 Enable-Migrations : No context type was found in the assembly

use -ProjectName option in Package Manager Console:

Enable-Migrations -ProjectName Toombu.DataAccess -StartUpProjectName Toombu.Web -Verbose

Python: PIP install path, what is the correct location for this and other addons?

Also, when you uninstall the package, the first item listed is the directory to the executable.

Script parameters in Bash

In bash $1 is the first argument passed to the script, $2 second and so on

/usr/local/bin/abbyyocr9 -rl Swedish -if "$1" -of "$2" 2>&1

So you can use:

./your_script.sh some_source_file.png destination_file.txt

Explanation on double quotes;

consider three scripts:

# foo.sh
bash bar.sh $1

# cat foo2.sh
bash bar.sh "$1"

# bar.sh
echo "1-$1" "2-$2"

Now invoke:

$ bash foo.sh "a b"
1-a 2-b

$ bash foo2.sh "a b"
1-a b 2-

When you invoke foo.sh "a b" then it invokes bar.sh a b (two arguments), and with foo2.sh "a b" it invokes bar.sh "a b" (1 argument). Always have in mind how parameters are passed and expaned in bash, it will save you a lot of headache.

Thread Safe C# Singleton Pattern

The Lazy<T> version:

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy
        = new Lazy<Singleton>(() => new Singleton());

    public static Singleton Instance
        => lazy.Value;

    private Singleton() { }
}

Requires .NET 4 and C# 6.0 (VS2015) or newer.

How to enable support of CPU virtualization on Macbook Pro?

CPU Virtualization is enabled by default on all MacBooks with compatible CPUs (i7 is compatible). You can try to reset PRAM if you think it was disabled somehow, but I doubt it.

I think the issue might be in the old version of OS. If your MacBook is i7, then you better upgrade OS to something newer.

How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5

This solution is (only) for SQL Server 2005

You guys are lifesavers, but as @Dan Mork said, you need to add EXEC to the mix. What was tripping me up was:

  • 'EXEC ' before the Proc Name
  • Commas in between Params
  • Chopping off '@' on the Param Definitions (not sure that bit is required though).

:

context.Database.SqlQuery<EntityType>(
    "EXEC ProcName @param1, @param2", 
    new SqlParameter("param1", param1), 
    new SqlParameter("param2", param2)
);

Increasing nesting function calls limit

Do you have Zend, IonCube, or xDebug installed? If so, that is probably where you are getting this error from.

I ran into this a few years ago, and it ended up being Zend putting that limit there, not PHP. Of course removing it will let you go past the 100 iterations, but you will eventually hit the memory limits.

How can I print the contents of a hash in Perl?

For debugging purposes I will often use YAML.

use strict;
use warnings;

use YAML;

my %variable = ('abc' => 123, 'def' => [4,5,6]);

print "# %variable\n", Dump \%variable;

Results in:

# %variable
---
abc: 123
def:
  - 4
  - 5
  - 6

Other times I will use Data::Dump. You don't need to set as many variables to get it to output it in a nice format than you do for Data::Dumper.

use Data::Dump = 'dump';

print dump(\%variable), "\n";
{ abc => 123, def => [4, 5, 6] }

More recently I have been using Data::Printer for debugging.

use Data::Printer;
p %variable;
{
    abc   123,
    def   [
        [0] 4,
        [1] 5,
        [2] 6
    ]
}

( Result can be much more colorful on a terminal )

Unlike the other examples I have shown here, this one is designed explicitly to be for display purposes only. Which shows up more easily if you dump out the structure of a tied variable or that of an object.

use strict;
use warnings;

use MTie::Hash;
use Data::Printer;

my $h = tie my %h, "Tie::StdHash";
@h{'a'..'d'}='A'..'D';
p %h;
print "\n";
p $h;
{
    a   "A",
    b   "B",
    c   "C",
    d   "D"
} (tied to Tie::StdHash)

Tie::StdHash  {
    public methods (9) : CLEAR, DELETE, EXISTS, FETCH, FIRSTKEY, NEXTKEY, SCALAR, STORE, TIEHASH
    private methods (0)
    internals: {
        a   "A",
        b   "B",
        c   "C",
        d   "D"
    }
}

How to add Python to Windows registry

I faced to the same problem. I solved it by

  1. navigate to HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstallPath and edit the default key with the output of C:\> where python.exe command.
  2. navigate to HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstallPath\InstallGroup and edit the default key with Python 3.4

Note: My python version is 3.4 and you need to replace 3.4 with your python version.

Normally you can find Registry entries for Python in HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\<version>. You just need to copy those entries to HKEY_CURRENT_USER\Software\Python\PythonCore\<version>

Apache and IIS side by side (both listening to port 80) on windows2003

It's impossible for both servers to listen on the same port at the same IP address: since a single socket can only be opened by a single process, only the first server configured for a certain IP/port combination will successfully bind, and the second one will fail.

You will thus need a workaround to achieve what you want. Easiest is probably to run Apache on your primary IP/port combination, and have it route requests for IIS (which should be configured for a different IP and/or port) to it using mod_rewrite.

Keep in mind that the alternative IP and port IIS runs on should be reachable to the clients connecting to your server: if you only have a single IP address available, you should take care to pick an IIS port that isn't generally blocked by firewalls (8080 might be a good option, or 443, even though you're running regular HTTP and not SSL)

P.S. Also, please note that you do need to modify the IIS default configuration using httpcfg before it will allow other servers to run on port 80 on any IP address on the same server: see Micky McQuade's answer for the procedure to do that...

Adding an img element to a div with javascript

function image()
{
    //dynamically add an image and set its attribute
    var img=document.createElement("img");
    img.src="p1.jpg"
    img.id="picture"
    var foo = document.getElementById("fooBar");
    foo.appendChild(img);
}

<span id="fooBar">&nbsp;</span>

What is mutex and semaphore in Java ? What is the main difference?

Semaphore:

A counting semaphore. Conceptually, a semaphore maintains a set of permits. Each acquire() blocks if necessary until a permit is available, and then takes it. Each release() adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly.

Semaphores are often used to restrict the number of threads than can access some (physical or logical) resource

Java does not have built-in Mutex API. But it can be implemented as binary semaphore.

A semaphore initialized to one, and which is used such that it only has at most one permit available, can serve as a mutual exclusion lock. This is more commonly known as a binary semaphore, because it only has two states: one permit available, or zero permits available.

When used in this way, the binary semaphore has the property (unlike many Lock implementations), that the "lock" can be released by a thread other than the owner (as semaphores have no notion of ownership). This can be useful in some specialized contexts, such as deadlock recovery.

So key differences between Semaphore and Mutex:

  1. Semaphore restrict number of threads to access a resource throuhg permits. Mutex allows only one thread to access resource.

  2. No threads owns Semaphore. Threads can update number of permits by calling acquire() and release() methods. Mutexes should be unlocked only by the thread holding the lock.

  3. When a mutex is used with condition variables, there is an implied bracketing—it is clear which part of the program is being protected. This is not necessarily the case for a semaphore, which might be called the go to of concurrent programming—it is powerful but too easy to use in an unstructured, indeterminate way.

Editing in the Chrome debugger

Pretty easy, go to the 'scripts' tab. And select the source file you want and double-click any line to edit it.

Compare if BigDecimal is greater than zero

This works too:

value > BigDecimal.ZERO

Should I call Close() or Dispose() for stream objects?

The documentation says that these two methods are equivalent:

StreamReader.Close: This implementation of Close calls the Dispose method passing a true value.

StreamWriter.Close: This implementation of Close calls the Dispose method passing a true value.

Stream.Close: This method calls Dispose, specifying true to release all resources.

So, both of these are equally valid:

/* Option 1, implicitly calling Dispose */
using (StreamWriter writer = new StreamWriter(filename)) { 
   // do something
} 

/* Option 2, explicitly calling Close */
StreamWriter writer = new StreamWriter(filename)
try {
    // do something
}
finally {
    writer.Close();
}

Personally, I would stick with the first option, since it contains less "noise".

PHP: How to remove all non printable characters in a string?

I solved problem for UTF8 using https://github.com/neitanod/forceutf8

use ForceUTF8\Encoding;

$string = Encoding::fixUTF8($string);

SQL ROWNUM how to return rows between a specific range

 SELECT * from
 (
 select m.*, rownum r
 from maps006 m
 )
 where r > 49 and r < 101

What is the difference between the | and || or operators?

The singe pipe "|" is the "bitwise" or and should only be used when you know what you're doing. The double pipe "||" is a logical or, and can be used in logical statements, like "x == 0 || x == 1".

Here's an example of what the bitwise or does: if a=0101 and b=0011, then a|b=0111. If you're dealing with a logic system that treats any non-zero as true, then the bitwise or will act in the same way as the logical or, but it's counterpart (bitwise and, "&") will NOT. Also the bitwise or does not perform short circuit evaluation.

Differentiate between function overloading and function overriding

Function overloading is same name function but different arguments. Function over riding means same name function and same as arguments

Creating a blocking Queue<T> in .NET?

Starting with .NET 5.0/Core 3.0 you can use System.Threading.Channels
Benchmarks from this (Asynchronous Producer Consumer Pattern in .NET (C#)) article show a significant speed boost over BlockingCollection!

How do you display a Toast from a background thread on Android?

This is similar to other answers, however updated for new available apis and much cleaner. Also, does not assume you're in an Activity Context.

public class MyService extends AnyContextSubclass {

    public void postToastMessage(final String message) {
        Handler handler = new Handler(Looper.getMainLooper());

        handler.post(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
            }
        });
    }
}

Count the number of times a string appears within a string

do this , please note that you will have to define the regex for 'test'!!!

string s = "7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false";
string[] parts = (new Regex("")).Split(s);
//just do a count on parts

problem with php mail 'From' header

I realize this is an old thread, but i had the same problem since i moved to bluehost yesterday. It may not have been the selected answer but i support the bluehost article 206 reply.

I created a valid email in control panel and used it as my From address and it worked.

Android ListView headers

As an alternative, there's a nice 3rd party library designed just for this use case. Whereby you need to generate headers based on the data being stored in the adapter. They are called Rolodex adapters and are used with ExpandableListViews. They can easily be customized to behave like a normal list with headers.

Using the OP's Event objects and knowing the headers are based on the Date associated with it...the code would look something like this:

The Activity

    //There's no need to pre-compute what the headers are. Just pass in your List of objects. 
    EventDateAdapter adapter = new EventDateAdapter(this, mEvents);
    mExpandableListView.setAdapter(adapter);

The Adapter

private class EventDateAdapter extends NFRolodexArrayAdapter<Date, Event> {

    public EventDateAdapter(Context activity, Collection<Event> items) {
        super(activity, items);
    }

    @Override
    public Date createGroupFor(Event childItem) {
        //This is how the adapter determines what the headers are and what child items belong to it
        return (Date) childItem.getDate().clone();
    }

    @Override
    public View getChildView(LayoutInflater inflater, int groupPosition, int childPosition,
                             boolean isLastChild, View convertView, ViewGroup parent) {
        //Inflate your view

        //Gets the Event data for this view
        Event event = getChild(groupPosition, childPosition);

        //Fill view with event data
    }

    @Override
    public View getGroupView(LayoutInflater inflater, int groupPosition, boolean isExpanded,
                             View convertView, ViewGroup parent) {
        //Inflate your header view

        //Gets the Date for this view
        Date date = getGroup(groupPosition);

        //Fill view with date data
    }

    @Override
    public boolean hasAutoExpandingGroups() {
        //This forces our group views (headers) to always render expanded.
        //Even attempting to programmatically collapse a group will not work.
        return true;
    }

    @Override
    public boolean isGroupSelectable(int groupPosition) {
        //This prevents a user from seeing any touch feedback when a group (header) is clicked.
        return false;
    }
}

Regex Explanation ^.*$

"^.*$"

literally just means select everything

"^"  // anchors to the beginning of the line
".*" // zero or more of any character
"$"  // anchors to end of line

Setting graph figure size

I managed to get a good result with the following sequence (run Matlab twice at the beginning):

h = gcf; % Current figure handle
set(h,'Resize','off');
set(h,'PaperPositionMode','manual');
set(h,'PaperPosition',[0 0 9 6]);
set(h,'PaperUnits','centimeters');
set(h,'PaperSize',[9 6]); % IEEE columnwidth = 9cm
set(h,'Position',[0 0 9 6]);
% xpos, ypos must be set
txlabel = text(xpos,ypos,'$$[\mathrm{min}]$$','Interpreter','latex','FontSize',9);

% Dump colored encapsulated PostScript
print('-depsc2','-loose', 'signals');

Laravel 5.4 Specific Table Migration

Or you can simply delete migration file name from your database, in "migrations" table and then run : php artitsan migration

Using Rsync include and exclude options to include directory and file by pattern

Here's my "teach a person to fish" answer:

Rsync's syntax is definitely non-intuitive, but it is worth understanding.

  1. First, use -vvv to see the debug info for rsync.
$ rsync -nr -vvv --include="**/file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/

[sender] hiding directory 1280000000 because of pattern *
[sender] hiding directory 1260000000 because of pattern *
[sender] hiding directory 1270000000 because of pattern *

The key concept here is that rsync applies the include/exclude patterns for each directory recursively. As soon as the first include/exclude is matched, the processing stops.

The first directory it evaluates is /Storage/uploads. Storage/uploads has 1280000000/, 1260000000/, 1270000000/ dirs/files. None of them match file_11*.jpg to include. All of them match * to exclude. So they are excluded, and rsync ends.

  1. The solution is to include all dirs (*/) first. Then the first dir component will be 1260000000/, 1270000000/, 1280000000/ since they match */. The next dir component will be 1260000000/. In 1260000000/, file_11_00.jpg matches --include="file_11*.jpg", so it is included. And so forth.
$ rsync -nrv --include='*/' --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/

./
1260000000/
1260000000/file_11_00.jpg
1260000000/file_11_01.jpg
1270000000/
1270000000/file_11_00.jpg
1270000000/file_11_01.jpg
1280000000/
1280000000/file_11_00.jpg
1280000000/file_11_01.jpg

https://download.samba.org/pub/rsync/rsync.1

How can I display a pdf document into a Webview?

You can use the Mozilla pdf.js project. Basically it will show you the PDF. Take a look at their example.

I only use it on the browser (desktop and mobile) and it's working fine.

Matplotlib transparent line plots

Plain and simple:

plt.plot(x, y, 'r-', alpha=0.7)

(I know I add nothing new, but the straightforward answer should be visible).

How do I generate random number for each row in a TSQL Select?

The Rand() function will generate the same random number, if used in a table SELECT query. Same applies if you use a seed to the Rand function. An alternative way to do it, is using this:

SELECT ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)) AS [RandomNumber]

Got the information from here, which explains the problem very well.

Replace non-ASCII characters with a single space

Potentially for a different question, but I'm providing my version of @Alvero's answer (using unidecode). I want to do a "regular" strip on my strings, i.e. the beginning and end of my string for whitespace characters, and then replace only other whitespace characters with a "regular" space, i.e.

"Ceñía?mañana????"

to

"Ceñía mañana"

,

def safely_stripped(s: str):
    return ' '.join(
        stripped for stripped in
        (bit.strip() for bit in
         ''.join((c if unidecode(c) else ' ') for c in s).strip().split())
        if stripped)

We first replace all non-unicode spaces with a regular space (and join it back again),

''.join((c if unidecode(c) else ' ') for c in s)

And then we split that again, with python's normal split, and strip each "bit",

(bit.strip() for bit in s.split())

And lastly join those back again, but only if the string passes an if test,

' '.join(stripped for stripped in s if stripped)

And with that, safely_stripped('????Ceñía?mañana????') correctly returns 'Ceñía mañana'.

Simple example for Intent and Bundle

Try this: if you need pass values between the activities you use this...

This is code for Main_Activity put the values to intent

 String name="aaaa";
 Intent intent=new Intent(Main_Activity.this,Other_Activity.class);
 intent.putExtra("name", name);
 startActivity(intent);

This code for Other_Activity and get the values form intent

    Bundle b = new Bundle();
    b = getIntent().getExtras();
    String name = b.getString("name");

Read only file system on Android

I just only needed this:

su -c "mount -o rw,remount /system"

How to assign multiple classes to an HTML container?

Just remove the comma like this:

<article class="column wrapper"> 

PyTorch: How to get the shape of a Tensor as a list of int

Previous answers got you list of torch.Size Here is how to get list of ints

listofints = [int(x) for x in tensor.shape]

How to convert PDF files to images

The thread "converting PDF file to a JPEG image" is suitable for your request.

One solution is to use a third-party library. ImageMagick is a very popular and is freely available too. You can get a .NET wrapper for it here. The original ImageMagick download page is here.

And you also can take a look at the thread "How to open a page from a pdf file in pictureBox in C#".

If you use this process to convert a PDF to tiff, you can use this class to retrieve the bitmap from TIFF.

public class TiffImage
{
    private string myPath;
    private Guid myGuid;
    private FrameDimension myDimension;
    public ArrayList myImages = new ArrayList();
    private int myPageCount;
    private Bitmap myBMP;

    public TiffImage(string path)
    {
        MemoryStream ms;
        Image myImage;

        myPath = path;
        FileStream fs = new FileStream(myPath, FileMode.Open);
        myImage = Image.FromStream(fs);
        myGuid = myImage.FrameDimensionsList[0];
        myDimension = new FrameDimension(myGuid);
        myPageCount = myImage.GetFrameCount(myDimension);
        for (int i = 0; i < myPageCount; i++)
        {
            ms = new MemoryStream();
            myImage.SelectActiveFrame(myDimension, i);
            myImage.Save(ms, ImageFormat.Bmp);
            myBMP = new Bitmap(ms);
            myImages.Add(myBMP);
            ms.Close();
        }
        fs.Close();
    }
}

Use it like so:

private void button1_Click(object sender, EventArgs e)
{
    TiffImage myTiff = new TiffImage("D:\\Some.tif");
    //imageBox is a PictureBox control, and the [] operators pass back
    //the Bitmap stored at that position in the myImages ArrayList in the TiffImage
    this.pictureBox1.Image = (Bitmap)myTiff.myImages[0];
    this.pictureBox2.Image = (Bitmap)myTiff.myImages[1];
    this.pictureBox3.Image = (Bitmap)myTiff.myImages[2];
}

Leave only two decimal places after the dot

Simple solution:

double totalCost = 123.45678;
totalCost = Convert.ToDouble(String.Format("{0:0.00}", totalCost));

//output: 123.45

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.

How can I combine hashes in Perl?

Check out perlfaq4: How do I merge two hashes. There is a lot of good information already in the Perl documentation and you can have it right away rather than waiting for someone else to answer it. :)


Before you decide to merge two hashes, you have to decide what to do if both hashes contain keys that are the same and if you want to leave the original hashes as they were.

If you want to preserve the original hashes, copy one hash (%hash1) to a new hash (%new_hash), then add the keys from the other hash (%hash2 to the new hash. Checking that the key already exists in %new_hash gives you a chance to decide what to do with the duplicates:

my %new_hash = %hash1; # make a copy; leave %hash1 alone

foreach my $key2 ( keys %hash2 )
    {
    if( exists $new_hash{$key2} )
        {
        warn "Key [$key2] is in both hashes!";
        # handle the duplicate (perhaps only warning)
        ...
        next;
        }
    else
        {
        $new_hash{$key2} = $hash2{$key2};
        }
    }

If you don't want to create a new hash, you can still use this looping technique; just change the %new_hash to %hash1.

foreach my $key2 ( keys %hash2 )
    {
    if( exists $hash1{$key2} )
        {
        warn "Key [$key2] is in both hashes!";
        # handle the duplicate (perhaps only warning)
        ...
        next;
        }
    else
        {
        $hash1{$key2} = $hash2{$key2};
        }
    }

If you don't care that one hash overwrites keys and values from the other, you could just use a hash slice to add one hash to another. In this case, values from %hash2 replace values from %hash1 when they have keys in common:

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

How to make phpstorm display line numbers by default?

Simplest solution for line numbers in php storm..There are many other solutions but i think A big picture a good from 1000 words.

Simplest solution for line numbers in php storm..There are many other solutions but i think A big picture a good from 1000 words.

entity object cannot be referenced by multiple instances of IEntityChangeTracker. while adding related objects to entity in Entity Framework 4.1

I hit this same problem after implementing IoC for a project (ASP.Net MVC EF6.2).

Usually I would initialise a data context in the constructor of a controller and use the same context to initialise all my repositories.

However using IoC to instantiate the repositories caused them all to have separate contexts and I started getting this error.

For now I've gone back to just newing up the repositories with a common context while I think of a better way.

Pythonic way to print list items

I use this all the time :

#!/usr/bin/python

l = [1,2,3,7] 
print "".join([str(x) for x in l])

When should a class be Comparable and/or Comparator?

The text below comes from Comparator vs Comparable

Comparable

A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.

Comparator

A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.

Angular redirect to login page

Refer this code, auth.ts file

import { CanActivate } from '@angular/router';
import { Injectable } from '@angular/core';
import {  } from 'angular-2-local-storage';
import { Router } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {
constructor(public localStorageService:LocalStorageService, private router: Router){}
canActivate() {
// Imaginary method that is supposed to validate an auth token
// and return a boolean
var logInStatus         =   this.localStorageService.get('logInStatus');
if(logInStatus == 1){
    console.log('****** log in status 1*****')
    return true;
}else{
    console.log('****** log in status not 1 *****')
    this.router.navigate(['/']);
    return false;
}


}

}
// *****And the app.routes.ts file is as follow ******//
      import {  Routes  } from '@angular/router';
      import {  HomePageComponent   } from './home-page/home- page.component';
      import {  WatchComponent  } from './watch/watch.component';
      import {  TeachersPageComponent   } from './teachers-page/teachers-page.component';
      import {  UserDashboardComponent  } from './user-dashboard/user- dashboard.component';
      import {  FormOneComponent    } from './form-one/form-one.component';
      import {  FormTwoComponent    } from './form-two/form-two.component';
      import {  AuthGuard   } from './authguard';
      import {  LoginDetailsComponent } from './login-details/login-details.component';
      import {  TransactionResolver } from './trans.resolver'
      export const routes:Routes    =   [
    { path:'',              component:HomePageComponent                                                 },
    { path:'watch',         component:WatchComponent                                                },
    { path:'teachers',      component:TeachersPageComponent                                         },
    { path:'dashboard',     component:UserDashboardComponent,       canActivate: [AuthGuard],   resolve: { dashboardData:TransactionResolver } },
    { path:'formone',       component:FormOneComponent,                 canActivate: [AuthGuard],   resolve: { dashboardData:TransactionResolver } },
    { path:'formtwo',       component:FormTwoComponent,                 canActivate: [AuthGuard],   resolve: { dashboardData:TransactionResolver } },
    { path:'login-details', component:LoginDetailsComponent,            canActivate: [AuthGuard]    },

]; 

Android: Cancel Async Task

How to cancel AsyncTask

Full answer is here - Android AsyncTask Example

AsyncTask provides a better cancellation strategy, to terminate currently running task.

cancel(boolean mayInterruptIfitRunning)

myTask.cancel(false)- It makes isCancelled returns true. Helps to cancel the task.

myTask.cancel(true) – It also makes isCancelled() returns true, interrupt the background thread and relieves resources .

It is considered as an arrogant way, If there is any thread.sleep() method performing in background thread, cancel(true) will interrupt background thread at that time. But cancel(false) will wait for it and cancel task when that method completes.

If you invoke cancel() and doInBackground() hasn’t begun execute yet. onCancelled() will invoke.

After invoking cancel(…) you should check value returned by isCancelled() on doInbackground() periodically. just like shown below.

protected Object doInBackground(Params… params)  { 
 while (condition)
{
 ...
if (isCancelled()) 
break;
}
return null; 
}

How can I make my flexbox layout take 100% vertical space?

set the wrapper to height 100%

.vwrapper {
  display: flex;
  flex-direction: column;

  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: stretch;
  align-content: stretch;

  height: 100%;
}

and set the 3rd row to flex-grow

#row3 {
   background-color: green;
   flex: 1 1 auto;
   display: flex;
}

demo

org.hibernate.MappingException: Could not determine type for: java.util.Set

You may just need to add @Transient annotations on roles to not serialize the set.

Why does Java have transient fields?

There is already an open DataReader associated with this Command which must be closed first

I solved this problem by changing await _accountSessionDataModel.SaveChangesAsync(); to _accountSessionDataModel.SaveChanges(); in my Repository class.

 public async Task<Session> CreateSession()
    {
        var session = new Session();

        _accountSessionDataModel.Sessions.Add(session);
        await _accountSessionDataModel.SaveChangesAsync();
     }

Changed it to:

 public Session CreateSession()
    {
        var session = new Session();

        _accountSessionDataModel.Sessions.Add(session);
        _accountSessionDataModel.SaveChanges();
     }

The problem was that I updated the Sessions in the frontend after creating a session (in code), but because SaveChangesAsync happens asynchronously, fetching the sessions caused this error because apparently the SaveChangesAsync operation was not yet ready.

Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

If uploading an image, try reducing the image quality, which is the second parameter of the Bitmap. This was the solution in my case. Previously it was 90, then I tried with 60 (as it is in the code below now).

Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
finalBitmap.compress(Bitmap.CompressFormat.JPEG,60,baos);
byte[] b = baos.toByteArray();

"’" showing on page instead of " ' "

I have some documents where was showing as … and ê was showing as ê. This is how it got there (python code):

# Adam edits original file using windows-1252
windows = '\x85\xea' 
# that is HORIZONTAL ELLIPSIS, LATIN SMALL LETTER E WITH CIRCUMFLEX

# Beth reads it correctly as windows-1252 and writes it as utf-8
utf8 = windows.decode("windows-1252").encode("utf-8")
print(utf8)

# Charlie reads it *incorrectly* as windows-1252 writes a twingled utf-8 version
twingled = utf8.decode("windows-1252").encode("utf-8")
print(twingled)

# detwingle by reading as utf-8 and writing as windows-1252 (it's really utf-8)
detwingled = twingled.decode("utf-8").encode("windows-1252")

assert utf8==detwingled

To fix the problem, I used python code like this:

with open("dirty.html","rb") as f:
    dt = f.read()
ct = dt.decode("utf8").encode("windows-1252")
with open("clean.html","wb") as g:
    g.write(ct)

(Because someone had inserted the twingled version into a correct UTF-8 document, I actually had to extract only the twingled part, detwingle it and insert it back in. I used BeautifulSoup for this.)

It is far more likely that you have a Charlie in content creation than that the web server configuration is wrong. You can also force your web browser to twingle the page by selecting windows-1252 encoding for a utf-8 document. Your web browser cannot detwingle the document that Charlie saved.

Note: the same problem can happen with any other single-byte code page (e.g. latin-1) instead of windows-1252.

Return the most recent record from ElasticSearch index

Since this question was originally asked and answered, some of the inner-workings of Elasticsearch have changed, particularly around timestamps. Here is a full example showing how to query for single latest record. Tested on ES 6/7.

1) Tell Elasticsearch to treat timestamp field as the timestamp

curl -XPUT "localhost:9200/my_index?pretty" -H 'Content-Type: application/json' -d '{"mappings":{"message":{"properties":{"timestamp":{"type":"date"}}}}}'

2) Put some test data into the index

curl -XPOST "localhost:9200/my_index/message/1" -H 'Content-Type: application/json' -d '{ "timestamp" : "2019-08-02T03:00:00Z", "message" : "hello world" }'
curl -XPOST "localhost:9200/my_index/message/2" -H 'Content-Type: application/json' -d '{ "timestamp" : "2019-08-02T04:00:00Z", "message" : "bye world" }'

3) Query for the latest record

curl -X POST "localhost:9200/my_index/_search" -H 'Content-Type: application/json' -d '{"query": {"match_all": {}},"size": 1,"sort": [{"timestamp": {"order": "desc"}}]}'

4) Expected results

{
   "took":0,
   "timed_out":false,
   "_shards":{
      "total":5,
      "successful":5,
      "skipped":0,
      "failed":0
   },
   "hits":{
      "total":2,
      "max_score":null,
      "hits":[
         {
            "_index":"my_index",
            "_type":"message",
            "_id":"2",
            "_score":null,
            "_source":{
               "timestamp":"2019-08-02T04:00:00Z",
               "message":"bye world"
            },
            "sort":[
               1564718400000
            ]
         }
      ]
   }
}

How can I turn a JSONArray into a JSONObject?

Typically, a Json object would contain your values (including arrays) as named fields within. So, something like:

JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
// populate the array
jo.put("arrayName",ja);

Which in JSON will be {"arrayName":[...]}.

JQuery - Get select value

var nationality = $("#dancerCountry").val(); should work. Are you sure that the element selector is working properly? Perhaps you should try:

var nationality = $('select[name="dancerCountry"]').val();

Passing data to a bootstrap modal

This is how you can send the id_data to a modal :

<input
    href="#"
    data-some-id="uid0123456789"
    data-toggle="modal"
    data-target="#my_modal"
    value="SHOW MODAL"
    type="submit"
    class="btn modal-btn"/>

<div class="col-md-5">
  <div class="modal fade" id="my_modal">
   <div class="modal-body modal-content">
     <h2 name="hiddenValue" id="hiddenValue" />
   </div>
   <div class="modal-footer" />
</div>

And the javascript :

    $(function () {
     $(".modal-btn").click(function (){
       var data_var = $(this).data('some-id');
       $(".modal-body h2").text(data_var);
     })
    });

NOW() function in PHP

Use strftime:

strftime("%F %T");
  • %F is the same as %Y-%m-%d.

  • %T is the same as %H:%M:%S.

Here's a demo on ideone.

How can I parse a YAML file in Python

Example:


defaults.yaml

url: https://www.google.com

environment.py

from ruamel import yaml

data = yaml.safe_load(open('defaults.yaml'))
data['url']

Android refresh current activity

The easiest way is to call onCreate(null); and your activity will be like new.

Android 5.0 - Add header/footer to a RecyclerView

I had the same problem on Lollipop and created two approaches to wrap the Recyclerview adapter. One is pretty easy to use, but I'm not sure how it will behave with a changing dataset. Because it wraps your adapter and you need to make yourself sure to call methods like notifyDataSetChanged on the right adapter-object.

The other shouldn't have such problems. Just let your regular adapter extend the class, implement the abstract methods and you should be ready. And here they are:

gists

HeaderRecyclerViewAdapterV1

import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;

/**
 * Created by sebnapi on 08.11.14.
 * <p/>
 * This is a Plug-and-Play Approach for adding a Header or Footer to
 * a RecyclerView backed list
 * <p/>
 * Just wrap your regular adapter like this
 * <p/>
 * new HeaderRecyclerViewAdapterV1(new RegularAdapter())
 * <p/>
 * Let RegularAdapter implement HeaderRecyclerView, FooterRecyclerView or both
 * and you are ready to go.
 * <p/>
 * I'm absolutely not sure how this will behave with changes in the dataset.
 * You can always wrap a fresh adapter and make sure to not change the old one or
 * use my other approach.
 * <p/>
 * With the other approach you need to let your Adapter extend HeaderRecyclerViewAdapterV2
 * (and therefore change potentially more code) but possible omit these shortcomings.
 * <p/>
 * TOTALLY UNTESTED - USE WITH CARE - HAVE FUN :)
 */
public class HeaderRecyclerViewAdapterV1 extends RecyclerView.Adapter {
    private static final int TYPE_HEADER = Integer.MIN_VALUE;
    private static final int TYPE_FOOTER = Integer.MIN_VALUE + 1;
    private static final int TYPE_ADAPTEE_OFFSET = 2;

    private final RecyclerView.Adapter mAdaptee;


    public HeaderRecyclerViewAdapterV1(RecyclerView.Adapter adaptee) {
        mAdaptee = adaptee;
    }

    public RecyclerView.Adapter getAdaptee() {
        return mAdaptee;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_HEADER && mAdaptee instanceof HeaderRecyclerView) {
            return ((HeaderRecyclerView) mAdaptee).onCreateHeaderViewHolder(parent, viewType);
        } else if (viewType == TYPE_FOOTER && mAdaptee instanceof FooterRecyclerView) {
            return ((FooterRecyclerView) mAdaptee).onCreateFooterViewHolder(parent, viewType);
        }
        return mAdaptee.onCreateViewHolder(parent, viewType - TYPE_ADAPTEE_OFFSET);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (position == 0 && holder.getItemViewType() == TYPE_HEADER && useHeader()) {
            ((HeaderRecyclerView) mAdaptee).onBindHeaderView(holder, position);
        } else if (position == mAdaptee.getItemCount() && holder.getItemViewType() == TYPE_FOOTER && useFooter()) {
            ((FooterRecyclerView) mAdaptee).onBindFooterView(holder, position);
        } else {
            mAdaptee.onBindViewHolder(holder, position - (useHeader() ? 1 : 0));
        }
    }

    @Override
    public int getItemCount() {
        int itemCount = mAdaptee.getItemCount();
        if (useHeader()) {
            itemCount += 1;
        }
        if (useFooter()) {
            itemCount += 1;
        }
        return itemCount;
    }

    private boolean useHeader() {
        if (mAdaptee instanceof HeaderRecyclerView) {
            return true;
        }
        return false;
    }

    private boolean useFooter() {
        if (mAdaptee instanceof FooterRecyclerView) {
            return true;
        }
        return false;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0 && useHeader()) {
            return TYPE_HEADER;
        }
        if (position == mAdaptee.getItemCount() && useFooter()) {
            return TYPE_FOOTER;
        }
        if (mAdaptee.getItemCount() >= Integer.MAX_VALUE - TYPE_ADAPTEE_OFFSET) {
            new IllegalStateException("HeaderRecyclerViewAdapter offsets your BasicItemType by " + TYPE_ADAPTEE_OFFSET + ".");
        }
        return mAdaptee.getItemViewType(position) + TYPE_ADAPTEE_OFFSET;
    }


    public static interface HeaderRecyclerView {
        public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup parent, int viewType);

        public void onBindHeaderView(RecyclerView.ViewHolder holder, int position);
    }

    public static interface FooterRecyclerView {
        public RecyclerView.ViewHolder onCreateFooterViewHolder(ViewGroup parent, int viewType);

        public void onBindFooterView(RecyclerView.ViewHolder holder, int position);
    }

}

HeaderRecyclerViewAdapterV2

import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;

/**
 * Created by sebnapi on 08.11.14.
 * <p/>
 * If you extend this Adapter you are able to add a Header, a Footer or both
 * by a similar ViewHolder pattern as in RecyclerView.
 * <p/>
 * If you want to omit changes to your class hierarchy you can try the Plug-and-Play
 * approach HeaderRecyclerViewAdapterV1.
 * <p/>
 * Don't override (Be careful while overriding)
 * - onCreateViewHolder
 * - onBindViewHolder
 * - getItemCount
 * - getItemViewType
 * <p/>
 * You need to override the abstract methods introduced by this class. This class
 * is not using generics as RecyclerView.Adapter make yourself sure to cast right.
 * <p/>
 * TOTALLY UNTESTED - USE WITH CARE - HAVE FUN :)
 */
public abstract class HeaderRecyclerViewAdapterV2 extends RecyclerView.Adapter {
    private static final int TYPE_HEADER = Integer.MIN_VALUE;
    private static final int TYPE_FOOTER = Integer.MIN_VALUE + 1;
    private static final int TYPE_ADAPTEE_OFFSET = 2;

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_HEADER) {
            return onCreateHeaderViewHolder(parent, viewType);
        } else if (viewType == TYPE_FOOTER) {
            return onCreateFooterViewHolder(parent, viewType);
        }
        return onCreateBasicItemViewHolder(parent, viewType - TYPE_ADAPTEE_OFFSET);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (position == 0 && holder.getItemViewType() == TYPE_HEADER) {
            onBindHeaderView(holder, position);
        } else if (position == getBasicItemCount() && holder.getItemViewType() == TYPE_FOOTER) {
            onBindFooterView(holder, position);
        } else {
            onBindBasicItemView(holder, position - (useHeader() ? 1 : 0));
        }
    }

    @Override
    public int getItemCount() {
        int itemCount = getBasicItemCount();
        if (useHeader()) {
            itemCount += 1;
        }
        if (useFooter()) {
            itemCount += 1;
        }
        return itemCount;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0 && useHeader()) {
            return TYPE_HEADER;
        }
        if (position == getBasicItemCount() && useFooter()) {
            return TYPE_FOOTER;
        }
        if (getBasicItemType(position) >= Integer.MAX_VALUE - TYPE_ADAPTEE_OFFSET) {
            new IllegalStateException("HeaderRecyclerViewAdapter offsets your BasicItemType by " + TYPE_ADAPTEE_OFFSET + ".");
        }
        return getBasicItemType(position) + TYPE_ADAPTEE_OFFSET;
    }

    public abstract boolean useHeader();

    public abstract RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup parent, int viewType);

    public abstract void onBindHeaderView(RecyclerView.ViewHolder holder, int position);

    public abstract boolean useFooter();

    public abstract RecyclerView.ViewHolder onCreateFooterViewHolder(ViewGroup parent, int viewType);

    public abstract void onBindFooterView(RecyclerView.ViewHolder holder, int position);

    public abstract RecyclerView.ViewHolder onCreateBasicItemViewHolder(ViewGroup parent, int viewType);

    public abstract void onBindBasicItemView(RecyclerView.ViewHolder holder, int position);

    public abstract int getBasicItemCount();

    /**
     * make sure you don't use [Integer.MAX_VALUE-1, Integer.MAX_VALUE] as BasicItemViewType
     *
     * @param position
     * @return
     */
    public abstract int getBasicItemType(int position);

}

Feedback and forks appreciated. I will use HeaderRecyclerViewAdapterV2 by my self and evolve, test and post the changes in the future.

EDIT: @OvidiuLatcu Yes I had some problems. Actually I stopped offsetting the Header implicitly by position - (useHeader() ? 1 : 0) and instead created a public method int offsetPosition(int position) for it. Because if you set an OnItemTouchListener on Recyclerview, you can intercept the touch, get the x,y coordinates of the touch, find the according child view and then call recyclerView.getChildPosition(...)and you will always get the non-offsetted position in the adapter! This is a shortcomming in the RecyclerView Code, I don't see an easy method to overcome this. This is why I now offset the positions explicit when I need to by my own code.

how do I make a single legend for many subplots with matplotlib?

For the automatic positioning of a single legend in a figure with many axes, like those obtained with subplots(), the following solution works really well:

plt.legend( lines, labels, loc = 'lower center', bbox_to_anchor = (0,-0.1,1,1),
            bbox_transform = plt.gcf().transFigure )

With bbox_to_anchor and bbox_transform=plt.gcf().transFigure you are defining a new bounding box of the size of your figureto be a reference for loc. Using (0,-0.1,1,1) moves this bouding box slightly downwards to prevent the legend to be placed over other artists.

OBS: use this solution AFTER you use fig.set_size_inches() and BEFORE you use fig.tight_layout()

python location on mac osx

I have a cook recipe for finding things in linux/macos

First update the locate db then do a

locate WHATiWANTtoSEARCH | less

do a /find to find what you are looking for.

to update your locate db in macos do this:

sudo /usr/libexec/locate.updatedb

it sometimes takes a while. Hope this helps :)

How to use ArgumentCaptor for stubbing?

The line

when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);

would do the same as

when(someObject.doSomething(Matchers.any())).thenReturn(true);

So, using argumentCaptor.capture() when stubbing has no added value. Using Matchers.any() shows better what really happens and therefor is better for readability. With argumentCaptor.capture(), you can't read what arguments are really matched. And instead of using any(), you can use more specific matchers when you have more information (class of the expected argument), to improve your test.

And another problem: If using argumentCaptor.capture() when stubbing it becomes unclear how many values you should expect to be captured after verification. We want to capture a value during verification, not during stubbing because at that point there is no value to capture yet. So what does the argument captors capture method capture during stubbing? It capture anything because there is nothing to be captured yet. I consider it to be undefined behavior and I don't want to use undefined behavior.

How can I create a small color box using html and css?

You can create these easily using the floating ability of CSS, for example. I have created a small example on Jsfiddle over here, all the related css and html is also provided there.

_x000D_
_x000D_
.foo {_x000D_
  float: left;_x000D_
  width: 20px;_x000D_
  height: 20px;_x000D_
  margin: 5px;_x000D_
  border: 1px solid rgba(0, 0, 0, .2);_x000D_
}_x000D_
_x000D_
.blue {_x000D_
  background: #13b4ff;_x000D_
}_x000D_
_x000D_
.purple {_x000D_
  background: #ab3fdd;_x000D_
}_x000D_
_x000D_
.wine {_x000D_
  background: #ae163e;_x000D_
}
_x000D_
<div class="foo blue"></div>_x000D_
<div class="foo purple"></div>_x000D_
<div class="foo wine"></div>
_x000D_
_x000D_
_x000D_

Best way to check if a Data Table has a null value in it

DataTable dt = new DataTable();
foreach (DataRow dr in dt.Rows)
{
    if (dr["Column_Name"] == DBNull.Value)
    {
        //Do something
    }
    else
    {
        //Do something
    }
}

TCPDF Save file to folder?

$pdf->Output() takes a second parameter $dest, which accepts a single character. The default, $dest='I' opens the PDF in the browser.

Use F to save to file

$pdf->Output('/path/to/file.pdf', 'F')

Updating state on props change in React Form

Use Memoize

The op's derivation of state is a direct manipulation of props, with no true derivation needed. In other words, if you have a prop which can be utilized or transformed directly there is no need to store the prop on state.

Given that the state value of start_time is simply the prop start_time.format("HH:mm"), the information contained in the prop is already in itself sufficient for updating the component.

However if you did want to only call format on a prop change, the correct way to do this per latest documentation would be via Memoize: https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization

Mac zip compress without __MACOSX folder?

I'm using this Automator Shell Script to fix it after. It's showing up as contextual menu item (right clicking on any file showing up in Finder).

while read -r p; do
  zip -d "$p" __MACOSX/\* || true
  zip -d "$p" \*/.DS_Store || true
done
  1. Create a new Service with Automator
  2. Select "Files and Folders" in "Finder"
  3. Add a "Shell Script Action"

automator shell script

contextual menu item in Finder

how to add jquery in laravel project

You can link libraries from cdn (Content delivery network):

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

Or link libraries locally, add css files in the css folder and jquery in js folder. You have to keep both folders in the laravel public folder then you can link like below:

<link rel="stylesheet" href="{{asset('css/bootstrap-theme.min.css')}}">
<script src="{{asset('js/jquery.min.js')}}"></script>

or else

{{ HTML::style('css/style.css') }}
{{ HTML::script('js/functions.js') }}

If you link js files and css files locally (like in the last two examples) you need to add js and css files to the js and css folders which are in public\js or public\css not in resources\assets.

How to convert String to Date value in SAS?

This code helps:

data final; set final;

first_date = INPUT(compress(char_date),date9.); format first_date date9.;

run;

I personally have tried it on SAS

CMD what does /im (taskkill)?

If you type the executable name and a /? switch at the command line, there is typically help information available. Doing so with taskkill /? provides the following, for instance:

TASKKILL [/S system [/U username [/P [password]]]]
         { [/FI filter] [/PID processid | /IM imagename] } [/T] [/F]

Description:
    This tool is used to terminate tasks by process id (PID) or image name.

Parameter List:
    /S    system           Specifies the remote system to connect to.

    /U    [domain\]user    Specifies the user context under which the
                           command should execute.

    /P    [password]       Specifies the password for the given user
                           context. Prompts for input if omitted.

    /FI   filter           Applies a filter to select a set of tasks.
                           Allows "*" to be used. ex. imagename eq acme*

    /PID  processid        Specifies the PID of the process to be terminated.
                           Use TaskList to get the PID.

    /IM   imagename        Specifies the image name of the process
                           to be terminated. Wildcard '*' can be used
                           to specify all tasks or image names.

    /T                     Terminates the specified process and any
                           child processes which were started by it.

    /F                     Specifies to forcefully terminate the process(es).

    /?                     Displays this help message.

Filters:
    Filter Name   Valid Operators           Valid Value(s)
    -----------   ---------------           -------------------------
    STATUS        eq, ne                    RUNNING |
                                            NOT RESPONDING | UNKNOWN
    IMAGENAME     eq, ne                    Image name
    PID           eq, ne, gt, lt, ge, le    PID value
    SESSION       eq, ne, gt, lt, ge, le    Session number.
    CPUTIME       eq, ne, gt, lt, ge, le    CPU time in the format
                                            of hh:mm:ss.
                                            hh - hours,
                                            mm - minutes, ss - seconds
    MEMUSAGE      eq, ne, gt, lt, ge, le    Memory usage in KB
    USERNAME      eq, ne                    User name in [domain\]user
                                            format
    MODULES       eq, ne                    DLL name
    SERVICES      eq, ne                    Service name
    WINDOWTITLE   eq, ne                    Window title

    NOTE
    ----
    1) Wildcard '*' for /IM switch is accepted only when a filter is applied.
    2) Termination of remote processes will always be done forcefully (/F).
    3) "WINDOWTITLE" and "STATUS" filters are not considered when a remote
       machine is specified.

Examples:
    TASKKILL /IM notepad.exe
    TASKKILL /PID 1230 /PID 1241 /PID 1253 /T
    TASKKILL /F /IM cmd.exe /T 
    TASKKILL /F /FI "PID ge 1000" /FI "WINDOWTITLE ne untitle*"
    TASKKILL /F /FI "USERNAME eq NT AUTHORITY\SYSTEM" /IM notepad.exe
    TASKKILL /S system /U domain\username /FI "USERNAME ne NT*" /IM *
    TASKKILL /S system /U username /P password /FI "IMAGENAME eq note*"

You can also find this information, as well as documentation for most of the other command-line utilities, in the Microsoft TechNet Command-Line Reference

Minimal web server using netcat

Type in nc -h and see if You have -e option available. If yes, You can create a script, for example:

script.sh

echo -e "HTTP/1.1 200 OK\n\n $(date)"

and run it like this:

while true ; do nc -l -p 1500 -e script.sh; done

Note that -e option needs to be enabled at compilation to be available.

Extract every nth element of a vector

To select every nth element from any starting position in the vector

nth_element <- function(vector, starting_position, n) { 
  vector[seq(starting_position, length(vector), n)] 
  }

# E.g.
vec <- 1:12

nth_element(vec, 1, 3)
# [1]  1  4  7 10

nth_element(vec, 2, 3)
# [1]  2  5  8 11

Post an object as data using Jquery Ajax

Is not necessary to pass the data as JSON string, you can pass the object directly, without defining contentType or dataType, like this:

$.ajax({
    type: "POST",
    url: "TelephoneNumbers.aspx/DeleteNumber",
    data: data0,

    success: function(data)
    {
        alert('Done');
    }
});

How to use Git for Unity3D source control?

Edit -> Project Settings -> Editor

Set Version Control to meta files. Set Asset Serialization to force text.

I think this is what you want.

Simple way to transpose columns and rows in SQL?

Based on this solution from bluefeet here is a stored procedure that uses dynamic sql to generate the transposed table. It requires that all the fields are numeric except for the transposed column (the column that will be the header in the resulting table):

/****** Object:  StoredProcedure [dbo].[SQLTranspose]    Script Date: 11/10/2015 7:08:02 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Paco Zarate
-- Create date: 2015-11-10
-- Description: SQLTranspose dynamically changes a table to show rows as headers. It needs that all the values are numeric except for the field using for     transposing.
-- Parameters: @TableName - Table to transpose
--             @FieldNameTranspose - Column that will be the new headers
-- Usage: exec SQLTranspose <table>, <FieldToTranspose>
-- =============================================
ALTER PROCEDURE [dbo].[SQLTranspose] 
  -- Add the parameters for the stored procedure here
  @TableName NVarchar(MAX) = '', 
  @FieldNameTranspose NVarchar(MAX) = ''
AS
BEGIN
  -- SET NOCOUNT ON added to prevent extra result sets from
  -- interfering with SELECT statements.
  SET NOCOUNT ON;

  DECLARE @colsUnpivot AS NVARCHAR(MAX),
  @query  AS NVARCHAR(MAX),
  @queryPivot  AS NVARCHAR(MAX),
  @colsPivot as  NVARCHAR(MAX),
  @columnToPivot as NVARCHAR(MAX),
  @tableToPivot as NVARCHAR(MAX), 
  @colsResult as xml

  select @tableToPivot = @TableName;
  select @columnToPivot = @FieldNameTranspose


  select @colsUnpivot = stuff((select ','+quotename(C.name)
       from sys.columns as C
       where C.object_id = object_id(@tableToPivot) and
             C.name <> @columnToPivot 
       for xml path('')), 1, 1, '')

  set @queryPivot = 'SELECT @colsResult = (SELECT  '','' 
                    + quotename('+@columnToPivot+')
                  from '+@tableToPivot+' t
                  where '+@columnToPivot+' <> ''''
          FOR XML PATH(''''), TYPE)'

  exec sp_executesql @queryPivot, N'@colsResult xml out', @colsResult out

  select @colsPivot = STUFF(@colsResult.value('.', 'NVARCHAR(MAX)'),1,1,'')

  set @query 
    = 'select name, rowid, '+@colsPivot+'
        from
        (
          select '+@columnToPivot+' , name, value, ROW_NUMBER() over (partition by '+@columnToPivot+' order by '+@columnToPivot+') as rowid
          from '+@tableToPivot+'
          unpivot
          (
            value for name in ('+@colsUnpivot+')
          ) unpiv
        ) src
        pivot
        (
          sum(value)
          for '+@columnToPivot+' in ('+@colsPivot+')
        ) piv
        order by rowid'
  exec(@query)
END

You can test it with the table provided with this command:

exec SQLTranspose 'yourTable', 'color'

Sort arrays of primitive types in descending order

Here's a full program that sorts objects based on a inner field.

package Algorithms.BranchAndBound;

import java.util.Arrays;
import java.util.Comparator;

public class KnapSack01 {
    private class ItemVals {
        double weight;
        double cost;
        double ratio;

        public ItemVals(double weight, double cost) {
            this.weight = weight;
            this.cost = cost;
            this.ratio = weight/cost;
        }
    }

    public ItemVals[] createSortedItemVals(double[] weight, double[] cost) {
        ItemVals[] itemVals = new ItemVals[weight.length];
        for(int i = 0; i < weight.length; i++) {
            ItemVals itemval = new ItemVals(weight[i], cost[i]);
            itemVals[i] = itemval;
        }
        Arrays.sort(itemVals, new Comparator<ItemVals>() {
            @Override
            public int compare(ItemVals o1, ItemVals o2) {
                return Double.compare(o2.ratio, o1.ratio);
            }
        });
        return itemVals;
    }

    public void printItemVals(ItemVals[] itemVals) {
        for (int i = 0; i < itemVals.length; i++) {
            System.out.println(itemVals[i].ratio);
        }
    }

    public static void main(String[] args) {
        KnapSack01 knapSack01 = new KnapSack01();
        double[] weight = {2, 3.14, 1.98, 5, 3};
        double[] cost = {40, 50, 100, 95, 30};
        ItemVals[] itemVals = knapSack01.createSortedItemVals(weight, cost);
        knapSack01.printItemVals(itemVals);
    }
}

Use CSS to remove the space between images

I prefer do like this

img { float: left; }

to remove the space between images

Change the class from factor to numeric of many columns in a data frame

Further to Ramnath's answer, the behaviour you are experiencing is that due to as.numeric(x) returning the internal, numeric representation of the factor x at the R level. If you want to preserve the numbers that are the levels of the factor (rather than their internal representation), you need to convert to character via as.character() first as per Ramnath's example.

Your for loop is just as reasonable as an apply call and might be slightly more readable as to what the intention of the code is. Just change this line:

stats[,i] <- as.numeric(stats[,i])

to read

stats[,i] <- as.numeric(as.character(stats[,i]))

This is FAQ 7.10 in the R FAQ.

HTH

CSS background image to fit height, width should auto-scale in proportion

body.bg {
    background-size: cover;
    background-repeat: no-repeat;
    min-height: 100vh;
    background: white url(../images/bg-404.jpg) center center no-repeat;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
}   
Try This
_x000D_
_x000D_
    body.bg {_x000D_
     background-size: cover;_x000D_
     background-repeat: no-repeat;_x000D_
     min-height: 100vh;_x000D_
     background: white url(http://lorempixel.com/output/city-q-c-1920-1080-7.jpg) center center no-repeat;_x000D_
     -webkit-background-size: cover;_x000D_
     -moz-background-size: cover;_x000D_
     -o-background-size: cover;_x000D_
    } 
_x000D_
    <body class="bg">_x000D_
_x000D_
_x000D_
     _x000D_
    </body>
_x000D_
_x000D_
_x000D_

How to create an on/off switch with Javascript/CSS?

check out this generator: On/Off FlipSwitch

you can get various different style outcomes and its css only - no javascript!

Case-insensitive string comparison in C++

boost::iequals is not utf-8 compatible in the case of string. You can use boost::locale.

comparator<char,collator_base::secondary> cmpr;
cout << (cmpr(str1, str2) ? "str1 < str2" : "str1 >= str2") << endl;
  • Primary -- ignore accents and character case, comparing base letters only. For example "facade" and "Façade" are the same.
  • Secondary -- ignore character case but consider accents. "facade" and "façade" are different but "Façade" and "façade" are the same.
  • Tertiary -- consider both case and accents: "Façade" and "façade" are different. Ignore punctuation.
  • Quaternary -- consider all case, accents, and punctuation. The words must be identical in terms of Unicode representation.
  • Identical -- as quaternary, but compare code points as well.

Call method in directive controller from other controller

I got much better solution .

here is my directive , I have injected on object reference in directive and has extend that by adding invoke function in directive code .

app.directive('myDirective', function () {
    return {
        restrict: 'E',
        scope: {
        /*The object that passed from the cntroller*/
        objectToInject: '=',
        },
        templateUrl: 'templates/myTemplate.html',

        link: function ($scope, element, attrs) {
            /*This method will be called whet the 'objectToInject' value is changes*/
            $scope.$watch('objectToInject', function (value) {
                /*Checking if the given value is not undefined*/
                if(value){
                $scope.Obj = value;
                    /*Injecting the Method*/
                    $scope.Obj.invoke = function(){
                        //Do something
                    }
                }    
            });
        }
    };
});

Declaring the directive in the HTML with a parameter:

<my-directive object-to-inject="injectedObject"></ my-directive>

my Controller:

app.controller("myController", ['$scope', function ($scope) {
   // object must be empty initialize,so it can be appended
    $scope.injectedObject = {};

    // now i can directly calling invoke function from here 
     $scope.injectedObject.invoke();
}];

What is a good pattern for using a Global Mutex in C#?

A solution (for WPF) without WaitOne because it can cause an AbandonedMutexException. This solution uses the Mutex constructor that returns the createdNew boolean to check if the mutex is already created. It also uses the GetType().GUID so renaming an executable doesn't allow multiple instances.

Global vs local mutex see note in: https://docs.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8

private Mutex mutex;
private bool mutexCreated;

public App()
{
    string mutexId = $"Global\\{GetType().GUID}";
    mutex = new Mutex(true, mutexId, out mutexCreated);
}

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    if (!mutexCreated)
    {
        MessageBox.Show("Already started!");
        Shutdown();
    }
}

Because Mutex implements IDisposable it is released automatically but for completeness call dispose:

protected override void OnExit(ExitEventArgs e)
{
    base.OnExit(e);
    mutex.Dispose();
}

Move everything into a base class and add the allowEveryoneRule from the accepted answer. Also added ReleaseMutex though it doesn't look like it's really needed because it is released automatically by the OS (what if the application crashes and never calls ReleaseMutex would you need to reboot?).

public class SingleApplication : Application
{
    private Mutex mutex;
    private bool mutexCreated;

    public SingleApplication()
    {
        string mutexId = $"Global\\{GetType().GUID}";

        MutexAccessRule allowEveryoneRule = new MutexAccessRule(
            new SecurityIdentifier(WellKnownSidType.WorldSid, null),
            MutexRights.FullControl, 
            AccessControlType.Allow);
        MutexSecurity securitySettings = new MutexSecurity();
        securitySettings.AddAccessRule(allowEveryoneRule);

        // initiallyOwned: true == false + mutex.WaitOne()
        mutex = new Mutex(initiallyOwned: true, mutexId, out mutexCreated, securitySettings);        
    }

    protected override void OnExit(ExitEventArgs e)
    {
        base.OnExit(e);
        if (mutexCreated)
        {
            try
            {
                mutex.ReleaseMutex();
            }
            catch (ApplicationException ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().FullName, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        mutex.Dispose();
    }

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        if (!mutexCreated)
        {
            MessageBox.Show("Already started!");
            Shutdown();
        }
    }
}

Fastest check if row exists in PostgreSQL

Use the EXISTS key word for TRUE / FALSE return:

select exists(select 1 from contact where id=12)

In Angular, how to add Validator to FormControl after control is created?

To add onto what @Delosdos has posted.

Set a validator for a control in the FormGroup: this.myForm.controls['controlName'].setValidators([Validators.required])

Remove the validator from the control in the FormGroup: this.myForm.controls['controlName'].clearValidators()

Update the FormGroup once you have run either of the above lines. this.myForm.controls['controlName'].updateValueAndValidity()

This is an amazing way to programmatically set your form validation.

Case insensitive 'Contains(string)'

.NET Core 2.0+ only (as of now)

.NET Core has had a pair of methods to deal with this since version 2.0 :

  • String.Contains(Char, StringComparison)
  • String.Contains(String, StringComparison)

Example:

"Test".Contains("test", System.StringComparison.CurrentCultureIgnoreCase);

In time, they will probably make their way into the .NET Standard and, from there, into all the other implementations of the Base Class Library.

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

1) Start by opening up git-bash.exe in Administrator mode. (Right click the file and select "Run as Administrator", or change settings in Properties → Compatibility → Run this program as administrator.)

2) Run cd ~. It will take you to C:/Users/<Your-Username>.

3) Run vi .bashrc. This will open you up into the editor. Hit INSERT and then start entering the following info:

alias ll="ls -la" # this changes the default ll on git bash to see hidden files.
cd "C:\directory\to\your\work\path\"
ll # this shows your your directory before you even type anything.

How to get the version of ionic framework?

At some point in time the object changed from ionic to an uppercase Ionic.

As of July 2017 you need to put Ionic.version into your console to get the version number.

What does "Table does not support optimize, doing recreate + analyze instead" mean?

That's really an informational message.

Likely, you're doing OPTIMIZE on an InnoDB table (table using the InnoDB storage engine, rather than the MyISAM storage engine).

InnoDB doesn't support the OPTIMIZE the way MyISAM does. It does something different. It creates an empty table, and copies all of the rows from the existing table into it, and essentially deletes the old table and renames the new table, and then runs an ANALYZE to gather statistics. That's the closest that InnoDB can get to doing an OPTIMIZE.

The message you are getting is basically MySQL server repeating what the InnoDB storage engine told MySQL server:

Table does not support optimize is the InnoDB storage engine saying...

"I (the InnoDB storage engine) don't do an OPTIMIZE operation like my friend (the MyISAM storage engine) does."

"doing recreate + analyze instead" is the InnoDB storage engine saying...

"I have decided to perform a different set of operations which will achieve an equivalent result."

Char array in a struct - incompatible assignment?

use strncpy to make sure you have no buffer overflow.

char name[]= "whatever_you_want";
strncpy( sara.first, name, sizeof(sara.first)-1 );
sara.first[sizeof(sara.first)-1] = 0;

cURL error 60: SSL certificate: unable to get local issuer certificate

Attention Wamp/Wordpress/windows users. I had this issue for hours and not even the correct answer was doing it for me, because i was editing the wrong php.ini file because the question was answered to XAMPP and not for WAMP users, even though the question was for WAMP.

here's what i did

Download the certificate bundle.

Put it inside of C:\wamp64\bin\php\your php version\extras\ssl

Make sure the file mod_ssl.so is inside of C:\wamp64\bin\apache\apache(version)\modules

Enable mod_ssl in httpd.conf inside of Apache directory C:\wamp64\bin\apache\apache2.4.27\conf

Enable php_openssl.dll in php.ini. Be aware my problem was that I had two php.ini files and I need to do this in both of them. First one can be located inside of your WAMP taskbar icon here.

enter image description here

and the other one is located in C:\wamp64\bin\php\php(Version)

find the location for both of the php.ini files and find the line curl.cainfo = and give it a path like this

curl.cainfo = "C:\wamp64\bin\php\php(Version)\extras\ssl\cacert.pem"

Now save the files and restart your server and you should be good to go

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

I am answering bit late to this question, but someone, in future, might find this useful. The below approach, besides lots of other approaches, works best, and I personally think would better suit a web application.

@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {

 ... other configurations

@Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.serializationInclusion(JsonInclude.Include.NON_NULL);
        builder.propertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
        builder.serializationInclusion(Include.NON_EMPTY);
        builder.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
        converters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()));
    }
}

Filter element based on .data() key/value

Just for the record, you can filter on data with jquery (this question is quite old, and jQuery evolved since then, so it's right to write this solution as well):

$('.navlink[data-selected="true"]');

or, better (for performance):

$('.navlink').filter('[data-selected="true"]');

or, if you want to get all the elements with data-selected set:

$('[data-selected]')

Note that this method will only work with data that was set via html-attributes. If you set or change data with the .data() call, this method will no longer work.

Remove a JSON attribute

The selected answer would work for as long as you know the key itself that you want to delete but if it should be truly dynamic you would need to use the [] notation instead of the dot notation.

For example:

var keyToDelete = "key1";
var myObj = {"test": {"key1": "value", "key2": "value"}}

//that will not work.
delete myObj.test.keyToDelete 

instead you would need to use:

delete myObj.test[keyToDelete];

Substitute the dot notation with [] notation for those values that you want evaluated before being deleted.

C# Creating and using Functions

static void Main(string[] args)
    {
        Console.WriteLine("geef een leeftijd");
        int a = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("geef een leeftijd");
        int b = Convert.ToInt32(Console.ReadLine());

        int einde = Sum(a, b);
        Console.WriteLine(einde);
    }
    static int Sum(int x, int y)
    {
        int result = x + y;
        return result;

Get a DataTable Columns DataType

dt.Columns[0].DataType.Name.ToString()

Razor If/Else conditional operator syntax

You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:

@(deletedView ? "Deleted" : "Created by")

Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

Below code worked for me.

instead of use <%@ include file="styles/default.css"%>

CSS Child vs Descendant selectors

Just think of what the words "child" and "descendant" mean in English:

  • My daughter is both my child and my descendant
  • My granddaughter is not my child, but she is my descendant.

Programmatically select a row in JTable

You use the available API of JTable and do not try to mess with the colors.

Some selection methods are available directly on the JTable (like the setRowSelectionInterval). If you want to have access to all selection-related logic, the selection model is the place to start looking

SQL Server - INNER JOIN WITH DISTINCT

add "distinct" after "select".

select distinct a.FirstName, a.LastName, v.District , v.LastName
from AddTbl a 
inner join ValTbl v  where a.LastName = v.LastName  order by Firstname

Question mark and colon in JavaScript

Properly parenthesized for clarity, it is

hsb.s = (max != 0) ? (255 * delta / max) : 0;

meaning return either

  • 255*delta/max if max != 0
  • 0 if max == 0

Concat all strings inside a List<string> using LINQ

You can simply use:

List<string> items = new List<string>() { "foo", "boo", "john", "doe" };

Console.WriteLine(string.Join(",", items));

Happy coding!

Should I use window.navigate or document.location in JavaScript?

window.navigate is NOT supported in some browsers, so that one should be avoided. Any of the other methods using the location property are the most reliable and consistent approach

How to remove numbers from string using Regex.Replace?

var result = Regex.Replace("123- abcd33", @"[0-9\-]", string.Empty);

How to save select query results within temporary table?

You can also do the following:

CREATE TABLE #TEMPTABLE
(
    Column1 type1,
    Column2 type2,
    Column3 type3
)

INSERT INTO #TEMPTABLE
SELECT ...

SELECT *
FROM #TEMPTABLE ...

DROP TABLE #TEMPTABLE

Permutations between two lists of unequal length

Note: This answer is for the specific question asked above. If you are here from Google and just looking for a way to get a Cartesian product in Python, itertools.product or a simple list comprehension may be what you are looking for - see the other answers.


Suppose len(list1) >= len(list2). Then what you appear to want is to take all permutations of length len(list2) from list1 and match them with items from list2. In python:

import itertools
list1=['a','b','c']
list2=[1,2]

[list(zip(x,list2)) for x in itertools.permutations(list1,len(list2))]

Returns

[[('a', 1), ('b', 2)], [('a', 1), ('c', 2)], [('b', 1), ('a', 2)], [('b', 1), ('c', 2)], [('c', 1), ('a', 2)], [('c', 1), ('b', 2)]]