Programs & Examples On #Z order

Z-order is an ordering of overlapping two-dimensional elements in a graphical user interface.

Defining Z order of views of RelativeLayout in Android

I encountered the same issues: In a relative layout parentView, I have 2 children childView1 and childView2. At first, I put childView1 above childView2 and I want childView1 to be on top of childView2. Changing the order of children views did not solve the problem for me. What worked for me is to set android:clipChildren="false" on parentView and in the code I set:

childView1.bringToFront();

parentView.invalidate();

How to bring view in front of everything?

You can use BindingAdapter like this:

@BindingAdapter("bringToFront")
public static void bringToFront(View view, Boolean flag) {
    if (flag) {
        view.bringToFront();
    }
}


  <ImageView
        ...
        app:bringToFront="@{true}"/>

How do I declare and initialize an array in Java?

Type[] variableName = new Type[capacity];

Type[] variableName = {comma-delimited values};



Type variableName[] = new Type[capacity]; 

Type variableName[] = {comma-delimited values};

is also valid, but I prefer the brackets after the type, because it's easier to see that the variable's type is actually an array.

ASP.NET MVC View Engine Comparison

I like ndjango. It is very easy to use and very flexible. You can easily extend view functionality with custom tags and filters. I think that "greatly tied to F#" is rather advantage than disadvantage.

Java: get greatest common divisor

Unless I have Guava, I define like this:

int gcd(int a, int b) {
  return a == 0 ? b : gcd(b % a, a);
}

Understanding Spring @Autowired usage

Yes, you can configure the Spring servlet context xml file to define your beans (i.e., classes), so that it can do the automatic injection for you. However, do note, that you have to do other configurations to have Spring up and running and the best way to do that, is to follow a tutorial ground up.

Once you have your Spring configured probably, you can do the following in your Spring servlet context xml file for Example 1 above to work (please replace the package name of com.movies to what the true package name is and if this is a 3rd party class, then be sure that the appropriate jar file is on the classpath) :

<beans:bean id="movieFinder" class="com.movies.MovieFinder" />

or if the MovieFinder class has a constructor with a primitive value, then you could something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg value="100" />
</beans:bean>

or if the MovieFinder class has a constructor expecting another class, then you could do something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg ref="otherBeanRef" />
</beans:bean>

...where 'otherBeanRef' is another bean that has a reference to the expected class.

Converting a String array into an int Array in java

Another short way:

int[] myIntArray = Arrays.stream(myStringArray).mapToInt(Integer::parseInt).toArray();

Adding a user on .htpasswd

Exact same thing, just omit the -c option. Apache's docs on it here.

htpasswd /etc/apache2/.htpasswd newuser

Also, htpasswd typically isn't run as root. It's typically owned by either the web server, or the owner of the files being served. If you're using root to edit it instead of logging in as one of those users, that's acceptable (I suppose), but you'll want to be careful to make sure you don't accidentally create a file as root (and thus have root own it and no one else be able to edit it).

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead?

Use setInterval()

setInterval(function(){
 alert("Hello"); 
}, 3000);

The above will execute alert("Hello"); every 3 seconds.

Ruby: kind_of? vs. instance_of? vs. is_a?

What is the difference?

From the documentation:

- (Boolean) instance_of?(class)
Returns true if obj is an instance of the given class.

and:

- (Boolean) is_a?(class)
- (Boolean) kind_of?(class)
Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

If that is unclear, it would be nice to know what exactly is unclear, so that the documentation can be improved.

When should I use which?

Never. Use polymorphism instead.

Why are there so many of them?

I wouldn't call two "many". There are two of them, because they do two different things.

How to install iPhone application in iPhone Simulator

Please note: this answer is obsolete, the functionality was removed from iOS simulator.

I have just found that you don't need to copy the mobile application bundle to the iPhone Simulator's folder to start it on the simulator, as described in the forum. That way you need to click on the app to get it started, not confortable when you want to do testing and start the app numerous times.

There are undocumented command line parameters for the iOS Simulator, which can be used for such purposes. The one you are looking for is: -SimulateApplication

An example command line starting up YourFavouriteApp:

/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app/Contents/MacOS/iPhone\ Simulator -SimulateApplication path_to_your_app/YourFavouriteApp.app/YourFavouriteApp

This will start up your application without any installation and works with iOS Simulator 4.2 at least. You cannot reach the home menu, though.

There are other unpublished command line parameters, like switching the SDK. Happy hunting for those...

extract date only from given timestamp in oracle sql

If you want the value from your timestamp column to come back as a date datatype, use something like this:

select trunc(my_timestamp_column,'dd') as my_date_column from my_table;

Is there a list of Pytz Timezones?

EDIT: I would appreciate it if you do not downvote this answer further. This answer is wrong, but I would rather retain it as a historical note. While it is arguable whether the pytz interface is error-prone, it can do things that dateutil.tz cannot do, especially regarding daylight-saving in the past or in the future. I have honestly recorded my experience in an article "Time zones in Python".


If you are on a Unix-like platform, I would suggest you avoid pytz and look just at /usr/share/zoneinfo. dateutil.tz can utilize the information there.

The following piece of code shows the problem pytz can give. I was shocked when I first found it out. (Interestingly enough, the pytz installed by yum on CentOS 7 does not exhibit this problem.)

import pytz
import dateutil.tz
from datetime import datetime
print((datetime(2017,2,13,14,29,29, tzinfo=pytz.timezone('Asia/Shanghai'))
     - datetime(2017,2,13,14,29,29, tzinfo=pytz.timezone('UTC')))
     .total_seconds())
print((datetime(2017,2,13,14,29,29, tzinfo=dateutil.tz.gettz('Asia/Shanghai'))
     - datetime(2017,2,13,14,29,29, tzinfo=dateutil.tz.tzutc()))
     .total_seconds())

-29160.0
-28800.0

I.e. the timezone created by pytz is for the true local time, instead of the standard local time people observe. Shanghai conforms to +0800, not +0806 as suggested by pytz:

pytz.timezone('Asia/Shanghai')
<DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD>

EDIT: Thanks to Mark Ransom's comment and downvote, now I know I am using pytz the wrong way. In summary, you are not supposed to pass the result of pytz.timezone(…) to datetime, but should pass the datetime to its localize method.

Despite his argument (and my bad for not reading the pytz documentation more carefully), I am going to keep this answer. I was answering the question in one way (how to enumerate the supported timezones, though not with pytz), because I believed pytz did not provide a correct solution. Though my belief was wrong, this answer is still providing some information, IMHO, which is potentially useful to people interested in this question. Pytz's correct way of doing things is counter-intuitive. Heck, if the tzinfo created by pytz should not be directly used by datetime, it should be a different type. The pytz interface is simply badly designed. The link provided by Mark shows that many people, not just me, have been misled by the pytz interface.

How to fix Python indentation

Use the reindent.py script that you find in the Tools/scripts/ directory of your Python installation:

Change Python (.py) files to use 4-space indents and no hard tab characters. Also trim excess spaces and tabs from ends of lines, and remove empty lines at the end of files. Also ensure the last line ends with a newline.

Have a look at that script for detailed usage instructions.

Switching from zsh to bash on OSX, and back again?

In Mac OS Catalina default interactive shell is zsh. To change shell to zsh from bash:

chsh -s /bin/zsh

Then you need to enter your Mac password. Quit the terminal and reopen it. To check whether it's changed successfully to ssh, issue the following command.

echo $SHELL

If the result is /bin/zsh, your task is completed.

To change it back to bash, issue the following command on terminal.

chsh -s /bin/bash

Verify it again using echo $SHELL. Then result should be /bin/bash.

Embed website into my site

You can embed websites into another website using the <embed> tag, like so:

<embed src="http://www.example.com" style="width:500px; height: 300px;">

You can change the height, width, and URL to suit your needs.

The <embed> tag is the most up-to-date way to embed websites, as it was introduced with HTML5.

How to convert a string of bytes into an int?

import array
integerValue = array.array("I", 'y\xcc\xa6\xbb')[0]

Warning: the above is strongly platform-specific. Both the "I" specifier and the endianness of the string->int conversion are dependent on your particular Python implementation. But if you want to convert many integers/strings at once, then the array module does it quickly.

How to read data from excel file using c#

CSharpJExcel for reading Excel 97-2003 files (XLS), ExcelPackage for reading Excel 2007/2010 files (Office Open XML format, XLSX), and ExcelDataReader that seems to have the ability to handle both formats

Good luck!

Random row selection in Pandas dataframe

sample

As of v0.20.0, you can use pd.DataFrame.sample, which can be used to return a random sample of a fixed number rows, or a percentage of rows:

df = df.sample(n=k)     # k rows
df = df.sample(frac=k)  # int(len(df.index) * k) rows

For reproducibility, you can specify an integer random_state, equivalent to using np.ramdom.seed. So, instead of setting, for example, np.random.seed = 0, you can:

df = df.sample(n=k, random_state=0)

How to truncate a foreign key constrained table?

You cannot TRUNCATE a table that has FK constraints applied on it (TRUNCATE is not the same as DELETE).

To work around this, use either of these solutions. Both present risks of damaging the data integrity.

Option 1:

  1. Remove constraints
  2. Perform TRUNCATE
  3. Delete manually the rows that now have references to nowhere
  4. Create constraints

Option 2: suggested by user447951 in their answer

SET FOREIGN_KEY_CHECKS = 0; 
TRUNCATE table $table_name; 
SET FOREIGN_KEY_CHECKS = 1;

$.ajax - dataType

jQuery Ajax loader is not working well when you call two APIs simultaneously. To resolve this problem you have to call the APIs one by one using the isAsync property in Ajax setting. You also need to make sure that there should not be any error in the setting. Otherwise, the loader will not work. E.g undefined content-type, data-type for POST/PUT/DELETE/GET call.

Best way to use multiple SSH private keys on one client

Here is the solution that I used inspired from the answer of sajib-khan. The default configuration is not set; it's my personal account on GitLab and the other specified is my company account. Here is what I did:

Generate the SSH key

ssh-keygen -t rsa -f ~/.ssh/company -C "[email protected]"

Edit the SSH configuration

nano ~/.ssh/config
    Host company.gitlab.com
    HostName gitlab.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/company

Delete the cached SSH key(s)

ssh-add -D

Test it!

ssh -T [email protected]

Welcome to GitLab, @hugo.sohm!

ssh -T [email protected]

Welcome to GitLab, @HugoSohm!

Use it!

Company account

git clone [email protected]:group/project.git

Personal/default account

git clone [email protected]:username/project.git

Here is the source that I used.

Python FileNotFound

try block should be around open. Not around prompt.

while True:
    prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
    try:
        sudoku = open(prompt, 'r').readlines()
    except FileNotFoundError:
        print("Wrong file or file path")
    else:
        break

Center div on the middle of screen

This should work with any div or screen size:

_x000D_
_x000D_
.center-screen {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  text-align: center;_x000D_
  min-height: 100vh;_x000D_
}
_x000D_
 <html>_x000D_
 <head>_x000D_
 </head>_x000D_
 <body>_x000D_
 <div class="center-screen">_x000D_
 I'm in the center_x000D_
 </div>_x000D_
 </body>_x000D_
 </html>
_x000D_
_x000D_
_x000D_

See more details about flex here. This should work on most of the browsers, see compatibility matrix here.

Update: If you don't want the scroll bar, make min-height smaller, for example min-height: 95vh;

Generate random int value from 3 to 6

Nice and simple, from Pinal Dave's site:

http://blog.sqlauthority.com/2007/04/29/sql-server-random-number-generator-script-sql-query/

DECLARE @Random INT;
DECLARE @Upper INT;
DECLARE @Lower INT
SET @Lower = 3 ---- The lowest random number
SET @Upper = 7 ---- One more than the highest random number
SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)
SELECT @Random

(I did make a slight change to the @Upper- to include the upper number, added 1.)

How long will my session last?

This is the one. The session will last for 1440 seconds (24 minutes).

session.gc_maxlifetime  1440    1440

Add a dependency in Maven

You'll have to do this in two steps:

1. Give your JAR a groupId, artifactId and version and add it to your repository.

If you don't have an internal repository, and you're just trying to add your JAR to your local repository, you can install it as follows, using any arbitrary groupId/artifactIds:

mvn install:install-file -DgroupId=com.stackoverflow... -DartifactId=yourartifactid... -Dversion=1.0 -Dpackaging=jar -Dfile=/path/to/jarfile

You can also deploy it to your internal repository if you have one, and want to make this available to other developers in your organization. I just use my repository's web based interface to add artifacts, but you should be able to accomplish the same thing using mvn deploy:deploy-file ....

2. Update dependent projects to reference this JAR.

Then update the dependency in the pom.xml of the projects that use the JAR by adding the following to the element:

<dependencies>
    ...
    <dependency>
        <groupId>com.stackoverflow...</groupId>
        <artifactId>artifactId...</artifactId>
        <version>1.0</version>
    </dependency>
    ...
</dependencies>

How do I handle newlines in JSON?

According to the specification, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf:

A string is a sequence of Unicode code points wrapped with quotation marks (U+0022). All characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark (U+0022), reverse solidus (U+005C), and the control characters U+0000 to U+001F. There are two-character escape sequence representations of some characters.

So you can't pass 0x0A or 0x0C codes directly. It is forbidden! The specification suggests to use escape sequences for some well-defined codes from U+0000 to U+001F:

  • \f represents the form feed character (U+000C).
  • \n represents the line feed character (U+000A).

As most of programming languages uses \ for quoting, you should escape the escape syntax (double-escape - once for language/platform, once for JSON itself):

jsonStr = "{ \"name\": \"Multi\\nline.\" }";

How to use vagrant in a proxy environment?

Installing proxyconf will solve this, but behind a proxy you can't install a plugin simply using the command vagrant plugin install, Bundler will raise an error.

set your proxy in your environment if you're using a unix like system

export http_proxy=http://user:password@host:port

or get a more detailed answer here: How to use bundler behind a proxy?

after this set up proxyconf

Java: Insert multiple rows into MySQL with PreparedStatement

we can be submit multiple updates together in JDBC to submit batch updates.

we can use Statement, PreparedStatement, and CallableStatement objects for bacth update with disable autocommit

addBatch() and executeBatch() functions are available with all statement objects to have BatchUpdate

here addBatch() method adds a set of statements or parameters to the current batch.

RegEx to exclude a specific string constant

You could use negative lookahead, or something like this:

^([^A]|A([^B]|B([^C]|$)|$)|$).*$

Maybe it could be simplified a bit.

Eclipse fonts and background color

Background color of views (navigator, console, tasks etc) is set according to the desktop (system) settings. On Linux/GNome I changed System/Preferences/Appeareance to change this color.

Editor colors are set chaotically by different editors, search for background in eclipse preferences to find different options. One easy way to get beautiful dark (and not only dark) themes is to install Afae plugin, and then pick theme within its preferences (twilight theme is beautiful, for example) - again, eclipse prefs, Afae group. Of course this applies only when you edit with Afae.

jquery: get id from class selector

$(".class").click(function(){
    alert($(this).attr('id'));
});

only on jquery button click we can do this class should be written there

How to force R to use a specified factor level as reference in a regression?

See the relevel() function. Here is an example:

set.seed(123)
x <- rnorm(100)
DF <- data.frame(x = x,
                 y = 4 + (1.5*x) + rnorm(100, sd = 2),
                 b = gl(5, 20))
head(DF)
str(DF)

m1 <- lm(y ~ x + b, data = DF)
summary(m1)

Now alter the factor b in DF by use of the relevel() function:

DF <- within(DF, b <- relevel(b, ref = 3))
m2 <- lm(y ~ x + b, data = DF)
summary(m2)

The models have estimated different reference levels.

> coef(m1)
(Intercept)           x          b2          b3          b4          b5 
  3.2903239   1.4358520   0.6296896   0.3698343   1.0357633   0.4666219 
> coef(m2)
(Intercept)           x          b1          b2          b4          b5 
 3.66015826  1.43585196 -0.36983433  0.25985529  0.66592898  0.09678759

delete map[key] in go?

Strangely enough,

package main

func main () {
    var sessions = map[string] chan int{};
    delete(sessions, "moo");
}

seems to work. This seems a poor use of resources though!

Another way is to check for existence and use the value itself:

package main

func main () {
    var sessions = map[string] chan int{};
    sessions["moo"] = make (chan int);
    _, ok := sessions["moo"];
    if ok {
        delete(sessions, "moo");
    }
}

Is there a "previous sibling" selector?

No. It is not possible via CSS. It takes the "Cascade" to heart ;-).


However, if you are able to add JavaScript to your page, a little bit of jQuery could get you to your end goal.
You can use jQuery's find to perform a "look-ahead" on your target element/class/id, then backtrack to select your target.
Then you use jQuery to re-write the DOM (CSS) for your element.

Based on this answer by Mike Brant, the following jQuery snippet could help.

$('p + ul').prev('p')

This first selects all <ul>s that immediately follow a <p>.
Then it "backtracks" to select all the previous <p>s from that set of <ul>s.

Effectively, "previous sibling" has been selected via jQuery.
Now, use the .css function to pass in your CSS new values for that element.


In my case I was looking to find a way to select a DIV with the id #full-width, but ONLY if it had a (indirect) descendant DIV with the class of .companies.

I had control of all the HTML under .companies, but could not alter any of the HTML above it.
And the cascade goes only 1 direction: down.

Thus I could select ALL #full-widths.
Or I could select .companies that only followed a #full-width.
But I could not select only #full-widths that proceeded .companies.

And, again, I was unable to add .companies any higher up in the HTML. That part of the HTML was written externally, and wrapped our code.

But with jQuery, I can select the required #full-widths, then assign the appropriate style:

$("#full-width").find(".companies").parents("#full-width").css( "width", "300px" );

This finds all #full-width .companies, and selects just those .companies, similar to how selectors are used to target specific elements in standard in CSS.
Then it uses .parents to "backtrack" and select ALL parents of .companies,
but filters those results to keep only #fill-width elements, so that in the end,
it only selects a #full-width element if it has a .companies class descendant.
Finally, it assigns a new CSS (width) value to the resulting element.

_x000D_
_x000D_
$(".parent").find(".change-parent").parents(".parent").css( "background-color", "darkred");
_x000D_
div {_x000D_
  background-color: lightblue;_x000D_
  width: 120px;_x000D_
  height: 40px;_x000D_
  border: 1px solid gray;_x000D_
  padding: 5px;_x000D_
}_x000D_
.wrapper {_x000D_
  background-color: blue;_x000D_
  width: 250px;_x000D_
  height: 165px;_x000D_
}_x000D_
.parent {_x000D_
  background-color: green;_x000D_
  width: 200px;_x000D_
  height: 70px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<html>_x000D_
<div class="wrapper">_x000D_
_x000D_
  <div class="parent">_x000D_
    "parent" turns red_x000D_
    <div class="change-parent">_x000D_
    descendant: "change-parent"_x000D_
    </div>_x000D_
  </div>_x000D_
  _x000D_
  <div class="parent">_x000D_
    "parent" stays green_x000D_
    <div class="nope">_x000D_
    descendant: "nope"_x000D_
    </div>_x000D_
  </div>_x000D_
  _x000D_
</div>_x000D_
Target <b>"<span style="color:darkgreen">parent</span>"</b> to turn <span style="color:red">red</span>.<br>_x000D_
<b>Only</b> if it <b>has</b> a descendant of "change-parent".<br>_x000D_
<br>_x000D_
(reverse cascade, look ahead, parent un-descendant)_x000D_
</html>
_x000D_
_x000D_
_x000D_

jQuery Reference Docs:
$() or jQuery(): DOM element.
.find: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
.parents: Get the immediately preceding sibling of each element in the set of matched elements. If a selector is provided, it retrieves the previous sibling only if it matches that selector (filters the results to only include the listed elements/selectors).
.css: Set one or more CSS properties for the set of matched elements.

What is Inversion of Control?

Inversion of Controls is about separating concerns.

Without IoC: You have a laptop computer and you accidentally break the screen. And darn, you find the same model laptop screen is nowhere in the market. So you're stuck.

With IoC: You have a desktop computer and you accidentally break the screen. You find you can just grab almost any desktop monitor from the market, and it works well with your desktop.

Your desktop successfully implements IoC in this case. It accepts a variety type of monitors, while the laptop does not, it needs a specific screen to get fixed.

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

Found a Fix:

  1. First ensure that printing is working from Report Manager (open a report in Report Manager and print from there).

  2. If it works go to Step 3, if you received the same error you need to install the following patches on the Report Server.

  3. Download and install the following update:

Automatically create an Enum based on values in a database lookup table?

I've done this with a T4 template. It is fairly trivial to drop a .tt file into your project, and set up Visual Studio to run the T4 template as a pre-build step.

The T4 generates a .cs file, which means you can have it just query the database and build an enum in a .cs file from the result. Wired up as a pre-build task, it would re-create your enum on every build, or you can run the T4 manually as needed instead.

&& (AND) and || (OR) in IF statements

No, if a is true (in a or test), b will not be tested, as the result of the test will always be true, whatever is the value of the b expression.

Make a simple test:

if (true || ((String) null).equals("foobar")) {
    ...
}

will not throw a NullPointerException!

Android Text over image

There are many ways. You use RelativeLayout or AbsoluteLayout.

With relative, you can have the image align with parent on the left side for example and also have the text align to the parent left too... then you can use margins and padding and gravity on the text view to get it lined where you want over the image.

How to get SQL from Hibernate Criteria API (*not* for logging)

I like this if you want to get just some parts of the query:

new CriteriaQueryTranslator(
    factory,
    executableCriteria,
    executableCriteria.getEntityOrClassName(), 
    CriteriaQueryTranslator.ROOT_SQL_ALIAS)
        .getWhereCondition();

For instance something like this:

String where = new CriteriaQueryTranslator(
    factory,
    executableCriteria,
    executableCriteria.getEntityOrClassName(), 
    CriteriaQueryTranslator.ROOT_SQL_ALIAS)
        .getWhereCondition();

String sql = "update my_table this_ set this_.status = 0 where " + where;

JSON.Net Self referencing loop detected

I am using Dot.Net Core 3.1 and did an search for

"Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property "

I am adding this to this question, as it will be an easy reference. You should use the following in the Startup.cs file:

 services.AddControllers()
                .AddNewtonsoftJson(options =>
                {
                    // Use the default property (Pascal) casing
                    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                });

Get bitcoin historical data

Actually, you CAN get the whole Bitcoin trades history from Bitcoincharts in CSV format here : http://api.bitcoincharts.com/v1/csv/

it is updated twice a day for active exchanges, and there is a few dead exchanges, too.

EDIT: Since there are no column headers in the CSVs, here's what they are : column 1) the trade's timestamp, column 2) the price, column 3) the volume of the trade

How to make the overflow CSS property work with hidden as value

I did not get it. I had a similar problem but in my nav bar.

What I was doing is I kept my navBar code in this way: nav>div.navlinks>ul>li*3>a

In order to put hover effects on a I positioned a to relative and designed a::before and a::after then i put a gray background on before and after elements and kept hover effects in such way that as one hovers on <a> they will pop from outside a to fill <a>.

The problem is that the overflow hidden is not working on <a>.

What i discovered is if i removed <li> and simply put <a> without <ul> and <li> then it worked.

What may be the problem?

SQL: How to to SUM two values from different tables

For your current structure, you could also try the following:

select cash.Country, cash.Value, cheque.Value, cash.Value + cheque.Value as [Total]
from Cash
join Cheque
on cash.Country = cheque.Country

I think I prefer a union between the two tables, and a group by on the country name as mentioned above.

But I would also recommend normalising your tables. Ideally you'd have a country table, with Id and Name, and a payments table with: CountryId (FK to countries), Total, Type (cash/cheque)

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

Try adding the drive letter:

include_path='.;c:\xampplite\php\pear\PEAR'

also verify that PEAR.php is actually there, it might be in \php\ instead:

include_path='.;c:\xampplite\php'

Why do I have ORA-00904 even when the column is present?

It is because one of the DBs the column was created with " which makes its name case-sensitive.

Oracle Table Column Name : GoodRec Hive cannot recognize case sensitivity : ERROR thrown was - Caused by: java.sql.SQLSyntaxErrorException: ORA-00904: "GOODREC": invalid identifier

Solution : Rename Oracle column name to all caps.

Does a `+` in a URL scheme/host/path represent a space?

You can find a nice list of corresponding URL encoded characters on W3Schools.

  • + becomes %2B
  • space becomes %20

Magento Product Attribute Get Value

First we must ensure that the desired attribute is loaded, and then output it. Use this:

$product = Mage::getModel('catalog/product')->load('<product_id>', array('<attribute_code>'));
$attributeValue = $product->getResource()->getAttribute('<attribute_code>')->getFrontend()->getValue($product);

How to make ng-repeat filter out duplicate results

UPDATE

I was recomending the use of Set but sorry this doesn't work for ng-repeat, nor Map since ng-repeat only works with array. So ignore this answer. anyways if you need to filter out duplicates one way is as other has said using angular filters, here is the link for it to the getting started section.


Old answer

Yo can use the ECMAScript 2015 (ES6) standard Set Data structure, instead of an Array Data Structure this way you filter repeated values when adding to the Set. (Remember sets don't allow repeated values). Really easy to use:

var mySet = new Set();

mySet.add(1);
mySet.add(5);
mySet.add("some text");
var o = {a: 1, b: 2};
mySet.add(o);

mySet.has(1); // true
mySet.has(3); // false, 3 has not been added to the set
mySet.has(5);              // true
mySet.has(Math.sqrt(25));  // true
mySet.has("Some Text".toLowerCase()); // true
mySet.has(o); // true

mySet.size; // 4

mySet.delete(5); // removes 5 from the set
mySet.has(5);    // false, 5 has been removed

mySet.size; // 3, we just removed one value

Powershell remoting with ip-address as target

The error message is giving you most of what you need. This isn't just about the TrustedHosts list; it's saying that in order to use an IP address with the default authentication scheme, you have to ALSO be using HTTPS (which isn't configured by default) and provide explicit credentials. I can tell you're at least not using SSL, because you didn't use the -UseSSL switch.

Note that SSL/HTTPS is not configured by default - that's an extra step you'll have to take. You can't just add -UseSSL.

The default authentication mechanism is Kerberos, and it wants to see real host names as they appear in AD. Not IP addresses, not DNS CNAME nicknames. Some folks will enable Basic authentication, which is less picky - but you should also set up HTTPS since you'd otherwise pass credentials in cleartext. Enable-PSRemoting only sets up HTTP.

Adding names to your hosts file won't work. This isn't an issue of name resolution; it's about how the mutual authentication between computers is carried out.

Additionally, if the two computers involved in this connection aren't in the same AD domain, the default authentication mechanism won't work. Read "help about_remote_troubleshooting" for information on configuring non-domain and cross-domain authentication.

From the docs at http://technet.microsoft.com/en-us/library/dd347642.aspx

HOW TO USE AN IP ADDRESS IN A REMOTE COMMAND
-----------------------------------------------------
    ERROR:  The WinRM client cannot process the request. If the
    authentication scheme is different from Kerberos, or if the client
    computer is not joined to a domain, then HTTPS transport must be used
    or the destination machine must be added to the TrustedHosts
    configuration setting.

The ComputerName parameters of the New-PSSession, Enter-PSSession and
Invoke-Command cmdlets accept an IP address as a valid value. However,
because Kerberos authentication does not support IP addresses, NTLM
authentication is used by default whenever you specify an IP address. 

When using NTLM authentication, the following procedure is required
for remoting.

1. Configure the computer for HTTPS transport or add the IP addresses
   of the remote computers to the TrustedHosts list on the local
   computer.

   For instructions, see "How to Add a Computer to the TrustedHosts
   List" below.


2. Use the Credential parameter in all remote commands.

   This is required even when you are submitting the credentials
   of the current user.

How to get the selected item of a combo box to a string variable in c#

Test this

  var selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
  MessageBox.Show(selected);

getResourceAsStream returns null

So there are several ways to get a resource from a jar and each has slightly different syntax where the path needs to be specified differently.

The best explanation I have seen is this article from InfoWorld. I'll summarize here, but if you want to know more you should check out the article.

Methods

  1. ClassLoader.getResourceAsStream().

Format: "/"-separated names; no leading "/" (all names are absolute).

Example: this.getClass().getClassLoader().getResourceAsStream("some/pkg/resource.properties");

  1. Class.getResourceAsStream()

Format: "/"-separated names; leading "/" indicates absolute names; all other names are relative to the class's package

Example: this.getClass().getResourceAsStream("/some/pkg/resource.properties");

Updated Sep 2020: Changed article link. Original article was from Javaworld, it is now hosted on InfoWorld (and has many more ads)

Correct way to push into state array

Using react hooks, you can do following way

const [countryList, setCountries] = useState([]);


setCountries((countryList) => [
        ...countryList,
        "India",
      ]);

adding x and y axis labels in ggplot2

[Note: edited to modernize ggplot syntax]

Your example is not reproducible since there is no ex1221new (there is an ex1221 in Sleuth2, so I guess that is what you meant). Also, you don't need (and shouldn't) pull columns out to send to ggplot. One advantage is that ggplot works with data.frames directly.

You can set the labels with xlab() and ylab(), or make it part of the scale_*.* call.

library("Sleuth2")
library("ggplot2")
ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  xlab("My x label") +
  ylab("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area("Nitrogen") + 
  scale_x_continuous("My x label") +
  scale_y_continuous("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

An alternate way to specify just labels (handy if you are not changing any other aspects of the scales) is using the labs function

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  labs(size= "Nitrogen",
       x = "My x label",
       y = "My y label",
       title = "Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

which gives an identical figure to the one above.

Long press on UITableView

Just add UILongPressGestureRecognizer to the given prototype cell in storyboard, then pull the gesture to the viewController's .m file to create an action method. I made it as I said.

How to get all table names from a database?

If you want to use a high-level API, that hides a lot of the JDBC complexity around database schema metadata, take a look at this article: http://www.devx.com/Java/Article/32443/1954

How to use '-prune' option of 'find' in sh?

If you read all the good answers here my understanding now is that the following all return the same results:

find . -path ./dir1\*  -prune -o -print

find . -path ./dir1  -prune -o -print

find . -path ./dir1\*  -o -print
#look no prune at all!

But the last one will take a lot longer as it still searches out everything in dir1. I guess the real question is how to -or out unwanted results without actually searching them.

So I guess prune means don't decent past matches but mark it as done...

http://www.gnu.org/software/findutils/manual/html_mono/find.html "This however is not due to the effect of the ‘-prune’ action (which only prevents further descent, it doesn't make sure we ignore that item). Instead, this effect is due to the use of ‘-o’. Since the left hand side of the “or” condition has succeeded for ./src/emacs, it is not necessary to evaluate the right-hand-side (‘-print’) at all for this particular file."

How can I get the name of an html page in Javascript?

Current page: It's possible to do even shorter. This single line sound more elegant to find the current page's file name:

var fileName = location.href.split("/").slice(-1); 

or...

var fileName = location.pathname.split("/").slice(-1)

This is cool to customize nav box's link, so the link toward the current is enlighten by a CSS class.

JS:

$('.menu a').each(function() {
    if ($(this).attr('href') == location.href.split("/").slice(-1)){ $(this).addClass('curent_page'); }
});

CSS:

a.current_page { font-size: 2em; color: red; }

How to connect Bitbucket to Jenkins properly

I had a similar problems, till I got it working. Below is the full listing of the integration:

  1. Generate public/private keys pair: ssh-keygen -t rsa
  2. Copy the public key (~/.ssh/id_rsa.pub) and paste it in Bitbucket SSH keys, in user’s account management console: enter image description here

  3. Copy the private key (~/.ssh/id_rsa) to new user (or even existing one) with private key credentials, in this case, username will not make a difference, so username can be anything: enter image description here

  4. run this command to test if you can get access to Bitbucket account: ssh -T [email protected]

  5. OPTIONAL: Now, you can use your git to to copy repo to your desk without passwjord git clone [email protected]:username/repo_name.git
  6. Now you can enable Bitbucket hooks for Jenkins push notifications and automatic builds, you will do that in 2 steps:

    1. Add an authentication token inside the job/project you configure, it can be anything: enter image description here

    2. In Bitbucket hooks: choose jenkins hooks, and fill the fields as below: enter image description here

Where:

**End point**: username:usertoken@jenkins_domain_or_ip
**Project name**: is the name of job you created on Jenkins
**Token**: Is the authorization token you added in the above steps in your Jenkins' job/project 

Recommendation: I usually add the usertoken as the authorization Token (in both Jenkins Auth Token job configuration and Bitbucket hooks), making them one variable to ease things on myself.

How to change heatmap.2 color range in R?

I think you need to set symbreaks = FALSE That should allow for asymmetrical color scales.

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

You need to set Transaction for every Account.

foreach(Account account : accounts){
    account.setTransaction(transactionObj);
}

Or it colud be enough (if appropriate) to set ids to null on many side.

// list of existing accounts
List<Account> accounts = new ArrayList<>(transactionObj.getAccounts());

foreach(Account account : accounts){
    account.setId(null);
}

transactionObj.setAccounts(accounts);

// just persist transactionObj using EntityManager merge() method.

Authenticated HTTP proxy with Java

(EDIT: As pointed out by the OP, the using a java.net.Authenticator is required too. I'm updating my answer accordingly for the sake of correctness.)

(EDIT#2: As pointed out in another answer, in JDK 8 it's required to remove basic auth scheme from jdk.http.auth.tunneling.disabledSchemes property)

For authentication, use java.net.Authenticator to set proxy's configuration and set the system properties http.proxyUser and http.proxyPassword.

final String authUser = "user";
final String authPassword = "password";
Authenticator.setDefault(
  new Authenticator() {
    @Override
    public PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(authUser, authPassword.toCharArray());
    }
  }
);

System.setProperty("http.proxyUser", authUser);
System.setProperty("http.proxyPassword", authPassword);

System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");

How to define a preprocessor symbol in Xcode

In response to Kevin Laity's comment (see cdespinosa's answer), about the GCC Preprocessing section not showing in your build settings, make the Active SDK the one that says (Base SDK) after it and this section will appear. You can do this by choosing the menu Project > Set Active Target > XXX (Base SDK). In different versions of XCode (Base SDK) maybe different, like (Project Setting or Project Default).

After you get this section appears, you can add your definitions to Processor Macros rather than creating a user-defined setting.

How do I make the scrollbar on a div only visible when necessary?

Use overflow: auto. Scrollbars will only appear when needed.

(Sidenote, you can also specify for only the x, or y scrollbar: overflow-x: auto and overflow-y: auto).

How do I delete specific characters from a particular String in Java?

The best method is what Mark Byers explains:

s = s.substring(0, s.length() - 1)

For example, if we want to replace \ to space " " with ReplaceAll, it doesn't work fine

String.replaceAll("\\", "");

or

String.replaceAll("\\$", "");   //if it is a path

.autocomplete is not a function Error

For my case, my another team member included another version of jquery.js when he add in bootstrap.min.js. After remove the extra jquery.js, the problem is solved

How to run script as another user without password?

Call visudo and add this:

user1 ALL=(user2) NOPASSWD: /home/user2/bin/test.sh

The command paths must be absolute! Then call sudo -u user2 /home/user2/bin/test.sh from a user1 shell. Done.

How do I extract text that lies between parentheses (round brackets)?

input.Remove(input.IndexOf(')')).Substring(input.IndexOf('(') + 1);

How do I make a text input non-editable?

you just need to add disabled at the end

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

How to convert a byte array to a hex string in Java?

Here's yet another method using Streams:

private static String toHexString(byte[] bytes) {
    return IntStream.range(0, bytes.length)
    .mapToObj(i -> String.format("%02X", bytes[i]))
    .collect(Collectors.joining());
}

Regular expression for a string that does not start with a sequence

You could use a negative look-ahead assertion:

^(?!tbd_).+

Or a negative look-behind assertion:

(^.{1,3}$|^.{4}(?<!tbd_).*)

Or just plain old character sets and alternations:

^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*

is the + operator less performant than StringBuffer.append()

JavaScript doesn't have a native StringBuffer object, so I'm assuming this is from a library you are using, or a feature of an unusual host environment (i.e. not a browser).

I doubt a library (written in JS) would produce anything faster, although a native StringBuffer object might. The definitive answer can be found with a profiler (if you are running in a browser then Firebug will provide you with a profiler for the JS engine found in Firefox).

Proper MIME media type for PDF files

The standard MIME type is application/pdf. The assignment is defined in RFC 3778, The application/pdf Media Type, referenced from the MIME Media Types registry.

MIME types are controlled by a standards body, The Internet Assigned Numbers Authority (IANA). This is the same organization that manages the root name servers and the IP address space.

The use of x-pdf predates the standardization of the MIME type for PDF. MIME types in the x- namespace are considered experimental, just as those in the vnd. namespace are considered vendor-specific. x-pdf might be used for compatibility with old software.

Reference member variables as class members

C++ provides a good mechanism to manage the life time of an object though class/struct constructs. This is one of the best features of C++ over other languages.

When you have member variables exposed through ref or pointer it violates the encapsulation in principle. This idiom enables the consumer of the class to change the state of an object of A without it(A) having any knowledge or control of it. It also enables the consumer to hold on to a ref/pointer to A's internal state, beyond the life time of the object of A. This is bad design. Instead the class could be refactored to hold a ref/pointer to the shared object (not own it) and these could be set using the constructor (Mandate the life time rules). The shared object's class may be designed to support multithreading/concurrency as the case may apply.

Update row with data from another row in the same table

Try this:

UPDATE data_table t, (SELECT DISTINCT ID, NAME, VALUE
                        FROM data_table
                       WHERE VALUE IS NOT NULL AND VALUE != '') t1
   SET t.VALUE = t1.VALUE
 WHERE t.ID = t1.ID
   AND t.NAME = t1.NAME

Boolean vs boolean in Java

I am a bit extending provided answers (since so far they concentrate on their "own"/artificial terminology focusing on programming a particular language instead of taking care of the bigger picture behind the scene of creating the programming languages, in general, i.e. when things like type-safety vs. memory considerations make the difference):

int is not boolean

Consider

    boolean bar = true;      
    System.out.printf("Bar is %b\n", bar);
    System.out.printf("Bar is %d\n", (bar)?1:0);
    int baz = 1;       
    System.out.printf("Baz is %d\n", baz);
    System.out.printf("Baz is %b\n", baz);

with output

    Bar is true
    Bar is 1
    Baz is 1
    Baz is true

Java code on 3rd line (bar)?1:0 illustrates that bar (boolean) cannot be implicitly converted (casted) into an int. I am bringing this up not to illustrate the details of implementation behind JVM, but to point out that in terms of low level considerations (as memory size) one does have to prefer values over type safety. Especially if that type safety is not truly/fully used as in boolean types where checks are done in form of

if value \in {0,1} then cast to boolean type, otherwise throw an exception.

All just to state that {0,1} < {-2^31, .. , 2^31 -1}. Seems like an overkill, right? Type safety is truly important in user defined types, not in implicit casting of primitives (although last are included in the first).

Bytes are not types or bits

Note that in memory your variable from range of {0,1} will still occupy at least a byte or a word (xbits depending on the size of the register) unless specially taken care of (e.g. packed nicely in memory - 8 "boolean" bits into 1 byte - back and forth).

By preferring type safety (as in putting/wrapping value into a box of a particular type) over extra value packing (e.g. using bit shifts or arithmetic), one does effectively chooses writing less code over gaining more memory. (On the other hand one can always define a custom user type which will facilitate all the conversion not worth than Boolean).

keyword vs. type

Finally, your question is about comparing keyword vs. type. I believe it is important to explain why or how exactly you will get performance by using/preferring keywords ("marked" as primitive) over types (normal composite user-definable classes using another keyword class) or in other words

boolean foo = true;

vs.

Boolean foo = true;

The first "thing" (type) can not be extended (subclassed) and not without a reason. Effectively Java terminology of primitive and wrapping classes can be simply translated into inline value (a LITERAL or a constant that gets directly substituted by compiler whenever it is possible to infer the substitution or if not - still fallback into wrapping the value).

Optimization is achieved due to trivial:

"Less runtime casting operations => more speed."

That is why when the actual type inference is done it may (still) end up in instantiating of wrapping class with all the type information if necessary (or converting/casting into such).

So, the difference between boolean and Boolean is exactly in Compilation and Runtime (a bit far going but almost as instanceof vs. getClass()).

Finally, autoboxing is slower than primitives

Note the fact that Java can do autoboxing is just a "syntactic sugar". It does not speed up anything, just allows you to write less code. That's it. Casting and wrapping into type information container is still performed. For performance reasons choose arithmetics which will always skip extra housekeeping of creating class instances with type information to implement type safety. Lack of type safety is the price you pay to gain performance. For code with boolean-valued expressions type safety (when you write less and hence implicit code) would be critical e.g. for if-then-else flow controls.

How do I 'foreach' through a two-dimensional array?

Multidimensional arrays aren't enumerable. Just iterate the good old-fashioned way:

for (int i = 0; i < table.GetLength(0); i++)
{
    Console.WriteLine(table[i, 0] + " " + table[i, 1]);
}

Win32Exception (0x80004005): The wait operation timed out

EfCore version of @JonSchneider's answer

myDbContext.Database.SetCommandTimeout(999);

Where myDbContext is your DbContext instance, and 999 is the timeout value in seconds.

(Syntax current as of Entity Framework Core 3.1)

Populate nested array in mongoose

You can populate multiple nested documents like this.

   Project.find(query)
    .populate({ 
      path: 'pages',
      populate: [{
       path: 'components',
       model: 'Component'
      },{
        path: 'AnotherRef',
        model: 'AnotherRef',
        select: 'firstname lastname'
      }] 
   })
   .exec(function(err, docs) {});

SELECT INTO a table variable in T-SQL

OK, Now with enough effort i am able to insert into @table using the below :

INSERT @TempWithheldTable SELECT
a.SuspendedReason, a.SuspendedNotes, a.SuspendedBy , a.ReasonCode FROM OPENROWSET( BULK 'C:\DataBases\WithHeld.csv', FORMATFILE = N'C:\DataBases\Format.txt',
ERRORFILE=N'C:\Temp\MovieLensRatings.txt' ) AS a;

The main thing here is selecting columns to insert .

Convert generator object to list for debugging

Simply call list on the generator.

lst = list(gen)
lst

Be aware that this affects the generator which will not return any further items.

You also cannot directly call list in IPython, as it conflicts with a command for listing lines of code.

Tested on this file:

def gen():
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5
import ipdb
ipdb.set_trace()

g1 = gen()

text = "aha" + "bebe"

mylst = range(10, 20)

which when run:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.

General method for escaping function/variable/debugger name conflicts

There are debugger commands p and pp that will print and prettyprint any expression following them.

So you could use it as follows:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c

There is also an exec command, called by prefixing your expression with !, which forces debugger to take your expression as Python one.

ipdb> !list(g1)
[]

For more details see help p, help pp and help exec when in debugger.

ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']

Grep to find item in Perl array

You can also check single value in multiple arrays like,

if (grep /$match/, @array, @array_one, @array_two, @array_Three)
{
    print "found it\n";
}

How to define static constant in a class in swift

Adding to @Martin's answer...

If anyone planning to keep an application level constant file, you can group the constant based on their type or nature

struct Constants {
    struct MixpanelConstants {
        static let activeScreen = "Active Screen";
    }
    struct CrashlyticsConstants {
        static let userType = "User Type";
    }
}

Call : Constants.MixpanelConstants.activeScreen

UPDATE 5/5/2019 (kinda off topic but ???)

After reading some code guidelines & from personal experiences it seems structs are not the best approach for storing global constants for a couple of reasons. Especially the above code doesn't prevent initialization of the struct. We can achieve it by adding some boilerplate code but there is a better approach

ENUMS

The same can be achieved using an enum with a more secure & clear representation

enum Constants {
    enum MixpanelConstants: String {
        case activeScreen = "Active Screen";
    }
    enum CrashlyticsConstants: String {
        case userType = "User Type";
    }
}

print(Constants.MixpanelConstants.activeScreen.rawValue)

Disable automatic sorting on the first column when using jQuery DataTables

In the newer version of datatables (version 1.10.7) it seems things have changed. The way to prevent DataTables from automatically sorting by the first column is to set the order option to an empty array.

You just need to add the following parameter to the DataTables options:

"order": [] 

Set up your DataTable as follows in order to override the default setting:

$('#example').dataTable( {
    "order": [],
    // Your other options here...
} );

That will override the default setting of "order": [[ 0, 'asc' ]].

You can find more details regarding the order option here: https://datatables.net/reference/option/order

Pass variables to AngularJS controller, best practice?

You could create a basket service. And generally in JS you use objects instead of lots of parameters.

Here's an example: http://jsfiddle.net/2MbZY/

var app = angular.module('myApp', []);

app.factory('basket', function() {
    var items = [];
    var myBasketService = {};

    myBasketService.addItem = function(item) {
        items.push(item);
    };
    myBasketService.removeItem = function(item) {
        var index = items.indexOf(item);
        items.splice(index, 1);
    };
    myBasketService.items = function() {
        return items;
    };

    return myBasketService;
});

function MyCtrl($scope, basket) {
    $scope.newItem = {};
    $scope.basket = basket;    
}

Button button = findViewById(R.id.button) always resolves to null in Android Studio

The button code should be moved to the PlaceholderFragment() class. There you will call the layout fragment_main.xml in the onCreateView method. Like so

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_main, container, false);
    Button buttonClick = (Button) view.findViewById(R.id.button);
    buttonClick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onButtonClick((Button) view);
        }

    });

    return view;
}

Squash my last X commits together using Git

In question it could be ambiguous what is meant by "last".

for example git log --graph outputs the following (simplified):

* commit H0
|
* merge
|\
| * commit B0
| |
| * commit B1
| | 
* | commit H1
| |
* | commit H2
|/
|

Then last commits by time are H0, merge, B0. To squash them you will have to rebase your merged branch on commit H1.

The problem is that H0 contains H1 and H2 (and generally more commits before merge and after branching) while B0 don't. So you have to manage changes from H0, merge, H1, H2, B0 at least.

It's possible to use rebase but in different manner then in others mentioned answers:

rebase -i HEAD~2

This will show you choice options (as mentioned in other answers):

pick B1
pick B0
pick H0

Put squash instead of pick to H0:

pick B1
pick B0
s H0

After save and exit rebase will apply commits in turn after H1. That means that it will ask you to resolve conflicts again (where HEAD will be H1 at first and then accumulating commits as they are applied).

After rebase will finish you can choose message for squashed H0 and B0:

* commit squashed H0 and B0
|
* commit B1
| 
* commit H1
|
* commit H2
|

P.S. If you just do some reset to BO: (for example, using reset --mixed that is explained in more detail here https://stackoverflow.com/a/18690845/2405850):

git reset --mixed hash_of_commit_B0
git add .
git commit -m 'some commit message'

then you squash into B0 changes of H0, H1, H2 (losing completely commits for changes after branching and before merge.

Argument of type 'X' is not assignable to parameter of type 'X'

In my case, it was that I had a custom interface called Item, but I imported accidentally because of the auto-completion, the angular Item class. Be sure that you're importing from the right package.

"Conversion to Dalvik format failed with error 1" on external JAR

What worked for me are the following:

  • Clean the build completely
  • Removed the extraneous android.jar file that I found in Project/Properties/Libraries.

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

Sorry, misunderstood your question.

According to Javascript - capturing onsubmit when calling form.submit():

I was recently asked: "Why doesn't the form.onsubmit event get fired when I submit my form using javascript?"

The answer: Current browsers do not adhere to this part of the html specification. The event only fires when it is activated by a user - and does not fire when activated by code.

(emphasis added).

Note: "activated by a user" also includes hitting submit buttons (probably including default submit behaviour from the enter key but I haven't tried this). Nor, I believe, does it get triggered if you (with code) click a submit button.

Easier way to create circle div than using an image?

You can try the radial-gradient CSS function:

.circle {
    width: 500px;
    height: 500px;
    border-radius: 50%;
    background: #ffffff; /* Old browsers */
    background: -moz-radial-gradient(center, ellipse cover, #ffffff 17%, #ff0a0a 19%, #ff2828 40%, #000000 41%); /* FF3.6-15 */
    background: -webkit-radial-gradient(center, ellipse cover, #ffffff 17%,#ff0a0a 19%,#ff2828 40%,#000000 41%); /* Chrome10-25,Safari5.1-6 */
    background: radial-gradient(ellipse at center, #ffffff 17%,#ff0a0a 19%,#ff2828 40%,#000000 41%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
}

Apply it to a div layer:

<div class="circle"></div>

Eclipse hangs on loading workbench

After some investigation about file dates I solved the same issue (which is a randomly recurrent trouble on my Kepler) by simply deleting the following file in my local workspace: .metadata.plugins\org.eclipse.jdt.core\variablesAndContainers.dat

with negligible impact on the workspace restoring.

I hope it can help someone else...

Adding dictionaries together, Python

dic0.update(dic1)

Note this doesn't actually return the combined dictionary, it just mutates dic0.

Zero an array in C code

int arr[20] = {0};

C99 [$6.7.8/21]

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.


Error: Selection does not contain a main type

Put your Main Java class file in src/main/java folder and check if there is not any error in 'Java Build Path' by following right click on project and select Java Build Path->Source.

Sorting data based on second column of a file

You can use the sort command:

sort -k2 -n yourfile

-n, --numeric-sort compare according to string numerical value

For example:

$ cat ages.txt 
Bob 12
Jane 48
Mark 3
Tashi 54

$ sort -k2 -n ages.txt 
Mark 3
Bob 12
Jane 48
Tashi 54

How to use multiple databases in Laravel

Laravel has inbuilt support for multiple database systems, you need to provide connection details in config/database.php file

return [
    'default' => env('DB_CONNECTION', 'mysql'),

    'connections' => [
        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],
'mysqlOne' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST_ONE', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE_ONE', 'forge'),
            'username' => env('DB_USERNAME_ONE', 'forge'),
            'password' => env('DB_PASSWORD_ONE', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],
];

Once you have this you can create two base model class for each connection and define the connection name in those models

//BaseModel.php
protected $connection = 'mysql';

//BaseModelOne.php
protected $connection = 'mysqlOne';

You can extend these models to create more models for tables in each DB.

How to enable DataGridView sorting when user clicks on the column header?

your data grid needs to be bound to a sortable list in the first place.

Create this event handler:

    void MakeColumnsSortable_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        //Add this as an event on DataBindingComplete
        DataGridView dataGridView = sender as DataGridView;
        if (dataGridView == null)
        {
            var ex = new InvalidOperationException("This event is for a DataGridView type senders only.");
            ex.Data.Add("Sender type", sender.GetType().Name);
            throw ex;
        }

        foreach (DataGridViewColumn column in dataGridView.Columns)
            column.SortMode = DataGridViewColumnSortMode.Automatic;
    }

And initialize the event of each of your datragrids like this:

        dataGridView1.DataBindingComplete += MakeColumnsSortable_DataBindingComplete;

drag drop files into standard html file input

The following works in Chrome and FF, but i've yet to find a solution that covers IE10+ as well:

_x000D_
_x000D_
// dragover and dragenter events need to have 'preventDefault' called_x000D_
// in order for the 'drop' event to register. _x000D_
// See: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Drag_operations#droptargets_x000D_
dropContainer.ondragover = dropContainer.ondragenter = function(evt) {_x000D_
  evt.preventDefault();_x000D_
};_x000D_
_x000D_
dropContainer.ondrop = function(evt) {_x000D_
  // pretty simple -- but not for IE :(_x000D_
  fileInput.files = evt.dataTransfer.files;_x000D_
_x000D_
  // If you want to use some of the dropped files_x000D_
  const dT = new DataTransfer();_x000D_
  dT.items.add(evt.dataTransfer.files[0]);_x000D_
  dT.items.add(evt.dataTransfer.files[3]);_x000D_
  fileInput.files = dT.files;_x000D_
_x000D_
  evt.preventDefault();_x000D_
};
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
<div id="dropContainer" style="border:1px solid black;height:100px;">_x000D_
   Drop Here_x000D_
</div>_x000D_
  Should update here:_x000D_
  <input type="file" id="fileInput" />_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

You'll probably want to use addEventListener or jQuery (etc.) to register your evt handlers - this is just for brevity's sake.

Div with horizontal scrolling only

I couldn't get the selected answer to work but after a bit of research, I found that the horizontal scrolling div must have white-space: nowrap in the css.

Here's complete working code:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Something</title>
    <style type="text/css">
        #scrolly{
            width: 1000px;
            height: 190px;
            overflow: auto;
            overflow-y: hidden;
            margin: 0 auto;
            white-space: nowrap
        }

        img{
            width: 300px;
            height: 150px;
            margin: 20px 10px;
            display: inline;
        }
    </style>
</head>
<body>
    <div id='scrolly'>
        <img src='img/car.jpg'></img>
        <img src='img/car.jpg'></img>
        <img src='img/car.jpg'></img>
        <img src='img/car.jpg'></img>
        <img src='img/car.jpg'></img>
        <img src='img/car.jpg'></img>
    </div>
</body>
</html>

How do I turn off Unicode in a VC++ project?

From VS2019 Project Properties - Advanced - Advanced Properties - Character Set enter image description here

Also if there is _UNICODE;UNICODE Preprocessors Definitions remove them. Project Properties - C/C++ - Preprocessor - Preprocessor Definition enter image description here

How to read file binary in C#?

using (FileStream fs = File.OpenRead(binarySourceFile.Path))
    using (BinaryReader reader = new BinaryReader(fs))
    {              
        // Read in all pairs.
        while (reader.BaseStream.Position != reader.BaseStream.Length)
        {
            Item item = new Item();
            item.UniqueId = reader.ReadString();
            item.StringUnique = reader.ReadString();
            result.Add(item);
        }
    }
    return result;  

MySQL load NULL values from CSV data

MySQL manual says:

When reading data with LOAD DATA INFILE, empty or missing columns are updated with ''. If you want a NULL value in a column, you should use \N in the data file. The literal word “NULL” may also be used under some circumstances.

So you need to replace the blanks with \N like this:

1,2,3,4,5
1,2,3,\N,5
1,2,3

How do I add items to an array in jQuery?

Since $.getJSON is async, I think your console.log(list.length); code is firing before your array has been populated. To correct this put your console.log statement inside your callback:

var list = new Array();
$.getJSON("json.js", function(data) {
    $.each(data, function(i, item) {
        console.log(item.text);
        list.push(item.text);
    });
    console.log(list.length);
});

How to keep keys/values in same order as declared?

Note that this answer applies to python versions prior to python3.7. CPython 3.6 maintains insertion order under most circumstances as an implementation detail. Starting from Python3.7 onward, it has been declared that implementations MUST maintain insertion order to be compliant.


python dictionaries are unordered. If you want an ordered dictionary, try collections.OrderedDict.

Note that OrderedDict was introduced into the standard library in python 2.7. If you have an older version of python, you can find recipes for ordered dictionaries on ActiveState.

Differences between Emacs and Vim

Seems an answer has been selected already, but the big difference to me has always been the modal vs. non-modal. Vim is modal, which means that it makes optimizations based on a specific set of usage modes. At least that's how I've always looked at it. This makes using Vim a different experience because instead of having a work area that you type code in, you really are telling an environment to act on the text. This is why people say things like with Vim you really are learning a language. The :wq and :s/foo/bar is all part of a shell like environment that edits and reads text.

Emacs on the other hand is much closer to most editors/word processors/etc. you see today. You have a workspace that has a highly programmable interface. That is why you see things like email, irc, shells, etc. As a programmer it is easy to think in terms of saying "take the line number I'm on and do something with the information". The desire to leave the editor becomes less because instead of having to quit, open some other app/language and do things on some text, you have Emacs where you can do these things within the scope of your editor.

The two ideas are not necessarily contrasting, but it is simply that they reveal two different focuses. Personally I use Emacs, but I've seen folks who know Vim really well and can honestly say it doesn't matter which you choose. I tried Vim first but Emacs ended up sticking for me. It is true that no matter what you choose, you should be at least somewhat proficient in Vim as it really is always available.

How can I make an entire HTML form "readonly"?

You add html invisible layer over the form. For instance

<div class="coverContainer">
<form></form>
</div>

and style:

.coverContainer{
    width: 100%;
    height: 100%;
    z-index: 100;
    background: rgba(0,0,0,0);
    position: absolute;
}

Ofcourse user can hide this layer in web browser.

How do you implement a re-try-catch?

https://github.com/tusharmndr/retry-function-wrapper/tree/master/src/main/java/io

int MAX_RETRY = 3; 
RetryUtil.<Boolean>retry(MAX_RETRY,() -> {
    //Function to retry
    return true;
});

Listening for variable changes in JavaScript

Easiest way I have found, starting from this answer:

// variable holding your data
const state = {
  count: null,
  update() {
    console.log(`this gets called and your value is ${this.pageNumber}`);
  },
  get pageNumber() {
    return this.count;
  },
  set pageNumber(pageNumber) {
    this.count = pageNumber;
    // here you call the code you need
    this.update(this.count);
  }
};

And then:

state.pageNumber = 0;
// watch the console

state.pageNumber = 15;
// watch the console

Using Font Awesome icon for bullet points, with a single list item element

I'd like to build upon some of the answers above and given elsewhere and suggest using absolute positioning along with the :before pseudo class. A lot of the examples above (and in similar questions) are utilizing custom HTML markup, including Font Awesome's method of handling. This goes against the original question, and isn't strictly necessary.

DEMO HERE

ul {
  list-style-type: none;
  padding-left: 20px;
}

li {
  position: relative;
  padding-left: 20px;
  margin-bottom: 10px
}

li:before {
  position: absolute;
  top: 0;
  left: 0;
  font-family: FontAwesome;
  content: "\f058";
  color: green;
}

That's basically it. You can get the ISO value for use in CSS content on the Font Awesome cheatsheet. Simply use the last 4 alphanumerics prefixed with a backslash. So [&#xf058;] becomes \f058

Does a valid XML file require an XML declaration?

Xml declaration is optional so your xml is well-formed without it. But it is recommended to use it so that wrong assumptions are not made by the parsers, specifically about the encoding used.

Is key-value observation (KVO) available in Swift?

This may be prove helpful to few people -

// MARK: - KVO

var observedPaths: [String] = []

func observeKVO(keyPath: String) {
    observedPaths.append(keyPath)
    addObserver(self, forKeyPath: keyPath, options: [.old, .new], context: nil)
}

func unObserveKVO(keyPath: String) {
    if let index = observedPaths.index(of: keyPath) {
        observedPaths.remove(at: index)
    }
    removeObserver(self, forKeyPath: keyPath)
}

func unObserveAllKVO() {
    for keyPath in observedPaths {
        removeObserver(self, forKeyPath: keyPath)
    }
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if let keyPath = keyPath {
        switch keyPath {
        case #keyPath(camera.iso):
            slider.value = camera.iso
        default:
            break
        }
    }
}

I had used KVO in this way in Swift 3. You can use this code with few changes.

Concatenating Files And Insert New Line In Between Files

If you have few enough files that you can list each one, then you can use process substitution in Bash, inserting a newline between each pair of files:

cat File1.txt <(echo) File2.txt <(echo) File3.txt > finalfile.txt

Start an activity from a fragment

If you are using getActivity() then you have to make sure that the calling activity is added already. If activity has not been added in such case so you may get null when you call getActivity()

in such cases getContext() is safe

then the code for starting the activity will be slightly changed like,

Intent intent = new Intent(getContext(), mFragmentFavorite.class);
startActivity(intent);

Activity, Service and Application extends ContextWrapper class so you can use this or getContext() or getApplicationContext() in the place of first argument.

scp with port number specified

Unlike ssh, scp uses the uppercase P switch to set the port instead of the lowercase p:

scp -P 80 ... # Use port 80 to bypass the firewall, instead of the scp default

The lowercase p switch is used with scp for the preservation of times and modes.

Here is an excerpt from scp's man page with all of the details concerning the two switches, as well as an explanation of why uppercase P was chosen for scp:

-P port   Specifies the port to connect to on the remote host. Note that this option is written with a capital 'P', because -p is already reserved for preserving the times and modes of the file in rcp(1).

-p           Preserves modification times, access times, and modes from the original file.

Update and aside to address one of the (heavily upvoted) comments:

With regard to Abdull's comment about scp option order, what he suggests:

scp -P80 -r some_directory -P 80 ...

..., intersperses options and parameters. getopt(1) clearly defines that parameters must come after options and not be interspersed with them:

The parameters getopt is called with can be divided into two parts: options which modify the way getopt will do the parsing (the options and the optstring in the SYNOPSIS), and the parameters which are to be parsed (parameters in the SYNOPSIS). The second part will start at the first non-option parameter that is not an option argument, or after the first occurrence of '--'. If no '-o' or '--options' option is found in the first part, the first parameter of the second part is used as the short options string.

Since the -r command line option takes no further arguments, some_directory is "the first non-option parameter that is not an option argument." Therefore, as clearly spelled out in the getopt(1) man page, all succeeding command line arguments that follow it (i.e., -P 80 ...) are assumed to be non-options (and non-option arguments).

So, in effect, this is how getopt(1) sees the example presented with the end of the options and the beginning of the parameters demarcated by succeeding text bing in gray:

scp -P80 -r some_directory -P 80 ...

This has nothing to do with scp behavior and everything to do with how POSIX standard applications parse command line options using the getopt(3) set of C functions.

For more details with regard to command line ordering and processing, please read the getopt(1) manpage using:

man 1 getopt

Event for Handling the Focus of the EditText

  1. Declare object of EditText on top of class:

     EditText myEditText;
    
  2. Find EditText in onCreate Function and setOnFocusChangeListener of EditText:

    myEditText = findViewById(R.id.yourEditTextNameInxml); 
    
    myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean hasFocus) {
                    if (!hasFocus) {
                         Toast.makeText(this, "Focus Lose", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(this, "Get Focus", Toast.LENGTH_SHORT).show();
                    }
    
                }
            });
    

It works fine.

SQLAlchemy IN clause

How about

session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all()

edit: Without the ORM, it would be

session.execute(
    select(
        [MyUserTable.c.id, MyUserTable.c.name], 
        MyUserTable.c.id.in_((123, 456))
    )
).fetchall()

select() takes two parameters, the first one is a list of fields to retrieve, the second one is the where condition. You can access all fields on a table object via the c (or columns) property.

Prevent double submission of forms in jQuery

Nathan's code but for jQuery Validate plugin

If you happen to use jQuery Validate plugin, they already have submit handler implemented, and in that case there is no reason to implement more than one. The code:

jQuery.validator.setDefaults({
  submitHandler: function(form){
    // Prevent double submit
    if($(form).data('submitted')===true){
      // Previously submitted - don't submit again
      return false;
    } else {
      // Mark form as 'submitted' so that the next submit can be ignored
      $(form).data('submitted', true);
      return true;
    }
  }
});

You can easily expand it within the } else {-block to disable inputs and/or submit button.

Cheers

How to express a NOT IN query with ActiveRecord/Rails?

The original post specifically mentions using numeric IDs, but I came here looking for the syntax for doing a NOT IN with an array of strings.

ActiveRecord will handle that nicely for you too:

Thing.where(['state NOT IN (?)', %w{state1 state2}])

Easiest way to pass an AngularJS scope variable from directive to controller?

Edited on 2014/8/25: Here was where I forked it.

Thanks @anvarik.

Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @

<div ng-controller="MyCtrl">
    <h2>Parent Scope</h2>
    <input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>    
    <br><br>
    <!-- attribute-foo binds to a DOM attribute which is always
    a string. That is why we are wrapping it in curly braces so
    that it can be interpolated. -->
    <my-component attribute-foo="{{foo}}" binding-foo="foo"
        isolated-expression-foo="updateFoo(newFoo)" >
        <h2>Attribute</h2>
        <div>
            <strong>get:</strong> {{isolatedAttributeFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedAttributeFoo">
            <i>// This does not update the parent scope.</i>
        </div>
        <h2>Binding</h2>
        <div>
            <strong>get:</strong> {{isolatedBindingFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedBindingFoo">
            <i>// This does update the parent scope.</i>
        </div>
        <h2>Expression</h2>    
        <div>
            <input ng-model="isolatedFoo">
            <button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
            <i>// And this calls a function on the parent scope.</i>
        </div>
    </my-component>
</div>
var myModule = angular.module('myModule', [])
    .directive('myComponent', function () {
        return {
            restrict:'E',
            scope:{
                /* NOTE: Normally I would set my attributes and bindings
                to be the same name but I wanted to delineate between
                parent and isolated scope. */                
                isolatedAttributeFoo:'@attributeFoo',
                isolatedBindingFoo:'=bindingFoo',
                isolatedExpressionFoo:'&'
            }        
        };
    })
    .controller('MyCtrl', ['$scope', function ($scope) {
        $scope.foo = 'Hello!';
        $scope.updateFoo = function (newFoo) {
            $scope.foo = newFoo;
        }
    }]);

semaphore implementation

The fundamental issue with your code is that you mix two APIs. Unfortunately online resources are not great at pointing this out, but there are two semaphore APIs on UNIX-like systems:

  • POSIX IPC API, which is a standard API
  • System V API, which is coming from the old Unix world, but practically available almost all Unix systems

Looking at the code above you used semget() from the System V API and tried to post through sem_post() which comes from the POSIX API. It is not possible to mix them.

To decide which semaphore API you want you don't have so many great resources. The simple best is the "Unix Network Programming" by Stevens. The section that you probably interested in is in Vol #2.

These two APIs are surprisingly different. Both support the textbook style semaphores but there are a few good and bad points in the System V API worth mentioning:

  • it builds on semaphore sets, so once you created an object with semget() that is a set of semaphores rather then a single one
  • the System V API allows you to do atomic operations on these sets. so you can modify or wait for multiple semaphores in a set
  • the SysV API allows you to wait for a semaphore to reach a threshold rather than only being non-zero. waiting for a non-zero threshold is also supported, but my previous sentence implies that
  • the semaphore resources are pretty limited on every unixes. you can check these with the 'ipcs' command
  • there is an undo feature of the System V semaphores, so you can make sure that abnormal program termination doesn't leave your semaphores in an undesired state

Group By Eloquent ORM

Eloquent uses the query builder internally, so you can do:

$users = User::orderBy('name', 'desc')
                ->groupBy('count')
                ->having('count', '>', 100)
                ->get();

Empty or Null value display in SSRS text boxes

I had a similar situation but the following worked best for me..

=Iif(Fields!Sales_Diff.Value)>1,Fields!Sales_Diff.Value),"")

Convert ascii char[] to hexadecimal char[] in C

void atoh(char *ascii_ptr, char *hex_ptr,int len)
{
    int i;

    for(i = 0; i < (len / 2); i++)
    {

        *(hex_ptr+i)   = (*(ascii_ptr+(2*i)) <= '9') ? ((*(ascii_ptr+(2*i)) - '0') * 16 ) :  (((*(ascii_ptr+(2*i)) - 'A') + 10) << 4);
        *(hex_ptr+i)  |= (*(ascii_ptr+(2*i)+1) <= '9') ? (*(ascii_ptr+(2*i)+1) - '0') :  (*(ascii_ptr+(2*i)+1) - 'A' + 10);

    }


}

Converting a SimpleXML Object to an Array

I found this in the PHP manual comments:

/**
 * function xml2array
 *
 * This function is part of the PHP manual.
 *
 * The PHP manual text and comments are covered by the Creative Commons 
 * Attribution 3.0 License, copyright (c) the PHP Documentation Group
 *
 * @author  k dot antczak at livedata dot pl
 * @date    2011-04-22 06:08 UTC
 * @link    http://www.php.net/manual/en/ref.simplexml.php#103617
 * @license http://www.php.net/license/index.php#doc-lic
 * @license http://creativecommons.org/licenses/by/3.0/
 * @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
 */
function xml2array ( $xmlObject, $out = array () )
{
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

    return $out;
}

It could help you. However, if you convert XML to an array you will loose all attributes that might be present, so you cannot go back to XML and get the same XML.

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

For Win7 Acrobat Pro X

Since I did all these without rechecking to see if the problem still existed afterwards, I am not sure which on of these actually fixed the problem, but one of them did. In fact, after doing the #3 and rebooting, it worked perfectly.

FYI: Below is the order in which I stepped through the repair.

  1. Go to Control Panel > folders options under each of the General, View and Search Tabs click the Restore Defaults button and the Reset Folders button

  2. Go to Internet Explorer, Tools > Options > Advanced > Reset ( I did not need to delete personal settings)

  3. Open Acrobat Pro X, under Edit > Preferences > General.
    At the bottom of page select Default PDF Handler. I chose Adobe Pro X, and click Apply.

You may be asked to reboot (I did).

Best Wishes

Python "SyntaxError: Non-ASCII character '\xe2' in file"

I had the same issue but it was because I copied and pasted the string as it is. Later when I manually typed the string as it is the error vanished.

I had the error due to the - sign. When I replaced it with manually inputting a - the error was solved.

Copied string 10 + 3 * 5/(16 - 4)

Manually typed string 10 + 3 * 5/(16 - 4)

you can clearly see there is a bit of difference between both the hyphens.

I think it's because of the different formatting used by different OS or maybe just different software.

How do you test that a Python function throws an exception?

I just discovered that the Mock library provides an assertRaisesWithMessage() method (in its unittest.TestCase subclass), which will check not only that the expected exception is raised, but also that it is raised with the expected message:

from testcase import TestCase

import mymod

class MyTestCase(TestCase):
    def test1(self):
        self.assertRaisesWithMessage(SomeCoolException,
                                     'expected message',
                                     mymod.myfunc)

Kotlin - Property initialization using "by lazy" vs. "lateinit"

lateinit vs lazy

  1. lateinit

    i) Use it with mutable variable[var]

     lateinit var name: String       //Allowed
     lateinit val name: String       //Not Allowed
    

ii) Allowed with only non-nullable data types

    lateinit var name: String       //Allowed
    lateinit var name: String?      //Not Allowed

iii) It is a promise to compiler that the value will be initialized in future.

NOTE: If you try to access lateinit variable without initializing it then it throws UnInitializedPropertyAccessException.

  1. lazy

    i) Lazy initialization was designed to prevent unnecessary initialization of objects.

ii) Your variable will not be initialized unless you use it.

iii) It is initialized only once. Next time when you use it, you get the value from cache memory.

iv) It is thread safe(It is initialized in the thread where it is used for the first time. Other threads use the same value stored in the cache).

v) The variable can only be val.

vi) The variable can only be non-nullable.

How to replace four spaces with a tab in Sublime Text 2?

On main menu;

View -> Indentation -> Convert Indentation to Tabs / Spaces

Could not open a connection to your authentication agent

For PowerShell in Windows

I was having trouble with PoSH and the Start-SshAgent / Add-SshKey commands, so I whipped up a quick script that might help some folks out. This is intended to be added to your PowerShell profile which you can edit by executing notepad $PROFILE

if ($(Get-Process ssh-agent) -eq $null)
{
    $ExecutionContext.InvokeCommand.ExpandString($(ssh-agent -c).Replace("setenv", "set"));
}

It will detect if the ssh-agent is running or not and only execute if there is no agent running already. Please note that $ExecutionContext.InvokeCommand.ExpandString is a pretty dangerous command so you may not want to use this solution if you are using an untrusted copy of ssh-agent.

Spring Data JPA Update @Query not updating?

I struggled with the same problem where I was trying to execute an update query like the same as you did-

@Modifying
@Transactional
@Query(value = "UPDATE SAMPLE_TABLE st SET st.status=:flag WHERE se.referenceNo in :ids")
public int updateStatus(@Param("flag")String flag, @Param("ids")List<String> references);

This will work if you have put @EnableTransactionManagement annotation on the main class. Spring 3.1 introduces the @EnableTransactionManagement annotation to be used in on @Configuration classes and enable transactional support.

How to give a delay in loop execution using Qt

So this question is nearly 10 years old, but it popped up on one of my searches, and I think that there are better solutions when programming in Qt: Signals & slots, timers, and finite state machines. The delays that are required can be implemented without sleeping the application in a way that interrupts other functions, and without concurrent programming and without spinning the processor - the Qt application will sleep when there are no events to process.

A hack for this is to have a sequence of timers with their timeout() signal connected to the slot for the event, which then kicks off the second timer. This is nice because it is simple. It's not so nice because it quickly becomes difficult to troubleshoot and maintain if there are logical branches, which there generally will be outside of any toy example.

QTimer

A better, more flexible option is the State Machine infrastructure within Qt. There you can configure an framework for an arbitrary sequence of events with multiple states and branches. An FSM is much easier to define, expand and maintain over time.

Qt State Machine

Typescript: difference between String and string

The two types are distinct in JavaScript as well as TypeScript - TypeScript just gives us syntax to annotate and check types as we go along.

String refers to an object instance that has String.prototype in its prototype chain. You can get such an instance in various ways e.g. new String('foo') and Object('foo'). You can test for an instance of the String type with the instanceof operator, e.g. myString instanceof String.

string is one of JavaScript's primitive types, and string values are primarily created with literals e.g. 'foo' and "bar", and as the result type of various functions and operators. You can test for string type using typeof myString === 'string'.

The vast majority of the time, string is the type you should be using - almost all API interfaces that take or return strings will use it. All JS primitive types will be wrapped (boxed) with their corresponding object types when using them as objects, e.g. accessing properties or calling methods. Since String is currently declared as an interface rather than a class in TypeScript's core library, structural typing means that string is considered a subtype of String which is why your first line passes compilation type checks.

Maximum Length of Command Line String

As @Sugrue I'm also digging out an old thread.

To explain why there is 32768 (I think it should be 32767, but lets believe experimental testing result) characters limitation we need to dig into Windows API.

No matter how you launch program with command line arguments it goes to ShellExecute, CreateProcess or any extended their version. These APIs basically wrap other NT level API that are not officially documented. As far as I know these calls wrap NtCreateProcess, which requires OBJECT_ATTRIBUTES structure as a parameter, to create that structure InitializeObjectAttributes is used. In this place we see UNICODE_STRING. So now lets take a look into this structure:

typedef struct _UNICODE_STRING {
    USHORT Length;
    USHORT MaximumLength;
    PWSTR  Buffer;
} UNICODE_STRING;

It uses USHORT (16-bit length [0; 65535]) variable to store length. And according this, length indicates size in bytes, not characters. So we have: 65535 / 2 = 32767 (because WCHAR is 2 bytes long).

There are a few steps to dig into this number, but I hope it is clear.


Also, to support @sunetos answer what is accepted. 8191 is a maximum number allowed to be entered into cmd.exe, if you exceed this limit, The input line is too long. error is generated. So, answer is correct despite the fact that cmd.exe is not the only way to pass arguments for new process.

Start HTML5 video at a particular position when loading?

You can link directly with Media Fragments URI, just change the filename to file.webm#t=50

Here's an example

This is pretty cool, you can do all sorts of things. But I don't know the current state of browser support.

How to directly move camera to current location in Google Maps Android API v2?

The above answer is not according to what Google Doc Referred for Location Tracking in Google api v2.

I just followed the official tutorial and ended up with this class that is fetching the current location and centring the map on it as soon as i get that.

you can extend this class to have LocationReciever to have periodic Location Update. I just executed this code on api level 7

http://developer.android.com/training/location/retrieve-current.html

Here it goes.

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;


public class MainActivity extends FragmentActivity implements 
    GooglePlayServicesClient.ConnectionCallbacks, 
    GooglePlayServicesClient.OnConnectionFailedListener{

private SupportMapFragment mapFragment;
private GoogleMap map;
private LocationClient mLocationClient;
/*
 * Define a request code to send to Google Play services
 * This code is returned in Activity.onActivityResult
 */
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

// Define a DialogFragment that displays the error dialog
public static class ErrorDialogFragment extends DialogFragment {

    // Global field to contain the error dialog
    private Dialog mDialog;

    // Default constructor. Sets the dialog field to null
    public ErrorDialogFragment() {
        super();
        mDialog = null;
    }

    // Set the dialog to display
    public void setDialog(Dialog dialog) {
        mDialog = dialog;
    }

    // Return a Dialog to the DialogFragment.
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return mDialog;
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    mLocationClient = new LocationClient(this, this, this);

    mapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
    map = mapFragment.getMap();

    map.setMyLocationEnabled(true);

}

/*
 * Called when the Activity becomes visible.
 */
@Override
protected void onStart() {
    super.onStart();
    // Connect the client.
    if(isGooglePlayServicesAvailable()){
        mLocationClient.connect();
    }

}

/*
 * Called when the Activity is no longer visible.
 */
@Override
protected void onStop() {
    // Disconnecting the client invalidates it.
    mLocationClient.disconnect();
    super.onStop();
}

/*
 * Handle results returned to the FragmentActivity
 * by Google Play services
 */
@Override
protected void onActivityResult(
                int requestCode, int resultCode, Intent data) {
    // Decide what to do based on the original request code
    switch (requestCode) {

        case CONNECTION_FAILURE_RESOLUTION_REQUEST:
            /*
             * If the result code is Activity.RESULT_OK, try
             * to connect again
             */
            switch (resultCode) {
                case Activity.RESULT_OK:
                    mLocationClient.connect();
                    break;
            }

    }
}

private boolean isGooglePlayServicesAvailable() {
    // Check that Google Play services is available
    int resultCode =  GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    // If Google Play services is available
    if (ConnectionResult.SUCCESS == resultCode) {
        // In debug mode, log the status
        Log.d("Location Updates", "Google Play services is available.");
        return true;
    } else {
        // Get the error dialog from Google Play services
        Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog( resultCode,
                                                                                                              this,
                                                                                                              CONNECTION_FAILURE_RESOLUTION_REQUEST);

        // If Google Play services can provide an error dialog
        if (errorDialog != null) {
            // Create a new DialogFragment for the error dialog
            ErrorDialogFragment errorFragment = new ErrorDialogFragment();
            errorFragment.setDialog(errorDialog);
            errorFragment.show(getSupportFragmentManager(), "Location Updates");
        }

        return false;
    }
}

/*
 * Called by Location Services when the request to connect the
 * client finishes successfully. At this point, you can
 * request the current location or start periodic updates
 */
@Override
public void onConnected(Bundle dataBundle) {
    // Display the connection status
    Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
    Location location = mLocationClient.getLastLocation();
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17);
    map.animateCamera(cameraUpdate);
}

/*
 * Called by Location Services if the connection to the
 * location client drops because of an error.
 */
@Override
public void onDisconnected() {
    // Display the connection status
    Toast.makeText(this, "Disconnected. Please re-connect.",
            Toast.LENGTH_SHORT).show();
}

/*
 * Called by Location Services if the attempt to
 * Location Services fails.
 */
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    /*
     * Google Play services can resolve some errors it detects.
     * If the error has a resolution, try sending an Intent to
     * start a Google Play services activity that can resolve
     * error.
     */
    if (connectionResult.hasResolution()) {
        try {
            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(
                    this,
                    CONNECTION_FAILURE_RESOLUTION_REQUEST);
            /*
            * Thrown if Google Play services canceled the original
            * PendingIntent
            */
        } catch (IntentSender.SendIntentException e) {
            // Log the error
            e.printStackTrace();
        }
    } else {
       Toast.makeText(getApplicationContext(), "Sorry. Location services not available to you", Toast.LENGTH_LONG).show();
    }
}

}

Is it a good idea to index datetime field in mysql?

Here author performed tests showed that integer unix timestamp is better than DateTime. Note, he used MySql. But I feel no matter what DB engine you use comparing integers are slightly faster than comparing dates so int index is better than DateTime index. Take T1 - time of comparing 2 dates, T2 - time of comparing 2 integers. Search on indexed field takes approximately O(log(rows)) time because index based on some balanced tree - it may be different for different DB engines but anyway Log(rows) is common estimation. (if you not use bitmask or r-tree based index). So difference is (T2-T1)*Log(rows) - may play role if you perform your query oftenly.

strcpy() error in Visual studio 2012

I had to use strcpy_s and it worked.

#include "stdafx.h"
#include<iostream>
#include<string>

using namespace std;

struct student
{
    char name[30];
    int age;
};

int main()
{

    struct student s1;
    char myname[30] = "John";
    strcpy_s (s1.name, strlen(myname) + 1 ,myname );
    s1.age = 21;

    cout << " Name: " << s1.name << " age: " << s1.age << endl;
    return 0;
}

Description for event id from source cannot be found

I got this error after creating an event source under the Application Log from the command line using "EventCreate". This command creates a new key under: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Application

If you look at the Key that's been created (e.g. SourceTest) there will be a string value calledEventMessageFile, which for me was set to %SystemRoot%\System32\EventCreate.exe.

Change this to c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll

Delete theCustomSource and TypesSupported values.

This should stop the "The description for Event ID...." message.

VBA - If a cell in column A is not blank the column B equals

A simpler way to do this would be:

Sub populateB()

For Each Cel in Range("A1:A100")
    If Cel.value <> "" Then Cel.Offset(0, 1).value = "Your Text"
Next

End Sub

c# how to add byte to byte array

You can't do that. It's not possible to resize an array. You have to create a new array and copy the data to it:

bArray = addByteToArray(bArray,  newByte);

code:

public byte[] addByteToArray(byte[] bArray, byte newByte)
{
    byte[] newArray = new byte[bArray.Length + 1];
    bArray.CopyTo(newArray, 1);
    newArray[0] = newByte;
    return newArray;
}

How do I print bold text in Python?

This depends if you're using linux/unix:

>>> start = "\033[1m"
>>> end = "\033[0;0m"
>>> print "The" + start + "text" + end + " is bold."
The text is bold.

The word text should be bold.

Bootstrap carousel width and height

I recommend the following for Bootstrap 3

.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
  min-height: 500px;    /* Set slide height here */

}

Creating an array of objects in Java

For generic class it is necessary to create a wrapper class. For Example:

Set<String>[] sets = new HashSet<>[10]

results in: "Cannot create a generic array"

Use instead:

        class SetOfS{public Set<String> set = new HashSet<>();}
        SetOfS[] sets = new SetOfS[10];  

How to Set Focus on JTextField?

If you want your JTextField to be focused when your GUI shows up, you can use this:

in = new JTextField(40);
f.addWindowListener( new WindowAdapter() {
    public void windowOpened( WindowEvent e ){
        in.requestFocus();
    }
}); 

Where f would be your JFrame and in is your JTextField.

How to upload & Save Files with Desired name

This would work very well -- You can use HTML5 to allow only image files to be uploaded. This is the code for uploader.htm --

<html>    
    <head>
        <script>
            function validateForm(){
                var image = document.getElementById("image").value;
                var name = document.getElementById("name").value;
                if (image =='')
                {
                    return false;
                }
                if(name =='')
                {
                    return false;
                } 
                else 
                {
                    return true;
                } 
                return false;
            }
        </script>
    </head>

    <body>
        <form method="post" action="upload.php" enctype="multipart/form-data">
            <input type="text" name="ext" size="30"/>
            <input type="text" name="name" id="name" size="30"/>
            <input type="file" accept="image/*" name="image" id="image" />
            <input type="submit" value='Save' onclick="return validateForm()"/>
        </form>
    </body>
</html>

Now the code for upload.php --

<?php  
$name = $_POST['name'];
$ext = $_POST['ext'];
if (isset($_FILES['image']['name']))
{
    $saveto = "$name.$ext";
    move_uploaded_file($_FILES['image']['tmp_name'], $saveto);
    $typeok = TRUE;
    switch($_FILES['image']['type'])
    {
        case "image/gif": $src = imagecreatefromgif($saveto); break;
        case "image/jpeg": // Both regular and progressive jpegs
        case "image/pjpeg": $src = imagecreatefromjpeg($saveto); break;
        case "image/png": $src = imagecreatefrompng($saveto); break;
        default: $typeok = FALSE; break;
    }
    if ($typeok)
    {
        list($w, $h) = getimagesize($saveto);
        $max = 100;
        $tw = $w;
        $th = $h;
        if ($w > $h && $max < $w)
        {
            $th = $max / $w * $h;
            $tw = $max;
        }
        elseif ($h > $w && $max < $h)
        {
            $tw = $max / $h * $w;
            $th = $max;
        }
        elseif ($max < $w)
        {
            $tw = $th = $max;
        }

        $tmp = imagecreatetruecolor($tw, $th);      
        imagecopyresampled($tmp, $src, 0, 0, 0, 0, $tw, $th, $w, $h);
        imageconvolution($tmp, array( // Sharpen image
            array(-1, -1, -1),
            array(-1, 16, -1),
            array(-1, -1, -1)      
        ), 8, 0);
        imagejpeg($tmp, $saveto);
        imagedestroy($tmp);
        imagedestroy($src);
    }
}
?>

How to get the last character of a string in a shell?

For portability you can say "${s#"${s%?}"}":

#!/bin/sh
m=bzzzM n=bzzzN
for s in \
    'vv'  'w'   ''    'uu  ' ' uu ' '  uu' / \
    'ab?' 'a?b' '?ab' 'ab??' 'a??b' '??ab' / \
    'cd#' 'c#d' '#cd' 'cd##' 'c##d' '##cd' / \
    'ef%' 'e%f' '%ef' 'ef%%' 'e%%f' '%%ef' / \
    'gh*' 'g*h' '*gh' 'gh**' 'g**h' '**gh' / \
    'ij"' 'i"j' '"ij' "ij'"  "i'j"  "'ij"  / \
    'kl{' 'k{l' '{kl' 'kl{}' 'k{}l' '{}kl' / \
    'mn$' 'm$n' '$mn' 'mn$$' 'm$$n' '$$mn' /
do  case $s in
    (/) printf '\n' ;;
    (*) printf '.%s. ' "${s#"${s%?}"}" ;;
    esac
done

Output:

.v. .w. .. . . . . .u. 
.?. .b. .b. .?. .b. .b. 
.#. .d. .d. .#. .d. .d. 
.%. .f. .f. .%. .f. .f. 
.*. .h. .h. .*. .h. .h. 
.". .j. .j. .'. .j. .j. 
.{. .l. .l. .}. .l. .l. 
.$. .n. .n. .$. .n. .n. 

What is the meaning of 'No bundle URL present' in react-native?

I know this question has many answers But these are not helped me. Below solution that helped me to resolve the error.

You have to go into your settings and allow this particular app.

  1. Open system preferences.
  2. Click 'security & privacy".
  3. Bottom right-click " Click the lock to make changes".
  4. Enter password.
  5. Under the general tab where it says ' app store and identified developers' you should see your blocked app.
  6. Final step: click "open anyway"

Source “launchPackager.command” cannot be opened because it is from an unidentified developer

Javascript ajax call on page onload

This is really easy using a JavaScript library, e.g. using jQuery you could write:

$(document).ready(function(){
$.ajax({ url: "database/update.html",
        context: document.body,
        success: function(){
           alert("done");
        }});
});

Without jQuery, the simplest version might be as follows, but it does not account for browser differences or error handling:

<html>
  <body onload="updateDB();">
  </body>
  <script language="javascript">
    function updateDB() {
      var xhr = new XMLHttpRequest();
      xhr.open("POST", "database/update.html", true);
      xhr.send(null);
      /* ignore result */
    }
  </script>
</html>

See also:

Extension exists but uuid_generate_v4 fails

Looks like the extension is not installed in the particular database you require it.

You should connect to this particular database with

 \CONNECT my_database

Then install the extension in this database

 CREATE EXTENSION "uuid-ossp";

Access Form - Syntax error (missing operator) in query expression

Put [] around any field names that had spaces (as Dreden says) and save your query, close it and reopen it.

Using Access 2016, I still had the error message on new queries after I added [] around any field names... until the Query was saved.

Once the Query is saved (and visible in the Objects' List), closed and reopened, the error message disappears. This seems to be a bug from Access.

How to "test" NoneType in python?

if variable is None:
   ...

if variable is not None:
   ...

Bootstrap Columns Not Working

Have you checked that those classes are present in the CSS? Are you using twitter-bootstrap-rails gem? It still uses Bootstrap 2.X version and those are Bootstrap 3.X classes. The CSS grid changed since.

You can switch to the bootstrap3 branch of the gem https://github.com/seyhunak/twitter-bootstrap-rails/tree/bootstrap3 or include boostrap in an alternative way.

Popup window in PHP?

For a popup javascript is required. Put this in your header:

<script>
function myFunction()
{
alert("I am an alert box!"); // this is the message in ""
}
</script>

And this in your body:

<input type="button" onclick="myFunction()" value="Show alert box">

When the button is pressed a box pops up with the message set in the header.

This can be put in any html or php file without the php tags.

-----EDIT-----

To display it using php try this:

<?php echo '<script>myfunction()</script>'; ?>

It may not be 100% correct but the principle is the same.

To display different messages you can either create lots of functions or you can pass a variable in to the function when you call it.

How to use Tomcat 8.5.x and TomEE 7.x with Eclipse?

For Tomcat 8.5.x users

You've to change the ServerInfo.properties file of Tomcat's /lib/catalina.jar file.

ServerInfo.properties file contains the following code

server.info=Apache Tomcat/8.5.4
server.number=8.5.4.0
server.built=Jul 6 2016 08:43:30 UTC

Just open the ServerInfo.properties file by opening the catalina.jar with winrar from your Tomcat's lib folder

ServerInfo.properties file location in catalina.jar is /org/apache/catalina/util/ServerInfo.properties

Notice : shutdown the Tomcat server(if it's already opened by cmd) before doing these things otherwise your file doesn't change and your winrar shows error.

Then change the following code in ServerInfo.properties

server.info=Apache Tomcat/8.0.8.5.4
server.number=8.5.4.0
server.built=Jul 6 2016 08:43:30 UTC

Restart your eclipse(if opened). Now it'll work...

ScreenShot of eclipse

How can I list all tags for a Docker image on a remote registry?

See CLI utility: https://www.npmjs.com/package/docker-browse

Allows enumeration of tags and images.

docker-browse tags <image> will list all tags for the image. e.g. docker-browse tags library/alpine

docker-browse images will list all images in the registry. Not currently available for index.docker.io.

You may connect it to any registry, including your private one, so long as it supports Docker Registry HTTP API V2

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

I used fake UserAgent.

How to use:

from fake_useragent import UserAgent
import requests
   

ua = UserAgent()
print(ua.chrome)
header = {'User-Agent':str(ua.chrome)}
print(header)
url = "https://www.hybrid-analysis.com/recent-submissions?filter=file&sort=^timestamp"
htmlContent = requests.get(url, headers=header)
print(htmlContent)

Output:

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17
{'User-Agent': 'Mozilla/5.0 (X11; OpenBSD i386) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36'}
<Response [200]>

Using XPATH to search text containing &nbsp;

Search for &nbsp; or only nbsp - did you try this?

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

You can also use window.matchMedia, which I use and prefer as it closely resembles CSS syntax:

if (window.matchMedia("(orientation: portrait)").matches) {
   // you're in PORTRAIT mode
}

if (window.matchMedia("(orientation: landscape)").matches) {
   // you're in LANDSCAPE mode
}

Tested on iPad 2.

Python: "TypeError: __str__ returned non-string" but still prints to output?

Method __str__ should return string, not print.

def __str__(self):
    return 'Memo={0}, Tag={1}'.format(self.memo, self.tags)

Determining 32 vs 64 bit in C++

Unfortunately, in a cross platform, cross compiler environment, there is no single reliable method to do this purely at compile time.

  • Both _WIN32 and _WIN64 can sometimes both be undefined, if the project settings are flawed or corrupted (particularly on Visual Studio 2008 SP1).
  • A project labelled "Win32" could be set to 64-bit, due to a project configuration error.
  • On Visual Studio 2008 SP1, sometimes the intellisense does not grey out the correct parts of the code, according to the current #define. This makes it difficult to see exactly which #define is being used at compile time.

Therefore, the only reliable method is to combine 3 simple checks:

  • 1) Compile time setting, and;
  • 2) Runtime check, and;
  • 3) Robust compile time checking.

Simple check 1/3: Compile time setting

Choose any method to set the required #define variable. I suggest the method from @JaredPar:

// Check windows
#if _WIN32 || _WIN64
   #if _WIN64
     #define ENV64BIT
  #else
    #define ENV32BIT
  #endif
#endif

// Check GCC
#if __GNUC__
  #if __x86_64__ || __ppc64__
    #define ENV64BIT
  #else
    #define ENV32BIT
  #endif
#endif

Simple check 2/3: Runtime check

In main(), double check to see if sizeof() makes sense:

#if defined(ENV64BIT)
    if (sizeof(void*) != 8)
    {
        wprintf(L"ENV64BIT: Error: pointer should be 8 bytes. Exiting.");
        exit(0);
    }
    wprintf(L"Diagnostics: we are running in 64-bit mode.\n");
#elif defined (ENV32BIT)
    if (sizeof(void*) != 4)
    {
        wprintf(L"ENV32BIT: Error: pointer should be 4 bytes. Exiting.");
        exit(0);
    }
    wprintf(L"Diagnostics: we are running in 32-bit mode.\n");
#else
    #error "Must define either ENV32BIT or ENV64BIT".
#endif

Simple check 3/3: Robust compile time checking

The general rule is "every #define must end in a #else which generates an error".

#if defined(ENV64BIT)
    // 64-bit code here.
#elif defined (ENV32BIT)
    // 32-bit code here.
#else
    // INCREASE ROBUSTNESS. ALWAYS THROW AN ERROR ON THE ELSE.
    // - What if I made a typo and checked for ENV6BIT instead of ENV64BIT?
    // - What if both ENV64BIT and ENV32BIT are not defined?
    // - What if project is corrupted, and _WIN64 and _WIN32 are not defined?
    // - What if I didn't include the required header file?
    // - What if I checked for _WIN32 first instead of second?
    //   (in Windows, both are defined in 64-bit, so this will break codebase)
    // - What if the code has just been ported to a different OS?
    // - What if there is an unknown unknown, not mentioned in this list so far?
    // I'm only human, and the mistakes above would break the *entire* codebase.
    #error "Must define either ENV32BIT or ENV64BIT"
#endif

Update 2017-01-17

Comment from @AI.G:

4 years later (don't know if it was possible before) you can convert the run-time check to compile-time one using static assert: static_assert(sizeof(void*) == 4);. Now it's all done at compile time :)

Appendix A

Incidentially, the rules above can be adapted to make your entire codebase more reliable:

  • Every if() statement ends in an "else" which generates a warning or error.
  • Every switch() statement ends in a "default:" which generates a warning or error.

The reason why this works well is that it forces you to think of every single case in advance, and not rely on (sometimes flawed) logic in the "else" part to execute the correct code.

I used this technique (among many others) to write a 30,000 line project that worked flawlessly from the day it was first deployed into production (that was 12 months ago).

How do I tokenize a string sentence in NLTK?

As @PavelAnossov answered, the canonical answer, use the word_tokenize function in nltk:

from nltk import word_tokenize
sent = "This is my text, this is a nice way to input text."
word_tokenize(sent)

If your sentence is truly simple enough:

Using the string.punctuation set, remove punctuation then split using the whitespace delimiter:

import string
x = "This is my text, this is a nice way to input text."
y = "".join([i for i in x if not in string.punctuation]).split(" ")
print y

How may I align text to the left and text to the right in the same line?

If you don't want to use floating elements and want to make sure that both blocks do not overlap, try:

<p style="text-align: left; width:49%; display: inline-block;">LEFT</p>
<p style="text-align: right; width:50%;  display: inline-block;">RIGHT</p>

Calculating percentile of dataset column

Using {dplyr}:

library(dplyr)

# percentiles
infert %>% 
  mutate(PCT = ntile(age, 100))

# quartiles
infert %>% 
  mutate(PCT = ntile(age, 4))

# deciles
infert %>% 
  mutate(PCT = ntile(age, 10))

Not equal to != and !== in PHP

!== should match the value and data type

!= just match the value ignoring the data type

$num = '1';
$num2 = 1;

$num == $num2; // returns true    
$num === $num2; // returns false because $num is a string and $num2 is an integer

Read from a gzip file in python

Try gzipping some data through the gzip libary like this...

import gzip
content = "Lots of content here"
f = gzip.open('Onlyfinnaly.log.gz', 'wb')
f.write(content)
f.close()

... then run your code as posted ...

import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content

This method worked for me as for some reason the gzip library fails to read some files.

Display all views on oracle database

for all views (you need dba privileges for this query)

select view_name from dba_views

for all accessible views (accessible by logged user)

select view_name from all_views

for views owned by logged user

select view_name from user_views

What's the difference between JPA and Hibernate?

Java - its independence is not only from the operating system, but also from the vendor.

Therefore, you should be able to deploy your application on different application servers. JPA is implemented in any Java EE- compliant application server and it allows to swap application servers, but then the implementation is also changing. A Hibernate application may be easier to deploy on a different application server.

Read each line of txt file to new array element

You were on the right track, but there were some problems with the code you posted. First of all, there was no closing bracket for the while loop. Secondly, $line_of_text would be overwritten with every loop iteration, which is fixed by changing the = to a .= in the loop. Third, you're exploding the literal characters '\n' and not an actual newline; in PHP, single quotes will denote literal characters, but double quotes will actually interpret escaped characters and variables.

    <?php
        $file = fopen("members.txt", "r");
        $i = 0;
        while (!feof($file)) {
            $line_of_text .= fgets($file);
        }
        $members = explode("\n", $line_of_text);
        fclose($file);
        print_r($members);
    ?>

How to send data with angularjs $http.delete() request?

You can do an http DELETE via a URL like /users/1/roles/2. That would be the most RESTful way to do it.

Otherwise I guess you can just pass the user id as part of the query params? Something like

$http.delete('/roles/' + roleid, {params: {userId: userID}}).then...

Call Class Method From Another Class

class CurrentValue:

    def __init__(self, value):
        self.value = value

    def set_val(self, k):
        self.value = k

    def get_val(self):
        return self.value


class AddValue:

    def av(self, ocv):
        print('Before:', ocv.get_val())
        num = int(input('Enter number to add : '))
        nnum = num + ocv.get_val()
        ocv.set_val(nnum)
        print('After add :', ocv.get_val())


cvo = CurrentValue(5)

avo = AddValue()

avo.av(cvo)

We define 2 classes, CurrentValue and AddValue We define 3 methods in the first class One init in order to give to the instance variable self.value an initial value A set_val method where we set the self.value to a k A get_val method where we get the valuue of self.value We define one method in the second class A av method where we pass as parameter(ovc) an object of the first class We create an instance (cvo) of the first class We create an instance (avo) of the second class We call the method avo.av(cvo) of the second class and pass as an argument the object we have already created from the first class. So by this way I would like to show how it is possible to call a method of a class from another class.

I am sorry for any inconvenience. This will not happen again.

Before: 5

Enter number to add : 14

After add : 19

Webpack how to build production code and how to use it

If you have a lot of duplicate code in your webpack.dev.config and your webpack.prod.config, you could use a boolean isProd to activate certain features only in certain situations and only have a single webpack.config.js file.

const isProd = (process.env.NODE_ENV === 'production');

 if (isProd) {
     plugins.push(new AotPlugin({
      "mainPath": "main.ts",
      "hostReplacementPaths": {
        "environments/index.ts": "environments/index.prod.ts"
      },
      "exclude": [],
      "tsConfigPath": "src/tsconfig.app.json"
    }));
    plugins.push(new UglifyJsPlugin({
      "mangle": {
        "screw_ie8": true
      },
      "compress": {
        "screw_ie8": true,
        "warnings": false
      },
      "sourceMap": false
    }));
  }

By the way: The DedupePlugin plugin was removed from Webpack. You should remove it from your configuration.

UPDATE:

In addition to my previous answer:

If you want to hide your code for release, try enclosejs.com. It allows you to:

  • make a release version of your application without sources
  • create a self-extracting archive or installer
  • Make a closed source GUI application
  • Put your assets inside the executable

You can install it with npm install -g enclose

Is there a .NET/C# wrapper for SQLite?

Here are the ones I can find:

Sources:

How to run an EXE file in PowerShell with parameters with spaces and quotes

There are quite a few methods you can use to do it.

There are other methods like using the Call Operator (&), Invoke-Expression cmdlet etc. But they are considered unsafe. Microsoft recommends using Start-Process.

Method 1

A simple example

Start-Process -NoNewWindow -FilePath "C:\wamp64\bin\mysql\mysql5.7.19\bin\mysql" -ArgumentList "-u root","-proot","-h localhost"

In your case

Start-Process -NoNewWindow -FilePath "C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" -ArgumentList "-verb:sync","-source:dbfullsql=`"Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;`"","-dest:dbfullsql=`"Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;`"","computername=10.10.10.10","username=administrator","password=adminpass"

In this method you separate each and every parameter in the ArgumentList using commas.

Method 2

Simple Example

Start-Process -NoNewWindow -FilePath "C:\wamp64\bin\mysql\mysql5.7.19\bin\mysql" -ArgumentList "-u root -proot -h localhost"

In your case

Start-Process -NoNewWindow -FilePath "C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" -ArgumentList "-verb:sync -source:dbfullsql=`"Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;`" -dest:dbfullsql=`"Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;`",computername=10.10.10.10,username=administrator,password=adminpass"

This method is easier as it allows to type your parameters in one go.

Note that in powershell to represent the quotation mark ( " ) in a string you should insert the grave accent ( ` ) (This is the key above the Tab key in the US keyboard).

-NoNewWindow parameter is used to display the new process in the current console window. By default Windows PowerShell opens a new window.

References : Powershell/Scripting/Start-Process

Creating C formatted strings (not printing them)

If you have the code to log_out(), rewrite it. Most likely, you can do:

static FILE *logfp = ...;

void log_out(const char *fmt, ...)
{
    va_list args;

    va_start(args, fmt);
    vfprintf(logfp, fmt, args);
    va_end(args);
}

If there is extra logging information needed, that can be printed before or after the message shown. This saves memory allocation and dubious buffer sizes and so on and so forth. You probably need to initialize logfp to zero (null pointer) and check whether it is null and open the log file as appropriate - but the code in the existing log_out() should be dealing with that anyway.

The advantage to this solution is that you can simply call it as if it was a variant of printf(); indeed, it is a minor variant on printf().

If you don't have the code to log_out(), consider whether you can replace it with a variant such as the one outlined above. Whether you can use the same name will depend on your application framework and the ultimate source of the current log_out() function. If it is in the same object file as another indispensable function, you would have to use a new name. If you cannot work out how to replicate it exactly, you will have to use some variant like those given in other answers that allocates an appropriate amount of memory.

void log_out_wrapper(const char *fmt, ...)
{
    va_list args;
    size_t  len;
    char   *space;

    va_start(args, fmt);
    len = vsnprintf(0, 0, fmt, args);
    va_end(args);
    if ((space = malloc(len + 1)) != 0)
    {
         va_start(args, fmt);
         vsnprintf(space, len+1, fmt, args);
         va_end(args);
         log_out(space);
         free(space);
    }
    /* else - what to do if memory allocation fails? */
}

Obviously, you now call the log_out_wrapper() instead of log_out() - but the memory allocation and so on is done once. I reserve the right to be over-allocating space by one unnecessary byte - I've not double-checked whether the length returned by vsnprintf() includes the terminating null or not.

PreparedStatement with Statement.RETURN_GENERATED_KEYS

You mean something like this?

long key = -1L;

PreparedStatement preparedStatement = connection.prepareStatement(YOUR_SQL_HERE, PreparedStatement.RETURN_GENERATED_KEYS);
preparedStatement.setXXX(index, VALUE);
preparedStatement.executeUpdate();

ResultSet rs = preparedStatement.getGeneratedKeys();

if (rs.next()) {
    key = rs.getLong(1);
}

Viewing full output of PS command

Just throw it on cat, which line-wraps automatically

ps aux | cat

How to append to a file in Node?

Here's a full script. Fill in your file names and run it and it should work! Here's a video tutorial on the logic behind the script.

var fs = require('fs');

function ReadAppend(file, appendFile){
  fs.readFile(appendFile, function (err, data) {
    if (err) throw err;
    console.log('File was read');

    fs.appendFile(file, data, function (err) {
      if (err) throw err;
      console.log('The "data to append" was appended to file!');

    });
  });
}
// edit this with your file names
file = 'name_of_main_file.csv';
appendFile = 'name_of_second_file_to_combine.csv';
ReadAppend(file, appendFile);

Converting Integers to Roman Numerals - Java

private static String toRoman(int n) {
    String[] romanNumerals = { "M",  "CM", "D", "CD", "C", "XC", "L",  "X", "IX", "V", "I" };
    int[] romanNumeralNums = {  1000, 900, 500,  400 , 100,  90,  50,   10,    9,   5,   1 };
    String finalRomanNum = "";

    for (int i = 0; i < romanNumeralNums.length; i ++) {
            int currentNum = n /romanNumeralNums[i];
            if (currentNum==0) {
                continue;
            }

            for (int j = 0; j < currentNum; j++) {
                finalRomanNum +=romanNumerals[i];
            }

            n = n%romanNumeralNums[i];
    }
    return finalRomanNum;
}

How can I change NULL to 0 when getting a single value from a SQL function?

SELECT COALESCE(
    (SELECT SUM(Price) AS TotalPrice 
    FROM Inventory
    WHERE (DateAdded BETWEEN @StartDate AND @EndDate))
    , 0)

If the table has rows in the response it returns the SUM(Price). If the SUM is NULL or there are no rows it will return 0.

Putting COALESCE(SUM(Price), 0) does NOT work in MSSQL if no rows are found.

How many files can I put in a directory?

I ran into a similar issue. I was trying to access a directory with over 10,000 files in it. It was taking too long to build the file list and run any type of commands on any of the files.

I thought up a little php script to do this for myself and tried to figure a way to prevent it from time out in the browser.

The following is the php script I wrote to resolve the issue.

Listing Files in a Directory with too many files for FTP

How it helps someone

What does '<?=' mean in PHP?

As of PHP 5.4.0, <?= ?> are always available even without the short_open_tag set in php.ini.

Furthermore, as of PHP 7.0, The ASP tags: <%, %> and the script tag <script language="php"> are removed from PHP.

What is the equivalent of "!=" in Excel VBA?

In VBA, the != operator is the Not operator, like this:

If Not strTest = "" Then ...

Android WebView Cookie Problem

I have a different approach from other people here, and it an approach that is guaranteed work without dealing with the CookieSyncManager (where you are at the mercy of semantics like "Note that even sync() happens asynchronously").

Essentially, we browse to the correct domain, then we execute javascript from the page context to set cookies for that domain (the same way the page itself would). Two drawbacks to the method are that may introduce an extra round trip time due to the extra http request you have to make; and if your site does not have the equivalent of a blank page, it may flash whatever URL you load first before taking you to the right place.

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.cookie.Cookie;
import android.annotation.SuppressLint;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebViewFragment {
    private static final String BLANK_PAGE = "/blank.html"

    private CookieSyncManager mSyncManager;
    private CookieManager mCookieManager;

    private String mTargetUrl;
    private boolean mInitializedCookies;
    private List<Cookie> mAllCookies;

    public WebViewFragment(Context ctx) {
        // We are still required to create an instance of Cookie/SyncManager.
        mSyncManager = CookieSyncManager.createInstance(ctx);
        mCookieManager = CookieManager.getInstance();
    }

    @SuppressLint("SetJavaScriptEnabled") public void loadWebView(
                String url, List<Cookie> cookies, String domain) {
        final WebView webView = ...

        webView.setWebViewClient(new CookeWebViewClient());
        webView.getSettings().setJavaScriptEnabled(true);

        mInitializedCookies = false;
        mTargetUrl = url;
        mAllCookies = cookies;
        // This is where the hack starts.
        // Instead of loading the url, we load a blank page.
        webView.loadUrl("http://" + domain + BLANK_PAGE);
    }

    public static String buildCookieString(final Cookie cookie) {
        // You may want to add the secure flag for https:
        // + "; secure"
        // In case you wish to convert session cookies to have an expiration:
        // + "; expires=Thu, 01-Jan-2037 00:00:10 GMT"
        // Note that you cannot set the HttpOnly flag as we are using
        // javascript to set the cookies.
        return cookie.getName() + "=" + cookie.getValue()
                    + "; path=" + cookie.getPath()
                    + "; domain=" + cookie.getDomain()
    };

    public synchronized String generateCookieJavascript() {
        StringBuilder javascriptCode = new StringBuilder();
        javascriptCode.append("javascript:(function(){");
        for (final Cookie cookie : mAllCookies) {
            String cookieString = buildCookieString(cookie);
            javascriptCode.append("document.cookie=\"");
            javascriptCode.append(
                     StringEscapeUtils.escapeJavascriptString(cookieString));
            javascriptCode.append("\";");
        }
        // We use javascript to load the next url because we do not
        // receive an onPageFinished event when this code finishes.
        javascriptCode.append("document.location=\"");
        javascriptCode.append(
                StringEscapeUtils.escapeJavascriptString(mTargetUrl));
        javascriptCode.append("\";})();");
        return javascriptCode.toString();
    }

    private class CookieWebViewClient extends WebViewClient {
        @Override public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (!mInitializedCookies) {
                mInitializedCookies = true;
                // Run our javascript code now that the temp page is loaded.
                view.loadUrl(generateCookieJavascript());
                return;
            }
        }
    }
}

If you trust the domain the cookies are from, you may be able to get away without apache commons, but you have to understand that this can present a XSS risk if you are not careful.

groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding

Please double check that jenkins is not blocking this import. Go to script approvals and check to see if it is blocking it. If it is click allow.

https://jenkins.io/doc/book/managing/script-approval/

Where do I find old versions of Android NDK?

The 64 bit versions are available also:

http://dl.google.com/android/ndk/android-ndk-r8e-darwin-x86_64.tar.bz2

just replace the R8E release/version/iteration

IIS7 Permissions Overview - ApplicationPoolIdentity

Remember to use the server's local name, not the domain name, when resolving the name

IIS AppPool\DefaultAppPool

(just a reminder because this tripped me up for a bit):enter image description here

Get docker container id from container name

The following command:

docker ps --format 'CONTAINER ID : {{.ID}} | Name: {{.Names}} | Image:  {{.Image}} |  Ports: {{.Ports}}'

Gives this output:

CONTAINER ID : d8453812a556 | Name: peer0.ORG2.ac.ae | Image:  hyperledger/fabric-peer:1.4 |  Ports: 0.0.0.0:27051->7051/tcp, 0.0.0.0:27053->7053/tcp
CONTAINER ID : d11bdaf8e7a0 | Name: peer0.ORG1.ac.ae | Image:  hyperledger/fabric-peer:1.4 |  Ports: 0.0.0.0:17051->7051/tcp, 0.0.0.0:17053->7053/tcp
CONTAINER ID : b521f48a3cf4 | Name: couchdb1 | Image:  hyperledger/fabric-couchdb:0.4.15 |  Ports: 4369/tcp, 9100/tcp, 0.0.0.0:5985->5984/tcp
CONTAINER ID : 14436927aff7 | Name: ca.ORG1.ac.ae | Image:  hyperledger/fabric-ca:1.4 |  Ports: 0.0.0.0:7054->7054/tcp
CONTAINER ID : 9958e9f860cb | Name: couchdb | Image:  hyperledger/fabric-couchdb:0.4.15 |  Ports: 4369/tcp, 9100/tcp, 0.0.0.0:5984->5984/tcp
CONTAINER ID : 107466b8b1cd | Name: ca.ORG2.ac.ae | Image:  hyperledger/fabric-ca:1.4 |  Ports: 0.0.0.0:7055->7054/tcp
CONTAINER ID : 882aa0101af2 | Name: orderer1.o1.ac.ae | Image:  hyperledger/fabric-orderer:1.4 |  Ports: 0.0.0.0:7050->7050/tcp`enter code here`

How can I override the OnBeforeUnload dialog and replace it with my own?

What worked for me, using jQuery and tested in IE8, Chrome and Firefox, is:

$(window).bind("beforeunload",function(event) {
    if(hasChanged) return "You have unsaved changes";
});

It is important not to return anything if no prompt is required as there are differences between IE and other browser behaviours here.

Typescript empty object for a typed variable

user: USER

this.user = ({} as USER)

Convert PDF to image with high resolution

PNG file you attached looks really blurred. In case if you need to use additional post-processing for each image you generated as PDF preview, you will decrease performance of your solution.

2JPEG can convert PDF file you attached to a nice sharpen JPG and crop empty margins in one call:

2jpeg.exe -src "C:\In\*.*" -dst "C:\Out" -oper Crop method:autocrop

RegEx for Javascript to allow only alphanumeric

Alphanumeric with case sensitive:

if (/^[a-zA-Z0-9]+$/.test("SoS007")) {
  alert("match")
}

Laravel Fluent Query Builder Join with subquery

I was looking for a solution to quite a related problem: finding the newest records per group which is a specialization of a typical greatest-n-per-group with N = 1.

The solution involves the problem you are dealing with here (i.e., how to build the query in Eloquent) so I am posting it as it might be helpful for others. It demonstrates a cleaner way of sub-query construction using powerful Eloquent fluent interface with multiple join columns and where condition inside joined sub-select.

In my example I want to fetch the newest DNS scan results (table scan_dns) per group identified by watch_id. I build the sub-query separately.

The SQL I want Eloquent to generate:

SELECT * FROM `scan_dns` AS `s`
INNER JOIN (
  SELECT x.watch_id, MAX(x.last_scan_at) as last_scan
  FROM `scan_dns` AS `x`
  WHERE `x`.`watch_id` IN (1,2,3,4,5,42)
  GROUP BY `x`.`watch_id`) AS ss
ON `s`.`watch_id` = `ss`.`watch_id` AND `s`.`last_scan_at` = `ss`.`last_scan`

I did it in the following way:

// table name of the model
$dnsTable = (new DnsResult())->getTable();

// groups to select in sub-query
$ids = collect([1,2,3,4,5,42]);

// sub-select to be joined on
$subq = DnsResult::query()
    ->select('x.watch_id')
    ->selectRaw('MAX(x.last_scan_at) as last_scan')
    ->from($dnsTable . ' AS x')
    ->whereIn('x.watch_id', $ids)
    ->groupBy('x.watch_id');
$qqSql = $subq->toSql();  // compiles to SQL

// the main query
$q = DnsResult::query()
    ->from($dnsTable . ' AS s')
    ->join(
        DB::raw('(' . $qqSql. ') AS ss'),
        function(JoinClause $join) use ($subq) {
            $join->on('s.watch_id', '=', 'ss.watch_id')
                 ->on('s.last_scan_at', '=', 'ss.last_scan')
                 ->addBinding($subq->getBindings());  
                 // bindings for sub-query WHERE added
        });

$results = $q->get();

UPDATE:

Since Laravel 5.6.17 the sub-query joins were added so there is a native way to build the query.

$latestPosts = DB::table('posts')
                   ->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
                   ->where('is_published', true)
                   ->groupBy('user_id');

$users = DB::table('users')
        ->joinSub($latestPosts, 'latest_posts', function ($join) {
            $join->on('users.id', '=', 'latest_posts.user_id');
        })->get();

Simple way to repeat a string

String::repeat

". ".repeat( 7 )  // Seven period-with-space pairs: . . . . . . . 

New in Java 11 is the method String::repeat that does exactly what you asked for:

String str = "abc";
String repeated = str.repeat(3);
repeated.equals("abcabcabc");

Its Javadoc says:

/**
 * Returns a string whose value is the concatenation of this
 * string repeated {@code count} times.
 * <p>
 * If this string is empty or count is zero then the empty
 * string is returned.
 *
 * @param count number of times to repeat
 *
 * @return A string composed of this string repeated
 * {@code count} times or the empty string if this
 * string is empty or count is zero
 *
 * @throws IllegalArgumentException if the {@code count} is
 * negative.
 *
 * @since 11
 */ 

adding a datatable in a dataset

Just give any name to the DataTable Like:

DataTable dt = new DataTable();
dt = SecondDataTable.Copy();    
dt .TableName = "New Name";
DataSet.Tables.Add(dt );