There seems to be some debate whether using StringBuilder is still needed with current compilers. So I thought I'll give my 2 cents of experience.
I have a JDBC
result set of 10k records (yes, I need all of them in one batch.) Using the + operator takes about 5 minutes on my machine with Java 1.8
. Using stringBuilder.append("")
takes less than a second for the same query.
So the difference is huge. Inside a loop StringBuilder
is much faster.
Just create an extension for the StringBuilder class:
Public Module Extensions
<Extension()>
Public Sub AppendFormatWithNewLine(ByRef sb As System.Text.StringBuilder, ByVal format As String, ParamArray values() As Object)
sb.AppendLine(String.Format(format, values))
End Sub
End Module
String is an immutable class. This means that once you instantiate an instance of a string like so:
String str1 = "hello";
The object in memory cannot be altered. Instead you will have to create a new instance, copy the old String and append whatever else as in this example:
String str1 = "hello";
str1 = str1 + " world!";
What is really happening hear is that we are NOT updating the existing str1 object... we are reallocating new memory all together, copying the "hello" data and appending " world!" to the end, then settings the str1 reference to point to this new memory. So it really looks more like this under the hood:
String str1 = "hello";
String str2 = str1 + " world!";
str1 = str2;
So it follows that this "copy + paste and move stuff around in memory" process can be very expensive if done repitively especially recursively.
When you are in that situation of having to do things over and over utilize StringBuilder. It is mutable and can append strings to the end of the current one because it's back by an [growing array] (not 100% if that is the actual data structure, could be a list).
You have two options. First one is very easy use Remove
method it is quite effective. Second way is to use ToString
with start index and end index (MSDN documentation)
You still have access to StreamWriter
:
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"\hereIam.txt"))
{
file.WriteLine(sb.ToString()); // "sb" is the StringBuilder
}
From the MSDN documentation: Writing to a Text File (Visual C#).
For newer versions of the .NET Framework (Version 2.0. onwards), this can be achieved with one line using the File.WriteAllText
method.
System.IO.File.WriteAllText(@"C:\TextFile.txt", stringBuilder.ToString());
I have defined this function:
function format() {
var args = arguments;
if (args.length <= 1) {
return args;
}
var result = args[0];
for (var i = 1; i < args.length; i++) {
result = result.replace(new RegExp("\\{" + (i - 1) + "\\}", "g"), args[i]);
}
return result;
}
And can be called like c#:
var text = format("hello {0}, your age is {1}.", "John", 29);
Result:
hello John, your age is 29.
When you already have all the "pieces" you wish to append, there is no point in using StringBuilder
at all. Using StringBuilder
and string concatenation in the same call as per your sample code is even worse.
This would be better:
return "select id1, " + " id2 " + " from " + " table";
In this case, the string concatenation is actually happening at compile-time anyway, so it's equivalent to the even-simpler:
return "select id1, id2 from table";
Using new StringBuilder().append("select id1, ").append(" id2 ")....toString()
will actually hinder performance in this case, because it forces the concatenation to be performed at execution time, instead of at compile time. Oops.
If the real code is building a SQL query by including values in the query, then that's another separate issue, which is that you should be using parameterized queries, specifying the values in the parameters rather than in the SQL.
I have an article on String
/ StringBuffer
which I wrote a while ago - before StringBuilder
came along. The principles apply to StringBuilder
in the same way though.
Here is the performance testing result for String vs StringBuffer vs StringBuilder. Finally, StringBuilder won the Test. See below for test code and result.
Code:
private static void performanceTestStringVsStringbuffereVsStringBuilder() {
// String vs StringBiffer vs StringBuilder performance Test
int loop = 100000;
long start = 0;
// String
String str = null;
start = System.currentTimeMillis();
for (int i = 1; i <= loop; i++) {
str += i + "test";
}
System.out.println("String - " + (System.currentTimeMillis() - start) + " ms");
// String buffer
StringBuffer sbuffer = new StringBuffer();
start = System.currentTimeMillis();
for (int i = 1; i <= loop; i++) {
sbuffer.append(i).append("test");
}
System.out.println("String Buffer - " + (System.currentTimeMillis() - start) + " ms");
// String builder
start = System.currentTimeMillis();
StringBuilder sbuilder = new StringBuilder();
for (int i = 1; i <= loop; i++) {
sbuffer.append(i).append("test");
}
System.out.println("String Builder - " + (System.currentTimeMillis() - start) + " ms");
}
Result:
100000 iteration for adding a single text
String - 37489 ms
String Buffer - 5 ms
String Builder - 4 ms
10000 iteration for adding a single text
String - 389 ms
String Buffer - 1 ms
String Builder - 1 ms
I had a similar requirement when I stumbled on this post. I wanted a fast way to build a String that can grow from both sides ie. add new letters on the front as well as back arbitrarily. I know this is an old post, but it inspired me to try out a few ways to create strings and I thought I'd share my findings. I am also using some Java 8 constructs in this, which could have optimised the speed in cases 4 and 5.
https://gist.github.com/SidWagz/e41e836dec65ff24f78afdf8669e6420
The Gist above has the detailed code that anyone can run. I took few ways of growing strings in this; 1) Append to StringBuilder, 2) Insert to front of StringBuilder as as shown by @Mehrdad, 3) Partially insert from front as well as end of the StringBuilder, 4) Using a list to append from end, 5) Using a Deque to append from the front.
// Case 2
StringBuilder build3 = new StringBuilder();
IntStream.range(0, MAX_STR)
.sequential()
.forEach(i -> {
if (i%2 == 0) build3.append(Integer.toString(i)); else build3.insert(0, Integer.toString(i));
});
String build3Out = build3.toString();
//Case 5
Deque<String> deque = new ArrayDeque<>();
IntStream.range(0, MAX_STR)
.sequential()
.forEach(i -> {
if (i%2 == 0) deque.addLast(Integer.toString(i)); else deque.addFirst(Integer.toString(i));
});
String dequeOut = deque.stream().collect(Collectors.joining(""));
I'll focus on the front append only cases ie. case 2 and case 5. The implementation of StringBuilder internally decides how the internal buffer grows, which apart from moving all buffer left to right in case of front appending limits the speed. While time taken when inserting directly to the front of the StringBuilder grows to really high values, as shown by @Mehrdad, if the need is to only have strings of length less than 90k characters (which is still a lot), the front insert will build a String in the same time as it would take to build a String of the same length by appending at the end. What I am saying is that time time penalty indeed kicks and is huge, but only when you have to build really huge strings. One could use a deque and join the strings at the end as shown in my example. But StringBuilder is a bit more intuitive to read and code, and the penalty would not matter for smaller strings.
Actually the performance for case 2 is much faster than case 1, which I don't seem to understand. I assume the growth for the internal buffer in StringBuilder would be the same in case of front append and back append. I even set the minimum heap to a very large amount to avoid delay in heap growth, if that would have played a role. Maybe someone who has a better understanding can comment below.
private String convertToString(java.sql.Clob data)
{
final StringBuilder builder= new StringBuilder();
try
{
final Reader reader = data.getCharacterStream();
final BufferedReader br = new BufferedReader(reader);
int b;
while(-1 != (b = br.read()))
{
builder.append((char)b);
}
br.close();
}
catch (SQLException e)
{
log.error("Within SQLException, Could not convert CLOB to string",e);
return e.toString();
}
catch (IOException e)
{
log.error("Within IOException, Could not convert CLOB to string",e);
return e.toString();
}
//enter code here
return builder.toString();
}
There are basically two alternatives, using setLength(0)
to reset the StringBuilder or creating a new one in each iteration. Both can have pros and cons depending on the usage.
If you know the expected capacity of the StringBuilder beforehand, creating a new one each time should be just as fast as setting a new length. It will also help the garbage collector, since each StringBuilder will be relatively short-lived and the gc is optimized for that.
When you don't know the capacity, reusing the same StringBuilder might be faster. Each time you exceed the capacity when appending, a new backing array has to be allocated and the previous content has to be copied. By reusing the same StringBuilder, it will reach the needed capacity after some iterations and there won't be any copying thereafter.
Note that if you are using Java 5 or newer, you should use StringBuilder
instead of StringBuffer
. From the API documentation:
As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread,
StringBuilder
. TheStringBuilder
class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.
In practice, you will almost never use this from multiple threads at the same time, so the synchronization that StringBuffer
does is almost always unnecessary overhead.
To avoid reinit(affect performance) of prefix
use TextUtils.isEmpty:
String prefix = "";
for (String item : list) {
sb.append(prefix);
if (TextUtils.isEmpty(prefix))
prefix = ",";
sb.append(item);
}
A String (System.String) is a type defined inside the .NET framework. The String class is not mutable. This means that every time you do an action to an System.String instance, the .NET compiler create a new instance of the string. This operation is hidden to the developer.
A System.Text.StringBuilder is class that represents a mutable string. This class provides some useful methods that make the user able to manage the String wrapped by the StringBuilder. Notice that all the manipulations are made on the same StringBuilder instance.
Microsoft encourages the use of StringBuilder because it is more effective in terms of memory usage.
For Kotlin,
StringBuilder().appendLine("your text");
Though this is a java question, this is also the first google result for Kotlin, might come in handy.
Hey guys here is a simple test program that shows how to allocate and pass an array using new or malloc. Just cut, paste and run it. Have fun!
struct Coordinate
{
int x,y;
};
void resize( int **p, int size )
{
free( *p );
*p = (int*) malloc( size * sizeof(int) );
}
void resizeCoord( struct Coordinate **p, int size )
{
free( *p );
*p = (Coordinate*) malloc( size * sizeof(Coordinate) );
}
void resizeCoordWithNew( struct Coordinate **p, int size )
{
delete [] *p;
*p = (struct Coordinate*) new struct Coordinate[size];
}
void SomeMethod(Coordinate Coordinates[])
{
Coordinates[0].x++;
Coordinates[0].y = 6;
}
void SomeOtherMethod(Coordinate Coordinates[], int size)
{
for (int i=0; i<size; i++)
{
Coordinates[i].x = i;
Coordinates[i].y = i*2;
}
}
int main()
{
//static array
Coordinate tenCoordinates[10];
tenCoordinates[0].x=0;
SomeMethod(tenCoordinates);
SomeMethod(&(tenCoordinates[0]));
if(tenCoordinates[0].x - 2 == 0)
{
printf("test1 coord change successful\n");
}
else
{
printf("test1 coord change unsuccessful\n");
}
//dynamic int
int *p = (int*) malloc( 10 * sizeof(int) );
resize( &p, 20 );
//dynamic struct with malloc
int myresize = 20;
int initSize = 10;
struct Coordinate *pcoord = (struct Coordinate*) malloc (initSize * sizeof(struct Coordinate));
resizeCoord(&pcoord, myresize);
SomeOtherMethod(pcoord, myresize);
bool pass = true;
for (int i=0; i<myresize; i++)
{
if (! ((pcoord[i].x == i) && (pcoord[i].y == i*2)))
{
printf("Error dynamic Coord struct [%d] failed with (%d,%d)\n",i,pcoord[i].x,pcoord[i].y);
pass = false;
}
}
if (pass)
{
printf("test2 coords for dynamic struct allocated with malloc worked correctly\n");
}
//dynamic struct with new
myresize = 20;
initSize = 10;
struct Coordinate *pcoord2 = (struct Coordinate*) new struct Coordinate[initSize];
resizeCoordWithNew(&pcoord2, myresize);
SomeOtherMethod(pcoord2, myresize);
pass = true;
for (int i=0; i<myresize; i++)
{
if (! ((pcoord2[i].x == i) && (pcoord2[i].y == i*2)))
{
printf("Error dynamic Coord struct [%d] failed with (%d,%d)\n",i,pcoord2[i].x,pcoord2[i].y);
pass = false;
}
}
if (pass)
{
printf("test3 coords for dynamic struct with new worked correctly\n");
}
return 0;
}
From the .NET blog Announcing .NET 2015 Preview: A New Era for .NET:
.NET Core has two major components. It includes a small runtime that is built from the same codebase as the .NET Framework CLR. The .NET Core runtime includes the same GC and JIT (RyuJIT), but doesn’t include features like Application Domains or Code Access Security. The runtime is delivered via NuGet, as part of the [ASP.NET Core] package.
.NET Core also includes the base class libraries. These libraries are largely the same code as the .NET Framework class libraries, but have been factored (removal of dependencies) to enable us to ship a smaller set of libraries. These libraries are shipped as System.* NuGet packages on NuGet.org.
And:
[ASP.NET Core] is the first workload that has adopted .NET Core. [ASP.NET Core] runs on both the .NET Framework and .NET Core. A key value of [ASP.NET Core] is that it can run on multiple versions of [.NET Core] on the same machine. Website A and website B can run on two different versions of .NET Core on the same machine, or they can use the same version.
In short: first, there was the Microsoft .NET Framework, which consists of a runtime that executes application and library code, and a nearly fully documented standard class library.
The runtime is the Common Language Runtime, which implements the Common Language Infrastructure, works with The JIT compiler to run the CIL (formerly MSIL) bytecode.
Microsoft's specification and implementation of .NET were, given its history and purpose, very Windows- and IIS-centered and "fat". There are variations with fewer libraries, namespaces and types, but few of them were useful for web or desktop development or are troublesome to port from a legal standpoint.
So in order to provide a non-Microsoft version of .NET, which could run on non-Windows machines, an alternative had to be developed. Not only the runtime has to be ported for that, but also the entire Framework Class Library to become well-adopted. On top of that, to be fully independent from Microsoft, a compiler for the most commonly used languages will be required.
Mono is one of few, if not the only alternative implementation of the runtime, which runs on various OSes besides Windows, almost all namespaces from the Framework Class Library as of .NET 4.5 and a VB and C# compiler.
Enter .NET Core: an open-source implementation of the runtime, and a minimal base class library. All additional functionality is delivered through NuGet packages, deploying the specific runtime, framework libraries and third-party packages with the application itself.
ASP.NET Core is a new version of MVC and WebAPI, bundled together with a thin HTTP server abstraction, that runs on the .NET Core runtime - but also on the .NET Framework.
I have faced this particular error when I didn't defined the main() function. Check if the main() function exists or check the name of the function letter by letter as Timothy described above or check if the file where the main function is located is included to your project.
Syntax
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
Parameters
start
: required. Initial index.start
is negative it is treated as "Math.max((array.length + start), 0)"
as per spec (example provided below) effectively from the end of array
.deleteCount
: optional. Number of elements to be removed (all from start
if not provided).item1, item2, ...
: optional. Elements to be added to the array from start
index.Returns: An array with deleted elements (empty array if none removed)
Mutate original array: Yes
const array = [1,2,3,4,5];
// Remove first element
console.log('Elements deleted:', array.splice(0, 1), 'mutated array:', array);
// Elements deleted: [ 1 ] mutated array: [ 2, 3, 4, 5 ]
// array = [ 2, 3, 4, 5]
// Remove last element (start -> array.length+start = 3)
console.log('Elements deleted:', array.splice(-1, 1), 'mutated array:', array);
// Elements deleted: [ 5 ] mutated array: [ 2, 3, 4 ]
_x000D_
More examples in MDN Splice examples
Syntax
array.slice([begin[, end]])
Parameters
begin
: optional. Initial index (default 0).begin
is negative it is treated as "Math.max((array.length + begin), 0)"
as per spec (example provided below) effectively from the end of array
.end
: optional. Last index for extraction but not including (default array.length). If end
is negative it is treated as "Math.max((array.length + begin),0)"
as per spec (example provided below) effectively from the end of array
.Returns: An array containing the extracted elements.
Mutate original: No
const array = [1,2,3,4,5];
// Extract first element
console.log('Elements extracted:', array.slice(0, 1), 'array:', array);
// Elements extracted: [ 1 ] array: [ 1, 2, 3, 4, 5 ]
// Extract last element (start -> array.length+start = 4)
console.log('Elements extracted:', array.slice(-1), 'array:', array);
// Elements extracted: [ 5 ] array: [ 1, 2, 3, 4, 5 ]
_x000D_
More examples in MDN Slice examples
Don't take this as absolute truth as depending on each scenario one might be performant than the other.
Performance test
You probably need to update the remote URL since github puts your username in it. You can take a look at the original URL by typing
git config --get remote.origin.url
Or just go to the repository page on Github and get the new URL. Then use
git remote set-url origin https://{new url with username replaced}
to update the URL with your new username.
I got the same error and figured out that i wrote my script using Anaconda but pyinstaller
tries to pack script on pure python. So, modules not exist in pythons library folder cause this problem.
Use XmlDocument.Load()
method to load XML from your file. Then use XmlDocument.InnerXml
property to get XML string.
XmlDocument doc = new XmlDocument();
doc.Load("path to your file");
string xmlcontents = doc.InnerXml;
Solutin 1:
step:1
Right click on your project -> Close Project. it will Close your project and all opened file(s) of the project
step:2
Right click on your project -> Open Project. it will Open your project and rebuild your project, Hope fully it will fix red exclamation mark
Solution 2:
Step:1
Right click on your Project -> Properties -> Java Build Path. Can you see missing in front of your library file(s) as per following screen-shot
Step:2 Click on Add Jar to select your Jar file if it is the placed in WEB-INF/lib of your project or Add External Jar if jar file placed somewhere on your computer
Step:3 Select the old missing file(s) and click on Remove click here for image
Solutioin 3: Right click on your Project -> Properties -> Java Build Path -> JRE System Library and reconfigure the JRE
and go to your project and remove .properties and .classpath in your project directories.
backup your project data and create a new one and follow the solutions 1 & 2
There's a technique called Immersive Full-Screen Mode available in KitKat.
2, 4, 5, 6, 7, 8, 9, 10, 11
(TypeScript) with Angular CLInpm install -g @angular/cli
ng new projectFolder
creates a new applicationng build --prod
(run in command line when directory is projectFolder
)
flag prod
bundle for production (see the Angular documentation for the list of option included with the production flag).
Compress using Brotli compression the resources using the following command
for i in dist/*; do brotli $i; done
bundles are generated by default to projectFolder/dist(/$projectFolder
for v6+)**
Sizes with Angular 11.0.5
with CLI 11.0.5
and option CSS without Angular routing
dist/main-[es-version].[hash].js
Your application bundled [ ES5 size: 136 KB for new Angular CLI application empty, 38 KB compressed].dist/polyfill-[es-version].[hash].bundle.js
the polyfill dependencies (@angular, RxJS...) bundled [ ES5 size: 36 KB for new Angular CLI application empty, 11 KB compressed].dist/index.html
entry point of your application.dist/runtime-[es-version].[hash].bundle.js
webpack loaderdist/style.[hash].bundle.css
the style definitionsdist/assets
resources copied from the Angular CLI assets configurationYou can get a preview of your application using the ng serve --prod
command that starts a local HTTP server such that the application with production files is accessible using http://localhost:4200.
For a production usage, you have to deploy all the files from the dist
folder in the HTTP server of your choice.
using System;
using System.IO;
class Test
{
public static void Main()
{
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
Console.WriteLine("Drive {0}", d.Name);
Console.WriteLine(" Drive type: {0}", d.DriveType);
if (d.IsReady == true)
{
Console.WriteLine(" Volume label: {0}", d.VolumeLabel);
Console.WriteLine(" File system: {0}", d.DriveFormat);
Console.WriteLine(
" Available space to current user:{0, 15} bytes",
d.AvailableFreeSpace);
Console.WriteLine(
" Total available space: {0, 15} bytes",
d.TotalFreeSpace);
Console.WriteLine(
" Total size of drive: {0, 15} bytes ",
d.TotalSize);
}
}
}
}
/*
This code produces output similar to the following:
Drive A:\
Drive type: Removable
Drive C:\
Drive type: Fixed
Volume label:
File system: FAT32
Available space to current user: 4770430976 bytes
Total available space: 4770430976 bytes
Total size of drive: 10731683840 bytes
Drive D:\
Drive type: Fixed
Volume label:
File system: NTFS
Available space to current user: 15114977280 bytes
Total available space: 15114977280 bytes
Total size of drive: 25958948864 bytes
Drive E:\
Drive type: CDRom
The actual output of this code will vary based on machine and the permissions
granted to the user executing it.
*/
To set precision for double values DecimalFormat
is good technique. To use this class import java.text.DecimalFormat
and create object of it for example
double no=12.786;
DecimalFormat dec = new DecimalFormat("#0.00");
System.out.println(dec.format(no));
So it will print two digits after decimal point here it will print 12.79
You could use a temp table which the stored procedure expects to exist. This will work on older versions of SQL Server, which do not support XML etc.
CREATE TABLE #temp
(INT myid)
GO
CREATE PROC myproc
AS
BEGIN
DELETE YourTable
FROM YourTable
LEFT OUTER JOIN #temp T ON T.myid=s.id
WHERE s.id IS NULL
END
Building on @xQbert's answer's, you can avoid the subquery AND make it generic enough to filter by any ID
SELECT id, signin, signout
FROM dTable
INNER JOIN(
SELECT id, MAX(signin) AS signin
FROM dTable
GROUP BY id
) AS t1 USING(id, signin)
An instance of Date always represents a date and cannot be empty. You can use a null value of date2 to represent "there is no date". You will have to check for null whenever you use date2 to avoid a NullPointerException, like when rendering your page:
if (date2 != null)
// print date2
else
// print nothing, or a default value
But for a better check:
if(str === null || str === '')
{
//enter code here
}
With jQuery it's as simple as this:
w=window.open();
w.document.write($('.report_left_inner').html());
w.print();
w.close();
To temporarily disable the draggable behavior use:
$('#item-id').draggable( "disable" )
To remove the draggable behavior permanently use:
$('#item-id').draggable( "destroy" )
To expand on my comment.
You can validate on the command line using php -l [filename]
, which does a syntax check only (lint). This will depend on your php.ini error settings, so you can edit you php.ini or set the error_reporting in the script.
Here's an example of the output when run on a file containing:
<?php
echo no quotes or semicolon
Results in:
PHP Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in badfile.php on line 2
Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in badfile.php on line 2
Errors parsing badfile.php
I suggested you build your own validator.
A simple page that allows you to upload a php file. It takes the uploaded file runs it through php -l
and echos the output.
Note: this is not a security risk it does not execute the file, just checks for syntax errors.
Here's a really basic example of creating your own:
<?php
if (isset($_FILES['file'])) {
echo '<pre>';
passthru('php -l '.$_FILES['file']['tmp_name']);
echo '</pre>';
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</form>
A console application does not automatically add a reference to System.Windows.Forms.dll.
Right-click your project in Solution Explorer and select Add reference... and then find System.Windows.Forms and add it.
You can also use any()
, map()
like so:
if any(map(l.startswith, x)):
pass # Do something
Or alternatively, using a generator expression:
if any(l.startswith(s) for s in x)
pass # Do something
Building on tkerwin's answer, if you happen to have nested parentheses like in
st = "sum((a+b)/(c+d))"
his answer will not work if you need to take everything between the first opening parenthesis and the last closing parenthesis to get (a+b)/(c+d)
, because find searches from the left of the string, and would stop at the first closing parenthesis.
To fix that, you need to use rfind
for the second part of the operation, so it would become
st[st.find("(")+1:st.rfind(")")]
It is very easy and simple setting problem that can be fixed in 5 seconds by following these steps
To allow you to save changes after you alter table, Please follow these steps for your sql setting:
Setters let you to validate data and getters let you format or derive data. Objects allow you to encapsulate data and its validation and formatting code into a neat package that encourages DRY.
For example, consider the following simple class that contains a birth date.
class BirthDate {
private $birth_date;
public function getBirthDate($format='Y-m-d') {
//format $birth_date ...
//$birth_date = ...
return $birth_date;
}
public function setBirthDate($birth_date) {
//if($birth_date is not valid) throw an exception ...
$this->birth_date = $birth_date;
}
public function getAge() {
//calculate age ...
return $age;
}
public function getDaysUntilBirthday() {
//calculate days until birth days
return $days;
}
}
You'll want to validate that the value being set is
And you don't want to do this validation all over your application (or over multiple applications for that matter). Instead, it's easier to make the member variable protected or private (in order to make the setter the only access point) and to validate in the setter because then you'll know that the object contains a valid birth date no matter which part of the application the object came from and if you want to add more validation then you can add it in a single place.
You might want to add multiple formatters that operate on the same member variable i.e. getAge()
and getDaysUntilBirthday()
and you might want to enforce a configurable format in getBirthDate()
depending on locale. Therefore I prefer consistently accessing values via getters as opposed to mixing $date->getAge()
with $date->birth_date
.
getters and setters are also useful when you extend objects. For example, suppose your application needed to allow 150+ year birth dates in some places but not in others. One way to solve the problem without repeating any code would be to extend the BirthDate
object and put the additional validation in the setter.
class LivingBirthDate extends BirthDate {
public function setBirthDate($birth_date) {
//if $birth_date is greater than 150 years throw an exception
//else pass to parent's setter
return parent::setBirthDate($birth_date);
}
}
Kotlin supports operators overloading
In Kotlin you can easily compare dates with compare operators. Because Kotlin already support operators overloading. So to compare date objects :
firstDate: Date = // your first date
secondDate: Date = // your second date
if(firstDate < secondDate){
// fist date is before second date
}
and if you're using calendar objects, you can easily compare like this:
if(cal1.time < cal2.time){
// cal1 date is before cal2 date
}
The primary flag seems to only work for vagrant ssh
for me.
In the past I have used the following method to hack around the issue.
# stage box intended for configuration closely matching production if ARGV[1] == 'stage' config.vm.define "stage" do |stage| box_setup stage, \ "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml" end end
Update @angular-devkit/build-angular to "^0.13.9" . Then run npm install
and after that, run npm serve
.
Specs:
Angular: 7.2.15
Angular CLI: 7.3.9
Node: 11.2.0
OS: darwin x64
You can do with little Trick: Suppose you have requirement of : ( Width,Height )
Wrap_content ,Wrap_content :
//use this as child
Wrap(
children: <Widget>[*your_child*])
Match_parent,Match_parent:
//use this as child
Container(
height: double.infinity,
width: double.infinity,child:*your_child*)
Match_parent,Wrap_content :
//use this as child
Row(
mainAxisSize: MainAxisSize.max,
children: <Widget>[*your_child*],
);
Wrap_content ,Match_parent:
//use this as child
Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[your_child],
);
I prefer to use array_multisort. See the documentation here.
The best way to send data from a parent component to a child is using props.
props
props
(array or object) in the child<child :name="variableOnParent">
See demo below:
Vue.component('child-comp', {
props: ['message'], // declare the props
template: '<p>At child-comp, using props in the template: {{ message }}</p>',
mounted: function () {
console.log('The props are also available in JS:', this.message);
}
})
new Vue({
el: '#app',
data: {
variableAtParent: 'DATA FROM PARENT!'
}
})
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
<div id="app">
<p>At Parent: {{ variableAtParent }}<br>And is reactive (edit it) <input v-model="variableAtParent"></p>
<child-comp :message="variableAtParent"></child-comp>
</div>
_x000D_
if you have generic types in your class you should use TypeReference
with convertValue()
.
final ObjectMapper mapper = new ObjectMapper();
final MyPojo<MyGenericType> pojo = mapper.convertValue(map, new TypeReference<MyPojo<MyGenericType>>() {});
Also you can use that to convert a pojo to java.util.Map
back.
final ObjectMapper mapper = new ObjectMapper();
final Map<String, Object> map = mapper.convertValue(pojo, new TypeReference<Map<String, Object>>() {});
A char simply contains a single alphabet and a string has a full word or number of words woth having a escape sequence inserted in the end automatically to tell the compiler that string has been ended here.(0)
For me (also XAMPP on Windows 7), this is what worked:
<Directory "C:\projects\myfolder\htdocs">`
AllowOverride All
Require all granted
Options Indexes FollowSymLinks
</Directory>`
It is this line that would cause the 403:
Order allow,deny
SELECT *
FROM tbl_name
WHERE coalesce(id_field,'unik_null_value')
IN ('value1', 'value2', 'value3', 'unik_null_value')
So that you eliminate the null from the check. Given a null value in id_field, the coalesce function would instead of null return 'unik_null_value', and by adding 'unik_null_value to the IN-list, the query would return posts where id_field is value1-3 or null.
You can use this JavaScript function:
function sortlist(mylist)
{
var lb = document.getElementById(mylist);
arrTexts = new Array();
arrValues = new Array();
arrOldTexts = new Array();
for(i=0; i<lb.length; i++)
{
arrTexts[i] = lb.options[i].text;
arrValues[i] = lb.options[i].value;
arrOldTexts[i] = lb.options[i].text;
}
arrTexts.sort();
for(i=0; i<lb.length; i++)
{
lb.options[i].text = arrTexts[i];
for(j=0; j<lb.length; j++)
{
if (arrTexts[i] == arrOldTexts[j])
{
lb.options[i].value = arrValues[j];
j = lb.length;
}
}
}
}
Get the graphviz-2.24.msi Graphviz.org. Then get zgrviewer.
Zgrviewer requires java (probably 1.5+). You might have to set the paths to the Graphviz binaries in Zgrviewer's preferences.
File -> Open -> Open with dot -> SVG pipeline (standard) ... Pick your .dot file.
You can zoom in, export, all kinds of fun stuff.
Try imaskjs. It has Number, RegExp and other masks. Very simple to extend.
I know this is an old question but the best workaround for your question is using a dummy subquery:
SELECT 'Hello World'
FROM (SELECT name='Nothing') n
WHERE 1=1
This way you can have WHERE and any clause (like Joins or Apply, etc.) after the select statement since the dummy subquery forces the use of the FROM clause without changing the result.
From the Java tutorial, you need to create a new font and register it in the graphics environment:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));
After this step is done, the font is available in calls to getAvailableFontFamilyNames()
and can be used in font constructors.
Thank to Brian for the code. I was trying to connect to the sql server with {call spname(?,?)}
and I got errors, but when I change my code to exec sp...
it works very well.
I post my code in hope this helps others with problems like mine:
ResultSet rs = null;
PreparedStatement cs=null;
Connection conn=getJNDIConnection();
try {
cs=conn.prepareStatement("exec sp_name ?,?,?,?,?,?,?");
cs.setEscapeProcessing(true);
cs.setQueryTimeout(90);
cs.setString(1, "valueA");
cs.setString(2, "valueB");
cs.setString(3, "0418");
//commented, because no need to register parameters out!, I got results from the resultset.
//cs.registerOutParameter(1, Types.VARCHAR);
//cs.registerOutParameter(2, Types.VARCHAR);
rs = cs.executeQuery();
ArrayList<ObjectX> listaObjectX = new ArrayList<ObjectX>();
while (rs.next()) {
ObjectX to = new ObjectX();
to.setFecha(rs.getString(1));
to.setRefId(rs.getString(2));
to.setRefNombre(rs.getString(3));
to.setUrl(rs.getString(4));
listaObjectX.add(to);
}
return listaObjectX;
} catch (SQLException se) {
System.out.println("Error al ejecutar SQL"+ se.getMessage());
se.printStackTrace();
throw new IllegalArgumentException("Error al ejecutar SQL: " + se.getMessage());
} finally {
try {
rs.close();
cs.close();
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
//module dependent on ngRoute
var app=angular.module("myApp",['ngRoute']);
//spa-Route Config file
app.config(function($routeProvider,$locationProvider){
$locationProvider.hashPrefix('');
$routeProvider
.when('/',{template:'HOME'})
.when('/about/:paramOne/:paramTwo',{template:'ABOUT',controller:'aboutCtrl'})
.otherwise({template:'Not Found'});
}
//aboutUs controller
app.controller('aboutCtrl',function($routeParams){
$scope.paramOnePrint=$routeParams.paramOne;
$scope.paramTwoPrint=$routeParams.paramTwo;
});
in index.html
<a ng-href="#/about/firstParam/secondParam">About</a>
firstParam and secondParam can be anything according to your needs.
Sometimes when we do these steps:
alter table my_table drop constraint my_pk;
alter table my_table add constraint my_pk primary key (city_id, buildtime, time);
The last statement fails with
ORA-00955 "name is already used by an existing object"
Oracle usually creates an unique index with the same name my_pk. In such a case you can drop the unique index or rename it based on whether the constraint is still relevant.
You can combine the dropping of primary key constraint and unique index into a single sql statement:
alter table my_table drop constraint my_pk drop index;
check this: ORA-00955 "name is already used by an existing object"
I used this method:
$(document).mousemove(function(e) {
window.x = e.pageX;
window.y = e.pageY;
});
function show_popup(str) {
$("#popup_content").html(str);
$("#popup").fadeIn("fast");
$("#popup").css("top", y);
$("#popup").css("left", x);
}
In this way I'll always have the distance from the top saved in y and the distance from the left saved in x.
These are questions which, in my opionion, requires different knowledge from different domains.
That said, maybe you want to read some books, personally I've used this book in my datbase university course (and found a decent one, but I've not read other books in this field, so my advice is to check out for some good books in database design).
Pointing CATALINA_BASE
to a different directory from CATALINA_HOME
allows you to separate the configuration directory from the binaries directory.
By default, CATALINA_BASE
(configurations) and CATALINA_HOME
(binaries) point to the same folder, but separating the configurations from the binaries can help you to run multiple instances of Tomcat side by side without duplicating the binaries.
It is also useful when you want to update the binaries, without modifying, or needing to backup/restore your configuration files for Tomcat.
There is an easier way to set CATALINA_BASE now with the makebase
utility. I have posted a tutorial that covers this subject at http://blog.rasia.io/blog/how-to-easily-setup-lucee-in-tomcat.html along with a video tutorial at
https://youtu.be/nuugoG5c-7M
To take advantage of this feature, simply create the config directory and point to it with the CATALINA_BASE
environment variable. You will have to put some files in that directory:
conf
directory from the original Tomcat installation directory, including its contents, and ensure that Tomcat has read permissions to it. Edit the configuration files according to your needs.logs
directory if conf/logging.properties
points to ${catalina.base}/logs
, and ensure that Tomcat has read/write permissions to it.temp
directory if you are not overriding the default of $CATALINA_TMPDIR
which points to ${CATALINA_BASE}/temp
, and ensure that Tomcat has write permissions to it.work
directory which defaults to ${CATALINA_BASE}/work
, and ensure that Tomcat has write permissions to it.I just ran into this... my gif didn't run on the server that I was testing on, but when I published the code it ran on my desktop just fine...
Are you sure you are not using a wrong path in the url
field? - I was facing the same error, and the problem was solved after I checked the path, found it wrong and replaced it with the right one.
Make sure that the URL you are specifying is correct for the AJAX request and that the file exists.
It is because display:inline-block
takes into account white-space in the html. If you remove the white-space between the div
's it works as expected. Live Example: http://jsfiddle.net/XCDsu/4/
<div id="col1">content</div><div id="col2">content</div>
For me, I was pushing the changes to a private repo to which I didn't had the write access. Make sure you have the valid access rights while performing push or pull operations.
You can directly verify via
Using the visibility
property only affects the visibility of the elements on the page; they will still be there in the page layout. To completely remove the elements from the page, use the display
property.
display:none // for hiding
display:block // for showing
Make sure to change your css file to use display instead of visibility too.
As for the javascript (this is not jQuery), make sure you hide the options by default when the page loads:
<script type="text/javascript">
window.onload = function() {
document.getElementById('ifYes').style.display = 'none';
}
function yesnoCheck() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.display = 'block';
}
else {
document.getElementById('ifYes').style.display = 'none';
}
}
</script>
If you haven't done so already, I would recommend taking a look at jQuery. jQuery code is much clearer and easier to write and understand.
For windows, If you want to know the port number of your local host on which Mysql is running you can use this query on MySQL Command line client --
SHOW VARIABLES WHERE Variable_name = 'port';
mysql> SHOW VARIABLES WHERE Variable_name = 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port | 3306 |
+---------------+-------+
1 row in set (0.00 sec)
It will give you the port number on which MySQL is running.
You have the checkPermissions function for pre Marshmallow devices in FragmentCompat. I use like this:
FragmentCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
Try to use jpg and png , also name your image in lowercase. Then drag and drop the image in res/drawable . then go to file and click save all . close eclipse then reopen it again . That is what worked for me .
If you want to pass the cookie to the browser, you have to append to the headers to be sent back. If you're using wsgi:
import requests
...
def application(environ, start_response):
cookie = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}
response_headers = [('Content-type', 'text/plain')]
response_headers.append(('Set-Cookie',cookie))
...
return [bytes(post_env),response_headers]
I'm successfully able to authenticate with Bugzilla and TWiki hosted on the same domain my python wsgi script is running by passing auth user/password to my python script and pass the cookies to the browser. This allows me to open the Bugzilla and TWiki pages in the same browser and be authenticated. I'm trying to do the same with SuiteCRM but i'm having trouble with SuiteCRM accepting the session cookies obtained from the python script even though it has successfully authenticated.
You can use Conditional formatting with the option "Formula Is". One possible formula is
=NOT(ISBLANK($B1))
Another possible formula is
=$B1<>""
Total Commander also has a binary compare option:
go to: File \\Compare by content
ps. I guess some people may alredy be using this tool and may not be aware of the built-in feature.
Just go to the application's Properties and change the Output type from Console Application to Windows Application.
If you want to create a garage and fill it up with new cars that can be accessed later, use this code:
for (int i = 0; i < garage.length; i++)
garage[i] = new Car("argument");
Also, the cars are later accessed using:
garage[0];
garage[1];
garage[2];
etc.
Checkbox only offer you 2 values (true, false). Nullable boolean has 3 values (true, false, null) so it's impossible to do it with a checkbox.
A good option is to use a drop down instead.
Model
public bool? myValue;
public List<SelectListItem> valueList;
Controller
model.valueList = new List<SelectListItem>();
model.valueList.Add(new SelectListItem() { Text = "", Value = "" });
model.valueList.Add(new SelectListItem() { Text = "Yes", Value = "true" });
model.valueList.Add(new SelectListItem() { Text = "No", Value = "false" });
View
@Html.DropDownListFor(m => m.myValue, valueList)
C# is a programming language, .NET is a blanket term that tends to cover both the .NET Framework (an application framework library) and the Common Language Runtime which is the runtime in which .NET assemblies are run.
Microsoft's implementation of C# is heavily integrated with the .NET Framework so it is understandable that the two concepts would be confused. However it is important to understand that they are two very different things.
Here is a class written in C#:
class Example { }
Here is a class written in C# that explicitly uses a .NET framework assembly, type, and method:
class Example
{
static void Main()
{
// Here we call into the .NET framework to
// write to the output console
System.Console.Write("hello, world");
}
}
As I mentioned before, it is very difficult to use Microsoft's implementation of C# without using the .NET framework as well. My first Example
implementation above even uses the .NET framework (implicitly, yes, but it does use it nonetheless) because Example
inherits from System.Object
.
Also, the reason I use the phrase Microsoft's implementation of C# is because there are other implementations of C# available.
Just write a string to the output stream. You might set the MIME-type to text/javascript
(edit: application/json
is apparently officialer) if you're feeling helpful. (There's a small but nonzero chance that it'll keep something from messing it up someday, and it's a good practice.)
Check if below are enabled
bz, mbstring, intl, ioncube_loader and Json extension.
For all looking for solutions which work in R markdown/ bookdown, these of the previous solutions do/do not work or need slight adaption:
Append { width=50% }
or { width=50% height=50% }
![foo](foo.png){ width=50% }
![foo](foo.png){ width=50% height=50% }
Important: no comma between width and height – i.e. { width=50%, height=30% }
won't work!
Append { height="36px" width="36px" }
![foo](foo.png){ height="36px" width="36px" }
{:height="36px" width="36px"}
with colon, as from @sayth, seems not to work with R markdown=WIDTHxHEIGHT
=WIDTHxHEIGHT
![foo](foo.png =100x20)
nor =WIDTH
only ![foo](foo.png =250x)
workI know this is old, BUT for anyone else looking:
Remove https:// from the hostname and add port 443 instead.
{
method: 'POST',
hostname: 'api.dropbox.com',
port: 443
}
df = data.frame(date=c("2012-02-01", "2012-02-01", "2012-02-02"))
df$day <- weekdays(as.Date(df$date))
df
## date day
## 1 2012-02-01 Wednesday
## 2 2012-02-01 Wednesday
## 3 2012-02-02 Thursday
Edit: Just to show another way...
The wday
component of a POSIXlt
object is the numeric weekday (0-6 starting on Sunday).
as.POSIXlt(df$date)$wday
## [1] 3 3 4
which you could use to subset a character vector of weekday names
c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday")[as.POSIXlt(df$date)$wday + 1]
## [1] "Wednesday" "Wednesday" "Thursday"
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.waist2height); {
final EditText edit = (EditText)findViewById(R.id.editText);
final RadioButton rb1 = (RadioButton) findViewById(R.id.radioCM);
final RadioButton rb2 = (RadioButton) findViewById(R.id.radioFT);
if(rb1.isChecked()){
edit.setVisibility(View.VISIBLE);
}
else if(rb2.isChecked()){
edit.setVisibility(View.INVISIBLE);
}
}
You didn't join the table in your query.
Your original query will always return nothing unless there are no records at all in eotm_dyn
, in which case it will return everything.
Assuming these tables should be joined on employeeID
, use the following:
SELECT *
FROM employees e
WHERE NOT EXISTS
(
SELECT null
FROM eotm_dyn d
WHERE d.employeeID = e.id
)
You can join these tables with a LEFT JOIN
keyword and filter out the NULL
's, but this will likely be less efficient than using NOT EXISTS
.
(1) SQLite has a built in rowid
pseudo-column so this works:
sqldf("select min(rowid) rowid, id, string
from test
group by id")
giving:
rowid id string
1 1 1 A
2 3 2 B
3 5 3 C
4 7 4 D
5 9 5 E
(2) Also sqldf
itself has a row.names=
argument:
sqldf("select min(cast(row_names as real)) row_names, id, string
from test
group by id", row.names = TRUE)
giving:
id string
1 1 A
3 2 B
5 3 C
7 4 D
9 5 E
(3) A third alternative which mixes the elements of the above two might be even better:
sqldf("select min(rowid) row_names, id, string
from test
group by id", row.names = TRUE)
giving:
id string
1 1 A
3 2 B
5 3 C
7 4 D
9 5 E
Note that all three of these rely on a SQLite extension to SQL where the use of min
or max
is guaranteed to result in the other columns being chosen from the same row. (In other SQL-based databases that may not be guaranteed.)
If you installed Python 2.7, I think you could use pip2
and pip2.7
to install packages specifically for Python 2, like
pip2 install some_pacakge
or
pip2.7 install some_package
And you may use pip3
or pip3.5
to install pacakges specifically for Python 3.
If the data type of the field is date or timestamp, Oracle should always give the correct result if you add the correct number given in number of days (or a the correct fraction of a day in your case). So if you are trying to bump the value in 30 minutes, you should use :
select field + 0.5/24 from table;
Based on the information you provided, I believe this is what you tried to do and I am quite sure it works.
It's not a cut and paste. The CASE
expression must return a value, and you are returning a string containing SQL (which is technically a value but of a wrong type). This is what you wanted to write, I think:
SELECT * FROM [Purchasing].[Vendor] WHERE
CASE
WHEN @url IS null OR @url = '' OR @url = 'ALL'
THEN PurchasingWebServiceURL LIKE '%'
WHEN @url = 'blank'
THEN PurchasingWebServiceURL = ''
WHEN @url = 'fail'
THEN PurchasingWebServiceURL NOT LIKE '%treyresearch%'
ELSE PurchasingWebServiceURL = '%' + @url + '%'
END
I also suspect that this might not work in some dialects, but can't test now (Oracle, I'm looking at you), due to not having booleans.
However, since @url
is not dependent on the table values, why not make three different queries, and choose which to evaluate based on your parameter?
Depending on what firewall software you have installed/available, you should be able to block the outgoing port and depending on how your firewall is setup it should just drop the connection request packet. No connection request, no connection, timeout ensues. This would probably work better if it was implemented at a router level (they tend to drop packets instead of sending resets, or whatever the equivalent is for the situation) but there's bound to be a software package that'd do the trick too.
In addition to AIXroot's answer, there is also a logout function that can be used to write a utmp logout record. So if you don't have any processes for user xxxx, but userdel says "userdel: account xxxx is currently in use", you can add a logout record manually. Create a file logout.c like this:
#include <stdio.h>
#include <utmp.h>
int main(int argc, char *argv[])
{
if (argc == 2) {
return logout(argv[1]);
}
else {
fprintf(stderr, "Usage: logout device\n");
return 1;
}
}
Compile it:
gcc -lutil -o logout logout.c
And then run it for whatever it says in the output of finger's "On since" line(s) as a parameter:
# finger xxxx
Login: xxxx Name:
Directory: /home/xxxx Shell: /bin/bash
On since Sun Feb 26 11:06 (GMT) on 127.0.0.1:6 (messages off) from 127.0.0.1
On since Fri Feb 24 16:53 (GMT) on pts/6, idle 3 days 17:16, from 127.0.0.1
Last login Mon Feb 10 14:45 (GMT) on pts/11 from somehost.example.com
Mail last read Sun Feb 27 08:44 2014 (GMT)
No Plan.
# userdel xxxx
userdel: account `xxxx' is currently in use.
# ./logout 127.0.0.1:6
# ./logout pts/6
# userdel xxxx
no crontab for xxxx
Don't set height
. Use min-height
and max-height
instead.
Use character classes: [ \t]
You can use retainAll method and get the intersection of your two sets.
This is just a workaround solution:
In normal cases, use the solutions that are shipped with git. These work great in most cases. Force to LF if you share the development on Windows and Unix based systems by setting .gitattributes.
In my case there were >10 programmers developing a project in Windows. This project was checked in with CRLF and there was no option to force to LF.
Some settings were internally written on my machine without any influence on the LF format; thus some files were globally changed to LF on each small file change.
My solution:
Windows-Machines: Let everything as it is. Care about nothing, since you are a default windows 'lone wolf' developer and you have to handle like this: "There is no other system in the wide world, is it?"
Unix-Machines
Add following lines to a config's [alias]
section. This command lists all changed (i.e. modified/new) files:
lc = "!f() { git status --porcelain \
| egrep -r \"^(\?| ).\*\\(.[a-zA-Z])*\" \
| cut -c 4- ; }; f "
Convert all those changed files into dos format:
unix2dos $(git lc)
Optionally ...
Create a git hook for this action to automate this process
Use params and include it and modify the grep
function to match only particular filenames, e.g.:
... | egrep -r "^(\?| ).*\.(txt|conf)" | ...
Feel free to make it even more convenient by using an additional shortcut:
c2dos = "!f() { unix2dos $(git lc) ; }; f "
... and fire the converted stuff by typing
git c2dos
Put this in the App.java:
public static void main(String[] args) throws UnknownHostException {
SpringApplication app = new SpringApplication(App.class);
SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
if (!source.containsProperty("spring.profiles.active") &&
!System.getenv().containsKey("SPRING_PROFILES_ACTIVE")) {
app.setAdditionalProfiles("production");
}
...
}
This is how it is done in JHipster
If you are using PHP 5 you can try this:
function a() {
$trace = debug_backtrace();
echo $trace[0]["function"];
}
SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.
You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...
From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.
If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/
Here is a picture that shows the difference between add()
and replace()
So add()
method keeps on adding fragments on top of the previous fragment in FragmentContainer.
While replace()
methods clears all the previous Fragment from Containers and then add it in FragmentContainer.
What is addToBackStack
addtoBackStack
method can be used with add() and replace methods. It serves a different purpose in Fragment API.
What is the purpose?
Fragment API unlike Activity API does not come with Back Button navigation by default. If you want to go back to the previous Fragment then the we use addToBackStack() method in Fragment. Let's understand both
Case 1:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragmentContainer, fragment, "TAG")
.addToBackStack("TAG")
.commit();
Case 2:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragmentContainer, fragment, "TAG")
.commit();
The accepted answer is correct, but I prefer:
@{int count = 0;}
@foreach (var item in Model.Resources)
{
@Html.Raw(count <= 3 ? "<div class=\"resource-row\">" : "")
// some code
@Html.Raw(count <= 3 ? "</div>" : "")
@(count++)
}
I hope this inspires someone, even though I'm late to the party.
=
operatorWe can use the public member function std::vector::operator=
of the container std::vector
for assigning values from a vector to another.
Besides, a constructor function also makes sense. A constructor function with another vector as parameter(e.g. x
) constructs a container with a copy of each of the elements in x
, in the same order.
std::vector::swap
std::vector::swap
is not copying a vector to another, it is actually swapping elements of two vectors, just as its name suggests. In other words, the source vector to copy from is modified after std::vector::swap
is called, which is probably not what you are expected.
If the elements in the source vector are pointers to other data, then a deep copy is wanted sometimes.
According to wikipedia:
A deep copy, meaning that fields are dereferenced: rather than references to objects being copied, new copy objects are created for any referenced objects, and references to these placed in B.
Actually, there is no currently a built-in way in C++ to do a deep copy. All of the ways mentioned above are shallow. If a deep copy is necessary, you can traverse a vector and make copy of the references manually. Alternatively, an iterator can be considered for traversing. Discussion on iterator is beyond this question.
Try
System.exit(0);
this should terminate thread main and end the main program
You can try this cool app available in play store called Html Page Source https://play.google.com/store/apps/details?id=com.scintillar.hps
It depends
It depends on a lot of things - your goals, your experience, your timeframe, etc.
The majority of game programming isn't language specific. 3D math is 3D math in C# as much as it is in C++. While the APIs may be different, and different 'bookkeeping' may be required, the fundamental logic and math will remain the same.
And it's true that most AAA game engines are C++ with a scripting language on top of them. That is undeniable. However, most AAA engines also have a bunch of in-house tools supporting them, and those may be in anything - Java, C#, C++, etc.
If you want to write a game, and are an experienced developer then C++ and C# have a lot going for them. C# has less housekeeping, while C++ has more available libraries and tools. For anything highly complex, however, you'd be best off trying to use an existing engine as a starting point.
If you want to write a game, and are a new developer then don't write an engine. Use an existing engine, and mod it or use its facilities to write your game. Trust me.
If you want to learn how to write an engine, and are an experienced developer you should probably think about C++. C# is possible as well, but the amount of code and ease of integration of C++ probably puts it over the top.
If you want to learn how to write an engine, and are a new developer I'd probably recommend C#/XNA. You'll get to the game 'stuff' faster, with less headache of learning the ins and outs of C++.
If you want a job in the industry then you need to figure out what kind of job you want. A high-level language can help get a foot in the door dealing with tools and/or web development, which can lead to opportunities on actual game work. Even knowledge of scripting languages can help if you want to go for more of the game designer/scripter position. Chances are that you will not get a job working on core engine stuff immediately, as the skills required to do so are pretty high. Strong C++ development skills are always helpful, especially in real-time or networked scenarios.
AAA game engine development involves some serious brain-twisting code.
If you want to start a professional development house then you probably aren't reading this, but already know that C++ is probably the only viable answer.
If you want to do casual game development then you should probably consider Flash or a similar technology.
public class Mulretun
{
public String name;;
public String location;
public String[] getExample()
{
String ar[] = new String[2];
ar[0]="siva";
ar[1]="dallas";
return ar; //returning two values at once
}
public static void main(String[] args)
{
Mulretun m=new Mulretun();
String ar[] =m.getExample();
int i;
for(i=0;i<ar.length;i++)
System.out.println("return values are: " + ar[i]);
}
}
o/p:
return values are: siva
return values are: dallas
the solution is easy: execute via sh
... -exec sh -c "zcat {} | agrep -dEOE 'grep' " \;
2016 Answer:
Javascript has this function, so no need for Jquery.
yournumber.toLocaleString("en");
Try to start the MySQL server:
mysql.server start
Web Call Server (Flashphoner)
Re-Streaming RTSP to WebRTC (Native browser feature for Chrome and FF either on Android or desktop)
Re-Streaming RTSP to Websockets (iOS Safari and Chrome/FF Desktop)
Take a look at this article.
I was having the same problem using the python email functions. Below is the code I was trying to retrieve email subject into a variable. This works fine for most emails and the variable populates. If you receive an email from Yahoo or the like and the sender did no fill out the subject line Yahoo does not create a subject line in the email and you get a NoneType returned from the function. Martineau provided a correct answer as well as Soviut. IMO Soviut's answer is more concise from a programming stand point; not necessarily from a Python one. Here is some code to show the technique:
import sys, email, email.Utils
afile = open(sys.argv[1], 'r')
m = email.message_from_file(afile)
subject = m["subject"]
# Soviut's Concise test for unset variable.
if subject is None:
subject = "[NO SUBJECT]"
# Alternative way to test for No Subject created in email (Thanks for NoneThing Yahoo!)
try:
if len(subject) == 0:
subject = "[NO SUBJECT]"
except TypeError:
subject = "[NO SUBJECT]"
print subject
afile.close()
Upgrading ipykernel
, notebook
and then downgrading tornado
to 4.2.0 solved the issue for me.
My current package versions related to jupyter:
jupyter==1.0.0
jupyter-client==5.2.2
jupyter-console==6.1.0
jupyter-core==4.4.0
jupyterlab==2.2.5
jupyterlab-server==1.2.0
ipykernel==5.3.4
notebook==5.2.2
tornado==4.2
pyparsing==2.4.2
ipython==5.5.0
ipython-genutils==0.2.0
prompt-toolkit==1.0.15
My initial guess without knowing the data would be that the UserNameToVerify is not a multiple of 4 in length. Check out the FromBase64String on msdn.
// Ok
byte[] b1 = Convert.FromBase64String("CoolDude");
// Exception
byte[] b2 = Convert.FromBase64String("MyMan");
Officially, you can't. But someone's been extracting them for your convenience and hosting them.
Note: You can get the older releases on the official site, but the latest ones are part of the WDK.
here is more detailed information -> [1]: https://crunchify.com/simplest-spring-mvc-hello-world-example-tutorial-spring-model-view-controller-tips/
logger
logs to syslog facilities. If you want the message to go to a particular file you have to modify the syslog configuration accordingly. You could add a line like this:
local7.* -/var/log/mycustomlog
and restart syslog. Then you can log like this:
logger -p local7.info "information message"
logger -p local7.err "error message"
and the messages will appear in the desired logfile with the correct log level.
Without making changes to the syslog configuration you could use logger
like this:
logger -s "foo bar" >> /var/log/mycustomlog
That would instruct logger
to print the message to STDERR as well (in addition to logging it to syslog), so you could redirect STDERR to a file. However, it would be utterly pointless, because the message is already logged via syslog anyway (with the default priority user.notice
).
you can do it using eloquent easily like this
$sum = Model::sum('sum_field');
its will return a sum of fields, if apply condition on it that is also simple
$sum = Model::where('status', 'paid')->sum('sum_field');
In my program I first check for Terminal Server and use the WTSClientHardwareId. Else the MAC address of the local PC should be adequate.
If you really want to use the list of properties you provided leave out things like Name
and DriverVersion
, Clockspeed
, etc. since it's possibly OS dependent. Try outputting the same info on both operating systems and leave out that which differs between.
I mostly use this function:
cf() {
cd "$(osascript -e 'tell app "Finder" to POSIX path of (insertion location as alias)')"
}
You could also assign a shortcut to a script like the ones below.
Reuse an existing tab or create a new window (Terminal):
tell application "Finder" to set p to POSIX path of (insertion location as alias)
tell application "Terminal"
if (exists window 1) and not busy of window 1 then
do script "cd " & quoted form of p in window 1
else
do script "cd " & quoted form of p
end if
activate
end tell
Reuse an existing tab or create a new tab (Terminal):
tell application "Finder" to set p to POSIX path of (insertion location as alias)
tell application "Terminal"
if not (exists window 1) then reopen
activate
if busy of window 1 then
tell application "System Events" to keystroke "t" using command down
end if
do script "cd " & quoted form of p in window 1
end tell
Always create a new tab (iTerm 2):
tell application "Finder" to set p to POSIX path of (insertion location as alias)
tell application "iTerm"
if exists current terminal then
current terminal
else
make new terminal
end if
tell (launch session "Default") of result to write text "cd " & quoted form of p
activate
end tell
The first two scripts have two advantages compared to the services added in 10.7:
This is similar to some of the above answers, but with this, you can specify if you want to remove rows with a percentage of missing values greater-than or equal-to a given percent (with the argument pct
)
drop_rows_all_na <- function(x, pct=1) x[!rowSums(is.na(x)) >= ncol(x)*pct,]
Where x
is a dataframe and pct
is the threshold of NA
-filled data you want to get rid of.
pct = 1
means remove rows that have 100% of its values NA
.
pct = .5
means remome rows that have at least half its values NA
The shape
method requires that a
be a Numpy ndarray. But Numpy can also calculate the shape of iterables of pure python objects:
np.shape([[1,2],[1,2]])
If you need exact your example, you should add format to ToString()
string test = DateTime.ParseExact(DateTime.Now.ToString("dd.MM.yyyy"), "dd.MM.yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
But it's better to use straight formatting:
string test = DateTime.Now.ToString("yyyy-MM-dd")
I am using Spring 4.1.6 and Jackson FasterXML 2.1.4.
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<!-- ?????null??-->
<property name="serializationInclusion" value="NON_NULL"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
this works at my applicationContext.xml configration
from flask import request
@app.route('/data')
def data():
# here we want to get the value of user (i.e. ?user=some-value)
user = request.args.get('user')
From Zvon.org XSLT Reference:
XPath function: boolean contains (string, string)
Hope this helps.
Use git reflog
to list all changes made in your git history. Copy an action id and type git reset ACTION_ID
In the early days of SQL, it was chosen as the solution to the problem of how to deal with duplicate column names (see below note).
To borrow a query from another answer:
SELECT P.ProductName,
P.ProductRetailPrice,
O.Quantity
FROM Products AS P
INNER JOIN Orders AS O ON O.ProductID = P.ProductID
WHERE O.OrderID = 123456
The column ProductID
(and possibly others) is common to both tables and since the join condition syntax requires reference to both, the 'dot qualification' provides disambiguation.
Of course, the better solution was to never have allowed duplicate column names in the first place! Happily, if you use the newer NATURAL JOIN
syntax, the need for the range variables P
and O
goes away:
SELECT ProductName, ProductRetailPrice, Quantity
FROM Products NATURAL JOIN Orders
WHERE OrderID = 123456
But why is the AS
keyword optional? My recollection from a personal discussion with a member of the SQL standard committee (either Joe Celko or Hugh Darwen) was that their recollection was that, at the time of defining the standard, one vendor's product (Microsoft's?) required its inclusion and another vendor's product (Oracle's?) required its omission, so the compromise chosen was to make it optional. I have no citation for this, you either believe me or not!
In the early days of the relational model, the cross product (or theta-join or equi-join) of relations whose headings are not disjoint appeared to produce a relation with two attributes of the same name; Codd's solution to this problem in his relational calculus was the use of dot qualification, which was later emulated in SQL (it was later realised that so-called natural join was primitive without loss; that is, natural join can replace all theta-joins and even cross product.)
$st = $data->prepare("SELECT * FROM exampleWHERE example LIKE :search LIMIT 10");
In pandas you can do str.len
with your boundary and using the Boolean result to filter it .
df[df['column name'].str.len().lt(2)]
Your debut
and fin
values are floating point values, not integers, because taille
is a float.
Make those values integers instead:
item = plateau[int(debut):int(fin)]
Alternatively, make taille
an integer:
taille = int(sqrt(len(plateau)))
100vh works for me, but at first I had used javascript (actually jQuery, but you can adapt it), to tackle a similar problw.
HTML
<body>
<div id="wrapper">
<div id="header">header</div>
<div id="content">content</div>
</div>
</body>
js/jQuery
var innerWindowHeight = $(window).height();
var headerHeight = $("#header").height();
var contentHeight = innerWindowHeight - headerHeight;
$(".content").height(contentHeight + "px");
Alternately, you can just use 111px if you don't want to calculate headerHeight.
Also, you may want to put this in a window resize event, to rerun the script if the window height increases for example.
You can try with this:
this.setState(prevState => {
prevState = JSON.parse(JSON.stringify(this.state.jasper));
prevState.name = 'someOtherName';
return {jasper: prevState}
})
or for other property:
this.setState(prevState => {
prevState = JSON.parse(JSON.stringify(this.state.jasper));
prevState.age = 'someOtherAge';
return {jasper: prevState}
})
Or you can use handleChage function:
handleChage(event) {
const {name, value} = event.target;
this.setState(prevState => {
prevState = JSON.parse(JSON.stringify(this.state.jasper));
prevState[name] = value;
return {jasper: prevState}
})
}
and HTML code:
<input
type={"text"}
name={"name"}
value={this.state.jasper.name}
onChange={this.handleChange}
/>
<br/>
<input
type={"text"}
name={"age"}
value={this.state.jasper.age}
onChange={this.handleChange}
/>
I made it work this way:
async getMarkers() {
const markers = [];
await firebase.firestore().collection('events').get()
.then(querySnapshot => {
querySnapshot.docs.forEach(doc => {
markers.push(doc.data());
});
});
return markers;
}
I ran into the same issue and found another way to do this. It worked for in my case as it was a relatively small application.
First, the user will a click button in the component which needs to be printed. This will set a flag that can be accessed by the app component. Like so
.html file
<button mat-button (click)="printMode()">Print Preview</button>
.ts file
printMode() {
this.utilities.printMode = true;
}
In the html of the app component, we hide everything except the router-outlet. Something like below
<div class="container">
<app-header *ngIf="!utilities.printMode"></app-header>
<mat-sidenav-container>
<mat-sidenav *ngIf="=!utilities.printMode">
<app-sidebar></app-sidebar>
</mat-sidenav>
<mat-sidenav-content>
<router-outlet></router-outlet>
</mat-sidenav-content>
</mat-sidenav-container>
</div>
With similar ngIf conidtions, we can also adjust the html template of the component to only show or hide things in printMode. So that the user will see only what needs to get printed when print preview is clicked.
We can now simply print or go back to normal mode with the below code
.html file
<button mat-button class="doNotPrint" (click)="print()">Print</button>
<button mat-button class="doNotPrint" (click)="endPrint()">Close</button>
.ts file
print() {
window.print();
}
endPrint() {
this.utilities.printMode = false;
}
.css file (so that the print and close button's don't get printed)
@media print{
.doNotPrint{display:none !important;}
}
You can assign a const
object to a non-const
object just fine. Because you're copying and thus creating a new object, const
ness is not violated.
int main() {
const int a = 3;
int b = a;
}
It's different if you want to obtain a pointer or reference to the original, const
object:
int main() {
const int a = 3;
int& b = a; // or int* b = &a;
}
// error: invalid initialization of reference of type 'int&' from
// expression of type 'const int'
You can use const_cast
to hack around the type safety if you really must, but recall that you're doing exactly that: getting rid of the type safety. It's still undefined to modify a
through b
in the below example:
int main() {
const int a = 3;
int& b = const_cast<int&>(a);
b = 3;
}
Although it compiles without errors, anything can happen including opening a black hole or transferring all your hard-earned savings into my bank account.
If you have arrived at what you think is a requirement to do this, I'd urgently revisit your design because something is very wrong with it.
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
/*width*/ ViewGroup.LayoutParams.MATCH_PARENT,
/*height*/ ViewGroup.LayoutParams.MATCH_PARENT,
/*weight*/ 1.0f
);
YOUR_VIEW.setLayoutParams(param);
Code posted by you is correct and should have worked. But check exactly what you have in the char*
. If the correct value is to big to be represented, functions will return a positive or negative HUGE_VAL
. Check what you have in the char*
against maximum values that float
and double
can represent on your computer.
Check this page for strtod
reference and this page for atof
reference.
I have tried the example you provided in both Windows and Linux and it worked fine.
No, this is not possible, because static member functions lack a this
pointer. And static members (both functions and variables) are not really class members per-se. They just happen to be invoked by ClassName::member
, and adhere to the class access specifiers. Their storage is defined somewhere outside the class; storage is not created each time you instantiated an object of the class. Pointers to class members are special in semantics and syntax. A pointer to a static member is a normal pointer in all regards.
virtual functions in a class needs the this
pointer, and is very coupled to the class, hence they can't be static.
Instinctively one thinks geometrically: horizontal (X) axis and then vertical (Y) axis. This is not, however, the case with a 2D array, rows come first and then columns.
Consider the following analogy: in geometry one walks to the ladder (X axis) and climbs it (Y axis). Conversely, in Java one descends the ladder (rows) and walks away (columns).
If all you want is to print from Monday
onwards, you can use list
's index
method to find the position where "Monday" is in the list, and iterate from there as explained in other posts. Using list.index
saves you hard-coding the index for "Monday", which is a potential source of error:
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
for d in days[days.index('Monday'):] :
print d
You can execute it just as you select a table using SELECT
clause. In addition you can provide parameters within parentheses.
Try with below syntax:
SELECT * FROM yourFunctionName(parameter1, parameter2)
This post is now nearly 5 years old! Python-2.7 will stop receiving official updates from python.org in 2020. Also, Python-3.7 has been released. Check out Python-Future on how to make your Python-2 code compatible with Python-3. For updating conda, the documentation now recommends using conda update --all
in each of your conda environments to update all packages and the Python executable for that version. Also, since they changed their name to Anaconda, I don't know if the Windows registry keys are still the same.
There have been no updates to Python(x,y) since June of 2015, so I think it's safe to assume it has been abandoned.
UPDATE: 2016-11-11As @cxw comments below, these answers are for the same bit-versions, and by bit-version I mean 64-bit vs. 32-bit. For example, these answers would apply to updating from 64-bit Python-2.7.10 to 64-bit Python-2.7.11, ie: the same bit-version. While it is possible to install two different bit versions of Python together, it would require some hacking, so I'll save that exercise for the reader. If you don't want to hack, I suggest that if switching bit-versions, remove the other bit-version first.
UPDATES: 2016-05-16PATH
and Registry. After extraction, create a symlink to conda
in your bin
or install conda from PyPI. Then create another symlink called conda-activate
to activate
in the Anaconda/Miniconda root bin folder. Now Anaconda/Miniconda is just like Ruby RVM. Just use conda-activate root
to enable Anaconda/Miniconda.conda update --all
to keep each conda environment updated,$ ln /c/Python33/python.exe python3
).If OP has 2.7.x and wants to install newer version of 2.7.x, then
It is recommended to uninstall any other Python distribution before installing Python(x,y)
Program Files\Enthought
or home\AppData\Local\Enthought\Canopy\App
for all users or per user respectively. Newer installations are updated by using the built in update tool. See their documentation.Other Python 2.7 Installations On Windows, ActivePython 2.7 cannot coexist with other Python 2.7 installations (for example, a Python 2.7 build from python.org). Uninstall any other Python 2.7 installations before installing ActivePython 2.7.
sage -upgrade
command.Anaconda can be updated by using the conda
command:
conda update --all
Anaconda/Miniconda lets users create environments to manage multiple Python versions including Python-2.6, 2.7, 3.3, 3.4 and 3.5. The root Anaconda/Miniconda installations are currently based on either Python-2.7 or Python-3.5.
Anaconda will likely disrupt any other Python installations. Installation uses MSI installer.
[UPDATE: 2016-05-16] Anaconda and Miniconda now use .exe
installers and provide options to disable Windows PATH
and Registry alterations.
Therefore Anaconda/Miniconda can be installed without disrupting existing Python installations depending on how it was installed and the options that were selected during installation. If the .exe
installer is used and the options to alter Windows PATH
and Registry are not disabled, then any previous Python installations will be disabled, but simply uninstalling the Anaconda/Miniconda installation should restore the original Python installation, except maybe the Windows Registry Python\PythonCore
keys.
Anaconda/Miniconda makes the following registry edits regardless of the installation options: HKCU\Software\Python\ContinuumAnalytics\
with the following keys: Help
, InstallPath
, Modules
and PythonPath
- official Python registers these keys too, but under Python\PythonCore
. Also uninstallation info is registered for Anaconda\Miniconda. Unless you select the "Register with Windows" option during installation, it doesn't create PythonCore
, so integrations like Python Tools for Visual Studio do not automatically see Anaconda/Miniconda. If the option to register Anaconda/Miniconda is enabled, then I think your existing Python Windows Registry keys will be altered and uninstallation will probably not restore them.
App\lib\site-packages
and App\Scripts
could be copied to the new installation, but if this didn't work then reinstalling all packages might have been necessary. Use pip list
to see what packages were installed and their versions. Some were installed by PortablePython. Use easy_install pip
to install pip if it wasn't installed.If OP has 2.7.x and wants to install a different version, e.g. <=2.6.x or >=3.x.x, then installing different versions side-by-side is fine. You must choose which version of Python (if any) to associate with *.py
files and which you want on your path, although you should be able to set up shells with different paths if you use BASH. AFAIK 2.7.x is backwards compatible with 2.6.x, so IMHO side-by-side installs is not necessary, however Python-3.x.x is not backwards compatible, so my recommendation would be to put Python-2.7 on your path and have Python-3 be an optional version by creating a shortcut to its executable called python3 (this is a common setup on Linux). The official Python default install path on Windows is
If OP is not updating Python, but merely updating packages, they may wish to look into virtualenv to keep the different versions of packages specific to their development projects separate. Pip is also a great tool to update packages. If packages use binary installers I usually uninstall the old package before installing the new one.
I hope this clears up any confusion.
The solution is very simple:
1- Copy your git path. forexample : http://github.com/yourname/my-git-project.git
2- Open notepad and Paste it. Then copy the path from notepad.
3- paste the path to command line
thats it.
on CMD
type
ren *.* *.jpg
. will select all files, and rename to * (what ever name they have) plus extension to jpg
Initialize DataTable:
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(String));
dt.Columns.Add("name", typeof(String));
for (int i = 0; i < 5; i++)
{
string index = i.ToString();
dt.Rows.Add(new object[] { index, "name" + index });
}
Query itself:
IList<Class1> items = dt.AsEnumerable().Select(row =>
new Class1
{
id = row.Field<string>("id"),
name = row.Field<string>("name")
}).ToList();
You should not start a container just to see the image contents. For instance, you might want to look for malicious content, not run it. Use "create" instead of "run";
docker create --name="tmp_$$" image:tag
docker export tmp_$$ | tar t
docker rm tmp_$$
Maybe you should try it with -quality 100 -size "1024x1024", because resize often gives results that are ugly to view.
i had a similar issue using enum with switch cases later i resolved it on my own....below is the corrected code, perhaps this might help.
//Menu Chooser Programe using enum
#include<iostream>
using namespace std;
int main()
{
enum level{Novice=1, Easy, Medium, Hard};
level diffLevel=Novice;
int i;
cout<<"\nenter a level: ";
cin>>i;
switch(i)
{
case Novice: cout<<"\nyou picked Novice\n"; break;
case Easy: cout<<"\nyou picked Easy\n"; break;
case Medium: cout<<"\nyou picked Medium\n"; break;
case Hard: cout<<"\nyou picked Hard\n"; break;
default: cout<<"\nwrong input!!!\n"; break;
}
return 0;
}
The change
event not firing on deselection is the desired behaviour. You should run a selector over the entire radio group rather than just the single radio button. And your radio group should have the same name (with different values)
Consider the following code:
$('input[name="job[video_need]"]').on('change', function () {
var value;
if ($(this).val() == 'none') {
value = 'hide';
} else {
value = 'show';
}
$('#video-script-collapse').collapse(value);
});
I have same use case as yours i.e. to show an input box when a particular radio button is selected. If the event was fired on de-selection as well, I would get 2 events each time.
If I understand this correctly, you're trying to make backspace delete both the visible * character on screen and the cached character in your pass variable?
If so, then just change your else block to this:
else
{
Console.Write("\b");
pass = pass.Remove(pass.Length -1);
}
Use:
<nav class="navbar navbar-inverse" role="navigation"></nav>
navbar-inverse {
background-color: #F8F8F8;
border-color: #E7E7E7;
}
The TableModel
behind the JTable handles all of the data behind the table. In order to add and remove rows from a table, you need to use a DefaultTableModel
To create the table with this model:
JTable table = new JTable(new DefaultTableModel(new Object[]{"Column1", "Column2"}));
To add a row:
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[]{"Column 1", "Column 2", "Column 3"});
You can also remove rows with this method.
Full details on the DefaultTableModel can be found here
Will this code work to send email?
Well, no, not without changing some parts since you're getting an error. You are currently trying to send mail via a SMTP server running on localhost but you aren't running any hence the ConnectException
.
Assuming the code is OK (I didn't really check), you'll have to either run a local SMTP server, or to use a (remote) one (from your ISP).
Regarding the code, you can find samples in the JavaMail download package as mentioned in the FAQ:
Where can I find some example programs that show how to use JavaMail?
Q: Where can I find some example programs that show how to use JavaMail?
A: There are many example programs included in the JavaMail download package, including simple command line programs illustrating various aspects of the JavaMail API, a Swing-based GUI application, a simple servlet-based application, and a complete web application using JSP pages and a tag library.
You can simply call it:
SubGraphButton_Click(sender, args);
Now, if your SubGraphButton_Click
does something with the args, you might be in trouble, but usually you don't do anything with them.
Take ownership of it and everything in it.
Mac OS High Sierra or newer: (ty to Kirk in the comments below)
$ sudo chown -R $(whoami) $(brew --prefix)/*
Previous versions of macos:
$ sudo chown -R $USER:admin /usr/local/include
Then do another
$ brew doctor
If you are maintaining old code, you probably cannot aim for "the best possible code ever"... That's one case when, in my opinion, you could lower the error_reporting
level.
These "undefined index" should only be Notices ; so, you could set the error_reporting
level to exclude notices.
One solution is with the error_reporting
function, like this :
// Report all errors except E_NOTICE
error_reporting(E_ALL ^ E_NOTICE);
The good thing with this solution is you can set it to exclude notices only when it's necessary (say, for instance, if there is only one or two files with that kind of code)
One other solution would be to set this in php.ini (might not be such a good idea if you are working on several applications, though, as it could mask useful notices ) ; see error_reporting
in php.ini.
But I insist : this is acceptable only because you are maintaining an old application -- you should not do that when developping new code !
When most people think of functions, they think of named functions:
function foo() { return "This string is returned from the 'foo' function"; }
These are called by name, of course:
foo(); //returns the string above
With lambda expressions, you can have anonymous functions:
@foo = lambda() {return "This is returned from a function without a name";}
With the above example, you can call the lambda through the variable it was assigned to:
foo();
More useful than assigning anonymous functions to variables, however, are passing them to or from higher-order functions, i.e., functions that accept/return other functions. In a lot of these cases, naming a function is unecessary:
function filter(list, predicate)
{ @filteredList = [];
for-each (@x in list) if (predicate(x)) filteredList.add(x);
return filteredList;
}
//filter for even numbers
filter([0,1,2,3,4,5,6], lambda(x) {return (x mod 2 == 0)});
A closure may be a named or anonymous function, but is known as such when it "closes over" variables in the scope where the function is defined, i.e., the closure will still refer to the environment with any outer variables that are used in the closure itself. Here's a named closure:
@x = 0;
function incrementX() { x = x + 1;}
incrementX(); // x now equals 1
That doesn't seem like much but what if this was all in another function and you passed incrementX
to an external function?
function foo()
{ @x = 0;
function incrementX()
{ x = x + 1;
return x;
}
return incrementX;
}
@y = foo(); // y = closure of incrementX over foo.x
y(); //returns 1 (y.x == 0 + 1)
y(); //returns 2 (y.x == 1 + 1)
This is how you get stateful objects in functional programming. Since naming "incrementX" isn't needed, you can use a lambda in this case:
function foo()
{ @x = 0;
return lambda()
{ x = x + 1;
return x;
};
}
Import numpy as np
FOR INDEX
S=[11,2,44,55,66,0,10,3,33]
r=np.argsort(S)
[output]=array([5, 1, 7, 6, 0, 8, 2, 3, 4])
argsort Returns the indices of S in sorted order
FOR VALUE
np.sort(S)
[output]=array([ 0, 2, 3, 10, 11, 33, 44, 55, 66])
I believe, you need to capture this
.
If you just want to kill any/all java processes, then all you need is;
killall java
If, however, you want to kill the wskInterface process in particular, then you're most of the way there, you just need to strip out the process id;
PID=`ps -ef | grep wskInterface | awk '{ print $2 }'`
kill -9 $PID
Should do it, there is probably an easier way though...
Because I had the same problem, I want to stress that actually the first comment by Brian Cain is the solution to the "IOError: [Errno 13]"-problem:
If executed in the temp directory (cd /tmp
), the IOError does not occur anymore if I run sudo pip install foo
.
app.all('*', function(req, res,next) {
/**
* Response settings
* @type {Object}
*/
var responseSettings = {
"AccessControlAllowOrigin": req.headers.origin,
"AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name",
"AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
"AccessControlAllowCredentials": true
};
/**
* Headers
*/
res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
res.header("Access-Control-Allow-Origin", responseSettings.AccessControlAllowOrigin);
res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
});
There have no differences between Integer.toString(5) and String.valueOf(5);
because String.valueOf returns:
public static String valueOf(int i) {
return Integer.toString(i);
}
public static String valueOf(float f) {
return Float.toString(f);
}
etc..
I ended up using the httpclient-4.3.6:
import org.apache.http.client.utils.URIBuilder;
public static void main (String [] args) {
URIBuilder uri = new URIBuilder();
uri.setScheme("http")
.setHost("www.example.com")
.setPath("/somepage.php")
.setParameter("username", "Hello Günter")
.setParameter("p1", "parameter 1");
System.out.println(uri.toString());
}
Output will be:
http://www.example.com/somepage.php?username=Hello+G%C3%BCnter&p1=paramter+1
My understanding is this:
As an alternative to WMI you can get fast accurate results by tapping in to WinSpool.drv (i.e. Windows API) - you can get all the details on the interfaces, structs & constants from pinvoke.net, or I've put the code together at http://delradiesdev.blogspot.com/2012/02/accessing-printer-status-using-winspool.html
There are a number of ways to do this, depending on what you really want. With no common columns, you need to decide whether you want to introduce a common column or get the product.
Let's say you have the two tables:
parts: custs:
+----+----------+ +-----+------+
| id | desc | | id | name |
+----+----------+ +-----+------+
| 1 | Sprocket | | 100 | Bob |
| 2 | Flange | | 101 | Paul |
+----+----------+ +-----+------+
Forget the actual columns since you'd most likely have a customer/order/part relationship in this case; I've just used those columns to illustrate the ways to do it.
A cartesian product will match every row in the first table with every row in the second:
> select * from parts, custs;
id desc id name
-- ---- --- ----
1 Sprocket 101 Bob
1 Sprocket 102 Paul
2 Flange 101 Bob
2 Flange 102 Paul
That's probably not what you want since 1000 parts and 100 customers would result in 100,000 rows with lots of duplicated information.
Alternatively, you can use a union to just output the data, though not side-by-side (you'll need to make sure column types are compatible between the two selects, either by making the table columns compatible or coercing them in the select):
> select id as pid, desc, null as cid, null as name from parts
union
select null as pid, null as desc, id as cid, name from custs;
pid desc cid name
--- ---- --- ----
101 Bob
102 Paul
1 Sprocket
2 Flange
In some databases, you can use a rowid/rownum column or pseudo-column to match records side-by-side, such as:
id desc id name
-- ---- --- ----
1 Sprocket 101 Bob
2 Flange 101 Bob
The code would be something like:
select a.id, a.desc, b.id, b.name
from parts a, custs b
where a.rownum = b.rownum;
It's still like a cartesian product but the where
clause limits how the rows are combined to form the results (so not a cartesian product at all, really).
I haven't tested that SQL for this since it's one of the limitations of my DBMS of choice, and rightly so, I don't believe it's ever needed in a properly thought-out schema. Since SQL doesn't guarantee the order in which it produces data, the matching can change every time you do the query unless you have a specific relationship or order by
clause.
I think the ideal thing to do would be to add a column to both tables specifying what the relationship is. If there's no real relationship, then you probably have no business in trying to put them side-by-side with SQL.
If you just want them displayed side-by-side in a report or on a web page (two examples), the right tool to do that is whatever generates your report or web page, coupled with two independent SQL queries to get the two unrelated tables. For example, a two-column grid in BIRT (or Crystal or Jasper) each with a separate data table, or a HTML two column table (or CSS) each with a separate data table.
Use USE
. This will enable you to select the database.
USE photogallery;
You can also specify the database you want when connecting:
$ mysql -u user -p photogallery
In general you can use pandas rename function here. Given your dataframe you could change to a new name like this. If you had more columns you could also rename those in the dictionary. The 0 is the current name of your column
import pandas as pd
import numpy as np
e = np.random.normal(size=100)
e_dataframe = pd.DataFrame(e)
e_dataframe.rename(index=str, columns={0:'new_column_name'})
I know it's not exactly what you are looking for, but maybe it'll help you.
You can try use a jQuery selector :contains()
, add a class and then do a normal style for a class.
As mscdex said NPM comes with the nodejs msi installed file. I happened to just install the node js installer (standalone). To separately add NPM I followed following step
SQL Server provides a built-in stored procedure that you can run to easily show the size of a table, including the size of the indexes
sp_spaceused ‘Tablename’
Probably not. While I can't log into the Apple Development site, according to this post you need an intel mac platform.
http://tinleyharrier.blogspot.com/2008/03/iphone-sdk-requirements.html
I use this code to remove my data but leave the formulas in the top row. It also removes all rows except for the top row and scrolls the page up to the top.
Sub CleanTheTable()
Application.ScreenUpdating = False
Sheets("Data").Select
ActiveSheet.ListObjects("TestTable").HeaderRowRange.Select
'Remove the filters if one exists.
If ActiveSheet.FilterMode Then
Selection.AutoFilter
End If
'Clear all lines but the first one in the table leaving formulas for the next go round.
With Worksheets("Data").ListObjects("TestTable")
.Range.AutoFilter
On Error Resume Next
.DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
.DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
ActiveWindow.SmallScroll Down:=-10000
End With
Application.ScreenUpdating = True
End Sub
If you are creating an array whose main feature is it's length, rather than the value of each index, defining an array as var a=Array(length);
is appropriate.
eg-
String.prototype.repeat= function(n){
n= n || 1;
return Array(n+1).join(this);
}
Underscore.js makes the transformation pretty clean:
var keys = _.map(x, function(v, k) { return k; });
Edit: I missed that you can do this too:
var keys = _.keys(x);
First, add the Material Design dependency.
implementation 'com.google.android.material:material:<version>'
To get the latest material design library version. check the official website github repository.
Current version is 1.2.0.
So, you have to add,
implementation 'com.google.android.material:material:1.2.0'
Then, you need to change the app theme to material theme by adding,
<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
in your style.xml. Dont forget to set the same theme in your application theme in your manifest file.
if the other div is sibling/child, or any combination of, of the parent yes
.showme{ _x000D_
display: none;_x000D_
}_x000D_
.showhim:hover .showme{_x000D_
display : block;_x000D_
}_x000D_
.showhim:hover .hideme{_x000D_
display : none;_x000D_
}_x000D_
.showhim:hover ~ .hideme2{ _x000D_
display:none;_x000D_
}
_x000D_
<div class="showhim">_x000D_
HOVER ME_x000D_
<div class="showme">hai</div> _x000D_
<div class="hideme">bye</div>_x000D_
</div>_x000D_
<div class="hideme2">bye bye</div>
_x000D_
This is just torazaburo's answer, updated to use a MouseEvent object.
function click(x, y)
{
var ev = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true,
'screenX': x,
'screenY': y
});
var el = document.elementFromPoint(x, y);
el.dispatchEvent(ev);
}
I'm surprised no one suggested Pandas. Although using a set of dependencies like Pandas might seem more heavy-handed than is necessary for such an easy task, it produces a very short script and Pandas is a great library for doing all sorts of CSV (and really all data types) data manipulation. Can't argue with 4 lines of code:
import pandas as pd
csv_input = pd.read_csv('input.csv')
csv_input['Berries'] = csv_input['Name']
csv_input.to_csv('output.csv', index=False)
Check out Pandas Website for more information!
Contents of output.csv
:
Name,Code,Berries
blackberry,1,blackberry
wineberry,2,wineberry
rasberry,1,rasberry
blueberry,1,blueberry
mulberry,2,mulberry
Swift 3.0
With Swift 3, the name of NSJSONSerialization
and its methods have changed, according to the Swift API Design Guidelines.
let dic = ["2": "B", "1": "A", "3": "C"]
do {
let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// here "decoded" is of type `Any`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch {
print(error.localizedDescription)
}
Swift 2.x
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
// here "decoded" is of type `AnyObject`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch let error as NSError {
print(error)
}
Swift 1
var error: NSError?
if let jsonData = NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted, error: &error) {
if error != nil {
println(error)
} else {
// here "jsonData" is the dictionary encoded in JSON data
}
}
if let decoded = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as? [String:String] {
if error != nil {
println(error)
} else {
// here "decoded" is the dictionary decoded from JSON data
}
}
Swift 3 used with UIWebViewDelegate shouldStartLoadWith
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let urlPath: String = (request.url?.absoluteString)!
print(urlPath)
if urlPath.characters.last == "#" {
return false
}else{
return true
}
}
You can embed websites into another website using the <embed>
tag, like so:
<embed src="http://www.example.com" style="width:500px; height: 300px;">
You can change the height, width, and URL to suit your needs.
The <embed>
tag is the most up-to-date way to embed websites, as it was introduced with HTML5.
it is now simply:
let serialQueue = DispatchQueue(label: "my serial queue")
the default is serial, to get concurrent, you use the optional attributes argument .concurrent
Based on your newly-added backstory with the question, why not just return an integer from 1 to 12 for the month, and let the main() function use a switch statement or if-else ladder to decide what to print? It's certainly not the best way to go - char* would be - but in the context of a class like this I imagine it's probably the most elegant.
As programmers we want the quickest, most fool-proof way to get our tools in order so we can start hacking. Here are how I got it to work in MacOS 10.13.1 (High Sierra):
Option 1: Go to System Preferences | Keyboard | Shortcut | Services
.
Under Files and Folders
section, enable New Terminal at Folder
and/or New Terminal Tab at Folder
and assign a shortcut key to it.
Option 2: If you want the shortcut key to work anywhere, create a new Service using Automator, then go to the Keyboard Shortcut to assign a shortcut key to it. Known limitation: not work from the desktop
Notes:
MacOS
, that's not necessary.You can also set a Constraint on a Table with the KEY fields and set On Conflict "Ignore"
When an applicable constraint violation occurs, the IGNORE resolution algorithm skips the one row that contains the constraint violation and continues processing subsequent rows of the SQL statement as if nothing went wrong. Other rows before and after the row that contained the constraint violation are inserted or updated normally. No error is returned when the IGNORE conflict resolution algorithm is used.
>>> a = "123"
>>> int(a)
123
Here's some freebie code:
def getTwoNumbers():
numberA = raw_input("Enter your first number: ")
numberB = raw_input("Enter your second number: ")
return int(numberA), int(numberB)
Create outlets from views that were created in StoryBoard.
@IBOutlet weak var redView: UIView!
@IBOutlet weak var orangeView: UIView!
@IBOutlet weak var greenView: UIView!
Override the touchesBegan method. There are 2 options, everyone can determine which one is better for him.
Detect touch in special view.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
if touch.view == self.redView {
tapOnredViewTapped()
} else if touch.view == self.orangeView {
orangeViewTapped()
} else if touch.view == self.greenView {
greenViewTapped()
} else {
return
}
}
}
Detect touch point on special view.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let location = touch.location(in: view)
if redView.frame.contains(location) {
redViewTapped()
} else if orangeView.frame.contains(location) {
orangeViewTapped()
} else if greenView.frame.contains(location) {
greenViewTapped()
}
}
}
Lastly, you need to declare the functions that will be called, depending on which view the user clicked.
func redViewTapped() {
print("redViewTapped")
}
func orangeViewTapped() {
print("orangeViewTapped")
}
func greenViewTapped() {
print("greenViewTapped")
}
There is a clear figure command, and it should do it for you:
plt.clf()
If you have multiple subplots in the same figure
plt.cla()
clears the current axes.
Put a single listener on the table. When it gets a click from an input with a button that has a name of "edit" and value "edit", change its value to "modify". Get rid of the input's id (they aren't used for anything here), or make them all unique.
<script type="text/javascript">
function handleClick(evt) {
var node = evt.target || evt.srcElement;
if (node.name == 'edit') {
node.value = "Modify";
}
}
</script>
<table id="table1" border="1" onclick="handleClick(event);">
<thead>
<tr>
<th>Select
</thead>
<tbody>
<tr>
<td>
<form name="f1" action="#" >
<input id="edit1" type="submit" name="edit" value="Edit">
</form>
<tr>
<td>
<form name="f2" action="#" >
<input id="edit2" type="submit" name="edit" value="Edit">
</form>
<tr>
<td>
<form name="f3" action="#" >
<input id="edit3" type="submit" name="edit" value="Edit">
</form>
</tbody>
</table>
Id be inclined to create classes that match the structure and add an instance to a collection then serialise and deserialise the collection to load and save the document.
First, let's make some test data:
create table client (client_id integer not null primary key auto_increment,
name varchar(64));
create table portfolio (portfolio_id integer not null primary key auto_increment,
client_id integer references client.id,
cash decimal(10,2),
stocks decimal(10,2));
insert into client (name) values ('John Doe'), ('Jane Doe');
insert into portfolio (client_id, cash, stocks) values (1, 11.11, 22.22),
(1, 10.11, 23.22),
(2, 30.30, 40.40),
(2, 40.40, 50.50);
If you didn't need the portfolio ID, it would be easy:
select client_id, name, max(cash + stocks)
from client join portfolio using (client_id)
group by client_id
+-----------+----------+--------------------+
| client_id | name | max(cash + stocks) |
+-----------+----------+--------------------+
| 1 | John Doe | 33.33 |
| 2 | Jane Doe | 90.90 |
+-----------+----------+--------------------+
Since you need the portfolio ID, things get more complicated. Let's do it in steps. First, we'll write a subquery that returns the maximal portfolio value for each client:
select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id
+-----------+----------+
| client_id | maxtotal |
+-----------+----------+
| 1 | 33.33 |
| 2 | 90.90 |
+-----------+----------+
Then we'll query the portfolio table, but use a join to the previous subquery in order to keep only those portfolios the total value of which is the maximal for the client:
select portfolio_id, cash + stocks from portfolio
join (select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
+--------------+---------------+
| portfolio_id | cash + stocks |
+--------------+---------------+
| 5 | 33.33 |
| 6 | 33.33 |
| 8 | 90.90 |
+--------------+---------------+
Finally, we can join to the client table (as you did) in order to include the name of each client:
select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
+-----------+----------+--------------+---------------+
| client_id | name | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
| 1 | John Doe | 5 | 33.33 |
| 1 | John Doe | 6 | 33.33 |
| 2 | Jane Doe | 8 | 90.90 |
+-----------+----------+--------------+---------------+
Note that this returns two rows for John Doe because he has two portfolios with the exact same total value. To avoid this and pick an arbitrary top portfolio, tag on a GROUP BY clause:
select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
group by client_id, cash + stocks
+-----------+----------+--------------+---------------+
| client_id | name | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
| 1 | John Doe | 5 | 33.33 |
| 2 | Jane Doe | 8 | 90.90 |
+-----------+----------+--------------+---------------+
Also if you want selected field from table and aggregated then as array .
SELECT json_agg(json_build_object('data_a',a,
'data_b',b,
)) from t;
The result will come .
[{'data_a':1,'data_b':'value1'}
{'data_a':2,'data_b':'value2'}]
I would go with 422 Unprocessable Entity
, which is used when a request is invalid but the issue is not in syntax or authentication.
As an argument against other answers, to use any non-4xx
error code would imply it's not a client error, and it obviously is. To use a non-4xx
error code to represent a client error just makes no sense at all.
It seems that 409 Conflict
is the most common answer here, but, according to the spec, that implies that the resource already exists and the new data you are applying to it is incompatible with its current state. If you are sending a POST
request, with, for example, a username that is already taken, it's not actually conflicting with the target resource, as the target resource (the resource you're trying to create) has not yet been posted. It's an error specifically for version control, when there is a conflict between the version of the resource stored and the version of the resource requested. It's very useful for that purpose, for example when the client has cached an old version of the resource and sends a request based on that incorrect version which would no longer be conditionally valid. "In this case, the response representation would likely contain information useful for merging the differences based on the revision history." The request to create another user with that username is just unprocessable, having nothing to do with version control.
For the record, 422 is also the status code GitHub uses when you try to create a repository by a name already in use.
Follow these Steps:
1: Enter:
git reflog show
This will display all the Commit history, you need to select the sha-1 that has the last commit that you want to get back
2: create a branch name with the Sha-1 ID you selected eg: 8c87714
git branch your-branch-name 8c87714
I have tried to make note about these and have collected and written examples from a java perspective.
Putting it here for any java developer who is looking into the same subject.
The other answers didn't work for me. This did:
<div class="span6">
<h2>Document</h2>
</p>
<textarea class="field span12" id="textarea" rows="6" placeholder="Enter a short synopsis"></textarea>
<button class="btn">Upload</button>
</div>
Note the span12
in a div with span6
.
HTML:
<div class="image-holder">
<img src="http://codemancers.com/img/who-we-are-bg.png" />
</div>
CSS:
.image-holder {
display:inline-block;
position: relative;
}
.image-holder:after {
content:'';
top: 0;
left: 0;
z-index: 10;
width: 100%;
height: 100%;
display: block;
position: absolute;
background: blue;
opacity: 0.1;
}
.image-holder:hover:after {
opacity: 0;
}
My preferred method is to use PadRight. Instead of clearing the line first, this clears the remainder of the line after the new text is displayed, saving a step:
Console.CursorTop = 0;
Console.CursorLeft = 0;
Console.Write("Whatever...".PadRight(Console.BufferWidth));
Even though your question says "using javascript", you can use the prefetch
attribute of a link tag to preload any asset. As of this writing (Aug 10, 2016) it isn't supported in Safari, but is pretty much everywhere else:
<link rel="prefetch" href="(url)">
More info on support here: http://caniuse.com/#search=prefetch
Note that IE 9,10 aren't listed in the caniuse
matrix because Microsoft has discontinued support for them.
So if you were really stuck on using javascript, you could use jquery to dynamically add these elements to your page as well ;-)
This was too good of an answer not to post it here. It's from a Gilles, a fellow user from askubuntu:
The clipboard is provided by the X server. It doesn't matter whether the server is headless or not, what matters is that your local graphical session is available to programs running on the remote machine. Thanks to X's network-transparent design, this is possible.
I assume that you're connecting to the remote server with SSH from a machine running Linux. Make sure that X11 forwarding is enabled both in the client configuration and in the server configuration. In the client configuration, you need to have the line
ForwardX11 yes
in~/.ssh/config
to have it on by default, or pass the option-X
to thessh
command just for that session. In the server configuration, you need to have the lineX11Forwarding yes
in/etc/ssh/sshd_config
(it is present by default on Ubuntu).To check whether X11 forwarding is enabled, look at the value of the
DISPLAY
environment variable:echo $DISPLAY
. You should see a value likelocalhost:10
(applications running on the remote machine are told to connect to a display running on the same machine, but that display connection is in fact forwarded by SSH to your client-side display). Note that ifDISPLAY
isn't set, it's no use setting it manually: the environment variable is always set correctly if the forwarding is in place. If you need to diagnose SSH connection issues, pass the option-vvv
tossh
to get a detailed trace of what's happening.If you're connecting through some other means, you may or may not be able to achieve X11 forwarding. If your client is running Windows, PuTTY supports X11 forwarding; you'll have to run an X server on the Windows machine such as Xming.
By Gilles from askubuntu
:.,$d
This will delete all content from current line to end of the file. This is very useful when you're dealing with test vector generation or stripping.
Just to add on to what @Zaph says in the comments.
I have the same problem as you, as to know, the array of String
is not saved. Even though Apple bridges types such as String and NSString, I wasn't able to save an array of [String]
neither of [AnyObject]
.
However an array of [NSString]
works for me.
So your code could look like that :
var key = "keySave"
var array1: [NSString] = [NSString]()
array1.append("value 1")
array1.append("value 2")
//save
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(array1, forKey: key)
defaults.synchronize()
//read
if let testArray : AnyObject? = defaults.objectForKey(key) {
var readArray : [NSString] = testArray! as [NSString]
}
Note that I created an array of NSString and not a dictionary. I didn't check if it works with a dictionary, but probably you will have to define the things as [NSString : NSString]
to have it working.
EDIT
Re-reading your question and your title, you are talking of array of array
. I think that as long as you stay with NSString
, an array of array will work. However, if you think my answer is irrelevant, just let me know in the comments and I will remove it.
You can find the headers option in the Network tab in Developer's console in Chrome:
Also, in my version of Chrome (50.0.2661.102), it gives an extension named LIVE HTTP Headers which gives information about the request headers for all the HTTP requests.
update: added image
[System.Net.Dns]::GetHostByName('remotehost').HostName
Volatile tells the compiler not to optimize anything that has to do with the volatile variable.
There are at least three common reasons to use it, all involving situations where the value of the variable can change without action from the visible code: When you interface with hardware that changes the value itself; when there's another thread running that also uses the variable; or when there's a signal handler that might change the value of the variable.
Let's say you have a little piece of hardware that is mapped into RAM somewhere and that has two addresses: a command port and a data port:
typedef struct
{
int command;
int data;
int isbusy;
} MyHardwareGadget;
Now you want to send some command:
void SendCommand (MyHardwareGadget * gadget, int command, int data)
{
// wait while the gadget is busy:
while (gadget->isbusy)
{
// do nothing here.
}
// set data first:
gadget->data = data;
// writing the command starts the action:
gadget->command = command;
}
Looks easy, but it can fail because the compiler is free to change the order in which data and commands are written. This would cause our little gadget to issue commands with the previous data-value. Also take a look at the wait while busy loop. That one will be optimized out. The compiler will try to be clever, read the value of isbusy just once and then go into an infinite loop. That's not what you want.
The way to get around this is to declare the pointer gadget as volatile. This way the compiler is forced to do what you wrote. It can't remove the memory assignments, it can't cache variables in registers and it can't change the order of assignments either:
This is the correct version:
void SendCommand (volatile MyHardwareGadget * gadget, int command, int data)
{
// wait while the gadget is busy:
while (gadget->isbusy)
{
// do nothing here.
}
// set data first:
gadget->data = data;
// writing the command starts the action:
gadget->command = command;
}
I am building on what Jorge recommended. Goto File->Settings->compiler.
Here you will see a field to add compiler options where you plug in --stacktrace
Got hit by the same issue while accessing SQLServer from IIS. Adding TrustServerCertificate=True didnot help.
Could see a comment in MS docs: Make sure the SQLServer service account has access to the TLS Certificate you are using. (NT Service\MSSQLSERVER)
Open personal store and right click on the certificate -> manage private keys -> Add the SQL service account and give full control.
Restart the SQL service. It worked.
I encountered the same problem in VS2013 Ultimate. My problem was that I was creating a Windows Service and forgot to uninstall it. So the Service was running and VS couldn't access one of the DLLs which caused that the whole test suite wasn't loaded at all.
cut -c1
This is POSIX, and unlike case
actually extracts the first char if you need it for later:
myvar=abc
first_char="$(printf '%s' "$myvar" | cut -c1)"
if [ "$first_char" = a ]; then
echo 'starts with a'
else
echo 'does not start with a'
fi
awk substr
is another POSIX but less efficient alternative:
printf '%s' "$myvar" | awk '{print substr ($0, 0, 1)}'
printf '%s'
is to avoid problems with escape characters: https://stackoverflow.com/a/40423558/895245 e.g.:
myvar='\n'
printf '%s' "$myvar" | cut -c1
outputs \
as expected.
${::}
does not seem to be POSIX.
See also: How to extract the first two characters of a string in shell scripting?
You are missing #
hash character before id selectors, this should work:
$(document).ready(function() {
$("#div2").hide();
$("#preview").click(function() {
$("#div1").hide();
$("#div2").show();
});
});
$('#checkAll').on('change', function(){
if($(this).attr('checked')){
$('input[type=checkbox]').attr('checked',true);
}
else{
$('input[type=checkbox]').removeAttr('checked');
}
});
I ended up having to open up the port that I was using (8081 by default). On Linux, you can do the following
sudo iptables -A INPUT -p tcp --dport 8081 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
sudo iptables -A OUTPUT -p tcp --sport 8081 -m conntrack --ctstate ESTABLISHED -j ACCEPT
You can test to see whether you actually need to do this. Just navigate to your dev server in Chrome on your Android device. If it doesn't respond, then this might be what you need. If it does respond, then this won't help you.
Object.assign()
ECMAScript 2015 (ES6)
This is a new technology, part of the ECMAScript 2015 (ES6) standard. This technology's specification has been finalized, but check the compatibility table for usage and implementation status in various browsers.
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };
var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.