Programs & Examples On #Enumerable.range

await vs Task.Wait - Deadlock?

Some important facts were not given in other answers:

"async await" is more complex at CIL level and thus costs memory and CPU time.

Any task can be canceled if the waiting time is unacceptable.

In the case "async await" we do not have a handler for such a task to cancel it or monitoring it.

Using Task is more flexible then "async await".

Any sync functionality can by wrapped by async.

public async Task<ActionResult> DoAsync(long id) 
{ 
    return await Task.Run(() => { return DoSync(id); } ); 
} 

"async await" generate many problems. We do not now is await statement will be reached without runtime and context debugging. If first await not reached everything is blocked. Some times even await seems to be reached still everything is blocked:

https://github.com/dotnet/runtime/issues/36063

I do not see why I'm must live with the code duplication for sync and async method or using hacks.

Conclusion: Create Task manually and control them is much better. Handler to Task give more control. We can monitor Tasks and manage them:

https://github.com/lsmolinski/MonitoredQueueBackgroundWorkItem

Sorry for my english.

Random date in C#

Useful extension based of @Jeremy Thompson's solution

public static class RandomExtensions
{
    public static DateTime Next(this Random random, DateTime start, DateTime? end = null)
    {
        end ??= new DateTime();
        int range = (end.Value - start).Days;
        return start.AddDays(random.Next(range));
    }
}

Reset push notification settings for app

The same tech note as refered to in the accepted answer (TN2265 - Troubleshooting Push Notifications) has since been updated with a solution for iOS 5 and above.

In short: create a backup and restore from it every time.

On iOS 5 and later, reset the push notifications permissions alert by restoring the device from a backup (r. 11450187). Here are the steps to do this efficiently:

  1. Use the Xcode Organizer to install your app on the device. The key is to install the app for the first time without running it.
  2. Use iTunes to back up the device.
  3. Run the app. The push notifications permissions alert will be presented.
  4. When you want to reset the push notifications permissions alert, restore the device from the backup you created in the first step.

Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

If one wants to support Generics (in an extension method) this is the pattern...

public  static List<T> Deserialize<T>(this string SerializedJSONString)
{
    var stuff = JsonConvert.DeserializeObject<List<T>>(SerializedJSONString);
    return stuff;
}

It is used like this:

var rc = new MyHttpClient(URL);
//This response is the JSON Array (see posts above)
var response = rc.SendRequest();
var data = response.Deserialize<MyClassType>();

MyClassType looks like this (must match name value pairs of JSON array)

[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
 public class MyClassType
 {
    [JsonProperty(PropertyName = "Id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "Name")]
    public string Name { get; set; }

    [JsonProperty(PropertyName = "Description")]
    public string Description { get; set; }

    [JsonProperty(PropertyName = "Manager")]
    public string Manager { get; set; }

    [JsonProperty(PropertyName = "LastUpdate")]
    public DateTime LastUpdate { get; set; }
 }

Use NUGET to download Newtonsoft.Json add a reference where needed...

using Newtonsoft.Json;

Expression must have class type

a is a pointer. You need to use->, not .

How to save a spark DataFrame as csv on disk?

Writing dataframe to disk as csv is similar read from csv. If you want your result as one file, you can use coalesce.

df.coalesce(1)
      .write
      .option("header","true")
      .option("sep",",")
      .mode("overwrite")
      .csv("output/path")

If your result is an array you should use language specific solution, not spark dataframe api. Because all these kind of results return driver machine.

What's the difference between process.cwd() vs __dirname?

Knowing the scope of each can make things easier to remember.

process is node's global object, and .cwd() returns where node is running.

__dirname is module's property, and represents the file path of the module. In node, one module resides in one file.

Similarly, __filename is another module's property, which holds the file name of the module.

SQL Server: Cannot insert an explicit value into a timestamp column

There is some good information in these answers. Suppose you are dealing with databases which you can't alter, and that you are copying data from one version of the table to another, or from the same table in one database to another. Suppose also that there are lots of columns, and you either need data from all the columns, or the columns which you don't need don't have default values. You need to write a query with all the column names.

Here is a query which returns all the non-timestamp column names for a table, which you can cut and paste into your insert query. FYI: 189 is the type ID for timestamp.

declare @TableName nvarchar(50) = 'Product';

select stuff(
    (select 
        ', ' + columns.name
    from 
        (select id from sysobjects where xtype = 'U' and name = @TableName) tables
        inner join syscolumns columns on tables.id = columns.id
    where columns.xtype <> 189
    for xml path('')), 1, 2, '')

Just change the name of the table at the top from 'Product' to your table name. The query will return a list of column names:

ProductID, Name, ProductNumber, MakeFlag, FinishedGoodsFlag, Color, SafetyStockLevel, ReorderPoint, StandardCost, ListPrice, Size, SizeUnitMeasureCode, WeightUnitMeasureCode, Weight, DaysToManufacture, ProductLine, Class, Style, ProductSubcategoryID, ProductModelID, SellStartDate, SellEndDate, DiscontinuedDate, rowguid, ModifiedDate

If you are copying data from one database (DB1) to another database(DB2) you could use this query.

insert DB2.dbo.Product (ProductID, Name, ProductNumber, MakeFlag, FinishedGoodsFlag, Color, SafetyStockLevel, ReorderPoint, StandardCost, ListPrice, Size, SizeUnitMeasureCode, WeightUnitMeasureCode, Weight, DaysToManufacture, ProductLine, Class, Style, ProductSubcategoryID, ProductModelID, SellStartDate, SellEndDate, DiscontinuedDate, rowguid, ModifiedDate)
select ProductID, Name, ProductNumber, MakeFlag, FinishedGoodsFlag, Color, SafetyStockLevel, ReorderPoint, StandardCost, ListPrice, Size, SizeUnitMeasureCode, WeightUnitMeasureCode, Weight, DaysToManufacture, ProductLine, Class, Style, ProductSubcategoryID, ProductModelID, SellStartDate, SellEndDate, DiscontinuedDate, rowguid, ModifiedDate 
from DB1.dbo.Product

Iterate a certain number of times without storing the iteration number anywhere

This will print 'hello' 3 times without storing i...

[print('hello') for i in range(3)]

Difference between HttpModule and HttpClientModule

Use the HttpClient class from HttpClientModule if you're using Angular 4.3.x and above:

import { HttpClientModule } from '@angular/common/http';

@NgModule({
 imports: [
   BrowserModule,
   HttpClientModule
 ],
 ...

 class MyService() {
    constructor(http: HttpClient) {...}

It's an upgraded version of http from @angular/http module with the following improvements:

  • Interceptors allow middleware logic to be inserted into the pipeline
  • Immutable request/response objects
  • Progress events for both request upload and response download

You can read about how it works in Insider’s guide into interceptors and HttpClient mechanics in Angular.

  • Typed, synchronous response body access, including support for JSON body types
  • JSON is an assumed default and no longer needs to be explicitly parsed
  • Post-request verification & flush based testing framework

Going forward the old http client will be deprecated. Here are the links to the commit message and the official docs.

Also pay attention that old http was injected using Http class token instead of the new HttpClient:

import { HttpModule } from '@angular/http';

@NgModule({
 imports: [
   BrowserModule,
   HttpModule
 ],
 ...

 class MyService() {
    constructor(http: Http) {...}

Also, new HttpClient seem to require tslib in runtime, so you have to install it npm i tslib and update system.config.js if you're using SystemJS:

map: {
     ...
    'tslib': 'npm:tslib/tslib.js',

And you need to add another mapping if you use SystemJS:

'@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',

Difference between iCalendar (.ics) and the vCalendar (.vcs)

The VCS files can have its information coded in Quoted printable which is a nightmare. The above solution recommending "VCS to ICS Calendar Converter" is the way to go.

How do I get a button to open another activity?

Write code on xml file.

<Button android:width="wrap_content"
        android:height="wrap_content"
        android:id="@+id/button"
        android:text="Click"/>

Write Code in your java file

Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            startActivity(new Intent(getApplicationContext(),Secondclass.class));
           /* if you want to finish the first activity then just call
            finish(); */
        }
    });

How to set default value for form field in Symfony2?

If that field is bound to an entity (is a property of that entity) you can just set a default value for it.

An example:

public function getMyField() {
    if (is_null($this->MyField)) {
        $this->setMyField('my default value');
    }
    return $this->MyField;
}

What does -Xmn jvm option stands for

From GC Performance Tuning training documents of Oracle:

-Xmn[size]: Size of young generation heap space.

Applications with emphasis on performance tend to use -Xmn to size the young generation, because it combines the use of -XX:MaxNewSize and -XX:NewSize and almost always explicitly sets -XX:PermSize and -XX:MaxPermSize to the same value.

In short, it sets the NewSize and MaxNewSize values of New generation to the same value.

Print Combining Strings and Numbers

Yes there is. The preferred syntax is to favor str.format over the deprecated % operator.

print "First number is {} and second number is {}".format(first, second)

Batch file to run a command in cmd within a directory

Mine DID execute commands in order. Here's my version of what I was using it for:

START cmd.exe /k "U: & cd U:\Design_stuff\new_lcso_website_2017 & python -m http.server"

I needed to

  1. Change to my U drive
  2. CD to a specific folder containing a website I'm redesigning
  3. Execute python with the http server module (to display the contents in my browser).

If those commands are out of order, it would not display the correct files. I initially forgot to change to U: and, running the batch file on my Desktop, it created a web page in my browser at http://localhost:8000 showing me the contents of my Desktop instead of the folder I wanted.

Find MongoDB records where array field is not empty

db.find({ pictures: { $elemMatch: { $exists: true } } })

$elemMatch matches documents that contain an array field with at least one element that matches the specified query.

So you're matching all arrays with at least an element.

How to copy Outlook mail message into excel using VBA or Macros

Since you have not mentioned what needs to be copied, I have left that section empty in the code below.

Also you don't need to move the email to the folder first and then run the macro in that folder. You can run the macro on the incoming mail and then move it to the folder at the same time.

This will get you started. I have commented the code so that you will not face any problem understanding it.

First paste the below mentioned code in the outlook module.

Then

  1. Click on Tools~~>Rules and Alerts
  2. Click on "New Rule"
  3. Click on "start from a blank rule"
  4. Select "Check messages When they arrive"
  5. Under conditions, click on "with specific words in the subject"
  6. Click on "specific words" under rules description.
  7. Type the word that you want to check in the dialog box that pops up and click on "add".
  8. Click "Ok" and click next
  9. Select "move it to specified folder" and also select "run a script" in the same box
  10. In the box below, specify the specific folder and also the script (the macro that you have in module) to run.
  11. Click on finish and you are done.

When the new email arrives not only will the email move to the folder that you specify but data from it will be exported to Excel as well.

UNTESTED

Const xlUp As Long = -4162

Sub ExportToExcel(MyMail As MailItem)
    Dim strID As String, olNS As Outlook.Namespace
    Dim olMail As Outlook.MailItem
    Dim strFileName As String

    '~~> Excel Variables
    Dim oXLApp As Object, oXLwb As Object, oXLws As Object
    Dim lRow As Long

    strID = MyMail.EntryID
    Set olNS = Application.GetNamespace("MAPI")
    Set olMail = olNS.GetItemFromID(strID)

    '~~> Establish an EXCEL application object
    On Error Resume Next
    Set oXLApp = GetObject(, "Excel.Application")

    '~~> If not found then create new instance
    If Err.Number <> 0 Then
        Set oXLApp = CreateObject("Excel.Application")
    End If
    Err.Clear
    On Error GoTo 0

    '~~> Show Excel
    oXLApp.Visible = True

    '~~> Open the relevant file
    Set oXLwb = oXLApp.Workbooks.Open("C:\Sample.xls")

    '~~> Set the relevant output sheet. Change as applicable
    Set oXLws = oXLwb.Sheets("Sheet1")

    lRow = oXLws.Range("A" & oXLApp.Rows.Count).End(xlUp).Row + 1

    '~~> Write to outlook
    With oXLws
        '
        '~~> Code here to output data from email to Excel File
        '~~> For example
        '
        .Range("A" & lRow).Value = olMail.Subject
        .Range("B" & lRow).Value = olMail.SenderName
        '
    End With

    '~~> Close and Clean up Excel
    oXLwb.Close (True)
    oXLApp.Quit
    Set oXLws = Nothing
    Set oXLwb = Nothing
    Set oXLApp = Nothing

    Set olMail = Nothing
    Set olNS = Nothing
End Sub

FOLLOWUP

To extract the contents from your email body, you can split it using SPLIT() and then parsing out the relevant information from it. See this example

Dim MyAr() As String

MyAr = Split(olMail.body, vbCrLf)

For i = LBound(MyAr) To UBound(MyAr)
    '~~> This will give you the contents of your email
    '~~> on separate lines
    Debug.Print MyAr(i)
Next i

MongoDB: How to update multiple documents with a single command?

The following command can update multiple records of a collection

db.collection.update({}, 
{$set:{"field" : "value"}}, 
{ multi: true, upsert: false}
)

MySQL - UPDATE query with LIMIT

UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 LIMIT 1001, 1000

This query is not correct (or at least i don't know a possible way to use limit in UPDATE queries), you should put a where condition on you primary key (this assumes you have an auto_increment column as your primary key, if not provide more details):

UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 WHERE primary_key BETWEEN 1001 AND 2000

For the second query you must use IS

UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 WHERE panel_id is null

EDIT - if your primary_key is a column named MAX+1 you query should be (with backticks as stated correctly in the comment):

UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 WHERE `MAX+1` BETWEEN 1001 AND 2000

To update the rows with MAX+1 from 1001 TO 2000 (including 1001 and 2000)

Convert NSArray to NSString in Objective-C

Objective C Solution

NSArray * array = @[@"1", @"2", @"3"];
NSString * stringFromArray = [[array valueForKey:@"description"] componentsJoinedByString:@"-"];   // "1-2-3"

Those who are looking for a solution in Swift

If the array contains strings, you can use the String's join method:

var array = ["1", "2", "3"]

let stringFromArray = "-".join(array) // "1-2-3"

In Swift 2:

var array = ["1", "2", "3"]

let stringFromArray = array.joinWithSeparator("-") // "1-2-3"

In Swift 3 & 4

var array = ["1", "2", "3"]

let stringFromArray = array.joined(separator: "-") // "1-2-3"

Getting all names in an enum as a String[]

If you can use Java 8, this works nicely (alternative to Yura's suggestion, more efficient):

public static String[] names() {
    return Stream.of(State.values()).map(State::name).toArray(String[]::new);
}

JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null')

It might be obvious, but make sure that you are sending to the parser URL object not a String containing www adress. This will not work:

    ObjectMapper mapper = new ObjectMapper();
    String www = "www.sample.pl";
    Weather weather = mapper.readValue(www, Weather.class);

But this will:

    ObjectMapper mapper = new ObjectMapper();
    URL www = new URL("http://www.oracle.com/");
    Weather weather = mapper.readValue(www, Weather.class);

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

POSIX 7 quotes

POSIX 7 specifies both at http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.html:

CLOCK_REALTIME:

This clock represents the clock measuring real time for the system. For this clock, the values returned by clock_gettime() and specified by clock_settime() represent the amount of time (in seconds and nanoseconds) since the Epoch.

CLOCK_MONOTONIC (optional feature):

For this clock, the value returned by clock_gettime() represents the amount of time (in seconds and nanoseconds) since an unspecified point in the past (for example, system start-up time, or the Epoch). This point does not change after system start-up time. The value of the CLOCK_MONOTONIC clock cannot be set via clock_settime().

clock_settime() gives an important hint: POSIX systems are able to arbitrarily change CLOCK_REALITME with it, so don't rely on it flowing neither continuously nor forward. NTP could be implemented using clock_settime(), and could only affect CLOCK_REALITME.

The Linux kernel implementation seems to take boot time as the epoch for CLOCK_MONOTONIC: Starting point for CLOCK_MONOTONIC

How do I change UIView Size?

Assigning questionFrame.frame.size.height= screenSize.height * 0.30 will not reflect anything in the view. because it is a get-only property. If you want to change the frame of questionFrame you can use the below code.

questionFrame.frame = CGRect(x: 0, y: 0, width: 0, height: screenSize.height * 0.70)

How do I set proxy for chrome in python webdriver?

I had an issue with the same thing. ChromeOptions is very weird because it's not integrated with the desiredcapabilities like you would think. I forget the exact details, but basically ChromeOptions will reset to default certain values based on whether you did or did not pass a desired capabilities dict.

I did the following monkey-patch that allows me to specify my own dict without worrying about the complications of ChromeOptions

change the following code in /selenium/webdriver/chrome/webdriver.py:

def __init__(self, executable_path="chromedriver", port=0,
             chrome_options=None, service_args=None,
             desired_capabilities=None, service_log_path=None, skip_capabilities_update=False):
    """
    Creates a new instance of the chrome driver.

    Starts the service and then creates new instance of chrome driver.

    :Args:
     - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH
     - port - port you would like the service to run, if left as 0, a free port will be found.
     - desired_capabilities: Dictionary object with non-browser specific
       capabilities only, such as "proxy" or "loggingPref".
     - chrome_options: this takes an instance of ChromeOptions
    """
    if chrome_options is None:
        options = Options()
    else:
        options = chrome_options

    if skip_capabilities_update:
        pass
    elif desired_capabilities is not None:
        desired_capabilities.update(options.to_capabilities())
    else:
        desired_capabilities = options.to_capabilities()

    self.service = Service(executable_path, port=port,
        service_args=service_args, log_path=service_log_path)
    self.service.start()

    try:
        RemoteWebDriver.__init__(self,
            command_executor=self.service.service_url,
            desired_capabilities=desired_capabilities)
    except:
        self.quit()
        raise 
    self._is_remote = False

all that changed was the "skip_capabilities_update" kwarg. Now I just do this to set my own dict:

capabilities = dict( DesiredCapabilities.CHROME )

if not "chromeOptions" in capabilities:
    capabilities['chromeOptions'] = {
        'args' : [],
        'binary' : "",
        'extensions' : [],
        'prefs' : {}
    }

capabilities['proxy'] = {
    'httpProxy' : "%s:%i" %(proxy_address, proxy_port),
    'ftpProxy' : "%s:%i" %(proxy_address, proxy_port),
    'sslProxy' : "%s:%i" %(proxy_address, proxy_port),
    'noProxy' : None,
    'proxyType' : "MANUAL",
    'class' : "org.openqa.selenium.Proxy",
    'autodetect' : False
}

driver = webdriver.Chrome( executable_path="path_to_chrome", desired_capabilities=capabilities, skip_capabilities_update=True )

How do I run a PowerShell script when the computer starts?

This worked for me. Created a Scheduled task with below details: Trigger : At startup

Actions: Program/script : powershell.exe Arguments : -file

UEFA/FIFA scores API

You can find stats-dot-com - personally I think their are better than opta. ESPN seems don't provide data in full and do not provide live data feeds (unfortunatelly).

We've been seeking for official data feed providing for our fantasy games (solutionsforfantasysport.com) and still staying with stats-com mainly (used opta, datafactory as well)

How to update a plot in matplotlib?

In case anyone comes across this article looking for what I was looking for, I found examples at

How to visualize scalar 2D data with Matplotlib?

and

http://mri.brechmos.org/2009/07/automatically-update-a-figure-in-a-loop (on web.archive.org)

then modified them to use imshow with an input stack of frames, instead of generating and using contours on the fly.


Starting with a 3D array of images of shape (nBins, nBins, nBins), called frames.

def animate_frames(frames):
    nBins   = frames.shape[0]
    frame   = frames[0]
    tempCS1 = plt.imshow(frame, cmap=plt.cm.gray)
    for k in range(nBins):
        frame   = frames[k]
        tempCS1 = plt.imshow(frame, cmap=plt.cm.gray)
        del tempCS1
        fig.canvas.draw()
        #time.sleep(1e-2) #unnecessary, but useful
        fig.clf()

fig = plt.figure()
ax  = fig.add_subplot(111)

win = fig.canvas.manager.window
fig.canvas.manager.window.after(100, animate_frames, frames)

I also found a much simpler way to go about this whole process, albeit less robust:

fig = plt.figure()

for k in range(nBins):
    plt.clf()
    plt.imshow(frames[k],cmap=plt.cm.gray)
    fig.canvas.draw()
    time.sleep(1e-6) #unnecessary, but useful

Note that both of these only seem to work with ipython --pylab=tk, a.k.a.backend = TkAgg

Thank you for the help with everything.

php date validation

Try This

/^(19[0-9]{2}|2[0-9]{3})\-(0[1-9]|1[0-2])\-(0[1-9]|1[0-9]|2[0-9]|3[0-1])((T|\s)(0[0-9]{1}|1[0-9]{1}|2[0-3]{1})\:(0[0-9]{1}|1[0-9]{1}|2[0-9]{1}|3[0-9]{1}|4[0-9]{1}|5[0-9]{1})\:(0[0-9]{1}|1[0-9]{1}|2[0-9]{1}|3[0-9]{1}|4[0-9]{1}|5[0-9]{1})((\+|\.)[\d+]{4,8})?)?$/

this regular expression valid for :

  • 2017-01-01T00:00:00+0000
  • 2017-01-01 00:00:00+00:00
  • 2017-01-01T00:00:00+00:00
  • 2017-01-01 00:00:00+0000
  • 2017-01-01

Remember that this will be cover all case of date and date time with (-) character

How to ping a server only once from within a batch file?

Enter in a command prompt window ping /? and read the short help output after pressing RETURN. Or take a look on

  • Ping - Windows XP documentation
  • Ping - Microsoft TechNet article

Explanation for option -t given by Microsoft:

Pings the specified host until stopped. To see statistics and continue type Control-Break. To stop type Control-C.

You may want to use:

@%SystemRoot%\system32\ping.exe -n 1 www.google.de

Or to check first if a server is available:

@echo off
set MyServer=Server.MyDomain.de
%SystemRoot%\system32\ping.exe -n 1 %MyServer% >nul
if errorlevel 1 goto NoServer

echo %MyServer% is availabe.
rem Insert commands here, for example 1 or more net use to connect network drives.
goto :EOF

:NoServer
echo %MyServer% is not availabe yet.
pause
goto :EOF

Prevent flicker on webkit-transition of webkit-transform

I had to use:

-webkit-perspective: 1000;
-webkit-backface-visibility: hidden;    

on the element, or I would still get a flickr the first time a transition occurred after page load

SQL Server datetime LIKE select?

I solved my problem that way. Thank you for suggestions for improvements. Example in C#.

string dd, mm, aa, trc, data;
dd = nData.Text.Substring(0, 2);
mm = nData.Text.Substring(3, 2);
aa = nData.Text.Substring(6, 4);
trc = "-";
data = aa + trc + mm + trc + dd;

"Select * From bdPedidos Where Data Like '%" + data + "%'";

"Undefined reference to" template class constructor

This is a common question in C++ programming. There are two valid answers to this. There are advantages and disadvantages to both answers and your choice will depend on context. The common answer is to put all the implementation in the header file, but there's another approach will will be suitable in some cases. The choice is yours.

The code in a template is merely a 'pattern' known to the compiler. The compiler won't compile the constructors cola<float>::cola(...) and cola<string>::cola(...) until it is forced to do so. And we must ensure that this compilation happens for the constructors at least once in the entire compilation process, or we will get the 'undefined reference' error. (This applies to the other methods of cola<T> also.)

Understanding the problem

The problem is caused by the fact that main.cpp and cola.cpp will be compiled separately first. In main.cpp, the compiler will implicitly instantiate the template classes cola<float> and cola<string> because those particular instantiations are used in main.cpp. The bad news is that the implementations of those member functions are not in main.cpp, nor in any header file included in main.cpp, and therefore the compiler can't include complete versions of those functions in main.o. When compiling cola.cpp, the compiler won't compile those instantiations either, because there are no implicit or explicit instantiations of cola<float> or cola<string>. Remember, when compiling cola.cpp, the compiler has no clue which instantiations will be needed; and we can't expect it to compile for every type in order to ensure this problem never happens! (cola<int>, cola<char>, cola<ostream>, cola< cola<int> > ... and so on ...)

The two answers are:

  • Tell the compiler, at the end of cola.cpp, which particular template classes will be required, forcing it to compile cola<float> and cola<string>.
  • Put the implementation of the member functions in a header file that will be included every time any other 'translation unit' (such as main.cpp) uses the template class.

Answer 1: Explicitly instantiate the template, and its member definitions

At the end of cola.cpp, you should add lines explicitly instantiating all the relevant templates, such as

template class cola<float>;
template class cola<string>;

and you add the following two lines at the end of nodo_colaypila.cpp:

template class nodo_colaypila<float>;
template class nodo_colaypila<std :: string>;

This will ensure that, when the compiler is compiling cola.cpp that it will explicitly compile all the code for the cola<float> and cola<string> classes. Similarly, nodo_colaypila.cpp contains the implementations of the nodo_colaypila<...> classes.

In this approach, you should ensure that all the of the implementation is placed into one .cpp file (i.e. one translation unit) and that the explicit instantation is placed after the definition of all the functions (i.e. at the end of the file).

Answer 2: Copy the code into the relevant header file

The common answer is to move all the code from the implementation files cola.cpp and nodo_colaypila.cpp into cola.h and nodo_colaypila.h. In the long run, this is more flexible as it means you can use extra instantiations (e.g. cola<char>) without any more work. But it could mean the same functions are compiled many times, once in each translation unit. This is not a big problem, as the linker will correctly ignore the duplicate implementations. But it might slow down the compilation a little.

Summary

The default answer, used by the STL for example and in most of the code that any of us will write, is to put all the implementations in the header files. But in a more private project, you will have more knowledge and control of which particular template classes will be instantiated. In fact, this 'bug' might be seen as a feature, as it stops users of your code from accidentally using instantiations you have not tested for or planned for ("I know this works for cola<float> and cola<string>, if you want to use something else, tell me first and will can verify it works before enabling it.").

Finally, there are three other minor typos in the code in your question:

  • You are missing an #endif at the end of nodo_colaypila.h
  • in cola.h nodo_colaypila<T>* ult, pri; should be nodo_colaypila<T> *ult, *pri; - both are pointers.
  • nodo_colaypila.cpp: The default parameter should be in the header file nodo_colaypila.h, not in this implementation file.

Create hive table using "as select" or "like" and also specify delimiter

Create Table as select (CTAS) is possible in Hive.

You can try out below command:

CREATE TABLE new_test 
    row format delimited 
    fields terminated by '|' 
    STORED AS RCFile 
AS select * from source where col=1
  1. Target cannot be partitioned table.
  2. Target cannot be external table.
  3. It copies the structure as well as the data

Create table like is also possible in Hive.

  1. It just copies the source table definition.

Disabling the long-running-script message in Internet Explorer

In my case, while playing video, I needed to call a function everytime currentTime of video updates. So I used timeupdate event of video and I came to know that it was fired at least 4 times a second (depends on the browser you use, see this). So I changed it to call a function every second like this:

var currentIntTime = 0;

var someFunction = function() {
    currentIntTime++;
    // Do something here
} 
vidEl.on('timeupdate', function(){
    if(parseInt(vidEl.currentTime) > currentIntTime) {
        someFunction();
    }
});

This reduces calls to someFunc by at least 1/3 and it may help your browser to behave normally. It did for me !!!

Python - TypeError: 'int' object is not iterable

This is very simple you are trying to convert an integer to a list object !!! of course it will fail and it should ...

To demonstrate/prove this to you by using the example you provided ...just use type function for each case as below and the results will speak for itself !

>>> type(cow)
<class 'range'>
>>> 
>>> type(cow[0])
<class 'int'>
>>> 
>>> type(0)
<class 'int'>
>>> 
>>> >>> list(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> 

Parsing JSON object in PHP using json_decode

Seems like you forgot the ["value"] or ->value:

echo $data[0]->weather->weatherIconUrl[0]->value;

ReportViewer Client Print Control "Unable to load client print control"?

I have had the same problem (on several different servers). Applying SP3 and Report Viewer SP1 has helped on some of the servers, allowing the client machines to connect and download the control with no problem. However, I have had one server that, even after applying the updates, when accessing the report viewer using a client machine, it was still giving me the error. On looking into the exact URL GET request that is being sent, I discovered that it is possible to force the client machine to connect directly to the Report Server to download the control.

The user would need to enter the following url:

http://reportservername/Reports/Reserved.ReportViewerWebControl.axd?ReportSession=51bjqv45xydgos2wghu5ceza&ControlID=7617dedbf0234f89b80cad8e64431014&Culture=2057&UICulture=9&ReportStack=1&OpType=PrintHtml

This should then pop up the required download/install prompt.

How to control the width and height of the default Alert Dialog in Android?

Appreciate answered by Sid because its dynamic but I want to add something.

What if you want to change width only, height will be as it is.

I have done like following:

    // All process of AlertDialog
    AlertDialog alert = builder.create();
    alert.show();

    // Creating Dynamic
    Rect displayRectangle = new Rect();

    Window window = getActivity().getWindow();
    window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
    alert.getWindow().setLayout((int) (displayRectangle.width() *
            0.8f), alert.getWindow().getAttributes().height);

Here I used alert.getWindow().getAttributes().height to keep height as it is of AlertDialog and Width will be changed as per screen resolution.

Hope it will helps. Thanks.

PHP - Get array value with a numeric index

array_values() will do pretty much what you want:

$numeric_indexed_array = array_values($your_array);
// $numeric_indexed_array = array('bar', 'bin', 'ipsum');
print($numeric_indexed_array[0]); // bar

Check which element has been clicked with jQuery

So you are doing this a bit backwards. Typically you'd do something like this:

?<div class='article'>
  Article 1
</div>
<div class='article'>
  Article 2
</div>
<div class='article'>
  Article 3
</div>?

And then in your jQuery:

$('.article').click(function(){
    article = $(this).text(); //$(this) is what you clicked!
    });?

When I see things like #search-item .search-article, #search-item .search-article, and #search-item .search-article I sense you are overspecifying your CSS which makes writing concise jQuery very difficult. This should be avoided if at all possible.

Failed to build gem native extension (installing Compass)

On yosemite, all you must do is install the command line tools. then it works.

Even if other gems installed fine. You must run xcode-select --install for gem install compass to work.

Good luck.

New lines inside paragraph in README.md

You can use a backslash at the end of a line.
So this:

a\
b\
c

will then look like:

a
b
c

Notice that there is no backslash at the end of the last line (after the 'c' character).

How do HashTables deal with collisions?

here's a very simple hash table implementation in java. in only implements put() and get(), but you can easily add whatever you like. it relies on java's hashCode() method that is implemented by all objects. you could easily create your own interface,

interface Hashable {
  int getHash();
}

and force it to be implemented by the keys if you like.

public class Hashtable<K, V> {
    private static class Entry<K,V> {
        private final K key;
        private final V val;

        Entry(K key, V val) {
            this.key = key;
            this.val = val;
        }
    }

    private static int BUCKET_COUNT = 13;

    @SuppressWarnings("unchecked")
    private List<Entry>[] buckets = new List[BUCKET_COUNT];

    public Hashtable() {
        for (int i = 0, l = buckets.length; i < l; i++) {
            buckets[i] = new ArrayList<Entry<K,V>>();
        }
    }

    public V get(K key) {
        int b = key.hashCode() % BUCKET_COUNT;
        List<Entry> entries = buckets[b];
        for (Entry e: entries) {
            if (e.key.equals(key)) {
                return e.val;
            }
        }
        return null;
    }

    public void put(K key, V val) {
        int b = key.hashCode() % BUCKET_COUNT;
        List<Entry> entries = buckets[b];
        entries.add(new Entry<K,V>(key, val));
    }
}

Call another rest api from my server in Spring-Boot

This website has some nice examples for using spring's RestTemplate. Here is a code example of how it can work to get a simple object:

private static void getEmployees()
{
    final String uri = "http://localhost:8080/springrestexample/employees.xml";

    RestTemplate restTemplate = new RestTemplate();
    String result = restTemplate.getForObject(uri, String.class);

    System.out.println(result);
}

Create a CSV File for a user in PHP

To have it send it as a CSV and have it give the file name, use header():

http://us2.php.net/header

header('Content-type: text/csv');
header('Content-disposition: attachment; filename="myfile.csv"');

As far as making the CSV itself, you would just loop through the result set, formatting the output and sending it, just like you would any other content.

How to filter input type="file" dialog by specific file type?

<asp:FileUpload ID="FileUploadExcel" ClientIDMode="Static" runat="server" />
<asp:Button ID="btnUpload" ClientIDMode="Static" runat="server" Text="Upload Excel File" />

.

$('#btnUpload').click(function () {
    var uploadpath = $('#FileUploadExcel').val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);

    if ($('#FileUploadExcel').val().length == 0) {
        // write error message
        return false;
    }

    if (fileExtension == "xls" || fileExtension == "xlsx") {
        //write code for success
    }
    else {
        //error code - select only excel files
        return false;
    }

});

Convert a string to datetime in PowerShell

$invoice = "Jul-16"
[datetime]$newInvoice = "01-" + $invoice

$newInvoice.ToString("yyyy-MM-dd")

There you go, use a type accelerator, but also into a new var, if you want to use it elsewhere, use it like so: $newInvoice.ToString("yyyy-MM-dd")as $newInvoice will always be in the datetime format, unless you cast it as a string afterwards, but will lose the ability to perform datetime functions - adding days etc...

Get the value of checked checkbox?

In my project, I usually use this snippets:

var type[];
$("input[name='messageCheckbox']:checked").each(function (i) {
                type[i] = $(this).val();
            });

And it works well.

Git cli: get user info from username

Use this to see the logged in user (the actual git account):

git config credential.username

And as other answers the user email and user name (this is differenct from user credentials):

git config user.name
git config user.email

To see the list of all configs:

git config --list

How to specify the actual x axis values to plot as x axis ticks in R

You'll find the answer to your question in the help page for ?axis.

Here is one of the help page examples, modified with your data:

Option 1: use xaxp to define the axis labels

plot(x,y, xaxt="n")
axis(1, xaxp=c(10, 200, 19), las=2)

Option 2: Use at and seq() to define the labels:

plot(x,y, xaxt="n")
axis(1, at = seq(10, 200, by = 10), las=2)

Both these options yield the same graphic:

enter image description here


PS. Since you have a large number of labels, you'll have to use additional arguments to get the text to fit in the plot. I use las to rotate the labels.

How to negate the whole regex?

Apply this if you use laravel.

Laravel has a not_regex where field under validation must not match the given regular expression; uses the PHP preg_match function internally.

'email' => 'not_regex:/^.+$/i'

How many values can be represented with n bits?

The thing you are missing is which encoding scheme is being used. There are different ways to encode binary numbers. Look into signed number representations. For 9 bits, the ranges and the amount of numbers that can be represented will differ depending on the system used.

Python re.sub replace with matched content

Simply use \1 instead of $1:

In [1]: import re

In [2]: method = 'images/:id/huge'

In [3]: re.sub(r'(:[a-z]+)', r'<span>\1</span>', method)
Out[3]: 'images/<span>:id</span>/huge'

Also note the use of raw strings (r'...') for regular expressions. It is not mandatory but removes the need to escape backslashes, arguably making the code slightly more readable.

E11000 duplicate key error index in mongodb mongoose

The error message is saying that there's already a record with null as the email. In other words, you already have a user without an email address.

The relevant documentation for this:

If a document does not have a value for the indexed field in a unique index, the index will store a null value for this document. Because of the unique constraint, MongoDB will only permit one document that lacks the indexed field. If there is more than one document without a value for the indexed field or is missing the indexed field, the index build will fail with a duplicate key error.

You can combine the unique constraint with the sparse index to filter these null values from the unique index and avoid the error.

unique indexes

Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value.

In other words, a sparse index is ok with multiple documents all having null values.

sparse indexes


From comments:

Your error says that the key is named mydb.users.$email_1 which makes me suspect that you have an index on both users.email and users.local.email (The former being old and unused at the moment). Removing a field from a Mongoose model doesn't affect the database. Check with mydb.users.getIndexes() if this is the case and manually remove the unwanted index with mydb.users.dropIndex(<name>).

What are the basic rules and idioms for operator overloading?

Conversion Operators (also known as User Defined Conversions)

In C++ you can create conversion operators, operators that allow the compiler to convert between your types and other defined types. There are two types of conversion operators, implicit and explicit ones.

Implicit Conversion Operators (C++98/C++03 and C++11)

An implicit conversion operator allows the compiler to implicitly convert (like the conversion between int and long) the value of a user-defined type to some other type.

The following is a simple class with an implicit conversion operator:

class my_string {
public:
  operator const char*() const {return data_;} // This is the conversion operator
private:
  const char* data_;
};

Implicit conversion operators, like one-argument constructors, are user-defined conversions. Compilers will grant one user-defined conversion when trying to match a call to an overloaded function.

void f(const char*);

my_string str;
f(str); // same as f( str.operator const char*() )

At first this seems very helpful, but the problem with this is that the implicit conversion even kicks in when it isn’t expected to. In the following code, void f(const char*) will be called because my_string() is not an lvalue, so the first does not match:

void f(my_string&);
void f(const char*);

f(my_string());

Beginners easily get this wrong and even experienced C++ programmers are sometimes surprised because the compiler picks an overload they didn’t suspect. These problems can be mitigated by explicit conversion operators.

Explicit Conversion Operators (C++11)

Unlike implicit conversion operators, explicit conversion operators will never kick in when you don't expect them to. The following is a simple class with an explicit conversion operator:

class my_string {
public:
  explicit operator const char*() const {return data_;}
private:
  const char* data_;
};

Notice the explicit. Now when you try to execute the unexpected code from the implicit conversion operators, you get a compiler error:

prog.cpp: In function ‘int main()’:
prog.cpp:15:18: error: no matching function for call to ‘f(my_string)’
prog.cpp:15:18: note: candidates are:
prog.cpp:11:10: note: void f(my_string&)
prog.cpp:11:10: note:   no known conversion for argument 1 from ‘my_string’ to ‘my_string&’
prog.cpp:12:10: note: void f(const char*)
prog.cpp:12:10: note:   no known conversion for argument 1 from ‘my_string’ to ‘const char*’

To invoke the explicit cast operator, you have to use static_cast, a C-style cast, or a constructor style cast ( i.e. T(value) ).

However, there is one exception to this: The compiler is allowed to implicitly convert to bool. In addition, the compiler is not allowed to do another implicit conversion after it converts to bool (a compiler is allowed to do 2 implicit conversions at a time, but only 1 user-defined conversion at max).

Because the compiler will not cast "past" bool, explicit conversion operators now remove the need for the Safe Bool idiom. For example, smart pointers before C++11 used the Safe Bool idiom to prevent conversions to integral types. In C++11, the smart pointers use an explicit operator instead because the compiler is not allowed to implicitly convert to an integral type after it explicitly converted a type to bool.

Continue to Overloading new and delete.

Use RSA private key to generate public key?

Seems to be a common feature of the prevalent asymmetric cryptography; the generation of public/private keys involves generating the private key, which contains the key pair:

openssl genrsa -out mykey.pem 1024

Then publish the public key:

openssl rsa -in mykey.pem -pubout > mykey.pub

or

openssl rsa -in mykey.pem -pubout -out mykey.pub

DSA & EC crypto keys have same feature: eg.

openssl genpkey -algorithm ed25519 -out pvt.pem

Then

openssl pkey -in pvt.pem -pubout > public.pem

or

openssl ec -in ecprivkey.pem -pubout -out ecpubkey.pem

The public component is involved in decryption, and keeping it as part of the private key makes decryption faster; it can be removed from the private key and calculated when needed (for decryption), as an alternative or complement to encrypting or protecting the private key with a password/key/phrase. eg.

openssl pkey -in key.pem -des3 -out keyout.pem

or

openssl ec -aes-128-cbc -in pk8file.pem -out tradfile.pem

You can replace the first argument "aes-128-cbc" with any other valid openssl cipher name

What properties can I use with event.target?

event.target returns the node that was targeted by the function. This means you can do anything you want to do with any other node like one you'd get from document.getElementById

I'm tried with jQuery

var _target = e.target;
console.log(_target.attr('href'));

Return an error :

.attr not function

But _target.attributes.href.value was works.

How do you create a yes/no boolean field in SQL server?

You can use the BIT field

To create new table:

CREATE TABLE Tb_Table1
(
ID              INT,
BitColumn       BIT DEFAULT 1
)

Adding Column in existing Table:

ALTER TABLE Tb_Table1 ADD BitColumn  BIT DEFAULT 1

To Insert record:

INSERT Tb_Table1 VALUES(11,0)

How to round up a number to nearest 10?

Try this:

ceil($roundee / 10) * 10;

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

I often want different columns to have different formats. Here is how I print a simple 2D array using some variety in the formatting by converting (slices of) my NumPy array to a tuple:

import numpy as np
dat = np.random.random((10,11))*100  # Array of random values between 0 and 100
print(dat)                           # Lines get truncated and are hard to read
for i in range(10):
    print((4*"%6.2f"+7*"%9.4f") % tuple(dat[i,:]))

Last element in .each() set

For future Googlers i've a different approach to check if it's last element. It's similar to last lines in OP question.

This directly compares elements rather than just checking index numbers.

$yourset.each(function() {
    var $this = $(this);
    if($this[0] === $yourset.last()[0]) {
        //$this is the last one
    }
});

What is the difference between 'E', 'T', and '?' for Java generics?

It's more convention than anything else.

  • T is meant to be a Type
  • E is meant to be an Element (List<E>: a list of Elements)
  • K is Key (in a Map<K,V>)
  • V is Value (as a return value or mapped value)

They are fully interchangeable (conflicts in the same declaration notwithstanding).

while-else-loop

This while else statement should only execute the else code when the condition is false, this means it will always execute it. But, there is a catch, when you use the break keyword within the while loop, the else statement should not execute.

The code that satisfies does condition is only:

boolean entered = false;
while (condition) {
   entered = true; // Set it to true stright away
   // While loop code


   // If you want to break out of this loop
   if (condition) {
      entered = false;
      break;
   }
} if (!entered) {
   // else code
}

OSError: [WinError 193] %1 is not a valid Win32 application

Python installers usually register .py files with the system. If you run the shell explicitly, it works:

import subprocess
subprocess.call(['hello.py', 'htmlfilename.htm'], shell=True)
# --- or ----
subprocess.call('hello.py htmlfilename.htm', shell=True)

You can check your file associations on the command line with

C:\>assoc .py
.py=Python.File

C:\>ftype Python.File
Python.File="C:\Python27\python.exe" "%1" %*

Controlling a USB power supply (on/off) with Linux

Note. The information in this answer is relevant for the older kernels (up to 2.6.32). See tlwhitec's answer for the information on the newer kernels.

# disable external wake-up; do this only once
echo disabled > /sys/bus/usb/devices/usb1/power/wakeup 

echo on > /sys/bus/usb/devices/usb1/power/level       # turn on
echo suspend > /sys/bus/usb/devices/usb1/power/level  # turn off

(You may need to change usb1 to usb n)

Source: Documentation/usb/power-management.txt.gz

ASP.NET MVC: What is the purpose of @section?

You want to use sections when you want a bit of code/content to render in a placeholder that has been defined in a layout page.

In the specific example you linked, he has defined the RenderSection in the _Layout.cshtml. Any view that uses that layout can define an @section of the same name as defined in Layout, and it will replace the RenderSection call in the layout.

Perhaps you're wondering how we know Index.cshtml uses that layout? This is due to a bit of MVC/Razor convention. If you look at the dialog where he is adding the view, the box "Use layout or master page" is checked, and just below that it says "Leave empty if it is set in a Razor _viewstart file". It isn't shown, but inside that _ViewStart.cshtml file is code like:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

The way viewstarts work is that any cshtml file within the same directory or child directories will run the ViewStart before it runs itself.

Which is what tells us that Index.cshtml uses Shared/_Layout.cshtml.

Finding modified date of a file/folder

Here's what worked for me:

$a = Get-ChildItem \\server\XXX\Received_Orders\*.* | Where{$_.LastWriteTime -ge (Get-Date).AddDays(-7)}
if ($a = (Get-ChildItem \\server\XXX\Received_Orders\*.* | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-7)}  
#Im using the -gt switch instead of -ge
{}
Else
{
'STORE XXX HAS NOT RECEIVED ANY ORDERS IN THE PAST 7 DAYS'
}


$b = Get-ChildItem \\COMP NAME\Folder\*.* | Where{$_.LastWriteTime -ge (Get-Date).AddDays(-1)}
if ($b = (Get-ChildItem \\COMP NAME\TFolder\*.* | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-1)))}
{}
Else
{
'STORE XXX DID NOT RUN ITS BACKUP LAST NIGHT'
}

How to use subList()

You could use streams in Java 8. To always get 10 entries at the most, you could do:

dataList.stream().skip(5).limit(10).collect(Collectors.toList());
dataList.stream().skip(30).limit(10).collect(Collectors.toList());

How to make UIButton's text alignment center? Using IB

You can do this from storyboard. Select your button. Set Line Break 'Word Wrap', Set your title 'Plain' to 'Attributed'. Select 'Center alignment'. This part is important => Click ...(More) Button. And select line breaking mode to 'Character Wrap'.

"find: paths must precede expression:" How do I specify a recursive search that also finds files in the current directory?

I came across this question when I was trying to find multiple filenames that I could not combine into a regular expression as described in @Chris J's answer, here is what worked for me

find . -name one.pdf -o -name two.txt -o -name anotherone.jpg

-o or -or is logical OR. See Finding Files on Gnu.org for more information.

I was running this on CygWin.

Activating Anaconda Environment in VsCode

I found a hacky solution replace your environment variable for the original python file so instead it can just call from the python.exe from your anaconda folder, so when you reference python it will reference anaconda's python.

So your only python path in env var should be like:

"C:\Anaconda3\envs\py34\", or wherever the python executable lives

If you need more details I don't mind explaining. :)

Getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory exception

If all else fails, as it had for me, try putting the commons-logging-x.y.z.jar in your Tomcat lib directory. It solved the problem! BTW, I am using Tomcat 6.

How to make a HTML Page in A4 paper size page(s)?

I saw this solution after searching at google, search for "A4 CSS page template" (codepen.io). It shows an A4 (A3,A5, also portrait) sized area in the browser, using the <page> tag. Inside this tag the content is shown, but absolute position is still with respect to browser area.

_x000D_
_x000D_
body {_x000D_
  background: rgb(204,204,204); _x000D_
}_x000D_
page {_x000D_
  background: white;_x000D_
  display: block;_x000D_
  margin: 0 auto;_x000D_
  margin-bottom: 0.5cm;_x000D_
  box-shadow: 0 0 0.5cm rgba(0,0,0,0.5);_x000D_
}_x000D_
page[size="A4"] {  _x000D_
  width: 21cm;_x000D_
  height: 29.7cm; _x000D_
}_x000D_
page[size="A4"][layout="portrait"] {_x000D_
  width: 29.7cm;_x000D_
  height: 21cm;  _x000D_
}_x000D_
@media print {_x000D_
  body, page {_x000D_
    margin: 0;_x000D_
    box-shadow: 0;_x000D_
  }_x000D_
}
_x000D_
<page size="A4">A4</page>_x000D_
<page size="A4" layout="portrait">A4 portrait</page>
_x000D_
_x000D_
_x000D_

This works for me without any other css/js-library to be included. Works for current browsers (IE, FF, Chrome).

What is the best collation to use for MySQL with PHP?

The accepted answer fairly definitively suggests using utf8_unicode_ci, and whilst for new projects that's great, I wanted to relate my recent contrary experience just in case it saves anyone some time.

Because utf8_general_ci is the default collation for Unicode in MySQL, if you want to use utf8_unicode_ci then you end up having to specify it in a lot of places.

For example, all client connections not only have a default charset (makes sense to me) but also a default collation (i.e. the collation will always default to utf8_general_ci for unicode).

Likely, if you use utf8_unicode_ci for your fields, your scripts that connect to the database will need to be updated to mention the desired collation explicitly -- otherwise queries using text strings can fail when your connection is using the default collation.

The upshot is that when converting an existing system of any size to Unicode/utf8, you may end up being forced to use utf8_general_ci because of the way MySQL handles defaults.

How to convert a byte to its binary string representation

I used this. Similar idea to other answers, but didn't see the exact approach anywhere :)

System.out.println(Integer.toBinaryString((b & 0xFF) + 0x100).substring(1));

0xFF is 255, or 11111111 (max value for an unsigned byte). 0x100 is 256, or 100000000

The & upcasts the byte to an integer. At that point, it can be anything from 0-255 (00000000 to 11111111, I excluded the leading 24 bits). + 0x100 and .substring(1) ensure there will be leading zeroes.

I timed it compared to João Silva's answer, and this is over 10 times faster. http://ideone.com/22DDK1 I didn't include Pshemo's answer as it doesn't pad properly.

View more than one project/solution in Visual Studio

Don't know whether this is useful but if you want to work with multiple projects without navigating through projects tree {like multi window} you can try opening VS in another virtual desktop (at least it's possible for Windows 10) by holding Ctrl+win+D. Then open another VS studio and open your other project there. You can switch between projects by Ctrl+win+arrow key {left/right}.

How do I use boolean variables in Perl?

My favourites have always been

use constant FALSE => 1==0;
use constant TRUE => not FALSE;

which is completely independent from the internal representation.

Using the RUN instruction in a Dockerfile with 'source' does not work

I had the same problem and in order to execute pip install inside virtualenv I had to use this command:

RUN pip install virtualenv virtualenvwrapper
RUN mkdir -p /opt/virtualenvs
ENV WORKON_HOME /opt/virtualenvs
RUN /bin/bash -c "source /usr/local/bin/virtualenvwrapper.sh \
    && mkvirtualenv myapp \
    && workon myapp \
    && pip install -r /mycode/myapp/requirements.txt"

I hope it helps.

Good MapReduce examples

One set of familiar operations that you can do in MapReduce is the set of normal SQL operations: SELECT, SELECT WHERE, GROUP BY, ect.

Another good example is matrix multiply, where you pass one row of M and the entire vector x and compute one element of M * x.

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

Can an Option in a Select tag carry multiple values?

I did this by using data attributes. Is a lot cleaner than other methods attempting to explode etc.

HTML

<select class="example">
    <option value="1" data-value="A">One</option>
    <option value="2" data-value="B">Two</option>
    <option value="3" data-value="C">Three</option>
    <option value="4" data-value="D">Four</option>
</select>

JS

$('select.example').change(function() {

    var other_val = $('select.example option[value="' + $(this).val() + '"]').data('value');

    console.log(other_val);

});

How to upgrade pip3?

Try this command:

pip3 install --upgrade setuptools pip

What exactly is an instance in Java?

I think that Object = Instance. Reference is a "link" to an Object.

Car c = new Car();

variable c stores a reference to an object of type Car.

Can Flask have optional URL parameters?

@user.route('/<user_id>', defaults={'username': default_value})
@user.route('/<user_id>/<username>')
def show(user_id, username):
   #
   pass

Algorithm to calculate the number of divisors of a given number

You might try this one. It's a bit hackish, but it's reasonably fast.

def factors(n):
    for x in xrange(2,n):
        if n%x == 0:
            return (x,) + factors(n/x)
    return (n,1)

Determine number of pages in a PDF file

I have good success using CeTe Dynamic PDF products. They're not free, but are well documented. They did the job for me.

http://www.dynamicpdf.com/

jQuery - keydown / keypress /keyup ENTERKEY detection?

update: nowadays we have mobile and custom keyboards and we cannot continue trusting these arbitrary key codes such as 13 and 186. in other words, stop using event.which/event.keyCode and start using event.key:

if (event.key === "Enter" || event.key === "ArrowUp" || event.key === "ArrowDown")

Strings as Primary Keys in SQL Database

I would probably use an integer as your primary key, and then just have your string (I assume it's some sort of ID) as a separate column.

create table sample (
  sample_pk             INT NOT NULL AUTO_INCREMENT,
  sample_id             VARCHAR(100) NOT NULL,
  ...
  PRIMARY KEY(sample_pk)
);

You can always do queries and joins conditionally on the string (ID) column (where sample_id = ...).

How to split page into 4 equal parts?

try this... obviously you need to set each div to 25%. You then will need to add your content as needed :) Hope that helps.

 <html>
   <head>
   <title>CSS devide window by 25% horizontally</title>
   <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
   <style type="text/css" media="screen"> 
     body {
     margin:0;
     padding:0;
     height:100%;
     }
     #top_div
     {
       height:25%;
       width:100%;
       background-color:#009900;
       margin:auto;
       text-align:center;
     }
     #mid1_div
     {
       height:25%;
       width:100%;
       background-color:#990000;
       margin:auto;
       text-align:center;
       color:#FFFFFF;
     }
     #mid2_div
     {
       height:25%;
       width:100%;
       background-color:#000000;
       margin:auto;
       text-align:center;
       color:#FFFFFF;
     }
     #bottom_div
     {
       height:25%;
       width:100%;
       background-color:#990000;
       margin:auto;
       text-align:center;
       color:#FFFFFF;
     }
   </style>
   </head>
   <body>
     <div id="top_div">Top- height is 25% of window height</div>
     <div id="mid1_div">Middle 1 - height is 25% of window height</div>
     <div id="mid2_div">Middle 2 - height is 25% of window height</div>
     <div id="bottom_div">Bottom - height is 25% of window height</div>
   </body>
 </html>

Tested and works fine, copy the code above into a HTML file, and open with your browser.

What's the difference between emulation and simulation?

An "emulator" is a term for a software-based hardware-simulator, but in general the two are synonyms.

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

Creating a new database and new connection in Oracle SQL Developer

Open Oracle SQLDeveloper

Right click on connection tab and select new connection

Enter HR_ORCL in connection name and HR for the username and password.

Specify localhost for your Hostname and enter ORCL for the SID.

Click Test.

The status of the connection Test Successfully.

The connection was not saved however click on Save button to save the connection. And then click on Connect button to connect your database.

The connection is saved and you see the connection list.

Vue.js—Difference between v-model and v-bind

v-model is for two way bindings means: if you change input value, the bound data will be changed and vice versa. But v-bind:value is called one way binding that means: you can change input value by changing bound data but you can't change bound data by changing input value through the element.

v-model is intended to be used with form elements. It allows you to tie the form element (e.g. a text input) with the data object in your Vue instance.

Example: https://jsfiddle.net/jamesbrndwgn/j2yb9zt1/1/

v-bind is intended to be used with components to create custom props. This allows you to pass data to a component. As the prop is reactive, if the data that’s passed to the component changes then the component will reflect this change

Example: https://jsfiddle.net/jamesbrndwgn/ws5kad1c/3/

Hope this helps you with basic understanding.

How to dismiss a Twitter Bootstrap popover by clicking outside?

Update: A slightly more robust solution: http://jsfiddle.net/mattdlockyer/C5GBU/72/

For buttons containing text only:

$('body').on('click', function (e) {
    //did not click a popover toggle or popover
    if ($(e.target).data('toggle') !== 'popover'
        && $(e.target).parents('.popover.in').length === 0) { 
        $('[data-toggle="popover"]').popover('hide');
    }
});

For buttons containing icons use (this code has a bug in Bootstrap 3.3.6, see the fix below in this answer)

$('body').on('click', function (e) {
        //did not click a popover toggle, or icon in popover toggle, or popover
        if ($(e.target).data('toggle') !== 'popover'
            && $(e.target).parents('[data-toggle="popover"]').length === 0
            && $(e.target).parents('.popover.in').length === 0) { 
            $('[data-toggle="popover"]').popover('hide');
        }
    });

For JS Generated Popovers Use '[data-original-title]' in place of '[data-toggle="popover"]'

Caveat: The solution above allows multiple popovers to be open at once.

One popover at a time please:

Update: Bootstrap 3.0.x, see code or fiddle http://jsfiddle.net/mattdlockyer/C5GBU/2/

$('body').on('click', function (e) {
    $('[data-toggle="popover"]').each(function () {
        //the 'is' for buttons that trigger popups
        //the 'has' for icons within a button that triggers a popup
        if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
            $(this).popover('hide');
        }
    });
});

This handles closing of popovers already open and not clicked on or their links have not been clicked.


Update: Bootstrap 3.3.6, see fiddle

Fixes issue where after closing, takes 2 clicks to re-open

$(document).on('click', function (e) {
    $('[data-toggle="popover"],[data-original-title]').each(function () {
        //the 'is' for buttons that trigger popups
        //the 'has' for icons within a button that triggers a popup
        if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {                
            (($(this).popover('hide').data('bs.popover')||{}).inState||{}).click = false  // fix for BS 3.3.6
        }

    });
});

Update: Using the conditional of the previous improvement, this solution was achieved. Fix the problem of double click and ghost popover:

$(document).on("shown.bs.popover",'[data-toggle="popover"]', function(){
    $(this).attr('someattr','1');
});
$(document).on("hidden.bs.popover",'[data-toggle="popover"]', function(){
    $(this).attr('someattr','0');
});
$(document).on('click', function (e) {
    $('[data-toggle="popover"],[data-original-title]').each(function () {
        //the 'is' for buttons that trigger popups
        //the 'has' for icons within a button that triggers a popup
        if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
            if($(this).attr('someattr')=="1"){
                $(this).popover("toggle");
            }
        }
    });
});

Failed to locate the winutils binary in the hadoop binary path

I was facing the same problem. Removing the bin\ from the HADOOP_HOME path solved it for me. The path for HADOOP_HOME variable should look something like.

C:\dev\hadoop2.6\

System restart may be needed. In my case, restarting the IDE was sufficient.

How can I split a text into sentences?

Also, be wary of additional top level domains that aren't included in some of the answers above.

For example .info, .biz, .ru, .online will throw some sentence parsers but aren't included above.

Here's some info on frequency of top level domains: https://www.westhost.com/blog/the-most-popular-top-level-domains-in-2017/

That could be addressed by editing the code above to read:

alphabets= "([A-Za-z])"
prefixes = "(Mr|St|Mrs|Ms|Dr)[.]"
suffixes = "(Inc|Ltd|Jr|Sr|Co)"
starters = "(Mr|Mrs|Ms|Dr|He\s|She\s|It\s|They\s|Their\s|Our\s|We\s|But\s|However\s|That\s|This\s|Wherever)"
acronyms = "([A-Z][.][A-Z][.](?:[A-Z][.])?)"
websites = "[.](com|net|org|io|gov|ai|edu|co.uk|ru|info|biz|online)"

Node.js Error: Cannot find module express

Unless you set Node_PATH, the only other option is to install express in the app directory, like npm install express --save. Express may already be installed but node cannot find it for some reason

How to print the full NumPy array, without truncation?

To turn it off and return to the normal mode

np.set_printoptions(threshold=False)

htaccess Access-Control-Allow-Origin

Try this in the .htaccess of the external root folder :

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

And if it only concerns .js scripts you should wrap the above code inside this:

<FilesMatch "\.(js)$">
...
</FilesMatch>

Mean filter for smoothing images in Matlab

and the convolution is defined through a multiplication in transform domain:

conv2(x,y) = fftshift(ifft2(fft2(x).*fft2(y)))

if one channel is considered... for more channels this has to be done every channel

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

After a bit of time (and more searching), I found this blog entry by Jomo Fisher.

One of the recent problems we’ve seen is that, because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode. If you see a message like this then you know you have run into the issue:

Mixed mode assembly is built against version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.

[Snip]

The good news for applications is that you have the option of falling back to .NET 2.0 era binding for these assemblies by setting an app.config flag like so:

<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0"/>
</startup>

So it looks like the way the runtime loads mixed-mode assemblies has changed. I can't find any details about this change, or why it was done. But the useLegacyV2RuntimeActivationPolicy attribute reverts back to CLR 2.0 loading.

Git: Cannot see new remote branch

You can checkout remote branch /n git fetch && git checkout remotebranch

How do I resolve `The following packages have unmet dependencies`

First, run

sudo apt-get install nodejs-dev node-gyp libssl1.0-dev

then run

sudo apt install npm

C# : Out of Memory exception

As .Net progresses, so does their ability to add new 32-bit configurations that trips everyone up it seems.

If you are on .Net Framework 4.7.2 do the following:

Go to Project Properties

Build

Uncheck 'prefer 32-bit'

Cheers!

how to check if string value is in the Enum list?

You can use the TryParse method that returns true if it successful:

Age age;

if(Enum.TryParse<Age>("myString", out age))
{
   //Here you can use age
}

Check if string contains only digits

Here's another interesting, readable way to check if a string contains only digits.

This method works by splitting the string into an array using the spread operator, and then uses the every() method to test whether all elements (characters) in the array are included in the string of digits '0123456789':

_x000D_
_x000D_
const digits_only = string => [...string].every(c => '0123456789'.includes(c));_x000D_
_x000D_
console.log(digits_only('123')); // true_x000D_
console.log(digits_only('+123')); // false_x000D_
console.log(digits_only('-123')); // false_x000D_
console.log(digits_only('123.')); // false_x000D_
console.log(digits_only('.123')); // false_x000D_
console.log(digits_only('123.0')); // false_x000D_
console.log(digits_only('0.123')); // false_x000D_
console.log(digits_only('Hello, world!')); // false
_x000D_
_x000D_
_x000D_

Two inline-block, width 50% elements wrap to second line

You can remove the whitespaces via css using white-space so you can keep your pretty HTML layout. Don't forget to set the white-space back to normal again if you want your text to wrap inside the columns.

Tested in IE9, Chrome 18, FF 12

.container { white-space: nowrap; }
.column { display: inline-block; width: 50%; white-space: normal; }

<div class="container">
  <div class="column">text that can wrap</div>
  <div class="column">text that can wrap</div>
</div>

Jquery find nearest matching element

Get the .column parent of the this element, get its previous sibling, then find any input there:

$(this).closest(".column").prev().find("input:first").val();

Demo: http://jsfiddle.net/aWhtP/

How to get the file-path of the currently executing javascript code

I've coded a simple function which allows to get the absolute location of the current javascript file, by using a try/catch method.

// Get script file location
// doesn't work for older browsers

var getScriptLocation = function() {
    var fileName    = "fileName";
    var stack       = "stack";
    var stackTrace  = "stacktrace";
    var loc     = null;

    var matcher = function(stack, matchedLoc) { return loc = matchedLoc; };

    try { 

        // Invalid code
        0();

    }  catch (ex) {

        if(fileName in ex) { // Firefox
            loc = ex[fileName];
        } else if(stackTrace in ex) { // Opera
            ex[stackTrace].replace(/called from line \d+, column \d+ in (.*):/gm, matcher);
        } else if(stack in ex) { // WebKit, Blink and IE10
            ex[stack].replace(/at.*?\(?(\S+):\d+:\d+\)?$/g, matcher);
        }

        return loc;
    }

};

You can see it here.

How to install all required PHP extensions for Laravel?

Laravel Server Requirements mention that BCMath, Ctype, JSON, Mbstring, OpenSSL, PDO, Tokenizer, and XML extensions are required. Most of the extensions are installed and enabled by default.

You can run the following command in Ubuntu to make sure the extensions are installed.

sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip

PHP version specific installation (if PHP 7.4 installed)

sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring

You may need other PHP extensions for your composer packages. Find from links below.

PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)

PHP extensions for Ubuntu 18.04 LTS (Bionic)

PHP extensions for Ubuntu 16.04 LTS (Xenial)

What is a pre-revprop-change hook in SVN, and how do I create it?

For PC users: The .bat extension did not work for me when used on Windows Server maching. I used VisualSvn as Django Reinhardt suggested, and it created a hook with a .cmd extension.

Serializing with Jackson (JSON) - getting "No serializer found"?

I had the same problem for a child class where I had control, object mapper was in a common module and was inaccessible. I solved it by adding this annotation for my child class whose object was to be serialized.

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)

Scrolling a flexbox with overflowing content

You can simply put overflow property to "auto"

_x000D_
_x000D_
     .contain{
          background-color: #999999;
          margin: 5px; 
          padding: 10px 5px;
          width: 20%;
          height: 20%;
          overflow: auto;
      }              
       
_x000D_
_x000D_
_x000D_

contain is one of my flex-item class name

result :

scroll bar seen properly

Doctrine 2: Update query with query builder

Let's say there is an administrator dashboard where users are listed with their id printed as a data attribute so it can be retrieved at some point via JavaScript.

An update could be executed this way …

class UserRepository extends \Doctrine\ORM\EntityRepository
{
    public function updateUserStatus($userId, $newStatus)
    {
        return $this->createQueryBuilder('u')
            ->update()
            ->set('u.isActive', '?1')
            ->setParameter(1, $qb->expr()->literal($newStatus))
            ->where('u.id = ?2')
            ->setParameter(2, $qb->expr()->literal($userId))
            ->getQuery()
            ->getSingleScalarResult()
        ;
    }

AJAX action handling:

# Post datas may be:
# handled with a specific custom formType — OR — retrieved from request object
$userId = (int)$request->request->get('userId');
$newStatus = (int)$request->request->get('newStatus');
$em = $this->getDoctrine()->getManager();
$r = $em->getRepository('NAMESPACE\User')
        ->updateUserStatus($userId, $newStatus);
if ( !empty($r) ){
    # Row updated
}

Working example using Doctrine 2.5 (on top of Symfony3).

How to create a function in a cshtml template?

You can use the @helper Razor directive:

@helper WelcomeMessage(string username)
{
    <p>Welcome, @username.</p>
}

Then you invoke it like this:

@WelcomeMessage("John Smith")

How do I get the information from a meta tag with JavaScript?

The other answers should probably do the trick, but this one is simpler and does not require jQuery:

document.head.querySelector("[property~=video][content]").content;

The original question used an RDFa tag with a property="" attribute. For the normal HTML <meta name="" …> tags you could use something like:

document.querySelector('meta[name="description"]').content

How do I make a matrix from a list of vectors in R?

> library(plyr)
> as.matrix(ldply(a))
      V1 V2 V3 V4 V5 V6
 [1,]  1  1  2  3  4  5
 [2,]  2  1  2  3  4  5
 [3,]  3  1  2  3  4  5
 [4,]  4  1  2  3  4  5
 [5,]  5  1  2  3  4  5
 [6,]  6  1  2  3  4  5
 [7,]  7  1  2  3  4  5
 [8,]  8  1  2  3  4  5
 [9,]  9  1  2  3  4  5
[10,] 10  1  2  3  4  5

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Check privileges and username/password for your MySQL user.

For catching errors it is always useful to use overrided _delegateError method. In your case this has to look like:

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "password",
  insecureAuth : true
});

var _delegateError = con._protocol._delegateError;

con._protocol._delegateError = function(err, sequence) {
    if (err.fatal)
        console.trace('MySQL fatal error: ' + err.message);

    return _delegateError.call(this, err, sequence);
};

con.connect(function(err) {
  if (err) throw err;

  console.log("Connected!");
});

This construction will help you to trace fatal errors.

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

Seems there is missing MongoDB driver. Include the following dependency to pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

How can building a heap be O(n) time complexity?

Your analysis is correct. However, it is not tight.

It is not really easy to explain why building a heap is a linear operation, you should better read it.

A great analysis of the algorithm can be seen here.


The main idea is that in the build_heap algorithm the actual heapify cost is not O(log n)for all elements.

When heapify is called, the running time depends on how far an element might move down in tree before the process terminates. In other words, it depends on the height of the element in the heap. In the worst case, the element might go down all the way to the leaf level.

Let us count the work done level by level.

At the bottommost level, there are 2^(h)nodes, but we do not call heapify on any of these, so the work is 0. At the next to level there are 2^(h - 1) nodes, and each might move down by 1 level. At the 3rd level from the bottom, there are 2^(h - 2) nodes, and each might move down by 2 levels.

As you can see not all heapify operations are O(log n), this is why you are getting O(n).

Object Dump JavaScript

console.log("my object: %o", myObj)

Otherwise you'll end up with a string representation sometimes displaying:

[object Object]

or some such.

Escape text for HTML

there are some special quotes characters which are not removed by HtmlEncode and will not be displayed in Edge or IE correctly like ” and “ . you can extent replacing these characters with something like below function.

private string RemoveJunkChars(string input)
{
    return HttpUtility.HtmlEncode(input.Replace("”", "\"").Replace("“", "\""));
}

How can I color a UIImage in Swift?

This function uses core graphics to achieve this.

func overlayImage(color: UIColor) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
    let context = UIGraphicsGetCurrentContext()

    color.setFill()

    context!.translateBy(x: 0, y: self.size.height)
    context!.scaleBy(x: 1.0, y: -1.0)

    context!.setBlendMode(CGBlendMode.colorBurn)
    let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
    context!.draw(self.cgImage!, in: rect)

    context!.setBlendMode(CGBlendMode.sourceIn)
    context!.addRect(rect)
    context!.drawPath(using: CGPathDrawingMode.fill)

    let coloredImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return coloredImage
}

copy db file with adb pull results in 'permission denied' error

I had just the same problem, here's how to deal with it:

  1. adb shell to the device
  2. su
  3. ls -l and check current access rights on the file you need. You'll need that later.
  4. go to the file needed and: chmod 777 file.ext. Note: now you have a temporary security issue. You've just allowed all the rights to everyone! Consider adding just R for users.
  5. open another console and: adb pull /path/to/file.ext c:\pc\path\to\file.exe
  6. Important: after you're done, revert the access rights back to the previous value (point 3)

Someone mentioned something similar earlier.

Thanks for the comments below.

What is the difference between a mutable and immutable string in C#?

In .NET System.String (aka string) is a immutable object. That means when you create an object you can not change it's value afterwards. You can only recreate a immutable object.

System.Text.StringBuilder is mutable equivalent of System.String and you can chane its value

For Example:

class Program
{
    static void Main(string[] args)
    {

        System.String str = "inital value";
        str = "\nsecond value";
        str = "\nthird value";

        StringBuilder sb = new StringBuilder();
        sb.Append("initial value");
        sb.AppendLine("second value");
        sb.AppendLine("third value");
    }
}

Generates following MSIL : If you investigate the code. You will see that whenever you chane an object of System.String you are actually creating new one. But in System.Text.StringBuilder whenever you change the value of text you dont recreate the object.

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       62 (0x3e)
  .maxstack  2
  .locals init ([0] string str,
           [1] class [mscorlib]System.Text.StringBuilder sb)
  IL_0000:  nop
  IL_0001:  ldstr      "inital value"
  IL_0006:  stloc.0
  IL_0007:  ldstr      "\nsecond value"
  IL_000c:  stloc.0
  IL_000d:  ldstr      "\nthird value"
  IL_0012:  stloc.0
  IL_0013:  newobj     instance void [mscorlib]System.Text.StringBuilder::.ctor()
  IL_0018:  stloc.1
  IL_0019:  ldloc.1
  IL_001a:  ldstr      "initial value"
  IL_001f:  callvirt   instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)
  IL_0024:  pop
  IL_0025:  ldloc.1
  IL_0026:  ldstr      "second value"
  IL_002b:  callvirt   instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::AppendLine(string)
  IL_0030:  pop
  IL_0031:  ldloc.1
  IL_0032:  ldstr      "third value"
  IL_0037:  callvirt   instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::AppendLine(string)
  IL_003c:  pop
  IL_003d:  ret
} // end of method Program::Main

How to make an autocomplete TextBox in ASP.NET?

1-Install AjaxControl Toolkit easily by Nugget

PM> Install-Package AjaxControlToolkit

2-then in markup

<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">  
</asp:ToolkitScriptManager>  

<asp:TextBox ID="txtMovie" runat="server"></asp:TextBox>  

<asp:AutoCompleteExtender  ID="AutoCompleteExtender1"  TargetControlID="txtMovie"   
    runat="server" />  

3- in code-behind : to get the suggestions

[System.Web.Services.WebMethodAttribute(),System.Web.Script.Services.ScriptMethodAttribute()]  
    public static string[] GetCompletionList(string prefixText, int count, string contextKey) {  
        // Create array of movies  
        string[] movies = {"Star Wars", "Star Trek", "Superman", "Memento", "Shrek", "Shrek II"};  

        // Return matching movies  
        return (from m in movies where m.StartsWith(prefixText,StringComparison.CurrentCultureIgnoreCase) select m).Take(count).ToArray();  
    }

source: http://www.asp.net/ajaxlibrary/act_autocomplete_simple.ashx

WARNING in budgets, maximum exceeded for initial

Open angular.json file and find budgets keyword.

It should look like:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "2mb",
          "maximumError": "5mb"
       }
    ]

As you’ve probably guessed you can increase the maximumWarning value to prevent this warning, i.e.:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "4mb", <===
          "maximumError": "5mb"
       }
    ]

What does budgets mean?

A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.

In our case budget is the limit for bundle sizes.

See also:

How to call Stored Procedure in a View?

If you are using Sql Server 2005 you can use table valued functions. You can call these directly and pass paramters, whilst treating them as if they were tables.

For more info check out Table-Valued User-Defined Functions

How do I find what Java version Tomcat6 is using?

Or you could use the Probe application and just look at its System Info page. Much easier than writing code, and once you start using it you'll never go back to Tomcat Manager.

How to test an SQL Update statement before running it?

One more option is to ask MySQL for the query plan. This tells you two things:

  • Whether there are any syntax errors in the query, if so the query plan command itself will fail
  • How MySQL is planning to execute the query, e.g. what indexes it will use

In MySQL and most SQL databases the query plan command is describe, so you would do:

describe update ...;

What is "not assignable to parameter of type never" error in typescript?

I got the same error in ReactJS function component, using ReactJS useState hook. The solution was to declare the type of useState at initialisation:

const [items , setItems] = useState<IItem[]>([]); // replace IItem[] with your own typing: string, boolean...

GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion

My Problem was that I was not in the correct git directory that I just cloned.

vuejs update parent data from child component

In child component:

this.$emit('eventname', this.variable)

In parent component:

<component @eventname="updateparent"></component>

methods: {
    updateparent(variable) {
        this.parentvariable = variable
    }
}

Remove duplicate values from JS array

Although ES6 Solution is the best, I'm baffled as to how nobody has shown the following solution:

function removeDuplicates(arr){
    o={}
    arr.forEach(function(e){
        o[e]=true
    })
    return Object.keys(o)
}

The thing to remember here is that objects MUST have unique keys. We are exploiting this to remove all the duplicates. I would have thought this would be the fastest solution (before ES6).

Bear in mind though that this also sorts the array.

PHP: How to get referrer URL?

Underscore. Not space.

$_SERVER['HTTP_REFERER']

Laravel $q->where() between dates

You can chain your wheres directly, without function(q). There's also a nice date handling package in laravel, called Carbon. So you could do something like:

$projects = Project::where('recur_at', '>', Carbon::now())
    ->where('recur_at', '<', Carbon::now()->addWeek())
    ->where('status', '<', 5)
    ->where('recur_cancelled', '=', 0)
    ->get();

Just make sure you require Carbon in composer and you're using Carbon namespace (use Carbon\Carbon;) and it should work.

EDIT: As Joel said, you could do:

$projects = Project::whereBetween('recur_at', array(Carbon::now(), Carbon::now()->addWeek()))
    ->where('status', '<', 5)
    ->where('recur_cancelled', '=', 0)
    ->get();

Disable and enable buttons in C#

Change this

button2.Enabled == true

to

button2.Enabled = true;

Sort an ArrayList based on an object field

You can use the Bean Comparator to sort on any property in your custom class.

for loop in Python

The range() function in python is a way to generate a sequence. Sequences are objects that can be indexed, like lists, strings, and tuples. An easy way to check for a sequence is to try retrieve indexed elements from them. It can also be checked using the Sequence Abstract Base Class(ABC) from the collections module.

from collections import Sequence as sq
isinstance(foo, sq)

The range() takes three arguments start, stop and step.

  1. start : The staring element of the required sequence
  2. stop : (n+1)th element of the required sequence
  3. step : The required gap between the elements of the sequence. It is an optional parameter that defaults to 1.

To get your desired result you can make use of the below syntax.

range(1,c+1,2)

Creating an Instance of a Class with a variable in Python

You can create variable like this:

x = 10 
print(x)

Or this:

globals()['y'] = 100
print(y)

Lets create a new class:

class Foo(object):
    def __init__(self):
        self.name = 'John'

You can create class instance this way:

instance_name_1 = Foo()

Or this way:

globals()['instance_name_2'] = Foo()

Lets create a function:

def create_new_instance(class_name,instance_name):
    globals()[instance_name] = class_name()
    print('Class instance '{}' created!'.format(instance_name))

Call a function:

create_new_instance(Foo,'new_instance') #Class instance 'new_instance' created!
print(new_instance.name) #John

Also we can write generator function:

def create_instance(class_name,instance_name):
    count = 0
    while True:
        name = instance_name + str(count)
        globals()[name] = class_name()
        count += 1
        print('Class instance: {}'.format(name))
        yield True

generator_instance = create_instance(Foo,'instance_') 

for i in range(5):
    next(generator_instance)

#out
#Class instance: instance_0
#Class instance: instance_1
#Class instance: instance_2
#Class instance: instance_3
#Class instance: instance_4

print(instance_0.name) #john
print(instance_1.name) #john
print(instance_2.name) #john
print(instance_3.name) #john
print(instance_4.name) #john

#print(instance_5.name) #error.. we only created 5 instances.. 

next(generator_instance) #Class instance: instance_5
print(instance_5.name) #John  Now it works.. 

Run .jar from batch-file

you can use the following command in the .bat file newly created:

@echo off
call C:\SWDTOOLS\**PATH\TO\JAVA**\java_1.7_64\jre\bin\java -jar workspace.jar  

Please give the path of the java if there are multiple versions of java installed in the system and make sure you specified the main method and manifest file is created while creating the jar file.

What is an index in SQL?

INDEX is a performance optimization technique that speeds up the data retrieval process. It is a persistent data structure that associated with a Table (or View) in order to increase performance during retrieving the data from that table (or View).

Index based search is applied more particularly when your queries include WHERE filter. Otherwise, i.e, a query without WHERE-filter selects whole data and process. Searching whole table without INDEX is called Table-scan.

You will find exact information for Sql-Indexes in clear and reliable way: follow these links:

  1. For cocnept-wise understanding: http://dotnetauthorities.blogspot.in/2013/12/Microsoft-SQL-Server-Training-Online-Learning-Classes-INDEX-Overview-and-Optimizations.html
  2. For implementation-wise understanding: http://dotnetauthorities.blogspot.in/2013/12/Microsoft-SQL-Server-Training-Online-Learning-Classes-INDEX-Creation-Deletetion-Optimizations.html

Regular expression to detect semi-colon terminated C++ for & while loops

This is the kind of thing you really shouldn't do with a regular expression. Just parse the string one character at a time, keeping track of opening/closing parentheses.

If this is all you're looking for, you definitely don't need a full-blown C++ grammar lexer/parser. If you want practice, you can write a little recursive-decent parser, but even that's a bit much for just matching parentheses.

How To Run PHP From Windows Command Line in WAMPServer

In windows, put your php.exe file in windows/system32 or any other system executable folders and then go to command line and type php and hit enter following it, if it doesnt generate any error then you are ready to use PHP on command line. If you have set your php.exe somewhere else than default system folders then you need to set the path of it in the environment variables! You can get there in following path....

control panel -> System -> Edith the environment variables of your account -> Environment Vaiables -> path -> edit then set the absolute path of your php.exe there and follow the same procedure as in first paragraph, if nothing in the error department, then you are ready to use php from command line!

Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

  1. Install Java 7u21 from here: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR

  2. set these variables:

    export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home"
    export PATH=$JAVA_HOME/bin:$PATH
    
  3. Run your app and fun :)

(Minor update: put variable value in quote)

@RequestParam vs @PathVariable

If the URL http://localhost:8080/MyApp/user/1234/invoices?date=12-05-2013 gets the invoices for user 1234 on December 5th, 2013, the controller method would look like:

@RequestMapping(value="/user/{userId}/invoices", method = RequestMethod.GET)
public List<Invoice> listUsersInvoices(
            @PathVariable("userId") int user,
            @RequestParam(value = "date", required = false) Date dateOrNull) {
  ...
}

Also, request parameters can be optional, and as of Spring 4.3.3 path variables can be optional as well. Beware though, this might change the URL path hierarchy and introduce request mapping conflicts. For example, would /user/invoices provide the invoices for user null or details about a user with ID "invoices"?

Get multiple elements by Id

Today you can select elements with the same id attribute this way:

document.querySelectorAll('[id=test]');

Or this way with jQuery:

$('[id=test]');

CSS selector #test { ... } should work also for all elements with id = "test". ?ut the only thing: document.querySelectorAll('#test') (or $('#test') ) - will return only a first element with this id. Is it good, or not - I can't tell . But sometimes it is difficult to follow unique id standart .

For example you have the comment widget, with HTML-ids, and JS-code, working with these HTML-ids. Sooner or later you'll need to render this widget many times, to comment a different objects into a single page: and here the standart will broken (often there is no time or not allow - to rewrite built-in code).

Spring MVC: How to return image in @ResponseBody?

In addition to a couple of answers here a few pointers (Spring 4.1).

Incase you don't have any messageconverters configured in your WebMvcConfig, having ResponseEntity inside your @ResponseBody works well.

If you do, i.e. you have a MappingJackson2HttpMessageConverter configured (like me) using the ResponseEntity returns a org.springframework.http.converter.HttpMessageNotWritableException.

The only working solution in this case is to wrap a byte[] in the @ResponseBody as follows:

@RequestMapping(value = "/get/image/{id}", method=RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
public @ResponseBody byte[] showImageOnId(@PathVariable("id") String id) {
    byte[] b = whatEverMethodUsedToObtainBytes(id);
    return b;
}

In this case do rememeber to configure the messageconverters properly (and add a ByteArrayHttpMessageConverer) in your WebMvcConfig, like so:

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(mappingJackson2HttpMessageConverter());
    converters.add(byteArrayHttpMessageConverter());
}

@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setObjectMapper(objectMapper);
    return converter;
}

@Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
    ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
    arrayHttpMessageConverter.setSupportedMediaTypes(getSupportedMediaTypes());
    return arrayHttpMessageConverter;
}

private List<MediaType> getSupportedMediaTypes() {
    List<MediaType> list = new ArrayList<MediaType>();
    list.add(MediaType.IMAGE_JPEG);
    list.add(MediaType.IMAGE_PNG);
    list.add(MediaType.APPLICATION_OCTET_STREAM);
    return list;
}

Java: notify() vs. notifyAll() all over again

There are three states for a thread.

  1. WAIT - The thread is not using any CPU cycle
  2. BLOCKED - The thread is blocked trying to acquire a monitor. It might still be using the CPU cycles
  3. RUNNING - The thread is running.

Now, when a notify() is called, JVM picks one thread and move them to the BLOCKED state and hence to the RUNNING state as there is no competition for the monitor object.

When a notifyAll() is called, JVM picks all the threads and move all of them to BLOCKED state. All these threads will get the lock of the object on a priority basis. Thread which is able to acquire the monitor first will be able to go to the RUNNING state first and so on.

Programmatically set the initial view controller using Storyboards

How to without a dummy initial view controller

Ensure all initial view controllers have a Storyboard ID.

In the storyboard, uncheck the "Is initial View Controller" attribute from the first view controller.

If you run your app at this point you'll read:

Failed to instantiate the default view controller for UIMainStoryboardFile 'MainStoryboard' - perhaps the designated entry point is not set?

And you'll notice that your window property in the app delegate is now nil.

In the app's setting, go to your target and the Info tab. There clear the value of Main storyboard file base name. On the General tab, clear the value for Main Interface. This will remove the warning.

Create the window and desired initial view controller in the app delegate's application:didFinishLaunchingWithOptions: method:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];

    UIViewController *viewController = // determine the initial view controller here and instantiate it with [storyboard instantiateViewControllerWithIdentifier:<storyboard id>];

    self.window.rootViewController = viewController;
    [self.window makeKeyAndVisible];

    return YES;
}

Convert a space delimited string to list

Use string's split() method.

states.split()

How is a tag different from a branch in Git? Which should I use, here?

It looks like the best way to explain is that tags act as read only branches. You can use a branch as a tag, but you may inadvertently update it with new commits. Tags are guaranteed to point to the same commit as long as they exist.

Automatically capture output of last command into a variable using Bash?

This is not strictly a bash solution but you can use piping with sed to get the last row of previous commands output.

First lets see what i have in folder "a"

rasjani@helruo-dhcp022206::~$ find a
a
a/foo
a/bar
a/bat
a/baz
rasjani@helruo-dhcp022206::~$ 

Then, your example with ls and cd would turn to sed & piping into something like this:

rasjani@helruo-dhcp022206::~$ cd `find a |sed '$!d'`
rasjani@helruo-dhcp022206::~/a/baz$ pwd
/home/rasjani/a/baz
rasjani@helruo-dhcp022206::~/a/baz$

So, the actual magic happens with sed, you pipe what ever output of what ever command into sed and sed prints the last row which you can use as parameter with back ticks. Or you can combine that to xargs also. ("man xargs" in shell is your friend)

How to return a html page from a restful controller in spring boot?

The answer from Kukkuz did not work for me until I added in this dependency into the pom file:

<!-- Spring boot Thymeleaf -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

From the guide here.

As well as updating the registry resources as outlined here.

It then started working just fine. If anyone in the future runs into the same issue and following the first answer does not solve your problem, follow these 2 other steps after utilizing the code in @Kukkuz's answer and see if that makes a difference.

Photoshop text tool adds punctuation to the beginning of text

You can try : go to edit>preferencec>type.. select type > choose text engine options select east asian. Restart photoshop. Create new peroject. Try text tool again.

(if you want to use your project created with other text engine type) copy /paste all layers to new project.

How to set the environmental variable LD_LIBRARY_PATH in linux

You should add more details about your distribution, for example under Ubuntu the right way to do this is to add a custom .conf file to /etc/ld.so.conf.d, for example

sudo gedit /etc/ld.so.conf.d/randomLibs.conf

inside the file you are supposed to write the complete path to the directory that contains all the libraries that you wish to add to the system, for example

/home/linux/myLocalLibs

remember to add only the path to the dir, not the full path for the file, all the libs inside that path will be automatically indexed.

Save and run sudo ldconfig to update the system with this libs.

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

C++ is a language and Visual C++ is a compiler for that language. Certainly, it (and every other compiler) introduces tiny modifications to the language, but the language recognized is mainly the same.

Can't drop table: A foreign key constraint fails

Use show create table tbl_name to view the foreign keys

You can use this syntax to drop a foreign key:

ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol

There's also more information here (see Frank Vanderhallen post): http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html

Remove and Replace Printed items

One way is to use ANSI escape sequences:

import sys
import time
for i in range(10):
    print("Loading" + "." * i)
    sys.stdout.write("\033[F") # Cursor up one line
    time.sleep(1)

Also sometimes useful (for example if you print something shorter than before):

sys.stdout.write("\033[K") # Clear to the end of line

How to correctly use the extern keyword in C

extern tells the compiler that this data is defined somewhere and will be connected with the linker.

With the help of the responses here and talking to a few friends here is the practical example of a use of extern.

Example 1 - to show a pitfall:

File stdio.h:

int errno;
/* other stuff...*/

myCFile1.c:
#include <stdio.h>

Code...

myCFile2.c:
#include <stdio.h>

Code...

If myCFile1.o and myCFile2.o are linked, each of the c files have separate copies of errno. This is a problem as the same errno is supposed to be available in all linked files.

Example 2 - The fix.

File stdio.h:

extern int errno;
/* other stuff...*/

File stdio.c

int errno;

myCFile1.c:
#include <stdio.h>

Code...

myCFile2.c:
#include <stdio.h>

Code...

Now if both myCFile1.o and MyCFile2.o are linked by the linker they will both point to the same errno. Thus, solving the implementation with extern.

How do I get the localhost name in PowerShell?

In PowerShell Core v6 (works on macOS, Linux and Windows):

[Environment]::MachineName

Is it possible to program iPhone in C++

I'm currently writing an Objective-C++ framework called Objective-X, wich makes PURE C++ iPHONE PROGRAMMING possible. You can do like this:

#import "ObjectiveX.h"

void GUIApplicationMain() {    
    GUIAlert Alert;
    GUILabel Label;
    GUIScreen MainScreen;

    Alert.set_text(@"Just a lovely alert box!");
    Alert.set_title(@"Hello!");
    Alert.set_button(@"Okay");
    Alert.show();

    Label.set_text(@"Ciao!");
    Label.set_position(100, 200, 120, 40);

    MainScreen.init();
    MainScreen.addGUIControl(Label.init());    
}

and compile it using GCC's appropriate commandline options. I've already compiled this helloworld app&it w0rkX0rz like a charm. ;-) It'll available soon on GoogleCode. Search for Objective-X or visit http://infotronix.orgfree.com/objectivex approx. a week later!

Updated (but apparently inactive) URL: http://code.google.com/p/objectivex/

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

let layout = myCollectionView.collectionViewLayout as? UICollectionViewFlowLayout
layout?.minimumLineSpacing = 8

How return error message in spring mvc @Controller

Evaluating the error response from another service invocated...

This was my solution for evaluating the error:

try {
        return authenticationFeign.signIn(userDto, dataRequest);
    }catch(FeignException ex){

        //ex.status();

        if(ex.status() == HttpStatus.UNAUTHORIZED.value()){
            System.out.println("is a error 401");
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
        return new ResponseEntity<>(HttpStatus.OK);

    }

How do I get a class instance of generic type T?

I wanted to pass T.class to a method which make use of Generics

The method readFile reads a .csv file specified by the fileName with fullpath. There can be csv files with different contents hence i need to pass the model file class so that i can get the appropriate objects. Since this is reading csv file i wanted to do in a generic way. For some reason or other none of the above solutions worked for me. I need to use Class<? extends T> type to make it work. I use opencsv library for parsing the CSV files.

private <T>List<T> readFile(String fileName, Class<? extends T> type) {

    List<T> dataList = new ArrayList<T>();
    try {
        File file = new File(fileName);

        Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        Reader headerReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

        CSVReader csvReader = new CSVReader(headerReader);
        // create csv bean reader
        CsvToBean<T> csvToBean = new CsvToBeanBuilder(reader)
                .withType(type)
                .withIgnoreLeadingWhiteSpace(true)
                .build();

        dataList = csvToBean.parse();
    }
    catch (Exception ex) {
        logger.error("Error: ", ex);
    }

    return dataList;
}

This is how the readFile method is called

List<RigSurfaceCSV> rigSurfaceCSVDataList = readSurfaceFile(surfaceFileName, RigSurfaceCSV.class);

Shell script not running, command not found

Add below lines in your .profile path

PATH=$PATH:$HOME/bin:$Dir_where_script_exists

export PATH

Now your script should work without ./

Raj Dagla

Javascript: Unicode string to hex

Here is my take: these functions convert a UTF8 string to a proper HEX without the extra zeroes padding. A real UTF8 string has characters with 1, 2, 3 and 4 bytes length.

While working on this I found a couple key things that solved my problems:

  1. str.split('') doesn't handle multi-byte characters like emojis correctly. The proper/modern way to handle this is with Array.from(str)
  2. encodeURIComponent() and decodeURIComponent() are great tools to convert between string and hex. They are pretty standard, they handle UTF8 correctly.
  3. (Most) ASCII characters (codes 0 - 127) don't get URI encoded, so they need to handled separately. But c.charCodeAt(0).toString(16) works perfectly for those
    function utf8ToHex(str) {
      return Array.from(str).map(c => 
        c.charCodeAt(0) < 128 ? c.charCodeAt(0).toString(16) : 
        encodeURIComponent(c).replace(/\%/g,'').toLowerCase()
      ).join('');
    },
    function hexToUtf8: function(hex) {
      return decodeURIComponent('%' + hex.match(/.{1,2}/g).join('%'));
    }

Demo: https://jsfiddle.net/lyquix/k2tjbrvq/

How to retrieve element value of XML using Java?

Since you are using this for configuration, your best bet is apache commons-configuration. For simple files it's way easier to use than "raw" XML parsers.

See the XML how-to

SoapFault exception: Could not connect to host

With me, this problem in base Address in app.config of WCF service: When I've used:

<baseAddresses><add baseAddress="http://127.0.0.1:9022/Service/GatewayService"/> </baseAddresses>

it's ok if use .net to connect with public ip or domain.

But when use PHP's SoapClient to connect to "http://[online ip]:9022/Service/GatewayService", it's throw exception "Coulod not connect to host"

I've changed baseAddress to [online ip]:9022 and everything's ok.

Trigger change event of dropdown

For some reason, the other jQuery solutions provided here worked when running the script from console, however, it did not work for me when triggered from Chrome Bookmarklets.

Luckily, this Vanilla JS solution (the triggerChangeEvent function) did work:

_x000D_
_x000D_
/**_x000D_
  * Trigger a `change` event on given drop down option element._x000D_
  * WARNING: only works if not already selected._x000D_
  * @see https://stackoverflow.com/questions/902212/trigger-change-event-of-dropdown/58579258#58579258_x000D_
  */_x000D_
function triggerChangeEvent(option) {_x000D_
  // set selected property_x000D_
  option.selected = true;_x000D_
  _x000D_
  // raise event on parent <select> element_x000D_
  if ("createEvent" in document) {_x000D_
    var evt = document.createEvent("HTMLEvents");_x000D_
    evt.initEvent("change", false, true);_x000D_
    option.parentNode.dispatchEvent(evt);_x000D_
  }_x000D_
  else {_x000D_
    option.parentNode.fireEvent("onchange");_x000D_
  }_x000D_
}_x000D_
_x000D_
// ################################################_x000D_
// Setup our test case_x000D_
// ################################################_x000D_
_x000D_
(function setup() {_x000D_
  const sel = document.querySelector('#fruit');_x000D_
  sel.onchange = () => {_x000D_
    document.querySelector('#result').textContent = sel.value;_x000D_
  };_x000D_
})();_x000D_
_x000D_
function runTest() {_x000D_
  const sel = document.querySelector('#selector').value;_x000D_
  const optionEl = document.querySelector(sel);_x000D_
  triggerChangeEvent(optionEl);_x000D_
}
_x000D_
<select id="fruit">_x000D_
  <option value="">(select a fruit)</option>_x000D_
  <option value="apple">Apple</option>_x000D_
  <option value="banana">Banana</option>_x000D_
  <option value="pineapple">Pineapple</option>_x000D_
</select>_x000D_
_x000D_
<p>_x000D_
  You have selected: <b id="result"></b>_x000D_
</p>_x000D_
<p>_x000D_
  <input id="selector" placeholder="selector" value="option[value='banana']">_x000D_
  <button onclick="runTest()">Trigger select!</button>_x000D_
</p>
_x000D_
_x000D_
_x000D_

Is Tomcat running?

$ sudo netstat -lpn |grep :8080

To check the port number

$ ps -aef|grep tomcat

Is any tomcat is running under the server.

tsssinfotech-K53U infotech # ps -aef|grep tomcat

root 9586 9567 0 11:35 pts/6 00:00:00 grep --colour=auto tomcat

Differences between arm64 and aarch64

It seems that ARM64 was created by Apple and AARCH64 by the others, most notably GNU/GCC guys.

After some googling I found this link:

The LLVM 64-bit ARM64/AArch64 Back-Ends Have Merged

So it makes sense, iPad calls itself ARM64, as Apple is using LLVM, and Edge uses AARCH64, as Android is using GNU GCC toolchain.

How do I rename a file using VBScript?

Rename File using VB SCript.

  1. Create Folder Source and Archive in D : Drive. [You can choose other drive but make change in code from D:\Source to C:\Source in case you create folder in C: Drive]
  2. Save files in Source folder to be renamed.
  3. Save below code and save it as .vbs e.g ChangeFileName.vbs
  4. Run file and the file will be renamed with existing file name and current date

    Option Explicit

    Dim fso,sfolder,fs,f1,CFileName,strRename,NewFilename,GFileName,CFolderName,CFolderName1,Dfolder,afolder

    Dim myDate

    myDate =Date

    Function pd(n, totalDigits)

        if totalDigits > len(n) then 
    
            pd = String(totalDigits-len(n),"0") & n 
    
        else 
    
            pd = n 
    
        end if 
    

    End Function

    myDate= Pd(DAY(date()),2) & _

    Pd(Month(date()),2) & _

    YEAR(Date())

    'MsgBox ("Create Folders 'Source' 'Destination ' and 'Archive' in D drive. Save PDF files into Source Folder ")

    sfolder="D:\Source\"

    'Dfolder="D:\Destination\"

    afolder="D:\archive\"

    Set fso= CreateObject("Scripting.FileSystemObject")

    Set fs= fso.GetFolder(sfolder)

    For each f1 in fs.files

            CFileName=sfolder & f1.name
    
            CFolderName1=f1.name
    
            CFolderName=Replace(CFolderName1,"." & fso.GetExtensionName(f1.Path),"")
    
            'Msgbox CFileName 
    
            'MsgBox CFolderName 
    
            'MsgBox myDate
    
            GFileName=fso.GetFileName(sfolder)
    
            'strRename="DA009B_"& CFolderName &"_20032019"
    
            strRename= "DA009B_"& CFolderName &"_"& myDate &""
    
            NewFilename=replace(CFileName,CFolderName,strRename)
    
            'fso.CopyFile CFolderName1 , afolder
    
            fso.MoveFile CFileName , NewFilename
    
            'fso.CopyFile CFolderName, Dfolder
    

    Next

    MsgBox "File Renamed Successfully !!! "

    Set fso= Nothing

    Set fs=Nothing

How do I create a local database inside of Microsoft SQL Server 2014?

Warning! SQL Server 14 Express, SQL Server Management Studio, and SQL 2014 LocalDB are separate downloads, make sure you actually installed SQL Server and not just the Management Studio! SQL Server 14 express with LocalDB download link

Youtube video about entire process.
Writeup with pictures about installing SQL Server

How to select a local server:

When you are asked to connect to a 'database server' right when you open up SQL Server Management Studio do this:

1) Make sure you have Server Type: Database

2) Make sure you have Authentication: Windows Authentication (no username & password)

3) For the server name field look to the right and select the drop down arrow, click 'browse for more'

4) New window pops up 'Browse for Servers', make sure to pick 'Local Servers' tab and under 'Database Engine' you will have the local server you set up during installation of SQL Server 14

How do I create a local database inside of Microsoft SQL Server 2014?

1) After you have connected to a server, bring up the Object Explorer toolbar under 'View' (Should open by default)

2) Now simply right click on 'Databases' and then 'Create new Database' to be taken through the database creation tools!

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

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

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

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

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

Free ASP.Net and/or CSS Themes

I have used Open source Web Design in the past. They have quite a few css themes, don't know about ASP.Net

How to Display Multiple Google Maps per page with API V3

Take a Look at this Bundle for Laravel that I Made Recently !


https://github.com/Maghrooni/googlemap

it helps you to create one or multiple maps in your page !

you can find the class on

src/googlemap.php

Pls Read the readme file first and don't forget to pass different ID if you want to have multiple Maps in one page

ASP.NET Identity DbContext confusion

If you drill down through the abstractions of the IdentityDbContext you'll find that it looks just like your derived DbContext. The easiest route is Olav's answer, but if you want more control over what's getting created and a little less dependency on the Identity packages have a look at my question and answer here. There's a code example if you follow the link, but in summary you just add the required DbSets to your own DbContext subclass.

Switch statement for greater-than/less-than

I hate using 30 if statements

I had the same situation lately, that's how I solved it:

before:

if(wind_speed >= 18) {
    scale = 5;
} else if(wind_speed >= 12) {
    scale = 4;
} else if(wind_speed >= 9) {
    scale = 3;
} else if(wind_speed >= 6) {
    scale = 2;
} else if(wind_speed >= 4) {
    scale = 1;
}

after:

var scales = [[4, 1], [6, 2], [9, 3], [12, 4], [18, 5]];
scales.forEach(function(el){if(wind_speed > el[0]) scale = el[1]});

And if you set "1, 2, 3, 4, 5" then it can be even simpler:

var scales = [4, 6, 9, 12, 18];
scales.forEach(function(el){if(wind_speed >= el) scale++});

How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?

I use Eclipse for cross compiling and I have to add the explicit directories for some of the standard C++ libraries. Right click your project and select Properties. You'll get the dialog shown in the image. Follow the image and use the + icon to explicitly add the paths to your C++ libraries. enter image description here

What is the cleanest way to ssh and run multiple commands in Bash?

Not sure if the cleanest for long commands but certainly the easiest:

ssh user@host "cmd1; cmd2; cmd3"

The HTTP request is unauthorized with client authentication scheme 'Ntlm'

1) I had to do the following with my configuration: (Add BackConnectionHostNames or Disable Loopback Check) http://support.microsoft.com/kb/896861

2) I was working off a dev system on an isolated dev network. I had gotten it working using the dev system's computer name in the URL to the web service, but when I modified the URL to the URL that would be used in production (rather than the computer name), I started getting the NTLM error.

3) I noticed the security log showed that the service account failing to login with an error similar to the one in the MSDN article.

4) Adding the BackConnectionHostNames made it so I could log into the server via a browser running on the server, but the service account still had NTLM errors when trying to authenticate for the web services. I wound up disabling the loop back check and that fixed it for me.

How to declare 2D array in bash

The below code will definitely work provided if you are working on a Mac you have bash version 4. Not only can you declare 0 but this is more of a universal approach to dynamically accepting values.

2D Array

declare -A arr
echo "Enter the row"
read r
echo "Enter the column"
read c
i=0
j=0
echo "Enter the elements"
while [ $i -lt $r ]
do
  j=0
  while [ $j -lt $c ]
  do
    echo $i $j
    read m
    arr[${i},${j}]=$m
    j=`expr $j + 1`
  done
  i=`expr $i + 1`
done

i=0
j=0
while [ $i -lt $r ]
do
  j=0
  while [ $j -lt $c ]
  do
    echo -n ${arr[${i},${j}]} " "
    j=`expr $j + 1`
  done
  echo ""
  i=`expr $i + 1`
done

You must enable the openssl extension to download files via https

You need to enable "extension=php_openssl.dll" in both files (php and apache). my pc files path are these :

  1. C:\wamp\bin\php\php5.3.13\php.ini

  2. C:\wamp\bin\apache\apache2.2.22\bin\php.ini

how to set length of an column in hibernate with maximum length

You need to alter your table. Increase the column width using a DDL statement.

please see here

http://dba-oracle.com/t_alter_table_modify_column_syntax_example.htm

Convert String to Integer in XSLT 1.0

Adding to jelovirt's answer, you can use number() to convert the value to a number, then round(), floor(), or ceiling() to get a whole integer.

Example

<xsl:variable name="MyValAsText" select="'5.14'"/>
<xsl:value-of select="number($MyValAsText) * 2"/> <!-- This outputs 10.28 -->
<xsl:value-of select="floor($MyValAsText)"/> <!-- outputs 5 -->
<xsl:value-of select="ceiling($MyValAsText)"/> <!-- outputs 6 -->
<xsl:value-of select="round($MyValAsText)"/> <!-- outputs 5 -->

What exceptions should be thrown for invalid or unexpected parameters in .NET?

Depending on the actual value and what exception fits best:

If this is not precise enough, just derive your own exception class from ArgumentException.

Yoooder's answer enlightened me. An input is invalid if it is not valid at any time, while an input is unexpected if it is not valid for the current state of the system. So in the later case an InvalidOperationException is a reasonable choice.

add an onclick event to a div

Assign the onclick like this:

divTag.onclick = printWorking;

The onclick property will not take a string when assigned. Instead, it takes a function reference (in this case, printWorking).
The onclick attribute can be a string when assigned in HTML, e.g. <div onclick="func()"></div>, but this is generally not recommended.

Count Rows in Doctrine QueryBuilder

You can also get the number of data by using the count function.

$query = $this->dm->createQueryBuilder('AppBundle:Items')
                    ->field('isDeleted')->equals(false)
                    ->getQuery()->count();

git: How to diff changed files versus previous versions after a pull?

I like to use:

git diff HEAD^

Or if I only want to diff a specific file:

git diff HEAD^ -- /foo/bar/baz.txt

NSURLErrorDomain error codes description

The NSURLErrorDomain error codes are listed here https://developer.apple.com/documentation/foundation/1508628-url_loading_system_error_codes

However, 400 is just the http status code (http://www.w3.org/Protocols/HTTP/HTRESP.html) being returned which means you've got something wrong with your request.

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

Here's my version that works for multiple pids, logs warnings if execution takes too long, and stops the subprocesses if execution takes longer than a given value.

function WaitForTaskCompletion {
    local pids="${1}" # pids to wait for, separated by semi-colon
    local soft_max_time="${2}" # If execution takes longer than $soft_max_time seconds, will log a warning, unless $soft_max_time equals 0.
    local hard_max_time="${3}" # If execution takes longer than $hard_max_time seconds, will stop execution, unless $hard_max_time equals 0.
    local caller_name="${4}" # Who called this function
    local exit_on_error="${5:-false}" # Should the function exit program on subprocess errors       

    Logger "${FUNCNAME[0]} called by [$caller_name]."

    local soft_alert=0 # Does a soft alert need to be triggered, if yes, send an alert once 
    local log_ttime=0 # local time instance for comparaison

    local seconds_begin=$SECONDS # Seconds since the beginning of the script
    local exec_time=0 # Seconds since the beginning of this function

    local retval=0 # return value of monitored pid process
    local errorcount=0 # Number of pids that finished with errors

    local pidCount # number of given pids

    IFS=';' read -a pidsArray <<< "$pids"
    pidCount=${#pidsArray[@]}

    while [ ${#pidsArray[@]} -gt 0 ]; do
        newPidsArray=()
        for pid in "${pidsArray[@]}"; do
            if kill -0 $pid > /dev/null 2>&1; then
                newPidsArray+=($pid)
            else
                wait $pid
                result=$?
                if [ $result -ne 0 ]; then
                    errorcount=$((errorcount+1))
                    Logger "${FUNCNAME[0]} called by [$caller_name] finished monitoring [$pid] with exitcode [$result]."
                fi
            fi
        done

        ## Log a standby message every hour
        exec_time=$(($SECONDS - $seconds_begin))
        if [ $((($exec_time + 1) % 3600)) -eq 0 ]; then
            if [ $log_ttime -ne $exec_time ]; then
                log_ttime=$exec_time
                Logger "Current tasks still running with pids [${pidsArray[@]}]."
            fi
        fi

        if [ $exec_time -gt $soft_max_time ]; then
            if [ $soft_alert -eq 0 ] && [ $soft_max_time -ne 0 ]; then
                Logger "Max soft execution time exceeded for task [$caller_name] with pids [${pidsArray[@]}]."
                soft_alert=1
                SendAlert

            fi
            if [ $exec_time -gt $hard_max_time ] && [ $hard_max_time -ne 0 ]; then
                Logger "Max hard execution time exceeded for task [$caller_name] with pids [${pidsArray[@]}]. Stopping task execution."
                kill -SIGTERM $pid
                if [ $? == 0 ]; then
                    Logger "Task stopped successfully"
                else
                    errrorcount=$((errorcount+1))
                fi
            fi
        fi

        pidsArray=("${newPidsArray[@]}")
        sleep 1
    done

    Logger "${FUNCNAME[0]} ended for [$caller_name] using [$pidCount] subprocesses with [$errorcount] errors."
    if [ $exit_on_error == true ] && [ $errorcount -gt 0 ]; then
        Logger "Stopping execution."
        exit 1337
    else
        return $errorcount
    fi
}

# Just a plain stupid logging function to be replaced by yours
function Logger {
    local value="${1}"

    echo $value
}

Example, wait for all three processes to finish, log a warning if execution takes loger than 5 seconds, stop all processes if execution takes longer than 120 seconds. Don't exit program on failures.

function something {

    sleep 10 &
    pids="$!"
    sleep 12 &
    pids="$pids;$!"
    sleep 9 &
    pids="$pids;$!"

    WaitForTaskCompletion $pids 5 120 ${FUNCNAME[0]} false
}
# Launch the function
someting
    

Mocha / Chai expect.to.throw not catching thrown errors

examples from doc... ;)

because you rely on this context:

  • which is lost when the function is invoked by .throw
  • there’s no way for it to know what this is supposed to be

you have to use one of these options:

  • wrap the method or function call inside of another function
  • bind the context

    // wrap the method or function call inside of another function
    expect(function () { cat.meow(); }).to.throw();  // Function expression
    expect(() => cat.meow()).to.throw();             // ES6 arrow function
    
    // bind the context
    expect(cat.meow.bind(cat)).to.throw();           // Bind