Programs & Examples On #Rfc2898

RFC 2898 issued by the IETF in 2000 is about "PKCS #5: Password-Based Cryptography Specification Version 2.0" and is mainly a republication of PKCS #5 v2.0 from RSA Laboratories' Public-Key Cryptography Standards (PKCS) series

AES Encrypt and Decrypt

Swift4:

let key = "ccC2H19lDDbQDfakxcrtNMQdd0FloLGG" // length == 32
let iv = "ggGGHUiDD0Qjhuvv" // length == 16
func encryptFile(_ path: URL) -> Bool{
    do{
        let data = try Data.init(contentsOf: path)
        let encodedData = try data.aesEncrypt(key: key, iv: iv)
        try encodedData.write(to: path)
        return true
    }catch{
        return false
    }
}

func decryptFile(_ path: URL) -> Bool{
    do{
        let data = try Data.init(contentsOf: path)
        let decodedData = try data.aesDecrypt(key: key, iv: iv)
        try decodedData.write(to: path)
        return true
    }catch{
        return false
    }
}

Install CryptoSwift

import CryptoSwift
extension Data {
    func aesEncrypt(key: String, iv: String) throws -> Data{
        let encypted = try AES(key: key.bytes, blockMode: CBC(iv: iv.bytes), padding: .pkcs7).encrypt(self.bytes)
        return Data(bytes: encypted)
    }

    func aesDecrypt(key: String, iv: String) throws -> Data {
        let decrypted = try AES(key: key.bytes, blockMode: CBC(iv: iv.bytes), padding: .pkcs7).decrypt(self.bytes)
        return Data(bytes: decrypted)
    }
}

Padding is invalid and cannot be removed?

Another scenario, again for the benefit of people searching.

For me this error occurred during the Dispose() method which masked a previous error unrelated to encryption.

Once the other component was fixed, this exception went away.

Change user-agent for Selenium web-driver

This is a short solution to change the request UserAgent on the fly.

Change UserAgent of a request with Chrome

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

driver = webdriver.Chrome(driver_path)
driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent":"python 2.7", "platform":"Windows"})
driver.get('http://amiunique.org')

then return your useragent:

agent = driver.execute_script("return navigator.userAgent")

Some sources

The source code of webdriver.py from SeleniumHQ (https://github.com/SeleniumHQ/selenium/blob/11c25d75bd7ed22e6172d6a2a795a1d195fb0875/py/selenium/webdriver/chrome/webdriver.py) extends its functionalities through the Chrome Devtools Protocol

def execute_cdp_cmd(self, cmd, cmd_args):
        """
        Execute Chrome Devtools Protocol command and get returned result

We can use the Chrome Devtools Protocol Viewer to list more extended functionalities (https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setUserAgentOverride) as well as the parameters type to use.

How to dismiss notification after action has been clicked

Found this to be an issue when using Lollipop's Heads Up Display notification. See design guidelines. Here's the complete(ish) code to implement.

Until now, having a 'Dismiss' button was less important, but now it's more in your face.

heads up notification

Building the Notification

int notificationId = new Random().nextInt(); // just use a counter in some util class...
PendingIntent dismissIntent = NotificationActivity.getDismissIntent(notificationId, context);

NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setPriority(NotificationCompat.PRIORITY_MAX) //HIGH, MAX, FULL_SCREEN and setDefaults(Notification.DEFAULT_ALL) will make it a Heads Up Display Style
        .setDefaults(Notification.DEFAULT_ALL) // also requires VIBRATE permission
        .setSmallIcon(R.drawable.ic_action_refresh) // Required!
        .setContentTitle("Message from test")
        .setContentText("message")
        .setAutoCancel(true)
        .addAction(R.drawable.ic_action_cancel, "Dismiss", dismissIntent)
        .addAction(R.drawable.ic_action_boom, "Action!", someOtherPendingIntent);

// Gets an instance of the NotificationManager service
NotificationManager notifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

// Builds the notification and issues it.
notifyMgr.notify(notificationId, builder.build());

NotificationActivity

public class NotificationActivity extends Activity {

    public static final String NOTIFICATION_ID = "NOTIFICATION_ID";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.cancel(getIntent().getIntExtra(NOTIFICATION_ID, -1));
        finish(); // since finish() is called in onCreate(), onDestroy() will be called immediately
    }

    public static PendingIntent getDismissIntent(int notificationId, Context context) {
        Intent intent = new Intent(context, NotificationActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.putExtra(NOTIFICATION_ID, notificationId);
        PendingIntent dismissIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        return dismissIntent;
    }

}

AndroidManifest.xml (attributes required to prevent SystemUI from focusing to a back stack)

<activity
    android:name=".NotificationActivity"
    android:taskAffinity=""
    android:excludeFromRecents="true">
</activity>

Best Way to View Generated Source of Webpage?

alert(document.documentElement.outerHTML);

ReactJS call parent method

To do this you pass a callback as a property down to the child from the parent.

For example:

var Parent = React.createClass({

    getInitialState: function() {
        return {
            value: 'foo'
        }
    },

    changeHandler: function(value) {
        this.setState({
            value: value
        });
    },

    render: function() {
        return (
            <div>
                <Child value={this.state.value} onChange={this.changeHandler} />
                <span>{this.state.value}</span>
            </div>
        );
    }
});

var Child = React.createClass({
    propTypes: {
        value:      React.PropTypes.string,
        onChange:   React.PropTypes.func
    },
    getDefaultProps: function() {
        return {
            value: ''
        };
    },
    changeHandler: function(e) {
        if (typeof this.props.onChange === 'function') {
            this.props.onChange(e.target.value);
        }
    },
    render: function() {
        return (
            <input type="text" value={this.props.value} onChange={this.changeHandler} />
        );
    }
});

In the above example, Parent calls Child with a property of value and onChange. The Child in return binds an onChange handler to a standard <input /> element and passes the value up to the Parent's callback if it's defined.

As a result the Parent's changeHandler method is called with the first argument being the string value from the <input /> field in the Child. The result is that the Parent's state can be updated with that value, causing the parent's <span /> element to update with the new value as you type it in the Child's input field.

How can I add a new column and data to a datatable that already contains data?

Only you want to set default value parameter. This calling third overloading method.

dt.Columns.Add("MyRow", type(System.Int32),0);

Convert a SQL query result table to an HTML table for email

Here is one way to do it from an article titled "Format query output into an HTML table - the easy way [archive]". You would need to substitute the details of your own query for the ones in this example, which gets a list of tables and a row count.

declare @body varchar(max)

set @body = cast( (
select td = dbtable + '</td><td>' + cast( entities as varchar(30) ) + '</td><td>' + cast( rows as varchar(30) )
from (
      select dbtable  = object_name( object_id ),
             entities = count( distinct name ),
             rows     = count( * )
      from sys.columns
      group by object_name( object_id )
      ) as d
for xml path( 'tr' ), type ) as varchar(max) )

set @body = '<table cellpadding="2" cellspacing="2" border="1">'
          + '<tr><th>Database Table</th><th>Entity Count</th><th>Total Rows</th></tr>'
          + replace( replace( @body, '&lt;', '<' ), '&gt;', '>' )
          + '</table>'

print @body

Once you have @body, you can then use whatever email mechanism you want.

How to manually send HTTP POST requests from Firefox or Chrome browser?

You can post requests directly from the browser with ReqBin. No plugin or desktop app is required.

https://reqbin.com

Dart SDK is not configured

Goto preferences -> Languages & Frameworks -> Flutter

Set your flutter sdk path for example :- /Users/apple/flutter-sdk/flutter

then apply your settings.

Make sure all dependencies are installed. if not run - flutter pub get to install dependencies

Android. Fragment getActivity() sometimes returns null

I know this is a old question but i think i must provide my answer to it because my problem was not solved by others.

first of all : i was dynamically adding fragments using fragmentTransactions. Second: my fragments were modified using AsyncTasks (DB queries on a server). Third: my fragment was not instantiated at activity start Fourth: i used a custom fragment instantiation "create or load it" in order to get the fragment variable. Fourth: activity was recreated because of orientation change

The problem was that i wanted to "remove" the fragment because of the query answer, but the fragment was incorrectly created just before. I don't know why, probably because of the "commit" be done later, the fragment was not added yet when it was time to remove it. Therefore getActivity() was returning null.

Solution : 1)I had to check that i was correctly trying to find the first instance of the fragment before creating a new one 2)I had to put serRetainInstance(true) on that fragment in order to keep it through orientation change (no backstack needed therefore no problem) 3)Instead of "recreating or getting old fragment" just before "remove it", I directly put the fragment at activity start. Instantiating it at activity start instead of "loading" (or instantiating) the fragment variable before removing it prevented getActivity problems.

Download a specific tag with Git

I'm not a git expert, but I think this should work:

git clone http://git.abc.net/git/abc.git
cd abc
git checkout my_abc 

OR

git clone http://git.abc.net/git/abc.git
cd abc
git checkout -b new_branch my_abc

The second variation establishes a new branch based on the tag, which lets you avoid a 'detached HEAD'. (git-checkout manual)

Every git repo contains the entire revision history, so cloning the repo gives you access to the latest commit, plus everything that came before, including the tag you're looking for.

How to programmatically turn off WiFi on Android device?

You need the following permissions in your manifest file:

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

Then you can use the following in your activity class:

WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); 
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);

Use the following to check if it's enabled or not

boolean wifiEnabled = wifiManager.isWifiEnabled()

You'll find a nice tutorial on the subject on this site.

raw vs. html_safe vs. h to unescape html

  1. html_safe :

    Marks a string as trusted safe. It will be inserted into HTML with no additional escaping performed.

    "<a>Hello</a>".html_safe
    #=> "<a>Hello</a>"
    
    nil.html_safe
    #=> NoMethodError: undefined method `html_safe' for nil:NilClass
    
  2. raw :

    raw is just a wrapper around html_safe. Use raw if there are chances that the string will be nil.

    raw("<a>Hello</a>")
    #=> "<a>Hello</a>"
    
    raw(nil)
    #=> ""
    
  3. h alias for html_escape :

    A utility method for escaping HTML tag characters. Use this method to escape any unsafe content.

    In Rails 3 and above it is used by default so you don't need to use this method explicitly

How do I use jQuery to redirect?

I found out why this happening.

After looking at my settings on my wamp, i did not check http headers, since activated this, it now works.

Thank you everyone for trying to solve this. :)

Passing base64 encoded strings in URL

In theory, yes, as long as you don't exceed the maximum url and/oor query string length for the client or server.

In practice, things can get a bit trickier. For example, it can trigger an HttpRequestValidationException on ASP.NET if the value happens to contain an "on" and you leave in the trailing "==".

Select subset of columns in data.table R

If it's not mandatory to specify column names:

> cor(dt[, !c(1:3, 5)])
             V4          V6          V7         V8          V9         V10
V4   1.00000000 -0.50472635 -0.07123705  0.9089868 -0.17232607 -0.77988709
V6  -0.50472635  1.00000000  0.05757776 -0.2374420  0.67334474  0.29476983
V7  -0.07123705  0.05757776  1.00000000 -0.1812176 -0.36093750  0.01102428
V8   0.90898683 -0.23744196 -0.18121755  1.0000000  0.21372140 -0.75798418
V9  -0.17232607  0.67334474 -0.36093750  0.2137214  1.00000000 -0.01179544
V10 -0.77988709  0.29476983  0.01102428 -0.7579842 -0.01179544  1.00000000

What is the HTML5 equivalent to the align attribute in table cells?

You can use inline css :
<td style = "text-align: center;">

How to replace substrings in windows batch file

Expanding from Andriy M, and yes you can do this from a file, even one with multiple lines

@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "INTEXTFILE=test.txt"
set "OUTTEXTFILE=test_out.txt"
set "SEARCHTEXT=bath"
set "REPLACETEXT=hello"

for /f "delims=" %%A in ('type "%INTEXTFILE%"') do (
    set "string=%%A"
    set "modified=!string:%SEARCHTEXT%=%REPLACETEXT%!"
    echo !modified!>>"%OUTTEXTFILE%"
)

del "%INTEXTFILE%"
rename "%OUTTEXTFILE%" "%INTEXTFILE%"
endlocal

EDIT

Thanks David Nelson, I have updated the script so it doesn't have the hard coded values anymore.

Escape double quote character in XML

New, improved answer to an old, frequently asked question...

When to escape double quote in XML

Double quote (") may appear without escaping:

  • In XML textual content:

    <NoEscapeNeeded>He said, "Don't quote me."</NoEscapeNeeded>
    
  • In XML attributes delimited by single quotes ('):

    <NoEscapeNeeded name='Pete "Maverick" Mitchell'/>
    

    Note: switching to single quotes (') also requires no escaping:

    <NoEscapeNeeded name="Pete 'Maverick' Mitchell"/>
    

Double quote (") must be escaped:

  • In XML attributes delimited by double quotes:

    <EscapeNeeded name="Pete &quot;Maverick&quot; Mitchell"/>
    

Bottom line

Double quote (") must be escaped as &quot; in XML only in very limited contexts.

jquery select option click handler

The problem that I had with the change handler was that it triggered on every keypress that I scrolled up and down the <select>.

I wanted to get the event for whenever an option was clicked or when enter was pressed on the desired option. This is how I ended up doing it:

let blockChange = false;

$element.keydown(function (e) {

    const keycode = (e.keyCode ? e.keyCode : e.which);

    // prevents select opening when enter is pressed
    if (keycode === 13) {
        e.preventDefault();
    }

    // lets the change event know that these keypresses are to be ignored
    if([38, 40].indexOf(keycode) > -1){
        blockChange = true;
    }

});

$element.keyup(function(e) {

    const keycode = (e.keyCode ? e.keyCode : e.which);
    // handle enter press
    if(keycode === 13) {
        doSomething();
    }

});

$element.change(function(e) {

    // this effective handles the click only as preventDefault was used on enter
    if(!blockChange) {
        doSomething();
    }
    blockChange = false;

});

Handling exceptions from Java ExecutorService tasks

I got around it by wrapping the supplied runnable submitted to the executor.

CompletableFuture.runAsync(() -> {
        try {
              runnable.run();
        } catch (Throwable e) {
              Log.info(Concurrency.class, "runAsync", e);
        }
}, executorService);

Android device is not connected to USB for debugging (Android studio)

I have a Samsung Galaxy S4. Although visible from Devices, my phone was not listed as connected from Android Studio. I tried a few things independently, and then together, and found that only a combination of steps fixed the issue, so this is for you if measures listed above or on another site did not work on their own.

  1. Enable USB debugging from "Developer Options"
  2. Download Kies from Samsung. I believe Samsung US has replaced Kies with a new software called Smart Switch, but this did not resolve anything for me. I found a Samsung UK download of Kies that worked fine.
  3. After connecting your phone to your PC via USB, go to your phone notifications and click on USB settings at the top. Switch it to Camera mode.

I repeat, only all 3 of these together fixed the issue, so if some fixes you have tried haven't worked, use these 3 and it could fix the problem for you. Best of luck.

How to Install pip for python 3.7 on Ubuntu 18?

I used apt-get to install python3.7 in ubuntu18.04. The installations are as follows.

  1. install python3.7
sudo apt-get install python3.7 
  1. install pip3. It should be noted that this may install pip3 for python3.6.
sudo apt-get install python3-pip 
  1. change the default of python3 for python3.7. This is where the magic is, which will make the pip3 refer to python3.7.
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 1

Hope it works for you.

How to select unique records by SQL

If you only need to remove duplicates then use DISTINCT. GROUP BY should be used to apply aggregate operators to each group

GROUP BY v DISTINCT

Parse string to date with moment.js

Maybe try the Intl polyfill for IE8 or the olyfill service ?

or

https://github.com/andyearnshaw/Intl.js/

How do I obtain crash-data from my Android application?

use this to catch the exception details:

String stackTrace = Log.getStackTraceString(exception); 

store this in database and maintain the log.

How do I use the Simple HTTP client in Android?

You can use this code:

int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.setConnectTimeout(TIME_OUT);
                conection.connect();
                // Getting file length
                int lenghtOfFile = conection.getContentLength();
                // Create a Input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(),
                        8192);
                // Output stream to write file
                OutputStream output = new FileOutputStream(
                        "/sdcard/9androidnet.jpg");

                byte data[] = new byte[1024];
                long total = 0;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                    // writing data to file
                    output.write(data, 0, count);
                }
                // flushing output
                output.flush();
                // closing streams
                output.close();
                input.close();
            } catch (SocketTimeoutException e) {
                connectionTimeout=true;
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

What does it mean: The serializable class does not declare a static final serialVersionUID field?

Any class that can be serialized (i.e. implements Serializable) should declare that UID and it must be changed whenever anything changes that affects the serialization (additional fields, removed fields, change of field order, ...). The field's value is checked during deserialization and if the value of the serialized object does not equal the value of the class in the current VM, an exception is thrown.

Note that this value is special in that it is serialized with the object even though it is static, for the reasons described above.

split string only on first instance of specified character

I avoid RegExp at all costs. Here is another thing you can do:

"good_luck_buddy".split('_').slice(1).join('_')

Basic text editor in command prompt?

The standard text editor in windows is notepad. There are no built-in command line editors.

Windows does not ship a C or C++ compiler. The .NET framework comes with several compilers, though: csc.exe (C# compiler), vbc.exe (VB.NET compiler), jsc.exe (JavaScript compiler).

If you want a free alternative you can download Visual Studio Express 2013 for Windows Desktop that comes with an optimizing C/C++ compiler (cl.exe).

What does a lazy val do?

Also lazy is useful without cyclic dependencies, as in the following code:

abstract class X {
  val x: String
  println ("x is "+x.length)
}

object Y extends X { val x = "Hello" }
Y

Accessing Y will now throw null pointer exception, because x is not yet initialized. The following, however, works fine:

abstract class X {
  val x: String
  println ("x is "+x.length)
}

object Y extends X { lazy val x = "Hello" }
Y

EDIT: the following will also work:

object Y extends { val x = "Hello" } with X 

This is called an "early initializer". See this SO question for more details.

WAMP shows error 'MSVCR100.dll' is missing when install

I had the same problem but none of the answer above worked. Here's what did the job for me:

  1. download msvcr110.dll, msvcr120.dll, msvcp120.dll and vcruntime140.dll from dll-files.com
  2. Copy them into System32
  3. Uninstall wamp
  4. Reinstall wamp

Apply function to all elements of collection through LINQ

A common way to approach this is to add your own ForEach generic method on IEnumerable<T>. Here's the one we've got in MoreLINQ:

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    source.ThrowIfNull("source");
    action.ThrowIfNull("action");
    foreach (T element in source)
    {
        action(element);
    }
}

(Where ThrowIfNull is an extension method on any reference type, which does the obvious thing.)

It'll be interesting to see if this is part of .NET 4.0. It goes against the functional style of LINQ, but there's no doubt that a lot of people find it useful.

Once you've got that, you can write things like:

people.Where(person => person.Age < 21)
      .ForEach(person => person.EjectFromBar());

When to use "new" and when not to, in C++?

You should use new when you wish an object to remain in existence until you delete it. If you do not use new then the object will be destroyed when it goes out of scope. Some examples of this are:

void foo()
{
  Point p = Point(0,0);
} // p is now destroyed.

for (...)
{
  Point p = Point(0,0);
} // p is destroyed after each loop

Some people will say that the use of new decides whether your object is on the heap or the stack, but that is only true of variables declared within functions.

In the example below the location of 'p' will be where its containing object, Foo, is allocated. I prefer to call this 'in-place' allocation.

class Foo
{

  Point p;
}; // p will be automatically destroyed when foo is.

Allocating (and freeing) objects with the use of new is far more expensive than if they are allocated in-place so its use should be restricted to where necessary.

A second example of when to allocate via new is for arrays. You cannot* change the size of an in-place or stack array at run-time so where you need an array of undetermined size it must be allocated via new.

E.g.

void foo(int size)
{
   Point* pointArray = new Point[size];
   ...
   delete [] pointArray;
}

(*pre-emptive nitpicking - yes, there are extensions that allow variable sized stack allocations).

PostgreSQL: ERROR: operator does not exist: integer = character varying

I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).

If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::.

Something along these lines:

create view view1
as 
select table1.col1,table2.col1,table3.col3
from table1 
inner join
table2 
inner join 
table3
on 
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;

Notice the varchar typecasting on the table1.col4.

Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.

Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).

How do I use disk caching in Picasso?

I don't know how good that solution is but it is definitely THE EASY ONE i just used in my app and it is working fine

you load the image like that

public void loadImage (){
Picasso picasso = Picasso.get(); 
picasso.setIndicatorsEnabled(true);
picasso.load(quiz.getImageUrl()).into(quizImage);
}

You can get the bimap like that

Bitmap bitmap = Picasso.get().load(quiz.getImageUrl()).get();

Now covert that Bitmap into a JPG file and store in the in the cache, below is complete code for getting the bimap and caching it

Thread thread = new Thread() {
 public void run() {
 File file = new File(getCacheDir() + "/" +member.getMemberId() + ".jpg");

try {
      Bitmap bitmap = Picasso.get().load(uri).get();
      FileOutputStream fOut = new FileOutputStream(file);                                        
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100,new FileOutputStream(file));
fOut.flush();
fOut.close();
    }
catch (Exception e) {
  e.printStackTrace();
    }
   }
};
     thread.start();
  })

the get() method of Piccasso need to be called on separate thread , i am saving that image also on that same thread.

Once the image is saved you can get all the files like that

List<File> files = new LinkedList<>(Arrays.asList(context.getExternalCacheDir().listFiles()));

now you can find the file you are looking for like below

for(File file : files){
                if(file.getName().equals("fileyouarelookingfor" + ".jpg")){ // you need the name of the file, for example you are storing user image and the his image name is same as his id , you can call getId() on user to get the file name
                    Picasso.get() // if file found then load it
                            .load(file)
                            .into(mThumbnailImage);
                    return; // return 
                }
        // fetch it over the internet here because the file is not found
       }

Java: JSON -> Protobuf & back conversion

Well, there is no shortcut to do it as per my findings, but somehow you
an achieve it in few simple steps

First you have to declare a bean of type 'ProtobufJsonFormatHttpMessageConverter'

@Bean  
@Primary  
public ProtobufJsonFormatHttpMessageConverter protobufHttpMessageConverter() {  
  return new ProtobufJsonFormatHttpMessageConverter(JsonFormat.parser(), JsonFormat.printer());  
}  

Then you can just write an Utility class like ResponseBuilder, because it can parse the request by default but without these changes it can not produce Json response. and then you can write few methods to convert the response types to its related object type.

public static <T> T build(Message message, Class<T> type) {
  Printer printer = JsonFormat.printer();
  Gson gson = new Gson();
  try {
    return gson.fromJson(printer.print(message), type);
  } catch (JsonSyntaxException | InvalidProtocolBufferException e) {
    throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "Response   conversion Error", e);
  }
}

Then you can call this method from your controller class as last line like -

return ResponseBuilder.build(<returned_service_object>, <Type>);

Hope this will help you to implement protobuf in json format.

openpyxl - adjust column width size

A slight improvement of the above accepted answer, that I think is more pythonic (asking for forgiveness is better than asking for permission)

column_widths = []
for row in workSheet.iter_rows():
    for i, cell in enumerate(row):
        try:
            column_widths[i] = max(column_widths[i], len(str(cell.value)))
        except IndexError:
            column_widths.append(len(str(cell.value)))

for i, column_width in enumerate(column_widths):
    workSheet.column_dimensions[get_column_letter(i + 1)].width = column_width

How to run functions in parallel?

If your functions are mainly doing I/O work (and less CPU work) and you have Python 3.2+, you can use a ThreadPoolExecutor:

from concurrent.futures import ThreadPoolExecutor

def run_io_tasks_in_parallel(tasks):
    with ThreadPoolExecutor() as executor:
        running_tasks = [executor.submit(task) for task in tasks]
        for running_task in running_tasks:
            running_task.result()

run_io_tasks_in_parallel([
    lambda: print('IO task 1 running!'),
    lambda: print('IO task 2 running!'),
])

If your functions are mainly doing CPU work (and less I/O work) and you have Python 2.6+, you can use the multiprocessing module:

from multiprocessing import Process

def run_cpu_tasks_in_parallel(tasks):
    running_tasks = [Process(target=task) for task in tasks]
    for running_task in running_tasks:
        running_task.start()
    for running_task in running_tasks:
        running_task.join()

run_cpu_tasks_in_parallel([
    lambda: print('CPU task 1 running!'),
    lambda: print('CPU task 2 running!'),
])

Testing web application on Mac/Safari when I don't own a Mac

Meanwhile, MacOS High Sierra can be run in VirtualBox (on a PC) for Free. It's not really fast but it works for general browser testing.

How to setup see here: https://www.howtogeek.com/289594/how-to-install-macos-sierra-in-virtualbox-on-windows-10/

I'm using this for a while now and it works quite well

What does it mean by command cd /d %~dp0 in Windows

~dp0 : d=drive, p=path, %0=full path\name of this batch-file.

cd /d %~dp0 will change the path to the same, where the batch file resides.

See for /? or call / for more details about the %~... modifiers.
See cd /? about the /d switch.

How do I load the contents of a text file into a javascript variable?

If you only want a constant string from the text file, you could include it as JavaScript:

_x000D_
_x000D_
// This becomes the content of your foo.txt file_x000D_
let text = `_x000D_
My test text goes here!_x000D_
`;
_x000D_
<script src="foo.txt"></script>_x000D_
<script>_x000D_
  console.log(text);_x000D_
</script>
_x000D_
_x000D_
_x000D_

The string loaded from the file becomes accessible to JavaScript after being loaded. The `(backtick) character begins and ends a template literal, allowing for both " and ' characters in your text block.

This approach works well when you're attempting to load a file locally, as Chrome will not allow AJAX on URLs with the file:// scheme.

Generating a UUID in Postgres for Insert statement?

Without extensions (cheat)

SELECT uuid_in(md5(random()::text || clock_timestamp()::text)::cstring);

output>> c2d29867-3d0b-d497-9191-18a9d8ee7830

(works at least in 8.4)

  • Thanks to @Erwin Brandstetter for clock_timestamp() explanation.

If you need a valid v4 UUID

SELECT uuid_in(overlay(overlay(md5(random()::text || ':' || clock_timestamp()::text) placing '4' from 13) placing to_hex(floor(random()*(11-8+1) + 8)::int)::text from 17)::cstring);

enter image description here * Thanks to @Denis Stafichuk @Karsten and @autronix


Also, in modern Postgres, you can simply cast:

SELECT md5(random()::text || clock_timestamp()::text)::uuid

Copy file from source directory to binary directory using CMake

This is what I used to copy some resource files: the copy-files is an empty target to ignore errors

 add_custom_target(copy-files ALL
    COMMAND ${CMAKE_COMMAND} -E copy_directory
    ${CMAKE_BINARY_DIR}/SOURCEDIRECTORY
    ${CMAKE_BINARY_DIR}/DESTINATIONDIRECTORY
    )

HTML/CSS: how to put text both right and left aligned in a paragraph

I wouldn't put it in the same <p>, since IMHO the two infos are semantically too different. If you must, I'd suggest this:

<p style="text-align:right">
 <span style="float:left">I'll be on the left</span>
 I'll be on the right
</p>

How to check if array element exists or not in javascript?

var myArray = ["Banana", "Orange", "Apple", "Mango"];

if (myArray.indexOf(searchTerm) === -1) {
  console.log("element doesn't exist");
}
else {
  console.log("element found");
}

Input text dialog Android

It's work for me

private void showForgotDialog(Context c) {
        final EditText taskEditText = new EditText(c);
        AlertDialog dialog = new AlertDialog.Builder(c)
                .setTitle("Forgot Password")
                .setMessage("Enter your mobile number?")
                .setView(taskEditText)
                .setPositiveButton("Reset", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String task = String.valueOf(taskEditText.getText());
                    }
                })
                .setNegativeButton("Cancel", null)
                .create();
        dialog.show();
    }

How to call? (Current activity name)

showForgotDialog(current_activity_name.this);

How to change the text of a button in jQuery?

    $( "#btnAddProfile" ).on( "click",function(event){
    $( event.target ).html( "Save" );
});

Remove all occurrences of a value from a list?

Let

>>> x = [1, 2, 3, 4, 2, 2, 3]

The simplest and efficient solution as already posted before is

>>> x[:] = [v for v in x if v != 2]
>>> x
[1, 3, 4, 3]

Another possibility which should use less memory but be slower is

>>> for i in range(len(x) - 1, -1, -1):
        if x[i] == 2:
            x.pop(i)  # takes time ~ len(x) - i
>>> x
[1, 3, 4, 3]

Timing results for lists of length 1000 and 100000 with 10% matching entries: 0.16 vs 0.25 ms, and 23 vs 123 ms.

Timing with length 1000

Timing with length 100000

Why can I not push_back a unique_ptr into a vector?

You need to move the unique_ptr:

vec.push_back(std::move(ptr2x));

unique_ptr guarantees that a single unique_ptr container has ownership of the held pointer. This means that you can't make copies of a unique_ptr (because then two unique_ptrs would have ownership), so you can only move it.

Note, however, that your current use of unique_ptr is incorrect. You cannot use it to manage a pointer to a local variable. The lifetime of a local variable is managed automatically: local variables are destroyed when the block ends (e.g., when the function returns, in this case). You need to dynamically allocate the object:

std::unique_ptr<int> ptr(new int(1));

In C++14 we have an even better way to do so:

make_unique<int>(5);

C# password TextBox in a ASP.net website

Simply select texbox property 'TextMode' and select password...

<asp:TextBox ID="TextBox1" TextMode="Password" runat="server" />

How to finish current activity in Android

I found many answers but not one is simple... I hope this will help you...

try{
    Intent intent = new Intent(CurrentActivity.this, NewActivity.class);
    startActivity(intent);
} finally {
    finish();
}

so, Very simple logic is here, as we know that in java we write code that has some chances of exception in a try block and handle that exception in catch block but in finally block we write code that has to be executed in any cost (Either the exception comes or not).

Search for executable files using find command

On GNU versions of find you can use -executable:

find . -type f -executable -print

For BSD versions of find, you can use -perm with + and an octal mask:

find . -type f -perm +111 -print

In this context "+" means "any of these bits are set" and 111 is the execute bits.

Note that this is not identical to the -executable predicate in GNU find. In particular, -executable tests that the file can be executed by the current user, while -perm +111 just tests if any execute permissions are set.

Older versions of GNU find also support the -perm +111 syntax, but as of 4.5.12 this syntax is no longer supported. Instead, you can use -perm /111 to get this behavior.

Classes cannot be accessed from outside package

Do you by any chance have two PUBLICclass classes in your project, where one is public (the one of which you posted the signature here), and another one which is package visible, and you import the wrong one in your code ?

How to use Redirect in the new react-router-dom of Reactjs

you can write a hoc for this purpose and write a method call redirect, here is the code:

import React, {useState} from 'react';
import {Redirect} from "react-router-dom";

const RedirectHoc = (WrappedComponent) => () => {
    const [routName, setRoutName] = useState("");
    const redirect = (to) => {
        setRoutName(to);
    };


    if (routName) {
        return <Redirect to={"/" + routName}/>
    }
    return (
        <>
            <WrappedComponent redirect={redirect}/>
        </>
    );
};

export default RedirectHoc;

Failed to connect to camera service

The problem is related to permission. Copy following code into onCreate() method. The issue will get solved.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[] {Manifest.permission.CAMERA}, 1);
    }
}

After that wait for the user action and handle his decision.

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case CAMERA_PERMISSION_REQUEST_CODE:
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //Start your camera handling here
            } else {
                AppUtils.showUserMessage("You declined to allow the app to access your camera", this);
            }
    }
}

this is error ORA-12154: TNS:could not resolve the connect identifier specified?

The database must have a name (example DB1), try this one:

OracleConnection con = new OracleConnection("data source=DB1;user id=fastecit;password=fastecit"); 

In case the TNS is not defined you can also try this one:

OracleConnection con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=DB1)));
User Id=fastecit;Password=fastecit"); 

How to close a JavaFX application on window close?

You MUST override the "stop()" method in your Application instance to make it works. If you have overridden even empty "stop()" then the application shuts down gracefully after the last stage is closed (actually the last stage must be the primary stage to make it works completely as in supposed to be). No any additional Platform.exit or setOnCloseRequest calls are need in such case.

SQL Server: how to select records with specific date from datetime column

The easiest way is to convert to a date:

SELECT *
FROM dbo.LogRequests
WHERE cast(dateX as date) = '2014-05-09';

Often, such expressions preclude the use of an index. However, according to various sources on the web, the above is sargable (meaning it will use an index), such as this and this.

I would be inclined to use the following, just out of habit:

SELECT *
FROM dbo.LogRequests
WHERE dateX >= '2014-05-09' and dateX < '2014-05-10';

How can I align text in columns using Console.WriteLine?

Try this

Console.WriteLine("{0,10}{1,10}{2,10}{3,10}{4,10}",
  customer[DisplayPos],
  sales_figures[DisplayPos],
  fee_payable[DisplayPos], 
  seventy_percent_value,
  thirty_percent_value);

where the first number inside the curly brackets is the index and the second is the alignment. The sign of the second number indicates if the string should be left or right aligned. Use negative numbers for left alignment.

Or look at http://msdn.microsoft.com/en-us/library/aa331875(v=vs.71).aspx

performing HTTP requests with cURL (using PROXY)

From man curl:

-x, --proxy <[protocol://][user:password@]proxyhost[:port]>

     Use the specified HTTP proxy. 
     If the port number is not specified, it is assumed at port 1080.

General way:

export http_proxy=http://your.proxy.server:port/

Then you can connect through proxy from (many) application.

And, as per comment below, for https:

export https_proxy=https://your.proxy.server:port/

Decompile an APK, modify it and then recompile it

I know this question has been answered and I am not trying to give better answer here. I'll just share my experience in this topic.

Once I lost my code and I had the apk file only. I decompiled it using the tool below and it made my day.

These tools MUST be used in such situation, otherwise, it is unethical and even sometimes it is illegal, (stealing somebody else's effort). So please use it wisely.

Those are my favorite tools for doing that:

javadecompilers.com

and to get the apk from google play you can google it or check out those sites:

On the date of posting this answer I tested all the links and it worked perfect for me.

NOTE: Apk Decompiling is not effective in case of proguarded code. Because Proguard shrink and obfuscates the code and rename classes to nonsense names which make it fairly hard to understand the code.

Bonus:

Basic tutorial of Using Proguard:

Why is there no Constant feature in Java?

This is a bit of an old question, but I thought I would contribute my 2 cents anyway since this thread came up in conversation today.

This doesn't exactly answer why is there no const? but how to make your classes immutable. (Unfortunately I have not enough reputation yet to post as a comment to the accepted answer)

The way to guarantee immutability on an object is to design your classes more carefully to be immutable. This requires a bit more care than a mutable class.

This goes back to Josh Bloch's Effective Java Item 15 - Minimize Mutability. If you haven't read the book, pick up a copy and read it over a few times I guarantee it will up your figurative "java game".

In item 15 Bloch suggest that you should limit the mutability of classes to ensure the object's state.

To quote the book directly:

An immutable class is simply a class whose instances cannot be modified. All of the information contained in each instance is provided when it is created and is fixed for the lifetime of the object. The Java platform libraries contain many immutable classes, including String, the boxed primitive classes, and BigInte- ger and BigDecimal. There are many good reasons for this: Immutable classes are easier to design, implement, and use than mutable classes. They are less prone to error and are more secure.

Bloch then describes how to make your classes immutable, by following 5 simple rules:

  1. Don’t provide any methods that modify the object’s state (i.e., setters, aka mutators)
  2. Ensure that the class can’t be extended (this means declaring the class itself as final).
  3. Make all fields final.
  4. Make all fields private.
  5. Ensure exclusive access to any mutable components. (by making defensive copies of the objects)

For more details I highly recommend picking up a copy of the book.

What is Python Whitespace and how does it work?

Whitespace is used to denote blocks. In other languages curly brackets ({ and }) are common. When you indent, it becomes a child of the previous line. In addition to the indentation, the parent also has a colon following it.

im_a_parent:
    im_a_child:
        im_a_grandchild
    im_another_child:
        im_another_grand_child

Off the top of my head, def, if, elif, else, try, except, finally, with, for, while, and class all start blocks. To end a block, you simple outdent, and you will have siblings. In the above im_a_child and im_another_child are siblings.

SQL Server SELECT into existing table

If the destination table does exist but you don't want to specify column names:

DECLARE @COLUMN_LIST NVARCHAR(MAX);
DECLARE @SQL_INSERT NVARCHAR(MAX);

SET @COLUMN_LIST = (SELECT DISTINCT
    SUBSTRING(
        (
            SELECT ', table1.' + SYSCOL1.name  AS [text()]
            FROM sys.columns SYSCOL1
            WHERE SYSCOL1.object_id = SYSCOL2.object_id and SYSCOL1.is_identity <> 1
            ORDER BY SYSCOL1.object_id
            FOR XML PATH ('')
        ), 2, 1000)
FROM
    sys.columns SYSCOL2
WHERE
    SYSCOL2.object_id = object_id('dbo.TableOne') )

SET @SQL_INSERT =  'INSERT INTO dbo.TableTwo SELECT ' + @COLUMN_LIST + ' FROM dbo.TableOne table1 WHERE col3 LIKE ' + @search_key
EXEC sp_executesql @SQL_INSERT

Showing an image from an array of images - Javascript

Also, when checking for the last image, you must compare with imgArray.length-1 because, for example, when array length is 2 then I will take the values 0 and 1, it won't reach the value 2, so you must compare with length-1 not with length, here is the fixed line:

if(i == imgArray.length-1)

make: Nothing to be done for `all'

Make is behaving correctly. hello already exists and is not older than the .c files, and therefore there is no more work to be done. There are four scenarios in which make will need to (re)build:

  • If you modify one of your .c files, then it will be newer than hello, and then it will have to rebuild when you run make.
  • If you delete hello, then it will obviously have to rebuild it
  • You can force make to rebuild everything with the -B option. make -B all
  • make clean all will delete hello and require a rebuild. (I suggest you look at @Mat's comment about rm -f *.o hello

How to SUM parts of a column which have same text value in different column in the same row

If your data has the names grouped as shown then you can use this formula in D2 copied down to get a total against the last entry for each name

=IF((A2=A3)*(B2=B3),"",SUM(C$2:C2)-SUM(D$1:D1))

See screenshot

enter image description here

How can I write a byte array to a file in Java?

You can use IOUtils.write(byte[] data, OutputStream output) from Apache Commons IO.

KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey key = kgen.generateKey();
byte[] encoded = key.getEncoded();
FileOutputStream output = new FileOutputStream(new File("target-file"));
IOUtils.write(encoded, output);

Getting next element while cycling through a list

As simple as this:

li = [0, 1, 2, 3]
while 1:
   for i, item in enumerate(x):
      k = i + 1 if i != len(x) - 1 else 0
      print('Current index {} : {}'.format(i,li[k]))

Setting Curl's Timeout in PHP

You can't run the request from a browser, it will timeout waiting for the server running the CURL request to respond. The browser is probably timing out in 1-2 minutes, the default network timeout.

You need to run it from the command line/terminal.

C# code to validate email address

For the simple email like [email protected], below code is sufficient. 

 public static bool ValidateEmail(string email)
        {
            System.Text.RegularExpressions.Regex emailRegex = new System.Text.RegularExpressions.Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
            System.Text.RegularExpressions.Match emailMatch = emailRegex.Match(email);
            return emailMatch.Success;
        }

CSS to line break before/after a particular `inline-block` item

A better solution is to use -webkit-columns:2;

http://jsfiddle.net/YMN7U/889/

 ul { margin:0.5em auto;
-webkit-columns:2;
}

get the value of DisplayName attribute

Please try below code, I think this will solve your problem.

var classObj = new Class1();
classObj.Name => "StackOverflow";

var property = new Class1().GetType().GetProperty(nameof(classObj.Name));
var displayNameAttributeValue = (property ?? throw new InvalidOperationException())
    .GetCustomAttributes(typeof(DisplayNameAttribute)) as DisplayNameAttribute; 

if (displayNameAttributeValue != null)
{
   Console.WriteLine("{0} = {1}", displayNameAttributeValue, classObj.Name);
}

Python - IOError: [Errno 13] Permission denied:

This happened to me when I was using 'shutil.copyfile' instead of 'shutil.copy'. The permissions were messed up.

Are there pointers in php?

entryId is an instance property of the current class ($this) And $entryId is a local variable

How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?

Since the question asked for either jQuery or vanilla JS, here's an answer with vanilla JS.

I've added some CSS to the demo below to change the button's font color to red when its aria-expanded is set to true

_x000D_
_x000D_
const button = document.querySelector('button');_x000D_
_x000D_
button.addEventListener('click', () => {_x000D_
  button.ariaExpanded = !JSON.parse(button.ariaExpanded);_x000D_
})
_x000D_
button[aria-expanded="true"] {_x000D_
  color: red;_x000D_
}
_x000D_
<button type="button" aria-expanded="false">Click me!</button>
_x000D_
_x000D_
_x000D_

Pycharm does not show plot

I have found a solution. This worked for me:

import numpy as np
import matplotlib.pyplot as plt

points = np.arange(-5, 5, 0.01)
dx, dy = np.meshgrid(points, points)
z = (np.sin(dx)+np.sin(dy))
plt.imshow(z)
plt.colorbar()
plt.title('plot for sin(x)+sin(y)')
plt.show()

Java, How to add values to Array List used as value in HashMap

Java 8+ has computeIfAbsent

examList.computeIfAbsent(map.get(id), k -> new ArrayList<>());
map.get(id).add(value);

https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#computeIfAbsent-K-java.util.function.Function-

CSS Box Shadow - Top and Bottom Only

essentially the shadow is the box shape just offset behind the actual box. in order to hide portions of the shadow, you need to create additional divs and set their z-index above the shadowed box so that the shadow is not visible.

If you'd like to have extremely specific control over your shadows, build them as images and created container divs with the right amount of padding and margins.. then use the png fix to make sure the shadows render properly in all browsers

Detecting superfluous #includes in C/C++?

This article explains a technique of #include removing by using the parsing of Doxygen. That's just a perl script, so it's quite easy to use.

Why when I transfer a file through SFTP, it takes longer than FTP?

UPDATE: As a commenter pointed out, the problem I outline below was fixed some time before this post. However, I knew of the HP-SSH project and I asked the author to weigh in. As they explain in the (rightfully) most upvoted answer, encryption is not the source of the problem. Yay for email and people smarter than myself!

Wow, a year-old question with nothing but incorrect answers. However, I must admit that I assumed the slowdown was due to encryption when I asked myself the same question. But ask yourself the next logical question: how quickly can your computer encrypt and decrypt data? If you think that rate is anywhere near the 4.5Mb/second reported by the OP (.5625MBs or roughly half the capacity of a 5.5" floppy disk!) smack yourself a few times, drink some coffee, and ask yourself the same question again.

It apparently has to do with what amounts to be an oversight in the packet size selection, or at least that's what the author of LIBSSH2 says,

The nature of SFTP and its ACK for every small data chunk it sends, makes an initial naive SFTP implementation suffer badly when sending data over high latency networks. If you have to wait a few hundred milliseconds for each 32KB of data then there will never be fast SFTP transfers. This sort of naive implementation is what libssh2 has offered up until and including libssh2 1.2.7.

So the speed hit is due to tiny packet sizes x mandatory ack responses for each packet, which is clearly insane.

The High Performance SSH/SCP (HP-SSH) project provides an OpenSSH patch set which apparently improves the internal buffers as well as parallelizing encryption. Note, however, that even the non-parallelized versions ran at speeds above the 40Mb/s unencrypted speeds obtained by some commenters. The fix involves changing the way in which OpenSSH was calling the encryption libraries, NOT the cipher and there is zero difference in speed between AES128 and AES256. Encryption takes some time, but it is marginal. It might have mattered back in the 90's but (like the speed of Java vs C) it just doesn't matter anymore.

How to change port for jenkins window service when 8080 is being used

Start Jenkins from cmd line with this command :

java -jar jenkins.war --httpPort=8081

grep regex whitespace behavior

This looks like a behavior difference in the handling of \s between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).

Note:

GNU grep 2.5.4
echo "foo bar" | grep "\s"
   (doesn't match)

whereas

GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar

Probably less trouble (as \s is not documented):

Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar

My advice is to avoid using \s ... use [ \t]* or [[:space:]] or something like it instead.

The current .NET SDK does not support targeting .NET Standard 2.0 error in Visual Studio 2017 update 15.3

When I upgraded Visual Studio to version 15.5.1, .Net Core SDK was upgraded to 2.X, so this error went away. When I run dotnet --info, I see the following now:

enter image description here

Using bootstrap with bower

You have install nodeJs on your system in order to execute npm commands. Once npm is properly working you can visit bower.io. There you will find complete documentation on this topic. You will find a command $ npm install bower. this will install bower on your machine. After installing bower you can install Bootstrap easily.

Here is a video tutorial on that

How to remove an iOS app from the App Store

Minor change in iTunes Connect,

  • Login to iTunes Connect
  • Select your app from My Apps section
  • Select App Store tab, Then select Pricing & Availability section
  • Under Availability section you will see two options 1) Available in all territories 2) Remove from sale, Kindly refer below screenshot for the same.
  • Select remove from sale if you would like to remove from all territories, if you would like to remove from specific territory then click on edit & remove from selected territory.

enter image description here

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

https://stackabuse.com/how-to-uninstall-node-js-from-mac-osx/

Run following commands to remove node completely from system in MACOS

sudo rm -rf ~/.npm ~/.nvm ~/node_modules ~/.node-gyp ~/.npmrc ~/.node_repl_history
sudo rm -rf /usr/local/bin/npm /usr/local/bin/node-debug /usr/local/bin/node /usr/local/bin/node-gyp
sudo rm -rf /usr/local/share/man/man1/node* /usr/local/share/man/man1/npm*
sudo rm -rf /usr/local/include/node /usr/local/include/node_modules
sudo rm -rf /usr/local/lib/node /usr/local/lib/node_modules /usr/local/lib/dtrace/node.d
sudo rm -rf /opt/local/include/node /opt/local/bin/node /opt/local/lib/node
sudo rm -rf /usr/local/share/doc/node
sudo rm -rf /usr/local/share/systemtap/tapset/node.stp

brew uninstall node
brew doctor
brew cleanup --prune-prefix



After this i will suggest to use following command to install node using nvm

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash

from https://github.com/nvm-sh/nvm

How to get a unique device ID in Swift?

The value of identifierForVendor changes when the user deletes all of that vendor’s apps from the device, if you want to keep the unique ID even for the subsequent fresh installations, you can try to use the following function

func vendorIdentifierForDevice()->String {
    //Get common part of Applicatoin Bundle ID, Note : getCommonPartOfApplicationBundleID is to be defined.
    let commonAppBundleID = getCommonPartOfApplicationBundleID()
    //Read from KeyChain using bunndle ID, Note : readFromKeyChain is to be defined.
    if let vendorID = readFromKeyChain(commonAppBundleID) {
        return vendorID
    } else {
        var vendorID = NSUUID().uuidString
        //Save to KeyChain using bunndle ID, Note : saveToKeyChain is to be defined.
        saveToKeyChain(commonAppBundleID, vendorID)
        return vendorID
    }
}

How do I implement IEnumerable<T>

Note that the IEnumerable<T> allready implemented by the System.Collections so another approach is to derive your MyObjects class from System.Collections as a base class (documentation):

System.Collections: Provides the base class for a generic collection.

We can later make our own implemenation to override the virtual System.Collections methods to provide custom behavior (only for ClearItems, InsertItem, RemoveItem, and SetItem along with Equals, GetHashCode, and ToString from Object). Unlike the List<T> which is not designed to be easily extensible.

Example:

public class FooCollection : System.Collections<Foo>
{
    //...
    protected override void InsertItem(int index, Foo newItem)
    {
        base.InsertItem(index, newItem);     
        Console.Write("An item was successfully inserted to MyCollection!");
    }
}

public static void Main()
{
    FooCollection fooCollection = new FooCollection();
    fooCollection.Add(new Foo()); //OUTPUT: An item was successfully inserted to FooCollection!
}

Please note that driving from collection recommended only in case when custom collection behavior is needed, which is rarely happens. see usage.

What is the difference between public, protected, package-private and private in Java?

David's answer provides the meaning of each access modifier. As for when to use each, I'd suggest making public all classes and the methods of each class that are meant for external use (its API), and everything else private.

Over time you'll develop a sense for when to make some classes package-private and when to declare certain methods protected for use in subclasses.

How to convert byte[] to InputStream?

Check out java.io.ByteArrayInputStream

How do you disable the unused variable warnings coming out of gcc in 3rd party code I do not wish to edit?

If you're using gcc and want to disable the warning for selected code, you can use the #pragma compiler directive:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
( your problematic library includes )
#pragma GCC diagnostic pop

For code you control, you may also use __attribute__((unused)) to instruct the compiler that specific variables are not used.

How to get file's last modified date on Windows command line?

You can do it

forfiles /M myfile.txt /C "cmd /c echo @fdate @ftime"

How to do SELECT MAX in Django?

See this. Your code would be something like the following:

from django.db.models import Max
# Generates a "SELECT MAX..." query
Argument.objects.aggregate(Max('rating')) # {'rating__max': 5}

You can also use this on existing querysets:

from django.db.models import Max
args = Argument.objects.filter(name='foo') # or whatever arbitrary queryset
args.aggregate(Max('rating')) # {'rating__max': 5}

If you need the model instance that contains this max value, then the code you posted is probably the best way to do it:

arg = args.order_by('-rating')[0]

Note that this will error if the queryset is empty, i.e. if no arguments match the query (because the [0] part will raise an IndexError). If you want to avoid that behavior and instead simply return None in that case, use .first():

arg = args.order_by('-rating').first() # may return None

Maximum call stack size exceeded error

I also faced similar issue here is the details when uploading logo using dropdown logo upload box

<div>
      <div class="uploader greyLogoBox" id="uploader" flex="64" onclick="$('#filePhoto').click()">
        <img id="imageBox" src="{{ $ctrl.companyLogoUrl }}" alt=""/>
        <input type="file" name="userprofile_picture"  id="filePhoto" ngf-select="$ctrl.createUploadLogoRequest()"/>
        <md-icon ng-if="!$ctrl.isLogoPresent" class="upload-icon" md-font-set="material-icons">cloud_upload</md-icon>
        <div ng-if="!$ctrl.isLogoPresent" class="text">Drag and drop a file here, or click to upload</div>
      </div>
      <script type="text/javascript">
          var imageLoader = document.getElementById('filePhoto');
          imageLoader.addEventListener('change', handleImage, false);

          function handleImage(e) {
              var reader = new FileReader();
              reader.onload = function (event) {

                  $('.uploader img').attr('src',event.target.result);
              }
              reader.readAsDataURL(e.target.files[0]);
          }
      </script>
      </div>

CSS.css

.uploader {
  position:relative;
  overflow:hidden;
  height:100px;
  max-width: 75%;
  margin: auto;
  text-align: center;

  img{
    max-width: 464px;
    max-height: 100px;
    z-index:1;
    border:none;
  }

  .drag-drop-zone {
    background: rgba(0, 0, 0, 0.04);
    border: 1px solid rgba(0, 0, 0, 0.12);
    padding: 32px;
  }
}

.uploader img{
  max-width: 464px;
  max-height: 100px;
  z-index:1;
  border:none;
}



.greyLogoBox {
  width: 100%;
  background: #EBEBEB;
  border: 1px solid #D7D7D7;
  text-align: center;
  height: 100px;
  padding-top: 22px;
  box-sizing: border-box;
}


#filePhoto{
  position:absolute;
  width:464px;
  height:100px;
  left:0;
  top:0;
  z-index:2;
  opacity:0;
  cursor:pointer;
}

before correction my code was :

function handleImage(e) {
              var reader = new FileReader();
              reader.onload = function (event) {
                  onclick="$('#filePhoto').click()"
                  $('.uploader img').attr('src',event.target.result);
              }
              reader.readAsDataURL(e.target.files[0]);
          }

The error in console:

enter image description here

I solved it by removing onclick="$('#filePhoto').click()" from div tag.

Assign output of a program to a variable using a MS batch file

You could use a batch macro for simple capturing of command outputs, a bit like the behaviour of the bash shell.

The usage of the macro is simple and looks like

%$set% VAR=application arg1 arg2

And it works even with pipes

%$set% allDrives="wmic logicaldisk get name /value | findstr "Name""

The macro uses the variable like an array and stores each line in a separate index.
In the sample of %$set% allDrives="wmic logicaldisk there will the following variables created:

allDrives.Len=5
allDrives.Max=4
allDrives[0]=Name=C:
allDrives[1]=Name=D:
allDrives[2]=Name=F:
allDrives[3]=Name=G:
allDrives[4]=Name=Z:
allDrives=<contains the complete text with line feeds>

To use it, it's not important to understand how the macro itself works.

The full example

@echo off
setlocal

call :initMacro

%$set% ipOutput="ipconfig"
call :ShowVariable ipOutput
echo First line is %ipOutput[0]%

echo( 
%$set% driveNames="wmic logicaldisk get name /value | findstr "Name""
call :ShowVariable driveNames

exit /b

:ShowVariable
setlocal EnableDelayedExpansion
for /L %%n in (0 1 !%~1.max!) do (
    echo %%n: !%~1[%%n]!
)
echo(
exit /b

:initMacro
if "!!"=="" (
    echo ERROR: Delayed Expansion must be disabled while defining macros
    (goto) 2>nul
    (goto) 2>nul
)
(set LF=^
%=empty=%
)
(set \n=^^^
%=empty=%
)

set $set=FOR /L %%N in (1 1 2) dO IF %%N==2 ( %\n%
    setlocal EnableDelayedExpansion                                 %\n%
    for /f "tokens=1,* delims== " %%1 in ("!argv!") do (            %\n%
        endlocal                                                    %\n%
        endlocal                                                    %\n%
        set "%%~1.Len=0"                                            %\n%
        set "%%~1="                                                 %\n%
        if "!!"=="" (                                               %\n%
            %= Used if delayed expansion is enabled =%              %\n%
                setlocal DisableDelayedExpansion                    %\n%
                for /F "delims=" %%O in ('"%%~2 | findstr /N ^^"') do ( %\n%
                if "!!" NEQ "" (                                    %\n%
                    endlocal                                        %\n%
                    )                                               %\n%
                setlocal DisableDelayedExpansion                    %\n%
                set "line=%%O"                                      %\n%
                setlocal EnableDelayedExpansion                     %\n%
                set pathExt=:                                       %\n%
                set path=;                                          %\n%
                set "line=!line:^=^^!"                              %\n%
                set "line=!line:"=q"^""!"                           %\n%
                call set "line=%%line:^!=q""^!%%"                   %\n%
                set "line=!line:q""=^!"                             %\n%
                set "line="!line:*:=!""                             %\n%
                for /F %%C in ("!%%~1.Len!") do (                   %\n%
                    FOR /F "delims=" %%L in ("!line!") Do (         %\n%
                        endlocal                                    %\n%
                        endlocal                                    %\n%
                        set "%%~1[%%C]=%%~L" !                      %\n%
                        if %%C == 0 (                               %\n%
                            set "%%~1=%%~L" !                       %\n%
                        ) ELSE (                                    %\n%
                            set "%%~1=!%%~1!!LF!%%~L" !             %\n%
                        )                                           %\n%
                    )                                               %\n%
                    set /a %%~1.Len+=1                              %\n%
                )                                                   %\n%
            )                                                       %\n%
        ) ELSE (                                                    %\n%
            %= Used if delayed expansion is disabled =%             %\n%
            for /F "delims=" %%O in ('"%%~2 | findstr /N ^^"') do ( %\n%
                setlocal DisableDelayedExpansion                    %\n%
                set "line=%%O"                                      %\n%
                setlocal EnableDelayedExpansion                     %\n%
                set "line="!line:*:=!""                             %\n%
                for /F %%C in ("!%%~1.Len!") DO (                   %\n%
                    FOR /F "delims=" %%L in ("!line!") DO (         %\n%
                        endlocal                                    %\n%
                        endlocal                                    %\n%
                        set "%%~1[%%C]=%%~L"                        %\n%
                    )                                               %\n%
                    set /a %%~1.Len+=1                              %\n%
                )                                                   %\n%
            )                                                       %\n%
        )                                                           %\n%
        set /a %%~1.Max=%%~1.Len-1                                  %\n%
)                                                                   %\n%
    ) else setlocal DisableDelayedExpansion^&set argv=

goto :eof

resource error in android studio after update: No Resource Found

you should change your compiledsdkversion and targetversion to 23 in the build gradle file specific to the app.Make sure you installed sdk 23, version 6.0 before this.You can watch this vid for more help.https://www.youtube.com/watch?v=pw4jKsOU7go

jquery UI dialog: how to initialize without a title bar?

I think that the best solution is to use the option dialogClass.

An extract from jquery UI docs:

during init : $('.selector').dialog({ dialogClass: 'noTitleStuff' });

or if you want after init. :

$('.selector').dialog('option', 'dialogClass', 'noTitleStuff');

So i created some dialog with option dialogClass='noTitleStuff' and the css like that:

.noTitleStuff .ui-dialog-titlebar {display:none}

too simple !! but i took 1 day to think why my previous id->class drilling method was not working. In fact when you call .dialog() method the div you transform become a child of another div (the real dialog div) and possibly a 'brother' of the titlebar div, so it's very difficult to try finding the latter starting from former.

What is the difference between field, variable, attribute, and property in Java POJOs?

Actually these two terms are often used to represent same thing, but there are some exceptional situations. A field can store the state of an object. Also all fields are variables. So it is clear that there can be variables which are not fields. So looking into the 4 type of variables (class variable, instance variable, local variable and parameter variable) we can see that class variables and instance variables can affect the state of an object. In other words if a class or instance variable changes,the state of object changes. So we can say that class variables and instance variables are fields while local variables and parameter variables are not.

If you want to understand more deeply, you can head over to the source below:-

http://sajupauledayan.com/java/fields-vs-variables-in-java

Aligning rotated xticklabels with their respective xticks

You can set the horizontal alignment of ticklabels, see the example below. If you imagine a rectangular box around the rotated label, which side of the rectangle do you want to be aligned with the tickpoint?

Given your description, you want: ha='right'

n=5

x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Ticklabel %i' % i for i in range(n)]

fig, axs = plt.subplots(1,3, figsize=(12,3))

ha = ['right', 'center', 'left']

for n, ax in enumerate(axs):
    ax.plot(x,y, 'o-')
    ax.set_title(ha[n])
    ax.set_xticks(x)
    ax.set_xticklabels(xlabels, rotation=40, ha=ha[n])

enter image description here

How to remove default chrome style for select Input?

-webkit-appearance: none;

and add your own style

This page didn't load Google Maps correctly. See the JavaScript console for technical details

There are 2 possibilities for this problem :

  1. you didn't enter the API KEY for map browser
  2. you didn't enabling the API Library especially for this Google Maps JavaScript API

just check on your Google developer console for that 2 items

Insert current date/time using now() in a field using MySQL/PHP

Just go to the column whenadded and change the default value to CURRENT_TIMESTAMP

How to close TCP and UDP ports via windows command line

Try the tools TCPView (GUI) and Tcpvcon (command line) by Sysinternals/Microsoft.
https://docs.microsoft.com/en-us/sysinternals/downloads/tcpview

Fatal error: Call to undefined function mysqli_connect()

Mine was a bit different for php7 on centos7.

In /etc/php.ini

; extension=mysqli

to

extension=mysqli

How to clear exisiting dropdownlist items when its content changes?

Just 2 simple steps to solve your issue

First of all check AppendDataBoundItems property and make it assign false

Secondly clear all the items using property .clear()

{
ddl1.Items.Clear();
ddl1.datasource = sql1;
ddl1.DataBind();
}

Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH

This error is definite mismatch between the data that is advertised in the HTTP Headers and the data transferred over the wire.

It could come from the following:

  1. Server: If a server has a bug with certain modules that changes the content but don't update the content-length in the header or just doesn't work properly. It was the case for the Node HTTP Proxy at some point (see here)

  2. Proxy: Any proxy between you and your server could be modifying the request and not update the content-length header.

As far as I know, I haven't see those problem in IIS but mostly with custom written code.

Let me know if that helps.

How to make a deep copy of Java ArrayList

Cloning the objects before adding them. For example, instead of newList.addAll(oldList);

for(Person p : oldList) {
    newList.add(p.clone());
}

Assuming clone is correctly overriden inPerson.

How to change string into QString?

Moreover, to convert whatever you want, you can use the QVariant class.

for example:

std::string str("hello !");
qDebug() << QVariant(str.c_str()).toString();
int test = 10;
double titi = 5.42;
qDebug() << QVariant(test).toString();
qDebug() << QVariant(titi).toString();
qDebug() << QVariant(titi).toInt();

output

"hello !"
"10"
"5.42"
5

Convert a String In C++ To Upper Case

The faster one if you use only ASCII characters:

for(i=0;str[i]!=0;i++)
  if(str[i]<='z' && str[i]>='a')
    str[i]+='A'-'a';

Please note that this code run faster but only works on ASCII and is not an "abstract" solution.

Extended version for other UTF8 alphabets:

...
if(str[i]<='z' && str[i]>='a') //is latin
    str[i]+='A'-'a';
else if(str[i]<='?' && str[i]>='?') //cyrillic
    str[i]+='?'-'?'
else if(str[i]<='?' && str[i]>='a') //greek
    str[i]+='O'-'?'
//etc...

If you need full UNICODE solutions or more conventional and abstract solutions, go for other answers and work with methods of C++ strings.

Convert a string to a double - is this possible?

Use doubleval(). But be very careful about using decimals in financial transactions, and validate that user input very carefully.

Passing a URL with brackets to curl

I was getting this error though there were no (obvious) brackets in my URL, and in my situation the --globoff command will not solve the issue.

For example (doing this on on mac in iTerm2):

for endpoint in $(grep some_string output.txt); do curl "http://1.2.3.4/api/v1/${endpoint}" ; done

I have grep aliased to "grep --color=always". As a result, the above command will result in this error, with some_string highlighted in whatever colour you have grep set to:

curl: (3) bad range in URL position 31:
http://1.2.3.4/api/v1/lalalasome_stringlalala

The terminal was transparently translating the [colour\codes]some_string[colour\codes] into the expected no-special-characters URL when viewed in terminal, but behind the scenes the colour codes were being sent in the URL passed to curl, resulting in brackets in your URL.

Solution is to not use match highlighting.

In CSS how do you change font size of h1 and h2

What have you tried? This should work.

h1 { font-size: 20pt; }
h2 { font-size: 16pt; }

Find the nth occurrence of substring in a string

Avoid a failure or incorrect output when the input value for occurrence provided is higher than the actual count of occurrence. For example, in a string 'overflow' if you would check the 3rd occurrence of 'o' ( it has only 2 occurrences ) then below code will return a warning or message indicating that the occurrence value has exceeded.

Input Occurrence entered has exceeded the actual count of Occurrence.

def check_nth_occurrence (string, substr, n):

## Count the Occurrence of a substr
    cnt = 0
    for i in string:
        if i ==substr:
            cnt = cnt + 1
        else:
            pass

## Check if the Occurrence input has exceeded the actual count of Occurrence

    if n > cnt:
        print (f' Input Occurrence entered has exceeded the actual count of Occurrence')
        return

## Get the Index value for first Occurrence of the substr

   index = string.find(substr)

## Get the Index value for nth Occurrence of Index
    while index >= 0 and n > 1:
        index = string.find(substr, index+ 1)
        n -= 1
  return index

Get the date of next monday, tuesday, etc

The PHP documentation for time() shows an example of how you can get a date one week out. You can modify this to instead go into a loop that iterates a maximum of 7 times, get the timestamp each time, get the corresponding date, and from that get the day of the week.

Download all stock symbol list of a market

Exchanges will usually publish an up-to-date list of securities on their web pages. For example, these pages offer CSV downloads:

NASDAQ Updated their site, so you will have to modify the URLS:

NASDAQ

AMEX

NYSE

Depending on your requirement, you could create the map of these URLs by exchange in your own code.

How to change an input button image using CSS?

You can use the <button> tag. For a submit, simply add type="submit". Then use a background image when you want the button to appear as a graphic.

Like so:

<button type="submit" style="border: 0; background: transparent">
    <img src="/images/Btn.PNG" width="90" height="50" alt="submit" />
</button>

More info: http://htmldog.com/reference/htmltags/button/

Linq : select value in a datatable column

If the return value is string and you need to search by Id you can use:

string name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name")).ToString();

or using generic variable:

var name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name"));

Xcode variables

The best source is probably Apple's official documentation. The specific variable you are looking for is CONFIGURATION.

how to use javascript Object.defineProperty

_x000D_
_x000D_
import { CSSProperties } from 'react'_x000D_
import { BLACK, BLUE, GREY_DARK, WHITE } from '../colours'_x000D_
_x000D_
export const COLOR_ACCENT = BLUE_x000D_
export const COLOR_DEFAULT = BLACK_x000D_
export const FAMILY = "'Segoe UI', sans-serif"_x000D_
export const SIZE_LARGE = '26px'_x000D_
export const SIZE_MEDIUM = '20px'_x000D_
export const WEIGHT = 400_x000D_
_x000D_
type Font = {_x000D_
  color: string,_x000D_
  size: string,_x000D_
  accent: Font,_x000D_
  default: Font,_x000D_
  light: Font,_x000D_
  neutral: Font,_x000D_
  xsmall: Font,_x000D_
  small: Font,_x000D_
  medium: Font,_x000D_
  large: Font,_x000D_
  xlarge: Font,_x000D_
  xxlarge: Font_x000D_
} & (() => CSSProperties)_x000D_
_x000D_
function font (this: Font): CSSProperties {_x000D_
  const css = {_x000D_
    color: this.color,_x000D_
    fontFamily: FAMILY,_x000D_
    fontSize: this.size,_x000D_
    fontWeight: WEIGHT_x000D_
  }_x000D_
  delete this.color_x000D_
  delete this.size_x000D_
  return css_x000D_
}_x000D_
_x000D_
const dp = (type: 'color' | 'size', name: string, value: string) => {_x000D_
  Object.defineProperty(font, name, { get () {_x000D_
    this[type] = value_x000D_
    return this_x000D_
  }})_x000D_
}_x000D_
_x000D_
dp('color', 'accent', COLOR_ACCENT)_x000D_
dp('color', 'default', COLOR_DEFAULT)_x000D_
dp('color', 'light', COLOR_LIGHT)_x000D_
dp('color', 'neutral', COLOR_NEUTRAL)_x000D_
dp('size', 'xsmall', SIZE_XSMALL)_x000D_
dp('size', 'small', SIZE_SMALL)_x000D_
dp('size', 'medium', SIZE_MEDIUM)_x000D_
_x000D_
export default font as Font
_x000D_
_x000D_
_x000D_

mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

?php

/* Database config */

$db_host        = 'localhost';
$db_user        = '~';
$db_pass        = '~';
$db_database    = 'banners'; 

/* End config */


$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_database);
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

?>

How do I solve the INSTALL_FAILED_DEXOPT error?

Restart your device.

In my case, the app run in most devices except for one: a cellphone that was too old and had been failing lately, the app thrown this error even without having installed the app once.

How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

You can use $mergeObjects in the aggregation based update. Something like

db.collection.update(
   { _id:...},
   [{"$set":{
      "some_key":{
        "$mergeObjects":[
          "$some_key",
          new info or { param2 : "val2_new", param3 : "val3_new"}
       ]
      }
   }}]
)

More examples here

VBA general way for pulling data out of SAP

This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.

However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.

In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.

Example Code

Here is a simple example based on a SAP system I have access to.

Public Sub SimpleSAPExport()
  Set SapGuiAuto  = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
  Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI 
  Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
  Set session = SAPCon.Children(0) 'Get the first session (window) on that connection

  'Start the transaction to view a table
  session.StartTransaction "SE16"

  'Select table T001
  session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
  session.findById("wnd[0]/tbar[1]/btn[7]").Press

  'Set our selection criteria
  session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
  session.findById("wnd[0]/tbar[1]/btn[8]").press

  'Click the export to file button
  session.findById("wnd[0]/tbar[1]/btn[45]").press

  'Choose the export format
  session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
  session.findById("wnd[1]/tbar[0]/btn[0]").press

  'Choose the export filename
  session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
  session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"

  'Export the file
  session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub

Script Recording

To help find the names of elements such aswnd[1]/tbar[0]/btn[0] you can use script recording. Click the customize local layout button, it probably looks a bit like this: Customize Local Layout
Then find the Script Recording and Playback menu item.
Script Recording and Playback
Within that the More button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.

Edit: Early and Late binding

The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI") defines the SapGuiAuto object.

If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx in the SAP GUI installation folder.

Simple function to sort an array of objects

var people = 
[{"name": 'a75',"item1": "false","item2":"false"}, 
{"name": 'z32',"item1": "true","item2":  "false"}, 
{"name": 'e77',"item1": "false","item2": "false"}]; 

function mycomparator(a,b) {   return parseInt(a.name) - parseInt(b.name);  } 
people.sort(mycomparator); 

something along the lines of this maybe (or as we used to say, this should work).

How to place a div on the right side with absolute position

Simple, use absolute positioning, and instead of specifying a top and a left, specify a top and a right!

For example:

#logo_image {
    width:80px;
    height:80px;
    top:10px;
    right:10px;
    z-index: 3;
    position:absolute;
}

How to get active user's UserDetails

Starting with Spring Security version 3.2, the custom functionality that has been implemented by some of the older answers, exists out of the box in the form of the @AuthenticationPrincipal annotation that is backed by AuthenticationPrincipalArgumentResolver.

An simple example of it's use is:

@Controller
public class MyController {
   @RequestMapping("/user/current/show")
   public String show(@AuthenticationPrincipal CustomUser customUser) {
        // do something with CustomUser
       return "view";
   }
}

CustomUser needs to be assignable from authentication.getPrincipal()

Here are the corresponding Javadocs of AuthenticationPrincipal and AuthenticationPrincipalArgumentResolver

Reload a DIV without reloading the whole page

try this

<script type="text/javascript">
window.onload = function(){


var auto_refresh = setInterval(
function ()
{
$('.View').html('');
$('.View').load('Small.php').fadeIn("slow");
}, 15000); // refresh every 15000 milliseconds

}
</script>

How do I name the "row names" column in r

The tibble package now has a dedicated function that converts row names to an explicit variable.

library(tibble)
rownames_to_column(mtcars, var="das_Auto") %>% head

Gives:

           das_Auto  mpg cyl disp  hp drat    wt  qsec vs am gear carb
1         Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
2     Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3        Datsun 710 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
4    Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
5 Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
6           Valiant 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

TypeError: only length-1 arrays can be converted to Python scalars while plot showing

Take note of what is printed for x. You are trying to convert an array (basically just a list) into an int. length-1 would be an array of a single number, which I assume numpy just treats as a float. You could do this, but it's not a purely-numpy solution.

EDIT: I was involved in a post a couple of weeks back where numpy was slower an operation than I had expected and I realised I had fallen into a default mindset that numpy was always the way to go for speed. Since my answer was not as clean as ayhan's, I thought I'd use this space to show that this is another such instance to illustrate that vectorize is around 10% slower than building a list in Python. I don't know enough about numpy to explain why this is the case but perhaps someone else does?

import numpy as np
import matplotlib.pyplot as plt
import datetime

time_start = datetime.datetime.now()

# My original answer
def f(x):
    rebuilt_to_plot = []
    for num in x:
        rebuilt_to_plot.append(np.int(num))
    return rebuilt_to_plot

for t in range(10000):
    x = np.arange(1, 15.1, 0.1)
    plt.plot(x, f(x))

time_end = datetime.datetime.now()

# Answer by ayhan
def f_1(x):
    return np.int(x)

for t in range(10000):
    f2 = np.vectorize(f_1)
    x = np.arange(1, 15.1, 0.1)
    plt.plot(x, f2(x))

time_end_2 = datetime.datetime.now()

print time_end - time_start
print time_end_2 - time_end

How to copy a file to another path?

I tried to copy an xml file from one location to another. Here is my code:

public void SaveStockInfoToAnotherFile()
{
    string sourcePath = @"C:\inetpub\wwwroot";
    string destinationPath = @"G:\ProjectBO\ForFutureAnalysis";
    string sourceFileName = "startingStock.xml";
    string destinationFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xml"; // Don't mind this. I did this because I needed to name the copied files with respect to time.
    string sourceFile = System.IO.Path.Combine(sourcePath, sourceFileName);
    string destinationFile = System.IO.Path.Combine(destinationPath, destinationFileName);

    if (!System.IO.Directory.Exists(destinationPath))
       {
         System.IO.Directory.CreateDirectory(destinationPath);
       }
    System.IO.File.Copy(sourceFile, destinationFile, true);
}

Then I called this function inside a timer_elapsed function of certain interval which I think you don't need to see. It worked. Hope this helps.

Linq to SQL how to do "where [column] in (list of values)"

I had been using the method in Jon Skeet's answer, but another one occurred to me using Concat. The Concat method performed slightly better in a limited test, but it's a hassle and I'll probably just stick with Contains, or maybe I'll write a helper method to do this for me. Either way, here's another option if anyone is interested:

The Method

// Given an array of id's
var ids = new Guid[] { ... };

// and a DataContext
var dc = new MyDataContext();

// start the queryable
var query = (
    from thing in dc.Things
    where thing.Id == ids[ 0 ]
    select thing 
);

// then, for each other id
for( var i = 1; i < ids.Count(); i++ ) {
    // select that thing and concat to queryable
    query.Concat(
        from thing in dc.Things
        where thing.Id == ids[ i ]
        select thing
    );
}

Performance Test

This was not remotely scientific. I imagine your database structure and the number of IDs involved in the list would have a significant impact.

I set up a test where I did 100 trials each of Concat and Contains where each trial involved selecting 25 rows specified by a randomized list of primary keys. I've run this about a dozen times, and most times the Concat method comes out 5 - 10% faster, although one time the Contains method won by just a smidgen.

double free or corruption (!prev) error in c program

I didn't check all the code but my guess is that the error is in the malloc call. You have to replace

 double *ptr = malloc(sizeof(double*) * TIME);

for

 double *ptr = malloc(sizeof(double) * TIME);

since you want to allocate size for a double (not the size of a pointer to a double).

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

Just run on ports above 1024 , anything below is privileged, its the same deal with Linux, i use 5000 for example on wins without any UAC priv escalation.

Setting the Textbox read only property to true using JavaScript

Try This :-

set Read Only False ( Editable TextBox)

document.getElementById("txtID").readOnly=false;

set Read Only true(Not Editable )

var v1=document.getElementById("txtID");
v1.setAttribute("readOnly","true");

This can work on IE and Firefox also.

Bridged networking not working in Virtualbox under Windows 10

My very simple solution that worked: select another networkcard!

  1. Make sure your guest is shut down
  2. Goto the guest Settings > Network > Adavanced
  3. Change the Adapter Type to another adapter.
  4. Start your guest and check if you got a decent IP for your network.

If it doesn't work, repeat steps and try yet another network adapter. The very basic PCnet adapters have a high succes-rate.

Good luck.

Change the mouse pointer using JavaScript

With regards to @CrazyJugglerDrummer second method it would be:

elementsToChange.style.cursor = "http://wiki-devel.sugarlabs.org/images/e/e2/Arrow.cur";

Android Studio Gradle project "Unable to start the daemon process /initialization of VM"

Happened to me because i was running a virtual machine at the same time, the ram was already allocated to that so android studio couldn't take up any ram, switching off virtual box and restarting did the trick for me.

How to add a browser tab icon (favicon) for a website?

Kindly use below code in header section your index file.

<link rel="icon" href="yourfevicon.ico" />

How do I go about adding an image into a java project with eclipse?

If you still have problems with Eclipse finding your files, you might try the following:

  1. Verify that the file exists according to the current execution environment by using the java.io.File class to get a canonical path format and verify that (a) the file exists and (b) what the canonical path is.
  2. Verify the default working directory by printing the following in your main:

        System.out.println("Working dir:  " + System.getProperty("user.dir"));
    

For (1) above, I put the following debugging code around the specific file I was trying to access:

            File imageFile = new File(source);
            System.out.println("Canonical path of target image: " + imageFile.getCanonicalPath());
            if (!imageFile.exists()) {
                System.out.println("file " + imageFile + " does not exist");
            }
            image = ImageIO.read(imageFile);                

For whatever reason, I ended up ignoring most of the other posts telling me to put the image files in "src" or some other variant, as I verified that the system was looking at the root of the Eclipse project directory hierarchy (e.g., $HOME/workspace/myProject).

Having the images in src/ (which is automatically copied to bin/) didn't do the trick on Eclipse Luna.

How to access child's state in React?

As the previous answers saids, try to move the state to a top component and modify the state through callbacks passed to it's children.

In case that you really need to access to a child state that is declared as a functional component (hooks) you can declare a ref in the parent component, then pass it as a ref attribute to the child but you need to use React.forwardRef and then the hook useImperativeHandle to declare a function you can call in the parent component.

Take a look at the following example:

const Parent = () => {
    const myRef = useRef();
    return <Child ref={myRef} />;
}

const Child = React.forwardRef((props, ref) => {
    const [myState, setMyState] = useState('This is my state!');
    useImperativeHandle(ref, () => ({getMyState: () => {return myState}}), [myState]);
})

Then you should be able to get myState in the Parent component by calling: myRef.current.getMyState();

CSS: How to remove pseudo elements (after, before,...)?

had a same problem few minutes ago and just content:none; did not do work but adding content:none !important; and display:none !important; worked for me

PHP split alternative?

  • preg_split if you need to split by regular expressions.
  • str_split if you need to split by characters.
  • explode if you need to split by something simple.

Also for the future, if you ever want to know what PHP wants you to use if something is deprecated you can always check out the function in the manual and it will tell you alternatives.

List all environment variables from the command line

As mentioned in other answers, you can use set to list all the environment variables or use

set [environment_variable] to get a specific variable with its value.

set [environment_variable]= can be used to remove a variable from the workspace.

How can I create a blank/hardcoded column in a sql query?

Thank you, in PostgreSQL this works for boolean

SELECT
hat,
shoe,
boat,
false as placeholder
FROM
objects

How to read keyboard-input?

try

raw_input('Enter your input:')  # If you use Python 2
input('Enter your input:')      # If you use Python 3

and if you want to have a numeric value just convert it:

try:
    mode=int(raw_input('Input:'))
except ValueError:
    print "Not a number"

Show Current Location and Nearby Places and Route between two places using Google Maps API in Android

  1. First go through this tutorial for getting familiar with Android Google Maps and this for API 2.

  2. To retrive the current location of device see this answer or this another answer and for API 2

  3. Then you can get places near by your location using Google Place API and for use of Place Api see this blog.

  4. After getting Placemarks of near by location use this blog with source code to show markers on map with balloon overlay with API 2.

  5. You also have great sample to draw route between two points on map look here in these links Link1 and Link2 and this Great Answer.

After following these steps you will be easily able to do your application. The only condition is, you will have to read it and understand it, because like magic its not going to be complete in a click.

javascript find and remove object in array based on key value

here is a solution if you are not using jquery:

myArray = myArray.filter(function( obj ) {
  return obj.id !== id;
});

MATLAB - multiple return values from a function?

Change the function that you get one single Result=[array, listp, freep]. So there is only one result to be displayed

Turn a single number into single digits Python

Here's a way to do it without turning it into a string first (based on some rudimentary benchmarking, this is about twice as fast as stringifying n first):

>>> n = 43365644
>>> [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10))-1, -1, -1)]
[4, 3, 3, 6, 5, 6, 4, 4]

Updating this after many years in response to comments of this not working for powers of 10:

[(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][bool(math.log(n,10)%1):]

The issue is that with powers of 10 (and ONLY with these), an extra step is required. ---So we use the remainder in the log_10 to determine whether to remove the leading 0--- We can't exactly use this because floating-point math errors cause this to fail for some powers of 10. So I've decided to cross the unholy river into sin and call upon regex.

In [32]: n = 43

In [33]: [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][not(re.match('10*', str(n))):]
Out[33]: [4, 3]

In [34]: n = 1000

In [35]: [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][not(re.match('10*', str(n))):]
Out[35]: [1, 0, 0, 0]

How to Insert Double or Single Quotes

Easier steps:

  1. Highlight the cells you want to add the quotes.
  2. Go to Format–>Cells–>Custom
  3. Copy/Paste the following into the Type field: \"@\" or \'@\'
  4. Done!

Sanitizing user input before adding it to the DOM in Javascript

Since the text that you are escaping will appear in an HTML attribute, you must be sure to escape not only HTML entities but also HTML attributes:

var ESC_MAP = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;'
};

function escapeHTML(s, forAttribute) {
    return s.replace(forAttribute ? /[&<>'"]/g : /[&<>]/g, function(c) {
        return ESC_MAP[c];
    });
}

Then, your escaping code becomes var user_id = escapeHTML(id, true).

For more information, see Foolproof HTML escaping in Javascript.

div with dynamic min-height based on browser window height

As mentioned elsewhere, the CSS function calc() can work nicely here. It is now mostly supported. You could use like:

.container
{
    min-height: 70%;
    min-height: -webkit-calc(100% - 300px);
    min-height: -moz-calc(100% - 300px);
    min-height: calc(100% - 300px);
}

Detect when an image fails to load in Javascript

The answer is nice, but it introduces one problem. Whenever you assign onload or onerror directly, it may replace the callback that was assigned earlier. That is why there's a nice method that "registers the specified listener on the EventTarget it's called on" as they say on MDN. You can register as many listeners as you want on the same event.

Let me rewrite the answer a little bit.

function testImage(url) {
    var tester = new Image();
    tester.addEventListener('load', imageFound);
    tester.addEventListener('error', imageNotFound);
    tester.src = url;
}

function imageFound() {
    alert('That image is found and loaded');
}

function imageNotFound() {
    alert('That image was not found.');
}

testImage("http://foo.com/bar.jpg");

Because the external resource loading process is asynchronous, it would be even nicer to use modern JavaScript with promises, such as the following.

function testImage(url) {

    // Define the promise
    const imgPromise = new Promise(function imgPromise(resolve, reject) {

        // Create the image
        const imgElement = new Image();

        // When image is loaded, resolve the promise
        imgElement.addEventListener('load', function imgOnLoad() {
            resolve(this);
        });

        // When there's an error during load, reject the promise
        imgElement.addEventListener('error', function imgOnError() {
            reject();
        })

        // Assign URL
        imgElement.src = url;

    });

    return imgPromise;
}

testImage("http://foo.com/bar.jpg").then(

    function fulfilled(img) {
        console.log('That image is found and loaded', img);
    },

    function rejected() {
        console.log('That image was not found');
    }

);

How to get a list of sub-folders and their files, ordered by folder-names

create a vbs file and copy all code below. Change directory location to wherever you want.

Dim fso
Dim ObjOutFile

Set fso = CreateObject("Scripting.FileSystemObject")

Set ObjOutFile = fso.CreateTextFile("OutputFiles.csv")

ObjOutFile.WriteLine("Type,File Name,File Path")

GetFiles("YOUR LOCATION")

ObjOutFile.Close

WScript.Echo("Completed")

Function GetFiles(FolderName)
    On Error Resume Next

    Dim ObjFolder
    Dim ObjSubFolders
    Dim ObjSubFolder
    Dim ObjFiles
    Dim ObjFile

    Set ObjFolder = fso.GetFolder(FolderName)
    Set ObjFiles = ObjFolder.Files

    For Each ObjFile In ObjFiles
    ObjOutFile.WriteLine("File," & ObjFile.Name & "," & ObjFile.Path)
    Next

    Set ObjSubFolders = ObjFolder.SubFolders

    For Each ObjFolder In ObjSubFolders

        ObjOutFile.WriteLine("Folder," & ObjFolder.Name & "," & ObjFolder.Path)


        GetFiles(ObjFolder.Path)
    Next

End Function

Save the code as vbs and run it. you will get a list in that directory

postgresql - add boolean column to table set default

Just for future reference, if you already have a boolean column and you just want to add a default do:

ALTER TABLE users
  ALTER COLUMN priv_user SET DEFAULT false;

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

The first line of link below saved my day:

To add values to options from your project’s build settings, prepend the value list with $(inherited).

https://github.com/CocoaPods/CocoaPods/wiki/Creating-a-project-that-uses-CocoaPods#faq

Also, do not forget to insert this line at the beginning of your pod file:

platform :iOS, '5.0'

How to use JNDI DataSource provided by Tomcat in Spring?

Another feature: instead of of server.xml, you can add "Resource" tag in
your_application/META-INF/Context.xml (according to tomcat docs) like this:

<Context>
<Resource name="jdbc/DatabaseName" auth="Container" type="javax.sql.DataSource"
  username="dbUsername" password="dbPasswd"
  url="jdbc:postgresql://localhost/dbname"
  driverClassName="org.postgresql.Driver"
  initialSize="5" maxWait="5000"
  maxActive="120" maxIdle="5"
  validationQuery="select 1"
  poolPreparedStatements="true"/>
</Context>

SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

As others have suggested, the best way to do this is to use a join instead of variable assignment. Re-writing your query to use a join (and using the explicit join syntax instead of the implicit join, which was also suggested--and is the best practice), you would get something like this:

select  
  OrderDetails.Sku,
  OrderDetails.mf_item_number,
  OrderDetails.Qty,
  OrderDetails.Price,
  Supplier.SupplierId, 
  Supplier.SupplierName,
  Supplier.DropShipFees, 
  Supplier_Item.Price as cost
from 
  OrderDetails
join Supplier on OrderDetails.Mfr_ID = Supplier.SupplierId
join Group_Master on Group_Master.Sku = OrderDetails.Sku 
join Supplier_Item on 
  Supplier_Item.SKU=OrderDetails.Sku and Supplier_Item.SupplierId=Supplier.SupplierID 
where 
  invoiceid='339740' 

Difference between $(document.body) and $('body')

$(document.body) is using the global reference document to get a reference to the body, whereas $('body') is a selector in which jQuery will get the reference to the <body> element on the document.

No major difference that I can see, not any noticeable performance gain from one to the other.

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

As this post gets a bit of popularity I edited it a bit. Spring Boot 2.x.x changed default JDBC connection pool from Tomcat to faster and better HikariCP. Here comes incompatibility, because HikariCP uses different property of jdbc url. There are two ways how to handle it:

OPTION ONE

There is very good explanation and workaround in spring docs:

Also, if you happen to have Hikari on the classpath, this basic setup does not work, because Hikari has no url property (but does have a jdbcUrl property). In that case, you must rewrite your configuration as follows:

app.datasource.jdbc-url=jdbc:mysql://localhost/test
app.datasource.username=dbuser
app.datasource.password=dbpass

OPTION TWO

There is also how-to in the docs how to get it working from "both worlds". It would look like below. ConfigurationProperties bean would do "conversion" for jdbcUrl from app.datasource.url

@Configuration
public class DatabaseConfig {
    @Bean
    @ConfigurationProperties("app.datasource")
    public DataSourceProperties dataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @ConfigurationProperties("app.datasource")
    public HikariDataSource dataSource(DataSourceProperties properties) {
        return properties.initializeDataSourceBuilder().type(HikariDataSource.class)
                .build();
    }
}

Html.DropdownListFor selected value not being set

For me general solution :)

@{
     var selectedCity = Model.Cities.Where(k => k.Id == Model.Addres.CityId).FirstOrDefault();
     if (selectedCity != null)
     { 
         @Html.DropDownListFor(model => model.Addres.CityId, new SelectList(Model.Cities, "Id", "Name", selectedCity.Id), new { @class = "form-control" })
     }
     else
     { 
         @Html.DropDownListFor(model => model.Cities, new SelectList(Model.Cities, "Id", "Name", "1"), new { @class = "form-control" })
     }
}

What is sharding and why is it important?

In my opinion the application tier should have no business determining where data should be stored

This is a good rule but like most things not always correct.

When you do your architecture you start with responsibilities and collaborations. Once you determine your functional architecture, you have to balance the non-functional forces.

If one of these non-functional forces is massive scalability, you have to adapt your architecture to cater for this force even if it means that your data storage abstraction now leaks into your application tier.

Spring Boot Remove Whitelabel Error Page

This depends on your spring boot version:

When SpringBootVersion <= 1.2 then use error.whitelabel.enabled = false

When SpringBootVersion >= 1.3 then use server.error.whitelabel.enabled = false

How to solve "Fatal error: Class 'MySQLi' not found"?

How to Enable mysqli in php.ini

  1. Edit/uncomment by removing ';'(colon) the following config in php.ini: 1st (uncomment and add config):
    include_path = "C:\php\includes"
    
    2nd (uncomment):
    extension_dir = "ext"
    
    3rd (uncomment and edit config):
    extension=C:/PHP/ext/php_mysql.dll
    extension=C:/PHP/ext/php_mysqli.dll
    
  2. Restart the IIS server
  3. Make sure that mysql is running on the system.

How to load php.ini file

  1. Rename any one of the file php.ini-production/php.ini-development to php.ini from C:\PHP(note now the extention will be ini i.e "php.ini").
  2. After renaming to php.ini file restart server
  3. See the changes in http://localhost/phpinfo.php

How do I empty an array in JavaScript?

In case you are interested in the memory allocation, you may compare each approach using something like this jsfiddle in conjunction with chrome dev tools' timeline tab. You will want to use the trash bin icon at the bottom to force a garbage collection after 'clearing' the array. This should give you a more definite answer for the browser of your choice. A lot of answers here are old and I wouldn't rely on them but rather test as in @tanguy_k's answer above.

(for an intro to the aforementioned tab you can check out here)

Stackoverflow forces me to copy the jsfiddle so here it is:

<html>
<script>
var size = 1000*100
window.onload = function() {
  document.getElementById("quantifier").value = size
}

function scaffold()
{
  console.log("processing Scaffold...");
  a = new Array
}
function start()
{
  size = document.getElementById("quantifier").value
  console.log("Starting... quantifier is " + size);
  console.log("starting test")
  for (i=0; i<size; i++){
    a[i]="something"
  }
  console.log("done...")
}

function tearDown()
{
  console.log("processing teardown");
  a.length=0
}

</script>
<body>
    <span style="color:green;">Quantifier:</span>
    <input id="quantifier" style="color:green;" type="text"></input>
    <button onclick="scaffold()">Scaffold</button>
    <button onclick="start()">Start</button>
    <button onclick="tearDown()">Clean</button>
    <br/>
</body>
</html>

And you should take note that it may depend on the type of the array elements, as javascript manages strings differently than other primitive types, not to mention arrays of objects. The type may affect what happens.

How to set cursor to input box in Javascript?

You have not provided enough code to help You likely submit the form and reload the page OR you have an object on the page like an embedded PDF that steals the focus.

Here is the canonical plain javascript method of validating a form It can be improved with onubtrusive JS which will remove the inline script, but this is the starting point DEMO

function validate(formObj) {
  document.getElementById("errorMsg").innerHTML = "";    
  var quantity = formObj.quantity;
  if (isNaN(quantity)) {
    quantity.value="";
    quantity.focus();
    document.getElementById("errorMsg").innerHTML = "Only numeric value is allowed";
    return false;
  }
  return true; // allow submit
}   

Here is the HTML

<form onsubmit="return validate(this)">
    <input type="text" name="quantity" value="" />
    <input type="submit" />
</form>    
<span id="errorMsg"></span>

Unpivot with column name

Your query is very close. You should be able to use the following which includes the subject in the final select list:

select u.name, u.subject, u.marks
from student s
unpivot
(
  marks
  for subject in (Maths, Science, English)
) u;

See SQL Fiddle with demo

How do I indent multiple lines at once in Notepad++?

It works fine for my v. 5.4.5 of Notepad++. I just select multiple lines and press TAB.

If you want TAB to be replaced by SPACE than you need to go Settings > Preferences and select Edit Components tab. Next check Replace by spaces check box in Tab Setting section.

Update: In a newer version of Notepad++ this option is in Settings > Preferences > Languaage section.

Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave

In macOS 10.14 this issue may also occur if you have two or more versions installed. If you like xCode GUI you can do it by going into preferences - CMD + ,, selecting Locations tab and choosing version of Command Line Tools. Please refer to the attached print screen.

enter image description here

How to use conditional breakpoint in Eclipse?

Put your breakpoint. Right-click the breakpoint image on the margin and choose Breakpoint Properties:

enter image description here

Configure condition as you see fit:

enter image description here

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

If you are using material-ui, go to type definition of the component, which is being underlined by TypeScript. Most likely you will see something like this

export { default } from './ComponentName';

You have 2 options to resolve the error:

1.Add .default when using the component in JSX:

import ComponentName from './ComponentName'

const Component = () => <ComponentName.default />

2.Rename the component, which is being exported as "default", when importing:

import { default as ComponentName } from './ComponentName'

const Component = () => <ComponentName />

This way you don't need to specify .default every time you use the component.

Why does z-index not work?

Your elements need to have a position attribute. (e.g. absolute, relative, fixed) or z-index won't work.

Clang vs GCC for my Linux Development project

As of right now, GCC has much better and more complete support for C++11 features than Clang. Also, the code generator for GCC performs better optimisation than the one in Clang (in my experience, I have not seen any exhaustive tests).

On the other hand, Clang often compiles code more quickly than GCC, and produces better error messages when there is something wrong with your code.

The choice of which one to use really depends on what things are important to you. I value C++11 support and code generation quality more than I value convenience of compilation. Because of this, I use GCC. For you, the trade-offs could be different.

CSS - Make divs align horizontally

Float: left, display: inline-block will both fail to align the elements horizontally if they exceed the width of the container.

It's important to note that the container should not wrap if the elements MUST display horizontally: white-space: nowrap

Understanding INADDR_ANY for socket programming

INADDR_ANY is used when you don't need to bind a socket to a specific IP. When you use this value as the address when calling bind(), the socket accepts connections to all the IPs of the machine.

Excel formula to reference 'CELL TO THE LEFT'

If you change your cell reference to use R1C1 notation (Tools|Options, General tab), then you can use a simple notation and paste it into any cell.

Now your formula is simply:

=RC[-1]

Singleton design pattern vs Singleton beans in Spring container

Singleton scope in spring means single instance in a Spring context ..
Spring container merely returns the same instance again and again for subsequent calls to get the bean.


And spring doesn't bother if the class of the bean is coded as singleton or not , in fact if the class is coded as singleton whose constructor as private, Spring use BeanUtils.instantiateClass (javadoc here) to set the constructor to accessible and invoke it.

Alternatively, we can use a factory-method attribute in bean definition like this

    <bean id="exampleBean" class="example.Singleton"  factory-method="getInstance"/>

Throwing exceptions from constructors

Apart from the fact that you do not need to throw from the constructor in your specific case because pthread_mutex_lock actually returns an EINVAL if your mutex has not been initialized and you can throw after the call to lock as is done in std::mutex:

void
lock()
{
  int __e = __gthread_mutex_lock(&_M_mutex);

  // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
  if (__e)
__throw_system_error(__e);
}

then in general throwing from constructors is ok for acquisition errors during construction, and in compliance with RAII ( Resource-acquisition-is-Initialization ) programming paradigm.

Check this example on RAII

void write_to_file (const std::string & message) {
    // mutex to protect file access (shared across threads)
    static std::mutex mutex;

    // lock mutex before accessing file
    std::lock_guard<std::mutex> lock(mutex);

    // try to open file
    std::ofstream file("example.txt");
    if (!file.is_open())
        throw std::runtime_error("unable to open file");

    // write message to file
    file << message << std::endl;

    // file will be closed 1st when leaving scope (regardless of exception)
    // mutex will be unlocked 2nd (from lock destructor) when leaving
    // scope (regardless of exception)
}

Focus on these statements:

  1. static std::mutex mutex
  2. std::lock_guard<std::mutex> lock(mutex);
  3. std::ofstream file("example.txt");

The first statement is RAII and noexcept. In (2) it is clear that RAII is applied on lock_guard and it actually can throw , whereas in (3) ofstream seems not to be RAII , since the objects state has to be checked by calling is_open() that checks the failbit flag.

At first glance it seems that it is undecided on what it the standard way and in the first case std::mutex does not throw in initialization , *in contrast to OP implementation * . In the second case it will throw whatever is thrown from std::mutex::lock, and in the third there is no throw at all.

Notice the differences:

(1) Can be declared static, and will actually be declared as a member variable (2) Will never actually be expected to be declared as a member variable (3) Is expected to be declared as a member variable, and the underlying resource may not always be available.

All these forms are RAII; to resolve this, one must analyse RAII.

  • Resource : your object
  • Acquisition ( allocation ) : you object being created
  • Initialization : your object is in its invariant state

This does not require you to initialize and connect everything on construction. For example when you would create a network client object you would not actually connect it to the server upon creation, since it is a slow operation with failures. You would instead write a connect function to do just that. On the other hand you could create the buffers or just set its state.

Therefore, your issue boils down to defining your initial state. If in your case your initial state is mutex must be initialized then you should throw from the constructor. In contrast it is just fine not to initialize then ( as is done in std::mutex ), and define your invariant state as mutex is created . At any rate the invariant is not compromized necessarily by the state of its member object, since the mutex_ object mutates between locked and unlocked through the Mutex public methods Mutex::lock() and Mutex::unlock().

class Mutex {
private:
  int e;
  pthread_mutex_t mutex_;

public:
  Mutex(): e(0) {
  e = pthread_mutex_init(&mutex_);
  }

  void lock() {

    e = pthread_mutex_lock(&mutex_);
    if( e == EINVAL ) 
    { 
      throw MutexInitException();
    }
    else (e ) {
      throw MutexLockException();
    }
  }

  // ... the rest of your class
};

Convert Current date to integer

The issue is that an Integer is not large enough to store a current date, you need to use a Long.

The date is stored internally as the number of milliseconds since 1/1/1970.

The maximum Integer value is 2147483648, whereas the number of milliseconds since 1970 is currently in the order of 1345618537869

Putting the maximum integer value into a date yields Monday 26th January 1970.

Edit: Code to display division by 1000 as per comment below:

    int i = (int) (new Date().getTime()/1000);
    System.out.println("Integer : " + i);
    System.out.println("Long : "+ new Date().getTime());
    System.out.println("Long date : " + new Date(new Date().getTime()));
    System.out.println("Int Date : " + new Date(((long)i)*1000L));

Integer : 1345619256
Long : 1345619256308
Long date : Wed Aug 22 16:37:36 CST 2012
Int Date : Wed Aug 22 16:37:36 CST 2012

enabling cross-origin resource sharing on IIS7

I found the information found at http://help.infragistics.com/Help/NetAdvantage/jQuery/2013.1/CLR4.0/html/igOlapXmlaDataSource_Configuring_IIS_for_Cross_Domain_OLAP_Data.html to be very helpful in setting up HTTP OPTIONS for a WCF service in IIS 7.

I added the following to my web.config and then moved the OPTIONSVerbHandler in the IIS 7 'hander mappings' list to the top of the list. I also gave the OPTIONSVerbHander read access by double clicking the hander in the handler mappings section then on 'Request Restrictions' and then clicking on the access tab.

Unfortunately I quickly found that IE doesn't seem to support adding headers to their XDomainRequest object (setting the Content-Type to text/xml and adding a SOAPAction header).

Just wanted to share this as I spent the better part of a day looking for how to handle it.

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS" />
            <add name="Access-Control-Allow-Headers" value="Content-Type, soapaction" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

// This pair of functions convert HSL to RGB and vice-versa.
// It's pretty optimized for execution speed

typedef unsigned char       BYTE
typedef struct _RGB
{
    BYTE R;
    BYTE G;
    BYTE B;
} RGB, *pRGB;
typedef struct _HSL
{
    float   H;  // color Hue (0.0 to 360.0 degrees)
    float   S;  // color Saturation (0.0 to 1.0)
    float   L;  // Luminance (0.0 to 1.0)
    float   V;  // Value (0.0 to 1.0)
} HSL, *pHSL;

float   *fMin       (float *a, float *b)
{
    return *a <= *b?  a : b;
}

float   *fMax       (float *a, float *b)
{
    return *a >= *b? a : b;
}

void    RGBtoHSL    (pRGB rgb, pHSL hsl)
{
// See https://en.wikipedia.org/wiki/HSL_and_HSV
// rgb->R, rgb->G, rgb->B: [0 to 255]
    float r =       (float) rgb->R / 255;
    float g =       (float) rgb->G / 255;
    float b =       (float) rgb->B / 255;
    float *min =    fMin(fMin(&r, &g), &b);
    float *max =    fMax(fMax(&r, &g), &b);
    float delta =   *max - *min;

// L, V [0.0 to 1.0]
    hsl->L = (*max + *min)/2;
    hsl->V = *max;
// Special case for H and S
    if (delta == 0)
    {
        hsl->H = 0.0f;
        hsl->S = 0.0f;
    }
    else
    {
// Special case for S
        if((*max == 0) || (*min == 1))
            hsl->S = 0;
        else
// S [0.0 to 1.0]
            hsl->S = (2 * *max - 2*hsl->L)/(1 - fabsf(2*hsl->L - 1));
// H [0.0 to 360.0]
        if      (max == &r)     hsl->H = fmod((g - b)/delta, 6);    // max is R
        else if (max == &g)     hsl->H = (b - r)/delta + 2;         // max is G
        else                    hsl->H = (r - g)/delta + 4;         // max is B
        hsl->H *= 60;
    }
}

void    HSLtoRGB    (pHSL hsl, pRGB rgb)
{
// See https://en.wikipedia.org/wiki/HSL_and_HSV
    float a, k, fm1, fp1, f1, f2, *f3;
// L, V, S: [0.0 to 1.0]
// rgb->R, rgb->G, rgb->B: [0 to 255]
    fm1 = -1;
    fp1 = 1;
    f1 = 1-hsl->L;
    a = hsl->S * *fMin(&hsl->L, &f1);
    k = fmod(0 + hsl->H/30, 12);
    f1 = k - 3;
    f2 = 9 - k;
    f3 = fMin(fMin(&f1, &f2), &fp1) ;
    rgb->R = (BYTE) (255 * (hsl->L - a * *fMax(f3, &fm1)));

    k = fmod(8 + hsl->H/30, 12);
    f1 = k - 3;
    f2 = 9 - k;
    f3 = fMin(fMin(&f1, &f2), &fp1) ;
    rgb->G = (BYTE) (255 * (hsl->L - a * *fMax(f3, &fm1)));

    k = fmod(4 + hsl->H/30, 12);
    f1 = k - 3;
    f2 = 9 - k;
    f3 = fMin(fMin(&f1, &f2), &fp1) ;
    rgb->B = (BYTE) (255 * (hsl->L - a * *fMax(f3, &fm1)));
}

Insert data into table with result from another select query

INSERT INTO `test`.`product` ( `p1`, `p2`, `p3`) 
SELECT sum(p1), sum(p2), sum(p3) 
FROM `test`.`product`;

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.

Python: How to get stdout after running os.system?

If all you need is the stdout output, then take a look at subprocess.check_output():

import subprocess

batcmd="dir"
result = subprocess.check_output(batcmd, shell=True)

Because you were using os.system(), you'd have to set shell=True to get the same behaviour. You do want to heed the security concerns about passing untrusted arguments to your shell.

If you need to capture stderr as well, simply add stderr=subprocess.STDOUT to the call:

result = subprocess.check_output([batcmd], stderr=subprocess.STDOUT)

to redirect the error output to the default output stream.

If you know that the output is text, add text=True to decode the returned bytes value with the platform default encoding; use encoding="..." instead if that codec is not correct for the data you receive.

Add a list item through javascript

The above answer was helpful for me, but it might be useful (or best practice) to add the name on submit, as I wound up doing. Hopefully this will be helpful to someone. CodePen Sample

    <form id="formAddName">
      <fieldset>
        <legend>Add Name </legend>
            <label for="firstName">First Name</label>
            <input type="text" id="firstName" name="firstName" />

        <button>Add</button>
      </fieldset>
    </form>

      <ol id="demo"></ol>

<script>
    var list = document.getElementById('demo');
    var entry = document.getElementById('formAddName');
    entry.onsubmit = function(evt) {
    evt.preventDefault();
    var firstName = document.getElementById('firstName').value;
    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(firstName));
    list.appendChild(entry);
  }
</script>

Java check to see if a variable has been initialized

Instance variables or fields, along with static variables, are assigned default values based on the variable type:

  • int: 0
  • char: \u0000 or 0
  • double: 0.0
  • boolean: false
  • reference: null

Just want to clarify that local variables (ie. declared in block, eg. method, for loop, while loop, try-catch, etc.) are not initialized to default values and must be explicitly initialized.

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

Even though utf8_decode is a useful solution, I prefer to correct the encoding errors on the table itself. In my opinion it is better to correct the bad characters themselves than making "hacks" in the code. Simply do a replace on the field on the table. To correct the bad encoded characters from OP :

update <table> set <field> = replace(<field>, "ë", "ë")
update <table> set <field> = replace(<field>, "Ã", "à")
update <table> set <field> = replace(<field>, "ì", "ì")
update <table> set <field> = replace(<field>, "ù", "ù")

Where <table> is the name of the mysql table and <field> is the name of the column in the table. Here is a very good check-list for those typically bad encoded windows-1252 to utf-8 characters -> Debugging Chart Mapping Windows-1252 Characters to UTF-8 Bytes to Latin-1 Characters.

Remember to backup your table before trying to replace any characters with SQL!

[I know this is an answer to a very old question, but was facing the issue once again. Some old windows machine didnt encoded the text correct before inserting it to the utf8_general_ci collated table.]

How do AX, AH, AL map onto EAX?

The below snippet examines EAX using GDB.

    (gdb) info register eax
    eax            0xaa55   43605
    (gdb) info register ax
    ax             0xaa55   -21931
    (gdb) info register ah
    ah             0xaa -86
    (gdb) info register al
    al             0x55 85
  1. EAX - Full 32 bit value
  2. AX - lower 16 bit value
  3. AH - Bits from 8 to 15
  4. AL - lower 8 bits of EAX/AX

mvn command is not recognized as an internal or external command

I have a stupid comment but someone else will have that issue. I was getting that same error when I was trying to put in ./mvnw clean package and I found out that I had to change it a bit to .\mvnw clean packageand I lived happily ever after.

SQL Server stored procedure parameters

Why would you pass a parameter to a stored procedure that doesn't use it?

It sounds to me like you might be better of building dynamic SQL statements and then executing them. What you are trying to do with the SP won't work, and even if you could change what you are doing in such a way to accommodate varying numbers of parameters, you would then essentially be using dynamically generated SQL you are defeating the purpose of having/using a SP in the first place. SP's have a role, but there are not the solution in all cases.

swift How to remove optional String Character

when you define any variable as a optional then you need to unwrap that optional value.Convert ? to !

Change input value onclick button - pure javascript or jQuery

My Attempt ( JsFiddle)

Javascript

$(document).ready(function () {
    $('#buttons input[type=button]').on('click', function () {
        var qty = $(this).data('quantity');
        var price = $('#totalPrice').text(); 
        $('#count').val(price * qty);
    });
});

Html

  Product price:$500
<br>Total price: $<span id='totalPrice'>500</span>
<br>
<div id='buttons'>
    <input id='qty2' type="button" data-quantity='2' value="2&#x00A;Qty">
    <input id='qty2' type="button" class="mnozstvi_sleva" data-quantity='4' value="4&#x00A;Qty">
</div>
<br>Total
<input type="text" id="count" value="1">

How to get only filenames within a directory using c#?

You could use the DirectoryInfo and FileInfo classes.

//GetFiles on DirectoryInfo returns a FileInfo object.
var pdfFiles = new DirectoryInfo("C:\\Documents").GetFiles("*.pdf");

//FileInfo has a Name property that only contains the filename part.
var firstPdfFilename = pdfFiles[0].Name;

How do I get length of list of lists in Java?

Java 8

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

public class HelloWorld{

     public static void main(String []args){
            List<List<String>> stringListList = new ArrayList<>();
            stringListList.add(Arrays.asList(new String[] {"(0,0)", "(0,1)"} ));
            stringListList.add(Arrays.asList(new String[] {"(1,0)", "(1,1)", "(1,2)"} ));
            stringListList.add(Arrays.asList(new String[] {"(2,0)", "(2,1)"} ));

            int count=stringListList.stream().mapToInt(i -> i.size()).sum();

            System.out.println("stringListList count: "+count);
     }
}