There is no such limit on the string length. To be certain, I just tested to create a string containing 60 megabyte.
The problem is likely that you are sending the data in a GET request, so it's sent in the URL. Different browsers have different limits for the URL, where IE has the lowest limist of about 2 kB. To be safe, you should never send more data than about a kilobyte in a GET request.
To send that much data, you have to send it in a POST request instead. The browser has no hard limit on the size of a post, but the server has a limit on how large a request can be. IIS for example has a default limit of 4 MB, but it's possible to adjust the limit if you would ever need to send more data than that.
Also, you shouldn't use += to concatenate long strings. For each iteration there is more and more data to move, so it gets slower and slower the more items you have. Put the strings in an array and concatenate all the items at once:
var items = $.map(keys, function(item, i) {
var value = $("#value" + (i+1)).val().replace(/"/g, "\\\"");
return
'{"Key":' + '"' + Encoder.htmlEncode($(this).html()) + '"' + ",'+
'" + '"Value"' + ':' + '"' + Encoder.htmlEncode(value) + '"}';
});
var jsonObj =
'{"code":"' + code + '",'+
'"defaultfile":"' + defaultfile + '",'+
'"filename":"' + currentFile + '",'+
'"lstResDef":[' + items.join(',') + ']}';
C99 allows VLA. And it puts some restrictions on how to declare VLA. For details, refer to 6.7.5.2 of the standard. C++ disallows VLA. But g++ allows it.
You can transpose the array if you want to get the length of the other dimension.
len(np.array([[2,3,1,0], [2,3,1,0], [3,2,1,1]]).T)
It's a CRLF problem. I fixed the problem using this:
git config --global core.eol lf
git config --global core.autocrlf input
find . -type f -print0 | xargs -0 dos2unix
Vanilla JavaScript solution:
document.body.innerHTML = document.body.innerHTML.replace(/Original/g, "New")
This is what worked for me in the end.
var showMenu = function(el, menu) {
//get the position of the placeholder element
var pos = $(el).offset();
var eWidth = $(el).outerWidth();
var mWidth = $(menu).outerWidth();
var left = (pos.left + eWidth - mWidth) + "px";
var top = 3+pos.top + "px";
//show the menu directly over the placeholder
$(menu).css( {
position: 'absolute',
zIndex: 5000,
left: left,
top: top
} );
$(menu).hide().fadeIn();
};
-qscale:v
to control qualityUse -qscale:v
(or the alias -q:v
) as an output option.
-qmin 1
output option (because the default is -qmin 2
).ffmpeg -i input.mp4 -qscale:v 2 output_%03d.jpg
See the image muxer documentation for more options involving image outputs.
ffmpeg -ss 60 -i input.mp4 -qscale:v 4 -frames:v 1 output.jpg
I'm pretty sure you only have to register MappingJacksonHttpMessageConverter
(the easiest way to do that is through <mvc:annotation-driven />
in XML or @EnableWebMvc
in Java)
See:
Here's a working example:
Maven POM
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>json</artifactId><packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version><name>json test</name>
<dependencies>
<dependency><!-- spring mvc -->
<groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>3.0.5.RELEASE</version>
</dependency>
<dependency><!-- jackson -->
<groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.4.2</version>
</dependency>
</dependencies>
<build><plugins>
<!-- javac --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version><configuration><source>1.6</source><target>1.6</target></configuration></plugin>
<!-- jetty --><plugin><groupId>org.mortbay.jetty</groupId><artifactId>jetty-maven-plugin</artifactId>
<version>7.4.0.v20110414</version></plugin>
</plugins></build>
</project>
in folder src/main/webapp/WEB-INF
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<servlet><servlet-name>json</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>json</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
json-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:mvc-context.xml" />
</beans>
in folder src/main/resources:
mvc-context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="test.json" />
</beans>
In folder src/main/java/test/json
TestController.java
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping(method = RequestMethod.POST, value = "math")
@ResponseBody
public Result math(@RequestBody final Request request) {
final Result result = new Result();
result.setAddition(request.getLeft() + request.getRight());
result.setSubtraction(request.getLeft() - request.getRight());
result.setMultiplication(request.getLeft() * request.getRight());
return result;
}
}
Request.java
public class Request implements Serializable {
private static final long serialVersionUID = 1513207428686438208L;
private int left;
private int right;
public int getLeft() {return left;}
public void setLeft(int left) {this.left = left;}
public int getRight() {return right;}
public void setRight(int right) {this.right = right;}
}
Result.java
public class Result implements Serializable {
private static final long serialVersionUID = -5054749880960511861L;
private int addition;
private int subtraction;
private int multiplication;
public int getAddition() { return addition; }
public void setAddition(int addition) { this.addition = addition; }
public int getSubtraction() { return subtraction; }
public void setSubtraction(int subtraction) { this.subtraction = subtraction; }
public int getMultiplication() { return multiplication; }
public void setMultiplication(int multiplication) { this.multiplication = multiplication; }
}
You can test this setup by executing mvn jetty:run
on the command line, and then sending a POST request:
URL: http://localhost:8080/test/math
mime type: application/json
post body: { "left": 13 , "right" : 7 }
I used the Poster Firefox plugin to do this.
Here's what the response looks like:
{"addition":20,"subtraction":6,"multiplication":91}
Here is a work around I found if you want to only shuffle a subset of the DataFrame:
shuffle_to_index = 20
df = pd.concat([df.iloc[np.random.permutation(range(shuffle_to_index))], df.iloc[shuffle_to_index:]])
This comment syntax should work for you:
@* enter comments here *@
The negated set of everything that is not alphanumeric & underscore for ASCII chars:
/[^\W]/g
For email or username validation i've used the following expression that allows 4 standard special characters - _ . @
/^[-.@_a-z0-9]+$/gi
For a strict alphanumeric only expression use:
/^[a-z0-9]+$/gi
Test @ RegExr.com
Quote:
Arrays of generic types are not allowed because they're not sound. The problem is due to the interaction of Java arrays, which are not statically sound but are dynamically checked, with generics, which are statically sound and not dynamically checked. Here is how you could exploit the loophole:
class Box<T> { final T x; Box(T x) { this.x = x; } } class Loophole { public static void main(String[] args) { Box<String>[] bsa = new Box<String>[3]; Object[] oa = bsa; oa[0] = new Box<Integer>(3); // error not caught by array store check String s = bsa[0].x; // BOOM! } }
We had proposed to resolve this problem using statically safe arrays (aka Variance) bute that was rejected for Tiger.
-- gafter
(I believe it is Neal Gafter, but am not sure)
See it in context here: http://forums.sun.com/thread.jspa?threadID=457033&forumID=316
To have unique Categories:
var uniqueCategories = repository.GetAllProducts()
.Select(p=>p.Category)
.Distinct();
function hasClass(ele,cls) {
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function removeClass(ele,cls) {
if (hasClass(ele,cls)) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
}
SQL Server may also return this error if the service account does not have permission to read the file being imported. Ensure that the service account has read access to the file location. For example:
icacls D:\ImportFiles /Grant "NT Service\MSSQLServer":(OI)(CI)R
Using round
:
>>> numvar = 135.12345678910
>>> str(round(numvar, 9))
'135.123456789'
Did you forget the Background Property. The brush should be an ImageBrush whose ImageSource could be set to your image path.
<Grid>
<Grid.Background>
<ImageBrush ImageSource="/path/to/image.png" Stretch="UniformToFill"/>
</Grid.Background>
<...>
</Grid>
I found the answer I was looking for. The thing to use here is the construct of
\left \middle \right
For example, in this case, two possible solutions are:
$\left( {\frac{a_1}{a_2}} \middle/ {\frac{b_1}{b_2}} \right) $
Or, in case the brackets are not necessary:
$\left. {\frac{a_1}{a_2}} \middle/ {\frac{b_1}{b_2}} \right. $
If you like doing it using ruby:
ruby -e "`gem list`.split(/$/).each { |line| puts `gem uninstall -Iax #{line.split(' ')[0]}` unless line.strip.empty? }"
Cheers
The great thing about yyyy-mm-dd
date format is that there is no need to extract month()
and year()
, you can do comparisons directly on strings:
SELECT *
FROM your_table
WHERE your_date_column >= '2010-09-01' AND your_date_column <= '2013-08-31';
Why not just call list()
on the Queryset
?
answers_list = list(answers)
This will also evaluate the QuerySet
/run the query. You can then remove/add from that list.
See Apple’s Info.plist reference for full details (thanks @gnasher729).
You can add exceptions for specific domains in your Info.plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>testdomain.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<true/>
<key>NSExceptionMinimumTLSVersion</key>
<string>TLSv1.2</string>
<key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
<false/>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<true/>
<key>NSThirdPartyExceptionMinimumTLSVersion</key>
<string>TLSv1.2</string>
<key>NSRequiresCertificateTransparency</key>
<false/>
</dict>
</dict>
</dict>
All the keys for each excepted domain are optional. The speaker did not elaborate on any of the keys, but I think they’re all reasonably obvious.
(Source: WWDC 2015 session 703, “Privacy and Your App”, 30:18)
You can also ignore all app transport security restrictions with a single key, if your app has a good reason to do so:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
If your app does not have a good reason, you may risk rejection:
Setting NSAllowsArbitraryLoads to true will allow it to work, but Apple was very clear in that they intend to reject apps who use this flag without a specific reason. The main reason to use NSAllowsArbitraryLoads I can think of would be user created content (link sharing, custom web browser, etc). And in this case, Apple still expects you to include exceptions that enforce the ATS for the URLs you are in control of.
If you do need access to specific URLs that are not served over TLS 1.2, you need to write specific exceptions for those domains, not use NSAllowsArbitraryLoads set to yes. You can find more info in the NSURLSesssion WWDC session.
Please be careful in sharing the NSAllowsArbitraryLoads solution. It is not the recommended fix from Apple.
— kcharwood (thanks @marco-tolman)
You can also do something like this ...
First create and Initialize the matrix or multidimensional arraylist
ArrayList<ArrayList<Integer>> list;
MultidimentionalArrayList(int x,int y)
{
list = new ArrayList<>();
for(int i=0;i<=x;i++)
{
ArrayList<Integer> temp = new ArrayList<>(Collections.nCopies(y+1,0));
list.add(temp);
}
}
void add(int row,int column,int val)
{
list.get(row).set(column,val); // list[row][column]=val
}
This static matrix can be change into dynamic if check that row and column are out of bound. just insert extra temp arraylist for row
int remove(int row, int column)
{
return list.get(row).remove(column);// del list[row][column]
}
This is due to a PHP 5.3.0 bug on Windows where MYSQL_ATTR_INIT_COMMAND is not available. The PHP bug report is:
http://bugs.php.net/bug.php?id=47224
If you are experiencing this, please update your WAMP product to a version that uses PHP 5.3.1 or later version.
it is wrong. correct will be
P3 P2 P4 P5 P1 0 3 4 6 10 as the correct difference are these
Waiting Time (0+3+4+6+10)/5 = 4.6
Ref: http://www.it.uu.se/edu/course/homepage/oskomp/vt07/lectures/scheduling_algorithms/handout.pdf
if the log4j.xml file is not in the project,and you are using tomcat, try going to tomcat instance and search for log4j. Try changing the consoleAppender level to debug and redeploy the application in tomcat. That might help.
In Windows console (Linux, too), you should replace '\r'
with its equivalent code \033[0G
:
process.stdout.write('ok\033[0G');
This uses a VT220 terminal escape sequence to send the cursor to the first column.
<head><script>var xxx = ${params.xxx}</script></head>
Using EL expression ${param.xxx} in <head>
to get params from a post method, and make sure the js file is included after <head>
so that you can handle a param like 'xxx' directly in your js file.
This can be done in java 8 using Stream.
import java.util.stream.Stream;
String[] stringList = {"Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue"};
boolean contains = Stream.of(stringList).anyMatch(x -> x.equals(say.getText());
dealing with dates, dateadd must be used for precision
declare @a DATE = getdate()
declare @b time(7) = getdate()
select @b, @A, GETDATE(), DATEADD(day, DATEDIFF(day, 0, @a), cast(@b as datetime2(0)))
The issue caused by the docker container which exits as soon as the "start" process finishes. i added a command that runs forever and it worked. This issue mentioned here
I like this approach
my_hash = {}
my_hash["goals"] = 3 #to show number
my_hash["penalties"] = "5" #to show string
print("I scored %(goals)d goals and took %(penalties)s penalties" % my_hash)
Note the appended d and s to the brackets respectively.
output will be:
I scored 3 goals and took 5 penalties
...additionally make sure to use:
mongoose.Promise = Promise;
This sets the mongoose promise to the native ES6 promise. Without this addition I got:
DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
ALTER TABLE xxx
AUTO_INCREMENT =1;
or
clear your table by TRUNCATE
DATABASE_URL=postgres://{user}:{password}@{hostname}:{port}/{database-name}
If I understood your problem correctly, $(this).parents('.box').children('.something1')
Is this what you are looking for?
Python 3
import openpyxl as xl
wb = xl.load_workbook("Sample.xlsx", enumerate)
#the 2 lines under do the same.
sheet = wb.get_sheet_by_name('sheet')
sheet = wb.worksheets[0]
row_count = sheet.max_row
column_count = sheet.max_column
#this works fore me.
In answer to this part of the original question "Is there any other C# method for hashing passwords" You can achieve this using ASP.NET Identity v3.0 https://www.nuget.org/packages/Microsoft.AspNet.Identity.EntityFramework/3.0.0-rc1-final
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using System.Security.Principal;
namespace HashTest{
class Program
{
static void Main(string[] args)
{
WindowsIdentity wi = WindowsIdentity.GetCurrent();
var ph = new PasswordHasher<WindowsIdentity>();
Console.WriteLine(ph.HashPassword(wi,"test"));
Console.WriteLine(ph.VerifyHashedPassword(wi,"AQAAAAEAACcQAAAAEA5S5X7dmbx/NzTk6ixCX+bi8zbKqBUjBhID3Dg1teh+TRZMkAy3CZC5yIfbLqwk2A==","test"));
}
}
}
You can set the line size as per the width of the window and set wrap off using the following command.
set linesize 160;
set wrap off;
I have used 160 as per my preference you can set it to somewhere between 100 - 200
and setting wrap will not your data and it will display the data properly.
use Contains of jquery Contains like this
if ($('.type:contains("> <")').length > 0)
{
//do stuffs to change
}
try setting this
CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"
in {$tomcat-folder}\bin\setenv.sh
(create it if necessary).
See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.
If you landed here just wondering how to limit to 2 decimal places I have a native javascript solution:
Javascript:
function limitDecimalPlaces(e, count) {
if (e.target.value.indexOf('.') == -1) { return; }
if ((e.target.value.length - e.target.value.indexOf('.')) > count) {
e.target.value = parseFloat(e.target.value).toFixed(count);
}
}
HTML:
<input type="number" oninput="limitDecimalPlaces(event, 2)" />
Note that this cannot AFAIK, defend against this chrome bug with the number input.
If you have added test.c to your Code::Blocks project, the definition will be seen twice - once via the #include and once by the linker. You need to:
Just noting a different way of questionable usefulness, using os.environ
:
import os
python_executable_path = os.environ['_']
e.g.
$ python -c "import os; print(os.environ['_'])"
/usr/bin/python
you can try
position: relative;
bottom: 20px;
but I don't see a problem on my browser (Google Chrome)
Somewhere in the code you are using, there is a call to the Win32 API, CoCreateInstance, to dynamically load a DLL and instantiate an object from it.
The mapping between the component ID and the DLL that is capable of instantiating that object is usually found in HEKY_CLASSES_ROOT\CLSID in the registry. To discuss this further would be to explain a lot about COM in Windows. But the error indicates that the COM guid is not present in the registry.
I don't much about what the PackAndGo DLL is (an Autodesk component), but I suspect you simply need to "install" that component or the software package it came with through the designated installer to have that DLL and appropriate COM registry keys on your computer you are trying to run your code on. (i.e. go run setup.exe for this product).
In other words, I think you need to install "Pack and Go" on this computer instead of just copying the DLL to the target machine.
Also, make sure you decide to build your code appropriate as 32-bit vs. 64-bit depending on the which build flavor (32 or 64 bit) of Pack And Go you install.
Try this,
.success { background-color: #ccffcc; float:left;}
The simplest change would be something like this:
public static void main (String[] args) throws Exception {
testconnect obj = new testconnect();
obj.con2 = DriverManager.getConnection(obj.getConnectionUrl2());
obj.con2.close();
}
The server SHOULD put double quotes around the filename, as mentioned by @cusman and @Touko in their replies.
For example:
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
The whole point of HttpOnly cookies is that they can't be accessed by JavaScript.
The only way (except for exploiting browser bugs) for your script to read them is to have a cooperating script on the server that will read the cookie value and echo it back as part of the response content. But if you can and would do that, why use HttpOnly cookies in the first place?
This will work:
decimal source = 2.4200m;
string output = ((double)source).ToString();
Or if your initial value is string
:
string source = "2.4200";
string output = double.Parse(source).ToString();
Pay attention to this comment.
Here is the best method that I've found: First, set your projects output type to "Windows Application", then P/Invoke AllocConsole to create a console window.
internal static class NativeMethods
{
[DllImport("kernel32.dll")]
internal static extern Boolean AllocConsole();
}
static class Program
{
static void Main(string[] args) {
if (args.Length == 0) {
// run as windows app
Application.EnableVisualStyles();
Application.Run(new Form1());
} else {
// run as console app
NativeMethods.AllocConsole();
Console.WriteLine("Hello World");
Console.ReadLine();
}
}
}
Only with 1 line of CSS… You can get this done.
body{ height: 100vh; }
Just use com.google.common.io.Resources class. Example:
URL url = Resources.getResource("file name")
After that you have methods like: .getContent(), .getFile(), .getPath() etc
Splash screen is a little unusable object in Android: it can not be loaded as soon as possible for hiding the delay of main activity starting. There are two reasons to use it: advertising and network operations.
Implementation as dialog makes jump without delay from splash screen to main UI of activity.
public class SplashDialog extends Dialog {
ImageView splashscreen;
SplashLoader loader;
int splashTime = 4000;
public SplashDialog(Context context, int theme) {
super(context, theme);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
setCancelable(false);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
cancel();
}
}, splashTime);
}
}
Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/white">
<ImageView
android:id="@+id/splashscreen"
android:layout_width="190dp"
android:layout_height="190dp"
android:background="@drawable/whistle"
android:layout_centerInParent="true" />
</RelativeLayout>
And start:
public class MyActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getIntent().getCategories() != null && getIntent().getCategories().contains("android.intent.category.LAUNCHER")) {
showSplashScreen();
}
}
protected Dialog splashDialog;
protected void showSplashScreen() {
splashDialog = new SplashDialog(this, R.style.SplashScreen);
splashDialog.show();
}
...
}
The error message told us, that the build-time dependency (in this case it is cc1
) was not found, so all we need — install the appropriate package to the system (using package manager // from sources // another way)
What is cc1
:
cc1
is the internal command which takes preprocessed C-language files and converts them to assembly. It's the actual part that compiles C. For C++, there's cc1plus, and other internal commands for different languages.
taken from this answer by Alan Shutko.
sudo apt-get update
sudo apt-get install --reinstall build-essential
If you are in docker-alpine environment install the build-base package by adding this to your Dockerfile
:
RUN apk add build-base
Better package name provided by Pablo Castellano. More details here.
If you need more packages for building purposes, consider adding of the alpine-sdk package:
RUN apk add alpine-sdk
Taken from github
This answer contains instructions for CentOS and Fedora Linux
sudo yum install gcc72-c++
Taken from this comment by CoderChris
You could also try to install missed dependencies by this (though, it is said to not to solve the issue):
sudo yum install gcc-c++.noarch
Taken from this answer
I was having the same issue and wanted to Mavenise entire eclipse workspace containing around 60 Eclipse projects. Doing so manually required a lot of time and alternate options were not that viable. To solve the issue I finally created a project called eclipse-to-maven on github. As eclipse doesn't have all necessary information about the dependencies, it does the following:
Based on <classpathentry/>
XML elements in .classpath file, it creates the dependencies on another project, identifies the library jar file and based on its name (for instance jakarta-oro-2.0.8.jar) identifies its version. Currently artifactId
and groupId
are same as I couldn't find something which could return me the Maven groupId of the dependency based on artifactId
. Though this is not a perfect solution it provides a good ground to speed up Mavenisation.
It moves all source folders according to Maven convention (like src/main/java
)
As Eclipse projects having names with spaces are difficult to deal on Linux/Unix environment, it renames them as well with names without spaces.
Resultant pom.xml files contain the dependencies and basic pom structure. You have to add required Maven plugins manually.
You can specify credentials by adding a new Generic Credential of your proxy server in Windows Credentials Manager:
1 In Web.config
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true">
<proxy usesystemdefault="True" />
</defaultProxy>
</system.net>
Internet or network address: your proxy address
User name: your user name
Password: you pass
This configuration worked for me, without change the code.
Displaying a video is much the same as displaying an image. The minor differences are to do with onload events and the fact that you need to render the video every frame or you will only see one frame not the animated frames.
The demo below has some minor differences to the example. A mute function (under the video click mute/sound on to toggle sound) and some error checking to catch IE9+ and Edge if they don't have the correct drivers.
Keeping answers current.The previous answers by user372551 is out of date (December 2010) and has a flaw in the rendering technique used. It uses the setTimeout
and a rate of 33.333..ms which setTimeout will round down to 33ms this will cause the frames to be dropped every two seconds and may drop many more if the video frame rate is any higher than 30. Using setTimeout
will also introduce video shearing created because setTimeout can not be synced to the display hardware.
There is currently no reliable method that can determine a videos frame rate unless you know the video frame rate in advance you should display it at the maximum display refresh rate possible on browsers. 60fps
The given top answer was for the time (6 years ago) the best solution as requestAnimationFrame
was not widely supported (if at all) but requestAnimationFrame
is now standard across the Major browsers and should be used instead of setTimeout to reduce or remove dropped frames, and to prevent shearing.
Loads a video and set it to loop. The video will not play until the you click on it. Clicking again will pause. There is a mute/sound on button under the video. The video is muted by default.
Note users of IE9+ and Edge. You may not be able to play the video format WebM as it needs additional drivers to play the videos. They can be found at tools.google.com Download IE9+ WebM support
// This code is from the example document on stackoverflow documentation. See HTML for link to the example._x000D_
// This code is almost identical to the example. Mute has been added and a media source. Also added some error handling in case the media load fails and a link to fix IE9+ and Edge support._x000D_
// Code by Blindman67._x000D_
_x000D_
_x000D_
// Original source has returns 404_x000D_
// var mediaSource = "http://video.webmfiles.org/big-buck-bunny_trailer.webm";_x000D_
// New source from wiki commons. Attribution in the leading credits._x000D_
var mediaSource = "http://upload.wikimedia.org/wikipedia/commons/7/79/Big_Buck_Bunny_small.ogv"_x000D_
_x000D_
var muted = true;_x000D_
var canvas = document.getElementById("myCanvas"); // get the canvas from the page_x000D_
var ctx = canvas.getContext("2d");_x000D_
var videoContainer; // object to hold video and associated info_x000D_
var video = document.createElement("video"); // create a video element_x000D_
video.src = mediaSource;_x000D_
// the video will now begin to load._x000D_
// As some additional info is needed we will place the video in a_x000D_
// containing object for convenience_x000D_
video.autoPlay = false; // ensure that the video does not auto play_x000D_
video.loop = true; // set the video to loop._x000D_
video.muted = muted;_x000D_
videoContainer = { // we will add properties as needed_x000D_
video : video,_x000D_
ready : false, _x000D_
};_x000D_
// To handle errors. This is not part of the example at the moment. Just fixing for Edge that did not like the ogv format video_x000D_
video.onerror = function(e){_x000D_
document.body.removeChild(canvas);_x000D_
document.body.innerHTML += "<h2>There is a problem loading the video</h2><br>";_x000D_
document.body.innerHTML += "Users of IE9+ , the browser does not support WebM videos used by this demo";_x000D_
document.body.innerHTML += "<br><a href='https://tools.google.com/dlpage/webmmf/'> Download IE9+ WebM support</a> from tools.google.com<br> this includes Edge and Windows 10";_x000D_
_x000D_
}_x000D_
video.oncanplay = readyToPlayVideo; // set the event to the play function that _x000D_
// can be found below_x000D_
function readyToPlayVideo(event){ // this is a referance to the video_x000D_
// the video may not match the canvas size so find a scale to fit_x000D_
videoContainer.scale = Math.min(_x000D_
canvas.width / this.videoWidth, _x000D_
canvas.height / this.videoHeight); _x000D_
videoContainer.ready = true;_x000D_
// the video can be played so hand it off to the display function_x000D_
requestAnimationFrame(updateCanvas);_x000D_
// add instruction_x000D_
document.getElementById("playPause").textContent = "Click video to play/pause.";_x000D_
document.querySelector(".mute").textContent = "Mute";_x000D_
}_x000D_
_x000D_
function updateCanvas(){_x000D_
ctx.clearRect(0,0,canvas.width,canvas.height); _x000D_
// only draw if loaded and ready_x000D_
if(videoContainer !== undefined && videoContainer.ready){ _x000D_
// find the top left of the video on the canvas_x000D_
video.muted = muted;_x000D_
var scale = videoContainer.scale;_x000D_
var vidH = videoContainer.video.videoHeight;_x000D_
var vidW = videoContainer.video.videoWidth;_x000D_
var top = canvas.height / 2 - (vidH /2 ) * scale;_x000D_
var left = canvas.width / 2 - (vidW /2 ) * scale;_x000D_
// now just draw the video the correct size_x000D_
ctx.drawImage(videoContainer.video, left, top, vidW * scale, vidH * scale);_x000D_
if(videoContainer.video.paused){ // if not playing show the paused screen _x000D_
drawPayIcon();_x000D_
}_x000D_
}_x000D_
// all done for display _x000D_
// request the next frame in 1/60th of a second_x000D_
requestAnimationFrame(updateCanvas);_x000D_
}_x000D_
_x000D_
function drawPayIcon(){_x000D_
ctx.fillStyle = "black"; // darken display_x000D_
ctx.globalAlpha = 0.5;_x000D_
ctx.fillRect(0,0,canvas.width,canvas.height);_x000D_
ctx.fillStyle = "#DDD"; // colour of play icon_x000D_
ctx.globalAlpha = 0.75; // partly transparent_x000D_
ctx.beginPath(); // create the path for the icon_x000D_
var size = (canvas.height / 2) * 0.5; // the size of the icon_x000D_
ctx.moveTo(canvas.width/2 + size/2, canvas.height / 2); // start at the pointy end_x000D_
ctx.lineTo(canvas.width/2 - size/2, canvas.height / 2 + size);_x000D_
ctx.lineTo(canvas.width/2 - size/2, canvas.height / 2 - size);_x000D_
ctx.closePath();_x000D_
ctx.fill();_x000D_
ctx.globalAlpha = 1; // restore alpha_x000D_
} _x000D_
_x000D_
function playPauseClick(){_x000D_
if(videoContainer !== undefined && videoContainer.ready){_x000D_
if(videoContainer.video.paused){ _x000D_
videoContainer.video.play();_x000D_
}else{_x000D_
videoContainer.video.pause();_x000D_
}_x000D_
}_x000D_
}_x000D_
function videoMute(){_x000D_
muted = !muted;_x000D_
if(muted){_x000D_
document.querySelector(".mute").textContent = "Mute";_x000D_
}else{_x000D_
document.querySelector(".mute").textContent= "Sound on";_x000D_
}_x000D_
_x000D_
_x000D_
}_x000D_
// register the event_x000D_
canvas.addEventListener("click",playPauseClick);_x000D_
document.querySelector(".mute").addEventListener("click",videoMute)
_x000D_
body {_x000D_
font :14px arial;_x000D_
text-align : center;_x000D_
background : #36A;_x000D_
}_x000D_
h2 {_x000D_
color : white;_x000D_
}_x000D_
canvas {_x000D_
border : 10px white solid;_x000D_
cursor : pointer;_x000D_
}_x000D_
a {_x000D_
color : #F93;_x000D_
}_x000D_
.mute {_x000D_
cursor : pointer;_x000D_
display: initial; _x000D_
}
_x000D_
<h2>Basic Video & canvas example</h2>_x000D_
<p>Code example from Stackoverflow Documentation HTML5-Canvas<br>_x000D_
<a href="https://stackoverflow.com/documentation/html5-canvas/3689/media-types-and-the-canvas/14974/basic-loading-and-playing-a-video-on-the-canvas#t=201607271638099201116">Basic loading and playing a video on the canvas</a></p>_x000D_
<canvas id="myCanvas" width = "532" height ="300" ></canvas><br>_x000D_
<h3><div id = "playPause">Loading content.</div></h3>_x000D_
<div class="mute"></div><br>_x000D_
<div style="font-size:small">Attribution in the leading credits.</div><br>
_x000D_
Using the canvas to render video gives you additional options in regard to displaying and mixing in fx. The following image shows some of the FX you can get using the canvas. Using the 2D API gives a huge range of creative possibilities.
Image relating to answer Fade canvas video from greyscale to color
See video title in above demo for attribution of content in above inmage.
I think Semaphore is what you are looking for, it will block the main process after counting down to 0. Sample code:
from multiprocessing import Process
from multiprocessing import Semaphore
import time
def f(name, sema):
print('process {} starting doing business'.format(name))
# simulate a time-consuming task by sleeping
time.sleep(5)
# `release` will add 1 to `sema`, allowing other
# processes blocked on it to continue
sema.release()
if __name__ == '__main__':
concurrency = 20
total_task_num = 1000
sema = Semaphore(concurrency)
all_processes = []
for i in range(total_task_num):
# once 20 processes are running, the following `acquire` call
# will block the main process since `sema` has been reduced
# to 0. This loop will continue only after one or more
# previously created processes complete.
sema.acquire()
p = Process(target=f, args=(i, sema))
all_processes.append(p)
p.start()
# inside main process, wait for all processes to finish
for p in all_processes:
p.join()
The following code is more structured since it acquires and releases sema
in the same function. However, it will consume too much resources if total_task_num
is very large:
from multiprocessing import Process
from multiprocessing import Semaphore
import time
def f(name, sema):
print('process {} starting doing business'.format(name))
# `sema` is acquired and released in the same
# block of code here, making code more readable,
# but may lead to problem.
sema.acquire()
time.sleep(5)
sema.release()
if __name__ == '__main__':
concurrency = 20
total_task_num = 1000
sema = Semaphore(concurrency)
all_processes = []
for i in range(total_task_num):
p = Process(target=f, args=(i, sema))
all_processes.append(p)
# the following line won't block after 20 processes
# have been created and running, instead it will carry
# on until all 1000 processes are created.
p.start()
# inside main process, wait for all processes to finish
for p in all_processes:
p.join()
The above code will create total_task_num
processes but only concurrency
processes will be running while other processes are blocked, consuming precious system resources.
Still no Truncate method in 2016 for C# strings. But - Using C# 6.0 Syntax:
public static class StringExtension
{
public static string Truncate(this string s, int max)
{
return s?.Length > max ? s.Substring(0, max) : s ?? throw new ArgumentNullException(s);
}
}
It works like a charm:
"Truncate me".Truncate(8);
Result: "Truncate"
Note:drawRect
and fillRect
are different.
Draws the outline of the specified rectangle:
public void drawRect(int x,
int y,
int width,
int height)
Fills the specified rectangle. The rectangle is filled using the graphics context's current color:
public abstract void fillRect(int x,
int y,
int width,
int height)
<?php
$string = "producturl.php?id=736375493?=tm";
preg_match('~id=(\d+)~', $string, $m );
var_dump($m[1]); // $m[1] is your string
?>
You can do:
super.alphaMethod1();
Note, that super
is a reference to the parent, but super() is it's constructor.
Suppose
letter= ['a','','b','c']
for i in range(len(letter)):
if letter[i] =='':
print(str(i) + ' is empty')
output- 1 is emtpy
So we can see index 1 is empty.
You simply use this in one row.
$query = $this->db->get_where('mytable',array('id'=>'3'));
Python datetime object has a method attribute, which prints in readable format.
>>> a = datetime.now()
>>> a.ctime()
'Mon May 21 18:35:18 2018'
>>>
I ran into this trying to integrate React Native into an existing swift project using cocoapods. The FB docs (at time of writing) did not specify that npm install react-native
wouldn't work without first having a package.json
file. Per the RN docs set your entry point: (index.js)
as index.ios.js
You can use this way to fulfill this requirement. I use the below method to validate the Password and Confirm Password.
To use this method you have to import FormGroup
from @angular/forms
library.
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
FormBuilder Group:
this.myForm= this.formBuilder.group({
password : ['', Validators.compose([Validators.required])],
confirmPassword : ['', Validators.compose([Validators.required])],
},
{validator: this.checkPassword('password', 'confirmPassword') }
);
Method to Validate two fields:
checkPassword(controlName: string, matchingControlName: string) {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.mustMatch) {
// return if another validator has already found an error on the matchingControl
return;
}
// set error on matchingControl if validation fails
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ mustMatch: true });
this.isPasswordSame = (matchingControl.status == 'VALID') ? true : false;
} else {
matchingControl.setErrors(null);
this.isPasswordSame = (matchingControl.status == 'VALID') ? true : false;
}
}
}
HTML: Here I am use personalized isPasswordSame variable you can use the inbuilt hasError or any other.
<form [formGroup]="myForm">
<ion-item>
<ion-label position="floating">Password</ion-label>
<ion-input required type="text" formControlName="password" placeholder="Enter Password"></ion-input>
</ion-item>
<ion-label *ngIf="myForm.controls.password.valid">
<p class="error">Please enter password!!</p>
</ion-label>
<ion-item>
<ion-label position="floating">Confirm Password</ion-label>
<ion-input required type="text" formControlName="confirmPassword" placeholder="Enter Confirm Password"></ion-input>
</ion-item>
<ion-label *ngIf="isPasswordSame">
<p class="error">Password and Confrim Password must be same!!</p>
</ion-label>
</form>
This is what worked for me.
1.clear db.
heroku pg:reset --app YOUR_APP
After running that you will have to type in your app name again to confirm.
2.migrate db to recreate.
heroku run rake db:migrate --app YOUR_APP
3.add seed data to db.
heroku run rake db:seed --app YOUR_APP
I agree with @aaronasterling's answer. However, if you want a non-binary string that you can cast into an int, then you can use the canonical algorithm:
def decToBin(n):
if n==0: return ''
else:
return decToBin(n/2) + str(n%2)
you should use rownum in oracle to do what you seek
where rownum <= 100
see also those answers to help you
check your Project Properties, your Reference Paths should be empty like this:
Regards
I use div instead of tables and am able to target classes within the main class, as below:
.main {
.width: 800px;
.margin: 0 auto;
.text-align: center;
}
.main .table {
width: 80%;
}
.main .row {
/ ***something ***/
}
.main .column {
font-size: 14px;
display: inline-block;
}
.main .left {
width: 140px;
margin-right: 5px;
font-size: 12px;
}
.main .right {
width: auto;
margin-right: 20px;
color: #fff;
font-size: 13px;
font-weight: normal;
}
<div class="main">
<div class="table">
<div class="row">
<div class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:
.main #red { color: red; }
<div class="main">
<div class="table">
<div class="row">
<div id="red" class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
You can read about it here.
return render_template('page.html'), 201
I have crafted this piece of code that worked for me to detect when I scroll to the end of an element!
let element = $('.element');
if ($(document).scrollTop() > element.offset().top + element.height()) {
/// do something ///
}
If you want to get the indices of the largest n
numbers in a list called data
, you can use Pandas sort_values
:
pd.Series(data).sort_values(ascending=False).index[0:n]
The correct answer is, that, because the '%'
-sign is part of your search expression, it should be part of your VALUE, so whereever you SET @LastName
(be it from a programming language or from TSQL) you should set it to '%' + [userinput] + '%'
or, in your example:
DECLARE @LastName varchar(max)
SET @LastName = 'ning'
SELECT Employee WHERE LastName LIKE '%' + @LastName + '%'
RecyclerView was created as a ListView improvement, so yes, you can create an attached list with ListView control, but using RecyclerView is easier as it:
Reuses cells while scrolling up/down : this is possible with implementing View Holder in the ListView adapter, but it was an optional thing, while in the RecycleView it's the default way of writing adapter.
Decouples list from its container : so you can put list items easily at run time in the different containers (linearLayout, gridLayout) with setting LayoutManager.
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
So, to conclude, RecyclerView is a more flexible control for handling "list data" that follows patterns of delegation of concerns and leaves for itself only one task - recycling items.
You could implement a ring buffer. Make an array of 1000 elements, and some fields to store the start and end indexes and total size. Then just store the last 1000 elements in the ring buffer, and recalculate the average as needed.
If you're on Django 1.10 or newer AND Postgres as your database, you can use ArrayField. It's better to use than django-taggit
or other alternatives, as it's native to the Django framework.
https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/fields/#arrayfield
from django.db import models
from django.contrib.postgres.fields import ArrayField
class ChessBoard(models.Model):
board = ArrayField(
ArrayField(
models.CharField(max_length=10, blank=True),
size=8,
),
size=8,
)
If you're on Django 3.1 or newer they've added support for JSONField with most database backends (MariaDB 10.2.7+, MySQL 5.7.8+, Oracle, PostgreSQL, and SQLite 3.9.0+). You can use this to store your Array!
https://docs.djangoproject.com/en/3.1/ref/models/fields/#jsonfield
from django.db import models
class ChessBoard(models.Model):
list_of_pieces = models.JSONField()
Check if there is a file called maintenance.flag and if so delete it.
Magento 1.x : maintenance.flag file is in : magento root directory
Magento 2.x : maintenance.flag file is in : var folder
When Magento is performing certain tasks it temporarily creates this file. Magento checks for its existence and if it's there will send users to the page you described.
It's supposed to automatically delete this file when done processing whatever task it was doing, but I've experienced occasions where something went wrong and it failed to delete it.
I had that same problem when I tried to add the firebase-database implementation, if I commented that line it works, so after a few tries I went to https://firebase.google.com/docs/android/setup
There I checked the versions of the available libraries and my firebase-core was at 16.0.1 (current version is 16.0.4) so I manually changed it and it worked just fine, build and sync were successful.
I think this is a simple example, how to check if a radio in a group of radios was checked.
if($('input[name=html_elements]:checked').length){
//a radio button was checked
}else{
//there was no radio button checked
}
You could use Javascript to achieve this effect. If you use a framework this sort of thing becomes quite simple. Here is an example in jQuery:
$('div#id').click(function (e) {
// Do whatever you want
});
This solution has the distinct advantage of keeping the logic not in your markup.
In this line:
fund = fund * (1 + 0.01 * growthRates) + depositPerYear
growthRates is a sequence ([3,4,5,0,3]
). You can't multiply that sequence by a float (0.1). It looks like what you wanted to put there was i
.
Incidentally, i
is not a great name for that variable. Consider something more descriptive, like growthRate
or rate
.
From my notes:
Which parses like this:
q=latN+lonW+(label) location of teardrop
t=k keyhole (satelite map)
t=h hybrid
ll=lat,-lon center of map
spn=w.w,h.h span of map, degrees
iwloc has something to do with the info window. hl is obviously language.
See also: http://www.seomoz.org/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters
Thanks to Don Branson,I solve my problem.I think next time i should use this code when i build my repo on server:
root@localhost:~#mkdir foldername
root@localhost:~#cd foldername
root@localhost:~#git init --bare
root@localhost:~#cd ../
root@localhost:~#chown -R usergroup:username foldername
And on client,i user this
$ git remote add origin git@servername:/var/git/foldername
$ git push origin master
Or you can do this without using Delay.
set /a "counter=0"
-> your for loop here
do (
statement1
statement2
call :increaseby1
)
:increaseby1
set /a "counter+=1"
In many cases the only suitable answer is the one of Igor Ostrovsky , other answers are based on objects hash code. But when you generate an hash code for an object you do so only based on his IMMUTABLE fields - such as object Id field (in case of a database entity) - Why is it important to override GetHashCode when Equals method is overridden?
This means , that if you compare two collections , the result might be true of the compare method even though the fields of the different items are non-equal . To deep compare collections , you need to use Igor's method and implement IEqualirity .
Please read the comments of me and mr.Schnider's on his most voted post.
James
You can define a Range, the size of your array and use it's value property:
Sub PrintArray(Data, SheetName As String, intStartRow As Integer, intStartCol As Integer)
Dim oWorksheet As Worksheet
Dim rngCopyTo As Range
Set oWorksheet = ActiveWorkbook.Worksheets(SheetName)
' size of array
Dim intEndRow As Integer
Dim intEndCol As Integer
intEndRow = UBound(Data, 1)
intEndCol = UBound(Data, 2)
Set rngCopyTo = oWorksheet.Range(oWorksheet.Cells(intStartRow, intStartCol), oWorksheet.Cells(intEndRow, intEndCol))
rngCopyTo.Value = Data
End Sub
The simplest solution is to apply Python str
function to the column you are trying to loop through.
If you are using pandas
, this can be implemented as:
dataframe['column_name']=dataframe['column_name'].apply(str)
What finally fixed this for me was to use GitHub desktop, go to repository settings, and remove user:pass@ from the repository url. Then, I attempted a push from the command line and was prompted for login credentials. After I put those in everything went back to normal. Both Visual Studio and command line are working, and of course, GitHub desktop.
GitHub Desktop->Repository->Repository Settings->Remote tab
Change Primary Remote Repository (origin) from:
https://pork@[email protected]/MyProject/MyProject.git
To:
https://github.com/MyProject/MyProject.git
Click "Save"
Credentials will be cleared.
A little more reusable function:
beginsWith = function(needle, haystack){
return (haystack.substr(0, needle.length) == needle);
}
you just add this style in your style.xml
file which is in your values folder
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
After that set this style to your activity class in your AndroidManifest.xml file
android:theme="@style/AppTheme.NoActionBar"
Edit:- If you are going with programmatic way to hide ActionBar then use below code in your activity onCreate()
method.
if(getSupportedActionbar()!=null)
this.getSupportedActionBar().hide();
and if you want to hide ActionBar from Fragment then
getActivity().getSupportedActionBar().hide();
AppCompat v7:-
Use following theme in your Activities where you don't want actiobBar Theme.AppComat.NoActionBar
or Theme.AppCompat.Light.NoActionBar
or if you want to hide in whole app then set this theme in your <application... />
in your AndroidManifest
.
In Kotlin:
add this line of code in your onCreate()
method or you can use above theme.
if (supportActionBar != null)
supportActionBar?.hide()
i hope this will help you more.
You can do that with the below code:
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition
OK, now I feel stupid. The first two definitely do not work but the second two do. Not sure how I convinced my self that I had tried them. Sorry for wasting everyone's time.
In case this helps anyone else, this can occur when you are trying to make a new file in a directory that does not exist.
Wrap in a div styled with "text-center" class.
One more trick for controller event listeners.
You can use wildcards to watch for an event from any component:
this.control({
'*':{
myCustomEvent: this.doSomething
}
});
try to handle the error, its an attribute error given by OpenCV
try:
img.shape
print("checked for shape".format(img.shape))
except AttributeError:
print("shape not found")
#code to move to next frame
You can %HOMEDRIVE%%HOMEPATH%
for the drive + \docs settings\username
or \users\username
.
You can do this with two command sequences. First define an array with the name of the files you do not want to exclude:
files=( backup.tar.gz script.php database.sql info.txt )
After that, loop through all files in the directory you want to exclude, checking if the filename is in the array you don't want to exclude; if its not then delete the file.
for file in *; do
if [[ ! " ${files[@]} " ~= "$file" ]];then
rm "$file"
fi
done
I had the same problem earlier when I tried to edit an open source project from the internet .
Solved it by just Cleaning the solution and rebuilding it .
Hope this helps.
As a number of people have pointed out, disabling the submit button has some negative side effects (at least in Chrome it prevents the name/value of the button pressed from being submitted). My solution was to simply add an attribute to indicate that submit has been requested, and then check for the presence of this attribute on every submit. Because I'm using the submit function, this is only called after all HTML 5 validation is successful. Here is my code:
$("form.myform").submit(function (e) {
// Check if we have submitted before
if ( $("#submit-btn").attr('attempted') == 'true' ) {
//stop submitting the form because we have already clicked submit.
e.preventDefault();
}
else {
$("#submit-btn").attr("attempted", 'true');
}
});
$ echo "This is a sentence." | tr -s " " "\012"
This
is
a
sentence.
For checking for spaces, use grep:
$ echo "This is a sentence." | grep " " > /dev/null
$ echo $?
0
$ echo "Thisisasentence." | grep " " > /dev/null
$ echo $?
1
Yes it's an issue in webkit and also reported in chromium: http://code.google.com/p/chromium/issues/detail?id=773 It's there since 2008... and still not fixed!!
I'm using a piece of javacsript and jQuery to make my way around this.
function showAlt(){$(this).replaceWith(this.alt)};
function addShowAlt(selector){$(selector).error(showAlt).attr("src", $(selector).src)};
addShowAlt("img");
If you only want one some images:
addShowAlt("#myImgID");
I used the cookie method:
In my manifest.js file I included a content script that only runs on my site:
"content_scripts": [
{
"matches": [
"*://*.mysite.co/*"
],
"js": ["js/mysite.js"],
"run_at": "document_idle"
}
],
in my js/mysite.js I have one line:
document.cookie = "extension_downloaded=True";
and in my index.html page I look for that cookie.
if (document.cookie.indexOf('extension_downloaded') != -1){
document.getElementById('install-btn').style.display = 'none';
}
If you want to have an affix on your header you can use this tricks, add position: relative on your th and change the position in eventListener('scroll')
I have created an example: https://codesandbox.io/s/rl1jjx0o
I use vue.js but you can use this, without vue.js
A simple solution using fscanf
:
void read_ints (const char* file_name)
{
FILE* file = fopen (file_name, "r");
int i = 0;
fscanf (file, "%d", &i);
while (!feof (file))
{
printf ("%d ", i);
fscanf (file, "%d", &i);
}
fclose (file);
}
Convert a String to ByteBuffer, then from ByteBuffer back to String using Java:
import java.nio.charset.Charset;
import java.nio.*;
String babel = "obufscate thdé alphebat and yolo!!";
System.out.println(babel);
//Convert string to ByteBuffer:
ByteBuffer babb = Charset.forName("UTF-8").encode(babel);
try{
//Convert ByteBuffer to String
System.out.println(new String(babb.array(), "UTF-8"));
}
catch(Exception e){
e.printStackTrace();
}
Which prints the printed bare string first, and then the ByteBuffer casted to array():
obufscate thdé alphebat and yolo!!
obufscate thdé alphebat and yolo!!
Also this was helpful for me, reducing the string to primitive bytes can help inspect what's going on:
String text = "?????";
//convert utf8 text to a byte array
byte[] array = text.getBytes("UTF-8");
//convert the byte array back to a string as UTF-8
String s = new String(array, Charset.forName("UTF-8"));
System.out.println(s);
//forcing strings encoded as UTF-8 as an incorrect encoding like
//say ISO-8859-1 causes strange and undefined behavior
String sISO = new String(array, Charset.forName("ISO-8859-1"));
System.out.println(sISO);
Prints your string interpreted as UTF-8, and then again as ISO-8859-1:
?????
ããã«ã¡ã¯
You can use grep to get the byte-offset of the matching part of a string:
echo $str | grep -b -o str
As per your example:
[user@host ~]$ echo "The cat sat on the mat" | grep -b -o cat
4:cat
you can pipe that to awk if you just want the first part
echo $str | grep -b -o str | awk 'BEGIN {FS=":"}{print $1}'
That's not possible using the built-in Array.prototype.map
. However, you could use a simple for
-loop instead, if you do not intend to map
any values:
var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] < 10) {
hasValueLessThanTen = true;
break;
}
}
Or, as suggested by @RobW
, use Array.prototype.some
to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:
var hasValueLessThanTen = myArray.some(function (val) {
return val < 10;
});
Sometimes the dependencies don't update even with Maven->Update Project->Force Update option checked using m2eclipse plugin.
In case it doesn't work for anyone else, this method worked for me:
mvn eclipse:eclipse
This will update your .classpath file with the new dependencies while preserving your .project settings and other eclipse config files.
If you want to clear your old settings for whatever reason, you can run:
mvn eclipse:clean
mvn eclipse:eclipse
mvn eclipse:clean will erase your old settings, then mvn eclipse:eclipse will create new .project, .classpath and other eclipse config files.
At the current version of Spring-Boot (1.4.1.RELEASE) , each pooling datasource implementation has its own prefix for properties.
For instance, if you are using tomcat-jdbc:
spring.datasource.tomcat.max-wait=10000
You can find the explanation out here
spring.datasource.max-wait=10000
this have no effect anymore.
I could able to make it work only by adding GRANT OPTION
, without that always receive permission denied error
GRANT ALL PRIVILEGES ON mydb.* TO 'myuser'@'localhost' WITH GRANT OPTION;
I combined parts from marxin's and kuxa's excellent answers to create a jQuery custom function that
sorts the options by their text values (case-insensitive),
maintains any already-selected value, and
returns the original jQuery objects against which the function is executed:
$.fn.extend({
sortSelect() {
return this.each(function(){
let $this = $(this),
original_selection = $this.val(),
$options = $this.find('option'),
arr = $options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
arr.sort((o1, o2) => {
// sort select
let t1 = o1.t.toLowerCase(),
t2 = o2.t.toLowerCase();
return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
});
$options.each((i, o) => {
o.value = arr[i].v;
$(o).text(arr[i].t);
});
$this.val(original_selection);
})
}
});
Working example on jsFiddle is available at https://jsfiddle.net/jhfrench/64och25e/.
Avoid PNG in any case if you want reliable IE6 compatibility.
The following example works on both ssl and non-ssl and is much faster as you use just one rule to manage http and https
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTPS}s on(s)|offs()
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]
[Tested]
This will redirect
http
to
https
to
I am not sure if this has to be explicitly enabled anywhere..but for this to work in the first place you need to include the javadoc jar files with the related jars in your project. Then when you do a Cntrl+Space it shows autocomplete and javadocs.
Just 2 simple steps to solve your issue
First of all check AppendDataBoundItems property and make it assign false
Secondly clear all the items using property .clear()
{
ddl1.Items.Clear();
ddl1.datasource = sql1;
ddl1.DataBind();
}
A really nice way to implement an isUTF8
-function can be found on php.net:
function isUTF8($string) {
return (utf8_encode(utf8_decode($string)) == $string);
}
These are really two questions.
The first one is answered here: Calling a Sub in VBA
To the second one, protip: there is no main subroutine in VBA. Forget procedural, general-purpose languages. VBA subs are "macros" - you can run them by hitting Alt+F8 or by adding a button to your worksheet and calling up the sub you want from the automatically generated "ButtonX_Click" sub.
Try this
getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath()
var isElement = function(e){
try{
// if e is an element attached to the DOM, we trace its lineage and use native functions to confirm its pedigree
var a = [e], t, s, l = 0, h = document.getElementsByTagName('HEAD')[0], ht = document.getElementsByTagName('HTML')[0];
while(l!=document.body&&l!=h&&l.parentNode) l = a[a.push(l.parentNode)-1];
t = a[a.length-1];
s = document.createElement('SCRIPT'); // safe to place anywhere and it won't show up
while(a.length>1){ // assume the top node is an element for now...
var p = a.pop(),n = a[a.length-1];
p.insertBefore(s,n);
}
if(s.parentNode)s.parentNode.removeChild(s);
if(t!=document.body&&t!=h&&t!=ht)
// the top node is not attached to the document, so we don't have to worry about it resetting any dynamic media
// test the top node
document.createElement('DIV').appendChild(t).parentNode.removeChild(t);
return e;
}
catch(e){}
return null;
}
I tested this on Firefox, Safari, Chrome, Opera and IE9. I couldn't find a way to hack it.
In theory, it tests every ancestor of the proposed element, as well as the element itself, by inserting a script tag before it.
If its first ancestor traces back to a known element, such as <html>
, <head>
or <body>
, and it hasn't thrown an error along the way, we have an element.
If the first ancestor is not attached to the document, we create an element and attempt to place the proposed element inside of it, (and then remove it from the new element).
So it either traces back to a known element, successfully attaches to a known element or fails.
It returns the element or null if it is not an element.
I'd recommend this article on CSS Tricks by Chris Coyier entitled Better Helvetica:
http://css-tricks.com/snippets/css/better-helvetica/
He basically recommends the following declaration for covering all the bases:
body {
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-weight: 300;
}
font-family:'Open Sans' , sans-serif;
For light:
font-weight : 100;
Or
font-weight : lighter;
For normal:
font-weight : 500;
Or
font-weight : normal;
For bold:
font-weight : 700;
Or
font-weight : bold;
For more bolder:
font-weight : 900;
Or
font-weight : bolder;
The main reason for using em or percentages is to allow the user to change the text size without breaking the design. If you design with fonts specified in px, they do not change size (in IE 6 and others) if the user chooses text size - larger. This is very bad for users with visual handicaps.
For several examples of and articles on designs like this (there are a myriad to choose from), see the latest issue of A List Apart: Fluid Grids, the older article How to Size Text in CSS or Dan Cederholm's Bulletproof Web Design.
Your images should still be displayed with px sizes, but, in general, it is not considered good form to size your text with px.
As much as I personally despise IE6, it is currently the only browser approved for the bulk of the users in our Fortune 200 company.
Rather than trying to roll your own logic for determining the country code of a phone number, I highly recommend using Google's libphonenumber project. This project is very extensive and well maintained, and has been ported to a several languages.
You have to check every ID in tableA against every ID in tableB. A fully featured RDBMS (such as Oracle) would be able to optimize that into an INDEX FULL FAST SCAN and not touch the table at all. I don't know whether H2's optimizer is as smart as that.
H2 does support the MINUS syntax so you should try this
select id from tableA
minus
select id from tableB
order by id desc
That may perform faster; it is certainly worth benchmarking.
I went through all the answers. But none of them is beginner friendly. So here I have given a very detailed answers fully explained with pictures.
Open Android Studio. Go to Project Window and scroll to drawable folder under res folder
Right click, select New --> drawable resource folder
In the window that appears, name the file rounded_corners
and click on OK
A new file rounded_corners.xml
gets created
Open the file. You are presented with the following code -->
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://android.com/apk/res/android">
</selector>
Replace it with the following code -->
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="8dp" />
<solid android:color="#66b3ff" />
</shape>
Here the design view can be seen on the right side
Adjust the value in android:radius
to make the button more or less rounded.
Then go to activity_main.xml
Put the following code -->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:padding="10dp">
<Button
android:id="@+id/_1"
android:text="1"
android:textSize="25dp"
android:textColor="#ffffff"
android:background="@drawable/rounded_corners"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"/>
</RelativeLayout>
Here I have placed the Button
inside a RelativeLayout
. You can use any Layout
you want.
For reference purpose MainActivity.java
code is as follows -->
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
I have a Pixel 4 API 30 avd installed. After running the code in the avd the display is as follows -->
I too was looking for a good way to do this, I found the best way was to set a transition on the "transform" property and then change the transform and then remove the transition.
I put it all together in a jQuery plugin
https://gist.github.com/dustinpoissant/8a4837c476e3939a5b3d1a2585e8d1b0
You would use the code like this:
$("#myElement").animateTransform("rotate(180deg)", 750, function(){
console.log("animation completed after 750ms");
});
Same as apply, now with spread :
const maxDate = new Date(Math.max(...dates));
(could be a comment on best answer)
string
? wstring
?std::string
is a basic_string
templated on a char
, and std::wstring
on a wchar_t
.
char
vs. wchar_t
char
is supposed to hold a character, usually an 8-bit character.
wchar_t
is supposed to hold a wide character, and then, things get tricky:
On Linux, a wchar_t
is 4 bytes, while on Windows, it's 2 bytes.
The problem is that neither char
nor wchar_t
is directly tied to unicode.
Let's take a Linux OS: My Ubuntu system is already unicode aware. When I work with a char string, it is natively encoded in UTF-8 (i.e. Unicode string of chars). The following code:
#include <cstring>
#include <iostream>
int main(int argc, char* argv[])
{
const char text[] = "olé" ;
std::cout << "sizeof(char) : " << sizeof(char) << std::endl ;
std::cout << "text : " << text << std::endl ;
std::cout << "sizeof(text) : " << sizeof(text) << std::endl ;
std::cout << "strlen(text) : " << strlen(text) << std::endl ;
std::cout << "text(ordinals) :" ;
for(size_t i = 0, iMax = strlen(text); i < iMax; ++i)
{
std::cout << " " << static_cast<unsigned int>(
static_cast<unsigned char>(text[i])
);
}
std::cout << std::endl << std::endl ;
// - - -
const wchar_t wtext[] = L"olé" ;
std::cout << "sizeof(wchar_t) : " << sizeof(wchar_t) << std::endl ;
//std::cout << "wtext : " << wtext << std::endl ; <- error
std::cout << "wtext : UNABLE TO CONVERT NATIVELY." << std::endl ;
std::wcout << L"wtext : " << wtext << std::endl;
std::cout << "sizeof(wtext) : " << sizeof(wtext) << std::endl ;
std::cout << "wcslen(wtext) : " << wcslen(wtext) << std::endl ;
std::cout << "wtext(ordinals) :" ;
for(size_t i = 0, iMax = wcslen(wtext); i < iMax; ++i)
{
std::cout << " " << static_cast<unsigned int>(
static_cast<unsigned short>(wtext[i])
);
}
std::cout << std::endl << std::endl ;
return 0;
}
outputs the following text:
sizeof(char) : 1
text : olé
sizeof(text) : 5
strlen(text) : 4
text(ordinals) : 111 108 195 169
sizeof(wchar_t) : 4
wtext : UNABLE TO CONVERT NATIVELY.
wtext : ol?
sizeof(wtext) : 16
wcslen(wtext) : 3
wtext(ordinals) : 111 108 233
You'll see the "olé" text in char
is really constructed by four chars: 110, 108, 195 and 169 (not counting the trailing zero). (I'll let you study the wchar_t
code as an exercise)
So, when working with a char
on Linux, you should usually end up using Unicode without even knowing it. And as std::string
works with char
, so std::string
is already unicode-ready.
Note that std::string
, like the C string API, will consider the "olé" string to have 4 characters, not three. So you should be cautious when truncating/playing with unicode chars because some combination of chars is forbidden in UTF-8.
On Windows, this is a bit different. Win32 had to support a lot of application working with char
and on different charsets/codepages produced in all the world, before the advent of Unicode.
So their solution was an interesting one: If an application works with char
, then the char strings are encoded/printed/shown on GUI labels using the local charset/codepage on the machine. For example, "olé" would be "olé" in a French-localized Windows, but would be something different on an cyrillic-localized Windows ("ol?" if you use Windows-1251). Thus, "historical apps" will usually still work the same old way.
For Unicode based applications, Windows uses wchar_t
, which is 2-bytes wide, and is encoded in UTF-16, which is Unicode encoded on 2-bytes characters (or at the very least, the mostly compatible UCS-2, which is almost the same thing IIRC).
Applications using char
are said "multibyte" (because each glyph is composed of one or more char
s), while applications using wchar_t
are said "widechar" (because each glyph is composed of one or two wchar_t
. See MultiByteToWideChar and WideCharToMultiByte Win32 conversion API for more info.
Thus, if you work on Windows, you badly want to use wchar_t
(unless you use a framework hiding that, like GTK+ or QT...). The fact is that behind the scenes, Windows works with wchar_t
strings, so even historical applications will have their char
strings converted in wchar_t
when using API like SetWindowText()
(low level API function to set the label on a Win32 GUI).
UTF-32 is 4 bytes per characters, so there is no much to add, if only that a UTF-8 text and UTF-16 text will always use less or the same amount of memory than an UTF-32 text (and usually less).
If there is a memory issue, then you should know than for most western languages, UTF-8 text will use less memory than the same UTF-16 one.
Still, for other languages (chinese, japanese, etc.), the memory used will be either the same, or slightly larger for UTF-8 than for UTF-16.
All in all, UTF-16 will mostly use 2 and occassionally 4 bytes per characters (unless you're dealing with some kind of esoteric language glyphs (Klingon? Elvish?), while UTF-8 will spend from 1 to 4 bytes.
See http://en.wikipedia.org/wiki/UTF-8#Compared_to_UTF-16 for more info.
When I should use std::wstring over std::string?
On Linux? Almost never (§).
On Windows? Almost always (§).
On cross-platform code? Depends on your toolkit...
(§) : unless you use a toolkit/framework saying otherwise
Can std::string
hold all the ASCII character set including special characters?
Notice: A std::string
is suitable for holding a 'binary' buffer, where a std::wstring
is not!
On Linux? Yes.
On Windows? Only special characters available for the current locale of the Windows user.
Edit (After a comment from Johann Gerell):
a std::string
will be enough to handle all char
-based strings (each char
being a number from 0 to 255). But:
char
s are NOT ASCII.char
from 0 to 127 will be held correctlychar
from 128 to 255 will have a signification depending on your encoding (unicode, non-unicode, etc.), but it will be able to hold all Unicode glyphs as long as they are encoded in UTF-8.Is std::wstring
supported by almost all popular C++ compilers?
Mostly, with the exception of GCC based compilers that are ported to Windows.
It works on my g++ 4.3.2 (under Linux), and I used Unicode API on Win32 since Visual C++ 6.
What is exactly a wide character?
On C/C++, it's a character type written wchar_t
which is larger than the simple char
character type. It is supposed to be used to put inside characters whose indices (like Unicode glyphs) are larger than 255 (or 127, depending...).
2015, using support v7 library with AppCompat theme, set this theme for your Activity.
<style name="AppTheme.AppStyled" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimaryDark">@color/md_indigo_100</item>
<item name="colorPrimary">@color/md_indigo_500</item>
<item name="colorAccent">@color/md_red_500</item>
<item name="android:textColorPrimary">@color/md_white_1000</item>
<item name="android:textColor">@color/md_purple_500</item>
<item name="android:textStyle">bold</item>
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
</style>
sys.dm_exec_procedure_stats contains the information about the execution functions, constraints and Procedures etc. But the life time of the row has a limit, The moment the execution plan is removed from the cache the entry will disappear.
Use [yourDatabaseName]
GO
SELECT
SCHEMA_NAME(sysobject.schema_id),
OBJECT_NAME(stats.object_id),
stats.last_execution_time
FROM
sys.dm_exec_procedure_stats stats
INNER JOIN sys.objects sysobject ON sysobject.object_id = stats.object_id
WHERE
sysobject.type = 'P'
ORDER BY
stats.last_execution_time DESC
This will give you the list of the procedures recently executed.
If you want to check if a perticular stored procedure executed recently
SELECT
SCHEMA_NAME(sysobject.schema_id),
OBJECT_NAME(stats.object_id),
stats.last_execution_time
FROM
sys.dm_exec_procedure_stats stats
INNER JOIN sys.objects sysobject ON sysobject.object_id = stats.object_id
WHERE
sysobject.type = 'P'
and (sysobject.object_id = object_id('schemaname.procedurename')
OR sysobject.name = 'procedurename')
ORDER BY
stats.last_execution_time DESC
For anyone looking for an Azure solution
SET NOCOUNT ON
CREATE TABLE Numbers (n bigint PRIMARY KEY)
GO
DECLARE @numbers table(number int);
WITH numbers(number) as (
SELECT 1 AS number
UNION all
SELECT number+1 FROM numbers WHERE number<10000
)
INSERT INTO @numbers(number)
SELECT number FROM numbers OPTION(maxrecursion 10000)
INSERT INTO Numbers(n) SELECT number FROM @numbers
Sourced from the sql azure team blog http://azure.microsoft.com/blog/2010/09/16/create-a-numbers-table-in-sql-azure/
In iOS7.0x the solution is a bit different. Here is what I came up with.
- (void)tableView:(UITableView *)tableView
willDisplayCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath
{
BOOL isFinishedLoadingTableView = [self isFinishedLoadingTableView:tableView
indexPath:indexPath];
if (isFinishedLoadingTableView) {
NSLog(@"end loading");
}
}
- (BOOL)isFinishedLoadingTableView:(UITableView *)tableView
indexPath:(NSIndexPath *)indexPath
{
// The reason we cannot just look for the last row is because
// in iOS7.0x the last row is updated before
// looping through all the visible rows in ascending order
// including the last row again. Strange but true.
NSArray * visibleRows = [tableView indexPathsForVisibleRows]; // did verify sorted ascending via logging
NSIndexPath *lastVisibleCellIndexPath = [visibleRows lastObject];
// For tableviews with multiple sections this will be more complicated.
BOOL isPreviousCallForPreviousCell =
self.previousDisplayedIndexPath.row + 1 == lastVisibleCellIndexPath.row;
BOOL isLastCell = [indexPath isEqual:lastVisibleCellIndexPath];
BOOL isFinishedLoadingTableView = isLastCell && isPreviousCallForPreviousCell;
self.previousDisplayedIndexPath = indexPath;
return isFinishedLoadingTableView;
}
This changed a bit in babel v6.
From the docs:
The polyfill will emulate a full ES6 environment. This polyfill is automatically loaded when using babel-node.
Installation:
$ npm install babel-polyfill
Usage in Node / Browserify / Webpack:
To include the polyfill you need to require it at the top of the entry point to your application.
require("babel-polyfill");
Usage in Browser:
Available from the dist/polyfill.js
file within a babel-polyfill
npm release. This needs to be included before all your compiled Babel code. You can either prepend it to your compiled code or include it in a <script>
before it.
NOTE: Do not require
this via browserify etc, use babel-polyfill
.
I was facing the same issue.
I wanted to catch all the errors at a central place and transform them.
Following is the code for how I handled it.
Create the following class which implements ExceptionMapper
and add @Provider
annotation on this class. This will handle all the exceptions.
Override toResponse
method and return the Response object populated with customised data.
//ExceptionMapperProvider.java
/**
* exception thrown by restful endpoints will be caught and transformed here
* so that client gets a proper error message
*/
@Provider
public class ExceptionMapperProvider implements ExceptionMapper<Throwable> {
private final ErrorTransformer errorTransformer = new ErrorTransformer();
public ExceptionMapperProvider() {
}
@Override
public Response toResponse(Throwable throwable) {
//transforming the error using the custom logic of ErrorTransformer
final ServiceError errorResponse = errorTransformer.getErrorResponse(throwable);
final ResponseBuilder responseBuilder = Response.status(errorResponse.getStatus());
if (errorResponse.getBody().isPresent()) {
responseBuilder.type(MediaType.APPLICATION_JSON_TYPE);
responseBuilder.entity(errorResponse.getBody().get());
}
for (Map.Entry<String, String> header : errorResponse.getHeaders().entrySet()) {
responseBuilder.header(header.getKey(), header.getValue());
}
return responseBuilder.build();
}
}
// ErrorTransformer.java
/**
* Error transformation logic
*/
public class ErrorTransformer {
public ServiceError getErrorResponse(Throwable throwable) {
ServiceError serviceError = new ServiceError();
//add you logic here
serviceError.setStatus(getStatus(throwable));
serviceError.setBody(getBody(throwable));
serviceError.setHeaders(getHeaders(throwable));
}
private String getStatus(Throwable throwable) {
//your logic
}
private Optional<String> getBody(Throwable throwable) {
//your logic
}
private Map<String, String> getHeaders(Throwable throwable) {
//your logic
}
}
//ServiceError.java
/**
* error data holder
*/
public class ServiceError {
private int status;
private Map<String, String> headers;
private Optional<String> body;
//setters and getters
}
this work for me, thanks. I want change text size only not change font name.
var fontSizeButtonBig:Int = 30
btnMenu9.titleLabel?.font = .systemFont(ofSize: CGFloat(fontSizeButtonBig))
Other solutions mix regex syntaxes. To use perl/PCRE patterns for both search and replace, and only process matching files, this works quite well:
grep -rlIZPi 'match1' | xargs -0r perl -pi -e 's/match2/replace/gi;'
match1
and match2
are usually identical but match1
can be simplified to remove more advanced features that are only relevant to the substitution, e.g. capturing groups.
Translation: grep
recursively and list matching filenames, each separated by nul to protect any special characters; pipe any filenames to xargs
which is expecting a nul-separated list; if any filenames are received, pass them to perl
to perform the actual substitutions.
For case-sensitive matching, drop the i
flag from grep
and the i
pattern modifier from the s///
expression, but not the i
flag from perl
itself. Remove the I
flag from grep
to include binary files.
By some reason sql server save some identity columns in different tables, the code that work for me, is the following:
select TABLE_NAME tabla,COLUMN_NAME columna
from INFORMATION_SCHEMA.COLUMNS
where COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
union all
select o.name tabla, c.name columna
from sys.objects o
inner join sys.columns c on o.object_id = c.object_id
where c.is_identity = 1
Or you can do it that manner:
for key in my_dict:
print key, my_dict[key]
You mention adding the additional include directory (C/C++|General) and additional lib dependency (Linker|Input), but have you also added the additional library directory (Linker|General)?
Including a sample error message might also help people answer the question since it's not even clear if the error is during compilation or linking.
echo '<p class="paragraph'.$i.'"></p>'
should do the trick.
Since you are using this for configuration, your best bet is apache commons-configuration. For simple files it's way easier to use than "raw" XML parsers.
See the XML how-to
Since many of the fancy solutions above don't work with UWP and because I love Linq and functional approaches I pressent you my version to this problem. To escape the comparison when the first difference occures, I chose .FirstOrDefault()
public static bool CompareByteArrays(byte[] ba0, byte[] ba1) =>
!(ba0.Length != ba1.Length || Enumerable.Range(1,ba0.Length)
.FirstOrDefault(n => ba0[n] != ba1[n]) > 0);
It's 2019 and you should be using this:
let arr = [...Array(20)].fill(10)
So basically 20
is the length
or a new instantiated Array
.
I often use git reset --mixed to revert a base version before multiple commits which you want to merge, then I make a new commit, that way could let your commit newest, assure your version is HEAD after you push to server.
commit ac72a4308ba70cc42aace47509a5e
Author: <[email protected]>
Date: Tue Jun 11 10:23:07 2013 +0500
Added algorithms for Cosine-similarity
commit 77df2a40e53136c7a2d58fd847372
Author: <[email protected]>
Date: Tue Jun 11 13:02:14 2013 -0700
Set stage for similar objects
commit 249cf9392da197573a17c8426c282
Author: Ralph <[email protected]>
Date: Thu Jun 13 16:44:12 2013 -0700
Fixed a bug in space world automation
If I want to merge head two commits into one, first I use :
git reset --mixed 249cf9392da197573a17c8426c282
"249cf9392da197573a17c8426c282" was third version, also is your base version before you merge, after that, I make a new commit :
git add .
git commit -m 'some commit message'
It's all, hope is another way for everybody.
FYI, from git reset --help
:
--mixed
Resets the index but not the working tree (i.e., the changed files are
preserved but not marked for commit) and reports what has not been
updated. This is the default action.
Try this,
this.props.router.push('/foo')
warning works for versions prior to v4
and
this.props.history.push('/foo')
for v4 and above
With ?# 6.0
var myDict = new Dictionary<string, string>
{
["Key1"] = "Value1",
["Key2"] = "Value2"
};
If you just want the unix timestamp, create an extension:
extension Date {
func currentTimeMillis() -> Int64 {
return Int64(self.timeIntervalSince1970 * 1000)
}
}
Then you can use it just like in other programming languages:
let timestamp = Date().currentTimeMillis()
Use my_map.count( key )
; it can only return 0 or 1, which is essentially the Boolean result you want.
Alternately my_map.find( key ) != my_map.end()
works too.
You can simply use one query to rule them all:
ALTER TABLE products
DROP FOREIGN KEY oldConstraintName,
ADD FOREIGN KEY (product_id, category_id) REFERENCES externalTableName (foreign_key_name, another_one_makes_composite_key) ON DELETE CASCADE ON UPDATE CASCADE
There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is InternalsVisibleTo. I've only ever used this attribute for testing - where it's very handy!
Example: To be placed in AssemblyInfo.cs
[assembly: InternalsVisibleTo("OtherAssembly")]
Mysql has a client-only set of utilities:
Mysql client shell https://dev.mysql.com/downloads/shell/
Other command line utilities https://dev.mysql.com/downloads/utilities/
Mac OSX version available.
Here is a working example:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;
public class j4496359 {
public static void main(String[] args) {
try {
String target = "Thu Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss zzz yyyy");
Date result = df.parse(target);
System.out.println(result);
} catch (ParseException pe) {
pe.printStackTrace();
}
}
}
Will print:
Thu Sep 28 13:29:30 CEST 2000
USE DBNAME
select ROUTINE_NAME from information_schema.routines
where routine_type = 'PROCEDURE'
GO
This will work on mssql.
Hello World!
You see, the main question while using hidden input is what kind of data you want to pass?
I will assume that you are trying to pass the user ID.
Which is not a really good idea to pass it here because field() method will generate input
and the value will be shown to user as we can't hide html from the users browser. This if you really care about security of your website.
please check this link, and you will see that it's impossible to hide value attribute from users to see.
so what to do then?
See, this is the core of OOP in PHP.
and I quote from Matt Zandstr in his great book PHP Objects, Patterns, and Practice fifth edition
I am still stuck with a great deal of unwanted flexibility, though. I rely on the client coder to change a ShopProduct object’s properties from their default values. This is problematic in two ways. First, it takes five lines to properly initialize a ShopProduct object, and no coder will thank you for that. Second, I have no way of ensuring that any of the properties are set when a ShopProduct object is initialized. What I need is a method that is called automatically when an object is instantiated from a class.
Please check this example of using __construct() method which is mentioned in his book too.
class ShopProduct {
public $title;
public $producerMainName;
public $producerFirstName;
public $price = 0;
public function __construct($title,$firstName,$mainName,$price) {
$this->title = $title;
$this->producerFirstName = $firstName;
$this->producerMainName = $mainName;
$this->price = $price;
}
}
$product1 = new ShopProduct("My Antonia","Willa","Cather",5.99 );
print "author: {$product1->getProducer()}\n";
This produces the following:
author: Willa Cather
Class Car {
private $user_id;
//.. your properties
public function __construct($title,$firstName,$mainName,$price){
$this->user_id = \Yii::$app->user->id;
//..Your magic
}
}
What you're really asking is a related, but substantially different question: how often do I want to truncate names in order to fit them in the database? The answer depends both on the frequency of different lengths of names as well as the maximum lengths chosen. This concern is balanced by the concerns about resources used by the database. Considering how little overhead difference there is between different max lengths for a varchar field I'd generally err on the side of never being forced to truncate a name and make the field as large as I dared.
use the following code to apply some margin
$(".button").click(function() {
$('html, body').animate({
scrollTop: $(".scrolltothis").offset().top + 50;
}, 500);
});
See this ans: Scroll down to div + a certain margin
I've used a mixture of solutions described above:
$ git branch temp <specific sha1>
$ git rebase --onto temp master topic
$ git branch -d temp
I found it much easier to read and understand. The accepted solution lead me to a merge conflict (too lazy to fix by hand):
$ git rebase temp
First, rewinding head to replay your work on top of it...
Applying: <git comment>
Using index info to reconstruct a base tree...
M pom.xml
.git/rebase-apply/patch:10: trailing whitespace.
<some code>
.git/rebase-apply/patch:17: trailing whitespace.
<some other code>
warning: 2 lines add whitespace errors.
Falling back to patching base and 3-way merge...
Auto-merging pom.xml
CONFLICT (content): Merge conflict in pom.xml
error: Failed to merge in the changes.
Patch failed at 0001 <git comment>
The copy of the patch that failed is found in: .git/rebase-apply/patch
When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort".
You can truncate all information after the month using date_trunc(text, timestamp)
:
select date_trunc('month',created_at)::date as date
from orders
order by date DESC;
created_at = '2019-12-16 18:28:13'
Output 1:
date_trunc('day',created_at)
// 2019-12-16 00:00:00
Output 2:
date_trunc('day',created_at)::date
// 2019-12-16
Output 3:
date_trunc('month',created_at)::date
// 2019-12-01
Output 4:
date_trunc('year',created_at)::date
// 2019-01-01
java [any other JVM options you need to give it] -jar foo.jar
Out of experience, I think the correct maximum z-index
is 2147483638.
In Spring 5
@PostMapping( "some/request/path" )
public void someControllerMethod( @RequestParam MultiValueMap body ) {
// import org.springframework.util.MultiValueMap;
String datax = (String) body .getFirst("datax");
}
You want:
grep -A 5 '19:55' file
From man grep
:
Context Line Control
-A NUM, --after-context=NUM
Print NUM lines of trailing context after matching lines.
Places a line containing a gup separator (described under --group-separator)
between contiguous groups of matches. With the -o or --only-matching
option, this has no effect and a warning is given.
-B NUM, --before-context=NUM
Print NUM lines of leading context before matching lines.
Places a line containing a group separator (described under --group-separator)
between contiguous groups of matches. With the -o or --only-matching
option, this has no effect and a warning is given.
-C NUM, -NUM, --context=NUM
Print NUM lines of output context. Places a line containing a group separator
(described under --group-separator) between contiguous groups of matches.
With the -o or --only-matching option, this has no effect and a warning
is given.
--group-separator=SEP
Use SEP as a group separator. By default SEP is double hyphen (--).
--no-group-separator
Use empty string as a group separator.
Solution using Jackson library. Sorted this problem by verifying the json on JSONLint.com and then using Jackson. Below is the code for the same.
Main Class:-
String jsonStr = "[{\r\n" + " \"name\": \"John\",\r\n" + " \"city\": \"Berlin\",\r\n"
+ " \"cars\": [\r\n" + " \"FIAT\",\r\n" + " \"Toyata\"\r\n"
+ " ],\r\n" + " \"job\": \"Teacher\"\r\n" + " },\r\n" + " {\r\n"
+ " \"name\": \"Mark\",\r\n" + " \"city\": \"Oslo\",\r\n" + " \"cars\": [\r\n"
+ " \"VW\",\r\n" + " \"Toyata\"\r\n" + " ],\r\n"
+ " \"job\": \"Doctor\"\r\n" + " }\r\n" + "]";
ObjectMapper mapper = new ObjectMapper();
MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);
for (MyPojo itr : jsonObj) {
System.out.println("Val of getName is: " + itr.getName());
System.out.println("Val of getCity is: " + itr.getCity());
System.out.println("Val of getJob is: " + itr.getJob());
System.out.println("Val of getCars is: " + itr.getCars() + "\n");
}
POJO:
public class MyPojo {
private List<String> cars = new ArrayList<String>();
private String name;
private String job;
private String city;
public List<String> getCars() {
return cars;
}
public void setCars(List<String> cars) {
this.cars = cars;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
} }
RESULT:-
Val of getName is: John
Val of getCity is: Berlin
Val of getJob is: Teacher
Val of getCars is: [FIAT, Toyata]
Val of getName is: Mark
Val of getCity is: Oslo
Val of getJob is: Doctor
Val of getCars is: [VW, Toyata]
setAutoSize method must come before setWidth:
$objPHPExcel->getActiveSheet()->getColumnDimensionByColumn('C')->setAutoSize(false);
$objPHPExcel->getActiveSheet()->getColumnDimensionByColumn('C')->setWidth('10');
1. Download SQLite Manager
2. Go to your DDMS tab in Eclipse
3. Go to the File Explorer --> data --> data --> "Your Package Name" --> pull file from device 4. Open file in SQLite Manager.
5. View data.
This BASH script will execute the python unittest test directory from anywhere in the file system, no matter what working directory you are in.
This is useful when staying in the ./src
or ./example
working directory and you need a quick unit test:
#!/bin/bash
this_program="$0"
dirname="`dirname $this_program`"
readlink="`readlink -e $dirname`"
python -m unittest discover -s "$readlink"/test -v
No need for a test/__init__.py
file to burden your package/memory-overhead during production.
You may:
Find: (\w)
Replace With: \L$1
Or select the text, ctrl+K+L.
After having all the proposed solutions fail my tests one way or the other, (edit: some were updated to pass the tests after I wrote this) I found the mozilla implementation for Array.indexOf and Array.lastIndexOf
I used those to implement my version of String.prototype.regexIndexOf and String.prototype.regexLastIndexOf as follows:
String.prototype.regexIndexOf = function(elt /*, from*/)
{
var arr = this.split('');
var len = arr.length;
var from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++) {
if (from in arr && elt.exec(arr[from]) )
return from;
}
return -1;
};
String.prototype.regexLastIndexOf = function(elt /*, from*/)
{
var arr = this.split('');
var len = arr.length;
var from = Number(arguments[1]);
if (isNaN(from)) {
from = len - 1;
} else {
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0)
from += len;
else if (from >= len)
from = len - 1;
}
for (; from > -1; from--) {
if (from in arr && elt.exec(arr[from]) )
return from;
}
return -1;
};
They seem to pass the test functions I provided in the question.
Obviously they only work if the regular expression matches one character but that is enough for my purpose since I will be using it for things like ( [abc] , \s , \W , \D )
I will keep monitoring the question in case someone provides a better/faster/cleaner/more generic implementation that works on any regular expression.
Yes. But place your "test" after the comma if you want the column...
> A <- matrix(sample(1:12,12,T),ncol=4)
> rownames(A) <- letters[1:3]
> colnames(A) <- letters[11:14]
> A[,"l"]
a b c
6 10 1
see also help(Extract)
There is a very simple way to select a number of rows using the R index for rows and columns. This lets you CLEANLY split the data set given a number of rows - say the 1st 80% of your data.
In R all rows and columns are indexed so DataSetName[1,1] is the value assigned to the first column and first row of "DataSetName". I can select rows using [x,] and columns using [,x]
For example: If I have a data set conveniently named "data" with 100 rows I can view the first 80 rows using
View(data[1:80,])
In the same way I can select these rows and subset them using:
train = data[1:80,]
test = data[81:100,]
Now I have my data split into two parts without the possibility of resampling. Quick and easy.
Based on @Rick answer which was really helpful.
You have to scape the string data
if you want to share it this way:
$('a.download').attr('href', 'data:application/csv;charset=utf-8,'+ encodeURI(data));
` Sorry I can not comment on @Rick's answer due to my current low reputation in StackOverflow.
An edit suggestion was shared and rejected.
If you do not want to use CURL, you could find some examples on stackoverflow, just like this one here: How do I send a POST request with PHP?. I would recommend you watch a few tutorials on how to use GET and POST methods within PHP or just take a look at the php.net manual here: httprequest::send. You can find a lot of tutorials: HTTP POST from PHP, without cURL and so on...
If you add jars in tomcat's lib folder you can see this error
to attach to a GUID:
SqlDataSource1.SelectParameters.Add("userId", System.Data.DbType.Guid, userID);
As far as I know PKCS#12 is just a certificate/public/private key store. If you extracted a public key from PKCS#12 file, OpenSSH should be able to use it as long as it was extracted in PEM format. You probably already know that you also need a corresponding private key (also in PEM) in order to use it for ssh-public-key authentication.
redis-cli -h <host> -p <port> keys *
where * is the pattern to list all keys
if(sender is TextBox) {
var text = (sender as TextBox).Text;
}
I created a sample project on github to load a UIView from a .xib file inside another .xib file. Or you can do it programmatically.
This is good for little widgets you want to reuse on different UIViewController objects.
You can quickly control this by typing built-in magic commands in Spyder's IPython console, which I find faster than picking these from the preferences menu. Changes take immediate effect, without needing to restart Spyder or the kernel.
To switch to "automatic" (i.e. interactive) plots, type:
%matplotlib auto
then if you want to switch back to "inline", type this:
%matplotlib inline
(Note: these commands don't work in non-IPython consoles)
See more background on this topic: Purpose of "%matplotlib inline"
"Default Namespace textbox in project properties is disabled" Same with me (VS 2010). I edited the project file ("xxx.csproj") and tweaked the item. That changed the default namespace.
Using ES6:
There are many ways to search
for strings and replace
in JavaScript
. One of them is as follow
const findFor = ['<', '>', '\n'];_x000D_
_x000D_
const replaceWith = ['<', '>', '<br/>'];_x000D_
_x000D_
const originalString = '<strong>Hello World</strong> \n Let\'s code';_x000D_
_x000D_
let modifiedString = originalString;_x000D_
_x000D_
findFor.forEach( (tag, i) => modifiedString = modifiedString.replace(new RegExp(tag, "g"), replaceWith[i]) )_x000D_
_x000D_
console.log('Original String: ', originalString);_x000D_
console.log('Modified String: ', modifiedString);
_x000D_
Project is works in DotNET Core 3.1+ or higher(future)
Add this package:
Microsoft.EntityFrameworkCore.Tools
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.8">
Following code will manage to refresh parent window post close :
function ManageQB_PopUp() {
$(document).ready(function () {
window.close();
});
window.onunload = function () {
var win = window.opener;
if (!win.closed) {
window.opener.location.reload();
}
};
}
If you have multiples docker containers launched, use this
$ docker rm $(docker ps -aq)
It will remove all the current dockers listed in the "ps -aq" command.
Source : aaam on https://github.com/docker/docker/issues/12487
The word check_
in the name means that if the command (the shell in this case that returns the exit status of the last command (yum
in this case)) returns non-zero status then it raises CalledProcessError
exception. It is by design. If the command that you want to run may return non-zero status on success then either catch this exception or don't use check_
methods. You could use subprocess.call
in your case because you are ignoring the captured output, e.g.:
import subprocess
rc = subprocess.call(['grep', 'pattern', 'file'],
stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
if rc == 0: # found
...
elif rc == 1: # not found
...
elif rc > 1: # error
...
You don't need shell=True
to run the commands from your question.
I am also new to R but trying to understand how ggplot works I think I get another way to do it. I just share probably not as a complete perfect solution but to add some different points of view.
I know ggplot is made to work with dataframes better but maybe it can be also sometimes useful to know that you can directly plot two vectors without using a dataframe.
Loading data. Original date vector length is 100 while var0 and var1 have length 50 so I only plot the available data (first 50 dates).
var0 <- 100 + c(0, cumsum(runif(49, -20, 20)))
var1 <- 150 + c(0, cumsum(runif(49, -10, 10)))
date <- seq(as.Date("2002-01-01"), by="1 month", length.out=50)
Plotting
ggplot() + geom_line(aes(x=date,y=var0),color='red') +
geom_line(aes(x=date,y=var1),color='blue') +
ylab('Values')+xlab('date')
However I was not able to add a correct legend using this format. Does anyone know how?
Here is an updated version of Paul Burke's answer. In versions below Android 4.4 (KitKat) we don't have the DocumentsContract class.
In order to work on versions below KitKat create this class:
public class DocumentsContract {
private static final String DOCUMENT_URIS =
"com.android.providers.media.documents " +
"com.android.externalstorage.documents " +
"com.android.providers.downloads.documents " +
"com.android.providers.media.documents";
private static final String PATH_DOCUMENT = "document";
private static final String TAG = DocumentsContract.class.getSimpleName();
public static String getDocumentId(Uri documentUri) {
final List<String> paths = documentUri.getPathSegments();
if (paths.size() < 2) {
throw new IllegalArgumentException("Not a document: " + documentUri);
}
if (!PATH_DOCUMENT.equals(paths.get(0))) {
throw new IllegalArgumentException("Not a document: " + documentUri);
}
return paths.get(1);
}
public static boolean isDocumentUri(Uri uri) {
final List<String> paths = uri.getPathSegments();
Logger.v(TAG, "paths[" + paths + "]");
if (paths.size() < 2) {
return false;
}
if (!PATH_DOCUMENT.equals(paths.get(0))) {
return false;
}
return DOCUMENT_URIS.contains(uri.getAuthority());
}
}
I see 2 easy options:
gradient option:
html {
min-height:100%;
background:linear-gradient(0deg, rgba(255, 0, 150, 0.3), rgba(255, 0, 150, 0.3)), url(http://lorempixel.com/800/600/nature/2);
background-size:cover;
}
shadow option:
html {
min-height:100%;
background:url(http://lorempixel.com/800/600/nature/2);
background-size:cover;
box-shadow:inset 0 0 0 2000px rgba(255, 0, 150, 0.3);
}
an old codepen of mine with few examples
a third option
The
background-blend-mode
CSS property sets how an element's background images should blend with each other and with the element's background color.
html {
min-height:100%;
background:url(http://lorempixel.com/800/600/nature/2) rgba(255, 0, 150, 0.3);
background-size:cover;
background-blend-mode: multiply;
}
Not sure if this helps, but with XSL, I'd do something like:
<xsl:for-each select="a/b">
<xsl:value-of select="c"/>
<xsl:value-of select="d"/>
<xsl:value-of select="e"/>
</xsl:for-each>
and won't this XPath select all children of B nodes:
a/b/*
Append ll suffix to hex digits for 64-bit (long long int), or ull suffix for unsigned 64-bit (unsigned long long)
selectRowToInput();
function selectRowToInput(){
var table = document.getElementById("table");
var rows = table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++)
{
var currentRow = table.rows[i];
currentRow.onclick = function() {
rows=this.rowIndex;
console.log(rows);
};
}
}
Do you mean the mysql text console? Then:
START TRANSACTION;
...
your queries.
...
COMMIT;
Is what I recommend.
However if you want to avoid typing this each time you need to run this sort of query, add the following to the [mysqld] section of your my.cnf file.
init_connect='set autocommit=0'
This would set autocommit
to be off for every client though.
Try pytest -s -v test_login.py
for more info in console.
-v
it's a short --verbose
-s
means 'disable all capturing'
If you are forced to use that List, or if your program has a structure like
then Thilos answer will be the best way to do it. If you combine it with the advice from Tom Hawtin - tackline, you get:
java.util.Collections.sort(listOfCountryNames, Collator.getInstance());
If you are free to decide, and if your application might get more complex, then you might change your code to use a TreeSet instead. This kind of collection sorts your entries just when they are inserted. No need to call sort().
Collection<String> countryNames =
new TreeSet<String>(Collator.getInstance());
countryNames.add("UK");
countryNames.add("Germany");
countryNames.add("Australia");
// Tada... sorted.
This has some subtle, but important advantages:
TreeSet<String> countyNames
and instantly knows: this is a sorted collection of Strings without duplicates, and I can be sure that this is true at every moment. So much information in a short declaration.Using the right collection for the right task is a key to write short and bug free code. It's not as demonstrative in this case, because you just save one line. But I've stopped counting how often I see someone using a List when they want to ensure there are no duplictes, and then build that functionality themselves. Or even worse, using two Lists when you really need a Map.
Don't get me wrong: Using Collections.sort is not an error or a flaw. But there are many cases when the TreeSet is much cleaner.
You can still get Fatal error: Call to undefined function imagecreatefromjpeg()
even if GD is installed.
The solution is to install/enable jped lib:
On Ubuntu:
apt-get install libjpeg-dev
apt-get install libfreetype6-dev
On CentOS:
yum install libjpeg-devel
yum install freetype-devel
If compiling from source add --with-jpeg-dir --with-freetype-dir
or --with-jpeg-dir=/usr --with-freetype-dir=/usr
.
For more details check https://www.tectut.com/2015/10/solved-call-to-undefined-function-imagecreatefromjpeg/