This is implemented in Nexus since Version 3.9.0.
An artifact can be any result of your build process. The important thing is that it doesn't matter on which client it was built it will be tranfered from the workspace back to the master (server) and stored there with a link to the build. The advantage is that it is versionized this way, you only have to setup backup on your master and that all artifacts are accesible via the web interface even if all build clients are offline.
It is possible to define a regular expression as the artifact name. In my case I zipped all the files I wanted to store in one file with a constant name during the build.
I had the exact same problem. Running mvn clean install
instead of mvn clean compile
resolved it.
The difference only occurs when using multi-maven-project since the project dependencies are uploaded to the local repository by using install.
In case you are getting 530 password incorrect
1 more step needed
in file /etc/shells
Add the following line
/bin/false
No need to start, it would automatically executed while you startup your mac terminal / bash. Whenever you do a change, you may need to restart the terminal.
~ is the default path for .bash_profile
Blockquote
Registering providers in a component
Here's a revised HeroesComponent that registers the HeroService in its providers array.
import { Component } from '@angular/core';
import { HeroService } from './hero.service';
@Component({
selector: 'my-heroes',
providers: [HeroService],
template: `
`
})
export class HeroesComponent { }
I used the below, less code
string fileName = "C:\file.docx";
MessageBox.Show(Path.Combine(Path.GetDirectoryName(fileName),Path.GetFileNameWithoutExtension(fileName)));
Output will be
C:\file
>>> () is () True >>> 1 is 1 True >>> (1,) == (1,) True >>> (1,) is (1,) False >>> a = (1,) >>> b = a >>> a is b True
Some objects are singletons, and thus is
with them is equivalent to ==
. Most are not.
Under "Start" enter "environment" in the search field. That will list the option to change the system variables directly in the start menu.
I installed the JDK 32 bit because of that I am getting the errors. After installing JDK 64 bit http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html jdk-8u131-linux-x64.tar.gz(please download the 64 version) and download 64 bit "eclipse-inst-linux64.tar.gz".
try this, the following code solved my problem
table.dataTable tbody th,table.dataTable tbody td
{
white-space: nowrap;
}
for more information pls refer Here.
Swift 2, with availability check:
import MessageUI
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients(["[email protected]"])
mail.setSubject("Bla")
mail.setMessageBody("<b>Blabla</b>", isHTML: true)
presentViewController(mail, animated: true, completion: nil)
} else {
print("Cannot send mail")
// give feedback to the user
}
// MARK: - MFMailComposeViewControllerDelegate
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
switch result.rawValue {
case MFMailComposeResultCancelled.rawValue:
print("Cancelled")
case MFMailComposeResultSaved.rawValue:
print("Saved")
case MFMailComposeResultSent.rawValue:
print("Sent")
case MFMailComposeResultFailed.rawValue:
print("Error: \(error?.localizedDescription)")
default:
break
}
controller.dismissViewControllerAnimated(true, completion: nil)
}
To find "hello" in your_string
if (your_string.indexOf('hello') > -1)
{
alert("hello found inside your_string");
}
For the alpha numeric you can use a regular expression:
My solution is best suited for :
- deleted your mdf file
- want to re-create your db.
In order to recreate your database you need add the connection using Visual Studio.
Step 1 : Go to Server Explorer add new connection( or look for a add db icon).
Step 2 : Change Datasource to Microsoft SQL Server Database File.
Step 3 : add any database name you desire in the Database file name field.(preferably the same name you have in the web.config AttachDbFilename attribute)
Step 4 : click browse and navigate to where you will like it to be located.
Step 5 : in the package manager console run command update-database
Try this background-position: center top;
This will do the trick for you.
You can use strcpy
but remember to end the array with '\0'
char array[20]; char string[100];
array[0]='1'; array[1]='7'; array[2]='8'; array[3]='.'; array[4]='9'; array[5]='\0';
strcpy(string, array);
printf("%s\n", string);
Quite old, yet I stumbled upon the very same issue. Try doing this:
df['col_replaced'] = df['col_with_npnans'].apply(lambda x: None if np.isnan(x) else x)
Found one solution for WIFI (works for Android 4.3, 4.4):
public static URL getFinalURL(URL url) {
try {
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setInstanceFollowRedirects(false);
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
con.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
con.addRequestProperty("Referer", "https://www.google.com/");
con.connect();
//con.getInputStream();
int resCode = con.getResponseCode();
if (resCode == HttpURLConnection.HTTP_SEE_OTHER
|| resCode == HttpURLConnection.HTTP_MOVED_PERM
|| resCode == HttpURLConnection.HTTP_MOVED_TEMP) {
String Location = con.getHeaderField("Location");
if (Location.startsWith("/")) {
Location = url.getProtocol() + "://" + url.getHost() + Location;
}
return getFinalURL(new URL(Location));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return url;
}
To get "User-Agent" and "Referer" by yourself, just go to developer mode of one of your installed browser (E.g. press F12 on Google Chrome). Then go to tab 'Network' and then click on one of the requests. You should see it's details. Just press 'Headers' sub tab (the image below)
for 1D and 2D arrays you can use np.savetxt to print using a specific format string:
>>> import sys
>>> x = numpy.arange(20).reshape((4,5))
>>> numpy.savetxt(sys.stdout, x, '%5.2f')
0.00 1.00 2.00 3.00 4.00
5.00 6.00 7.00 8.00 9.00
10.00 11.00 12.00 13.00 14.00
15.00 16.00 17.00 18.00 19.00
Your options with numpy.set_printoptions or numpy.array2string in v1.3 are pretty clunky and limited (for example no way to suppress scientific notation for large numbers). It looks like this will change with future versions, with numpy.set_printoptions(formatter=..) and numpy.array2string(style=..).
I would like to share a tip that may save you some time.
If you plan to use something like this in your urls.py
file:
url(r'^(?P<username>\w+)/$', views.profile_page,),
Which basically means www.example.com/<username>
. Be sure to place it at the end of your URL entries, because otherwise, it is prone to cause conflicts with the URL entries that follow below, i.e. accessing one of them will give you the nice error: User matching query does not exist.
I've just experienced it myself; hope it helps!
My solution (similar to KyleLanser's answer) (on a Unix box):
strings dumpfile.dmp | grep SCHEMA_LIST
Presuming that you meant
int a=5; int i;
i=++a + ++a + a++;
System.out.println(i);
a=5;
i=a++ + ++a + ++a;
System.out.println(i);
a=5;
a=++a + ++a + a++;
System.out.println(a);
This evaluates to:
i = (6, a is now 6) + (7, a is now 7) + (7, a is now 8)
so i is 6 + 7 + 7 = 20 and so 20 is printed.
i = (5, a is now 6) + (7, a is now 7) + (8, a is now 8)
so i is 5 + 7 + 8 = 20 and so 20 is printed again.
a = (6, a is now 6) + (7, a is now 7) + (7, a is now 8)
and after all of the right hand side is evaluated (including setting a to 8) THEN a is set to 6 + 7 + 7 = 20 and so 20 is printed a final time.
<div ng-class="{'has-error': userForm.mobileno.$error.pattern ,'has-success': userForm.mobileno.$valid}">
<input type="text" name="mobileno" ng-model="mobileno" ng-pattern="/^[7-9][0-9]{9}$/" required>
Here "userForm" is my form name.
Xcode 8.1
Product -> Archive Then export on the right hand side to somewhere on your drive.
I have a ListView
comprised of EditText
views. The scenario says that after editing text in one or more row(s) we should click on a button called "finish". I used onFocusChanged
on the EditText
view inside of listView
but after clicking on finish the data is not being saved. The problem was solved by adding
listView.clearFocus();
inside the onClickListener
for the "finish" button and the data was saved successfully.
I don't know TeamCity so I hope this can work for you.
The best way I've found to do this is with MSDeploy.exe. This is part of the WebDeploy project run by Microsoft. You can download the bits here.
With WebDeploy, you run the command line
msdeploy.exe -verb:sync -source:contentPath=c:\webApp -dest:contentPath=c:\DeployedWebApp
This does the same thing as the VS Publish command, copying only the necessary bits to the deployment folder.
Thank you for this
Here's what I did:
1.Created an Extensions.cs file in a Utils folder.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Web.ProjectName.Utils
{
public class Extensions
{
public static IEnumerable<SelectListItem> GetStatesList()
{
IList<SelectListItem> states = new List<SelectListItem>
{
new SelectListItem() {Text="Alabama", Value="AL"},
new SelectListItem() { Text="Alaska", Value="AK"},
new SelectListItem() { Text="Arizona", Value="AZ"},
new SelectListItem() { Text="Arkansas", Value="AR"},
new SelectListItem() { Text="California", Value="CA"},
new SelectListItem() { Text="Colorado", Value="CO"},
new SelectListItem() { Text="Connecticut", Value="CT"},
new SelectListItem() { Text="District of Columbia", Value="DC"},
new SelectListItem() { Text="Delaware", Value="DE"},
new SelectListItem() { Text="Florida", Value="FL"},
new SelectListItem() { Text="Georgia", Value="GA"},
new SelectListItem() { Text="Hawaii", Value="HI"},
new SelectListItem() { Text="Idaho", Value="ID"},
new SelectListItem() { Text="Illinois", Value="IL"},
new SelectListItem() { Text="Indiana", Value="IN"},
new SelectListItem() { Text="Iowa", Value="IA"},
new SelectListItem() { Text="Kansas", Value="KS"},
new SelectListItem() { Text="Kentucky", Value="KY"},
new SelectListItem() { Text="Louisiana", Value="LA"},
new SelectListItem() { Text="Maine", Value="ME"},
new SelectListItem() { Text="Maryland", Value="MD"},
new SelectListItem() { Text="Massachusetts", Value="MA"},
new SelectListItem() { Text="Michigan", Value="MI"},
new SelectListItem() { Text="Minnesota", Value="MN"},
new SelectListItem() { Text="Mississippi", Value="MS"},
new SelectListItem() { Text="Missouri", Value="MO"},
new SelectListItem() { Text="Montana", Value="MT"},
new SelectListItem() { Text="Nebraska", Value="NE"},
new SelectListItem() { Text="Nevada", Value="NV"},
new SelectListItem() { Text="New Hampshire", Value="NH"},
new SelectListItem() { Text="New Jersey", Value="NJ"},
new SelectListItem() { Text="New Mexico", Value="NM"},
new SelectListItem() { Text="New York", Value="NY"},
new SelectListItem() { Text="North Carolina", Value="NC"},
new SelectListItem() { Text="North Dakota", Value="ND"},
new SelectListItem() { Text="Ohio", Value="OH"},
new SelectListItem() { Text="Oklahoma", Value="OK"},
new SelectListItem() { Text="Oregon", Value="OR"},
new SelectListItem() { Text="Pennsylvania", Value="PA"},
new SelectListItem() { Text="Rhode Island", Value="RI"},
new SelectListItem() { Text="South Carolina", Value="SC"},
new SelectListItem() { Text="South Dakota", Value="SD"},
new SelectListItem() { Text="Tennessee", Value="TN"},
new SelectListItem() { Text="Texas", Value="TX"},
new SelectListItem() { Text="Utah", Value="UT"},
new SelectListItem() { Text="Vermont", Value="VT"},
new SelectListItem() { Text="Virginia", Value="VA"},
new SelectListItem() { Text="Washington", Value="WA"},
new SelectListItem() { Text="West Virginia", Value="WV"},
new SelectListItem() { Text="Wisconsin", Value="WI"},
new SelectListItem() { Text="Wyoming", Value="WY"}
};
return states;
}
}
}
2.In my model, where state will be abbreviated (e.g. "AL", "NY", etc.):
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Web.ProjectName.Models
{
public class ContactForm
{
...
[Required]
[Display(Name = "State")]
[RegularExpression("[A-Z]{2}")]
public string State { get; set; }
...
}
}
2.In my view I referenced it:
@model Web.ProjectName.Models.ContactForm
...
@Html.LabelFor(x => x.State, new { @class = "form-label" })
@Html.DropDownListFor(x => x.State, Web.ProjectName.Utils.Extensions.GetStatesList(), new { @class = "form-control" })
...
Login is depending upon the AMI which you have created. Use left hand side data as a username while doing login.
ubuntu- ubuntu AMIs
ec2-user- Amazon Linux AMI
centos- Centos AMI
debian or root- Debian AMIs6
ec2-user or fedora- Fedora
You can use the trim() method in a Swift String extension I wrote https://bit.ly/JString.
var string = "hello "
var trimmed = string.trim()
println(trimmed)// "hello"
Write a custom template filter:
from django.template.defaulttags import register
...
@register.filter
def get_item(dictionary, key):
return dictionary.get(key)
(I use .get
so that if the key is absent, it returns none. If you do dictionary[key]
it will raise a KeyError
then.)
usage:
{{ mydict|get_item:item.NAME }}
This worked for my GIT version 1.8.4:
I want to add one more answer :
It happens when you try to pass positional parameter with wrong position order along with keyword argument in calling function.
there is difference between parameter and argument
you can read in detail about here Arguments and Parameter in python
def hello(a,b=1, *args):
print(a, b, *args)
hello(1, 2, 3, 4,a=12)
since we have three parameters :
a is positional parameter
b=1 is keyword and default parameter
*args is variable length parameter
so we first assign a as positional parameter , means we have to provide value to positional argument in its position order, here order matter. but we are passing argument 1 at the place of a in calling function and then we are also providing value to a , treating as keyword argument. now a have two values :
one is positional value: a=1
second is keyworded value which is a=12
We have to change hello(1, 2, 3, 4,a=12)
to hello(1, 2, 3, 4,12)
so now a will get only one positional value which is 1 and b will get value 2 and rest of values will get *args (variable length parameter)
if we want that *args should get 2,3,4 and a should get 1 and b should get 12
then we can do like this
def hello(a,*args,b=1):
pass
hello(1, 2, 3, 4,b=12)
Something more :
def hello(a,*c,b=1,**kwargs):
print(b)
print(c)
print(a)
print(kwargs)
hello(1,2,1,2,8,9,c=12)
output :
1
(2, 1, 2, 8, 9)
1
{'c': 12}
You can pass --force-recreate
to docker compose up
, which should use fresh containers.
I think the reasoning behind reusing containers is to preserve any changes during development. Note that Compose does something similar with volumes, which will also persist between container recreation (a recreated container will attach to its predecessor's volumes). This can be helpful, for example, if you have a Redis container used as a cache and you don't want to lose the cache each time you make a small change. At other times it's just confusing.
I don't believe there is any way you can force this from the Compose file.
Arguably it does clash with immutable infrastructure principles. The counter-argument is probably that you don't use Compose in production (yet). Also, I'm not sure I agree that immutable infra is the basic idea of Docker, although it's certainly a good use case/selling point.
This will occur in SQL Server as well if you don't run all of the statements at once. If you are highlighting a set of statements and executing the following:
DECLARE @LoopVar INT
SET @LoopVar = (SELECT COUNT(*) FROM SomeTable)
And then try to highlight another set of statements such as:
PRINT 'LoopVar is: ' + CONVERT(NVARCHAR(255), @LoopVar)
You will receive this error.
In OS X
, Netbeans 8.0
Command + ,
to open the optionsFonts & Colors
tab
The advantage of lists appears if you need to insert items in the middle and don't want to start resizing the array and shifting things around.
You're correct in that this is typically not the case. I've had a few very specific cases like that, but not too many.
You could also use INDEX MATCH
, which is more "powerful" than vlookup. This would give you exactly what you are looking for:
If you wanted just a Date, you can do Date.strptime(invoice.date.to_s, '%s')
where invoice.date
comes in the form of anFixnum
and then converted to a String
.
Swift 4:
The simplest answer, in my case needing to ensure one onboarding tutorial view was portrait-only:
extension myViewController {
//manage rotation for this viewcontroller
override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
}
Eezy-peezy.
No need to explicitly go to the end of line before doing a
, use A
;
Append text at the end of line [count] times
<ESC>GA
Add a vertical align to the CSS content #column-content strong
too:
#column-content strong {
...
vertical-align: middle;
}
Also see your updated example.
=== UPDATE ===
With a span around the other text and another vertical align:
HTML:
... <span>yet another text content that should be centered vertically</span> ...
CSS:
#column-content span {
vertical-align: middle;
}
Also see the next example.
you can use a Scanner to read from input :
Scanner scanner = new Scanner(System.in);
char c = scanner.next().charAt(0); //charAt() method returns the character at the specified index in a string. The index of the first character is 0, the second character is 1, and so on.
I made some modification to @jvd10's solution. The '!important' seems too strong that the container doesn't adapt well when TOC sidebar is displayed. I removed it and added 'min-width' to limit the minimal width.
Here is my .juyputer/custom/custom.css:
/* Make the notebook cells take almost all available width and limit minimal width to 1110px */
.container {
width: 99%;
min-width: 1110px;
}
/* Prevent the edit cell highlight box from getting clipped;
* important so that it also works when cell is in edit mode*/
div.cell.selected {
border-left-width: 1px;
}
You can use IP Webcam, or perhaps use DLNA. For example Samsung devices come with an app called AllShare which can share and access DLNA enabled devices on the network. I think IP Webcam is your best bet, though. You should be able to open the stream it creates using MX Video player or something like that.
This seems to be answered - #include <fstream>
.
The message means :-
incomplete type
- the class has not been defined with a full class. The compiler has seen statements such as class ifstream;
which allow it to understand that a class exists, but does not know how much memory the class takes up.
The forward declaration allows the compiler to make more sense of :-
void BindInput( ifstream & inputChannel );
It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.
The has initializer
seems a bit extraneous, but is saying that the incomplete object is being created.
Here are helper functions which allow to convert digit in char to int and vice versa:
int toInt(char c) {
return c - '0';
}
char toChar(int i) {
return i + '0';
}
In my case, the error occured when I tried to pass a variable which was looking like a bytes-object (b"xxxx") but was actually a string.
You can convert the string to a real bytes object like this:
foo.strip('b"').replace("\\n", "\n").encode()
I also had the same error. In my case reason was I have created a update trigger on a table and under that trigger I am again updating the same table. And when I have removed the update statement from the trigger my problem has been resolved.
I found it. Perl has multi-line comments:
#!/usr/bin/perl
use strict;
use warnings;
=for comment
Example of multiline comment.
Example of multiline comment.
=cut
print "Multi Line Comment Example \n";
method = POST
will work if you 'post' a form to the url /test.
if you type a url in address bar of a browser and hit enter, it's always a GET
request, so you had to specify POST request.
Google for HTTP GET
and HTTP POST
(there are several others like PUT DELETE). They all have their own meaning.
In order to make examples from here work with Python 3.5.2, you can rewrite as follows :
import io
data =io.BytesIO(b"1, 2, 3\n4, 5, 6")
import numpy
numpy.genfromtxt(data, delimiter=",")
The reason for the change may be that the content of a file is in data (bytes) which do not make text until being decoded somehow. genfrombytes
may be a better name than genfromtxt
.
var userPasswordString = new Buffer(baseAuth, 'base64').toString('ascii');
Change this line from your code to this -
var userPasswordString = Buffer.from(baseAuth, 'base64').toString('ascii');
or in my case, I gave the encoding in reverse order
var userPasswordString = Buffer.from(baseAuth, 'utf-8').toString('base64');
There is no draft requirement for JS to use a specific sorting algorthim. As many have mentioned here, Mozilla uses merge sort.However, In Chrome's v8 source code, as of today, it uses QuickSort and InsertionSort, for smaller arrays.
From Lines 807 - 891
var QuickSort = function QuickSort(a, from, to) {
var third_index = 0;
while (true) {
// Insertion sort is faster for short arrays.
if (to - from <= 10) {
InsertionSort(a, from, to);
return;
}
if (to - from > 1000) {
third_index = GetThirdIndex(a, from, to);
} else {
third_index = from + ((to - from) >> 1);
}
// Find a pivot as the median of first, last and middle element.
var v0 = a[from];
var v1 = a[to - 1];
var v2 = a[third_index];
var c01 = comparefn(v0, v1);
if (c01 > 0) {
// v1 < v0, so swap them.
var tmp = v0;
v0 = v1;
v1 = tmp;
} // v0 <= v1.
var c02 = comparefn(v0, v2);
if (c02 >= 0) {
// v2 <= v0 <= v1.
var tmp = v0;
v0 = v2;
v2 = v1;
v1 = tmp;
} else {
// v0 <= v1 && v0 < v2
var c12 = comparefn(v1, v2);
if (c12 > 0) {
// v0 <= v2 < v1
var tmp = v1;
v1 = v2;
v2 = tmp;
}
}
// v0 <= v1 <= v2
a[from] = v0;
a[to - 1] = v2;
var pivot = v1;
var low_end = from + 1; // Upper bound of elements lower than pivot.
var high_start = to - 1; // Lower bound of elements greater than pivot.
a[third_index] = a[low_end];
a[low_end] = pivot;
// From low_end to i are elements equal to pivot.
// From i to high_start are elements that haven't been compared yet.
partition: for (var i = low_end + 1; i < high_start; i++) {
var element = a[i];
var order = comparefn(element, pivot);
if (order < 0) {
a[i] = a[low_end];
a[low_end] = element;
low_end++;
} else if (order > 0) {
do {
high_start--;
if (high_start == i) break partition;
var top_elem = a[high_start];
order = comparefn(top_elem, pivot);
} while (order > 0);
a[i] = a[high_start];
a[high_start] = element;
if (order < 0) {
element = a[i];
a[i] = a[low_end];
a[low_end] = element;
low_end++;
}
}
}
if (to - high_start < low_end - from) {
QuickSort(a, high_start, to);
to = low_end;
} else {
QuickSort(a, from, low_end);
from = high_start;
}
}
};
Update As of 2018 V8 uses TimSort, thanks @celwell. Source
Here's a version where you don't need a human to read a value and type it out themselves.
CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
Another option would be to employ the reusable Function
shared at the end of this answer.
Just adding to the other two answers, for those of us who need to have these Sequence
s created by a non-interactive script, while patching a live-ish DB for instance.
That is, when you don't wanna SELECT
the value manually and type it yourself into a subsequent CREATE
statement.
In short, you can not do:
CREATE SEQUENCE foo_a_seq
START WITH ( SELECT max(a) + 1 FROM foo );
... since the START [WITH]
clause in CREATE SEQUENCE
expects a value, not a subquery.
Note: As a rule of thumb, that applies to all non-CRUD (i.e.: anything other than
INSERT
,SELECT
,UPDATE
,DELETE
) statements in pgSQL AFAIK.
However, setval()
does! Thus, the following is absolutely fine:
SELECT setval('foo_a_seq', max(a)) FROM foo;
If there's no data and you don't (want to) know about it, use coalesce()
to set the default value:
SELECT setval('foo_a_seq', coalesce(max(a), 0)) FROM foo;
-- ^ ^ ^
-- defaults to: 0
However, having the current sequence value set to 0
is clumsy, if not illegal.
Using the three-parameter form of setval
would be more appropriate:
-- vvv
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
-- ^ ^
-- is_called
Setting the optional third parameter of setval
to false
will prevent the next nextval
from advancing the sequence before returning a value, and thus:
the next
nextval
will return exactly the specified value, and sequence advancement commences with the followingnextval
.
— from this entry in the documentation
On an unrelated note, you also can specify the column owning the Sequence
directly with CREATE
, you don't have to alter it later:
CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
In summary:
CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
Function
Alternatively, if you're planning on doing this for multiple columns, you could opt for using an actual Function
.
CREATE OR REPLACE FUNCTION make_into_serial(table_name TEXT, column_name TEXT) RETURNS INTEGER AS $$
DECLARE
start_with INTEGER;
sequence_name TEXT;
BEGIN
sequence_name := table_name || '_' || column_name || '_seq';
EXECUTE 'SELECT coalesce(max(' || column_name || '), 0) + 1 FROM ' || table_name
INTO start_with;
EXECUTE 'CREATE SEQUENCE ' || sequence_name ||
' START WITH ' || start_with ||
' OWNED BY ' || table_name || '.' || column_name;
EXECUTE 'ALTER TABLE ' || table_name || ' ALTER COLUMN ' || column_name ||
' SET DEFAULT nextVal(''' || sequence_name || ''')';
RETURN start_with;
END;
$$ LANGUAGE plpgsql VOLATILE;
Use it like so:
INSERT INTO foo (data) VALUES ('asdf');
-- ERROR: null value in column "a" violates not-null constraint
SELECT make_into_serial('foo', 'a');
INSERT INTO foo (data) VALUES ('asdf');
-- OK: 1 row(s) affected
Window -> Preferences -> JavaScript -> Validator (also per project settings possible)
or
Window -> Preferences -> Validation (disable validations and configure their settings)
Placing code in a using block ensures that the objects are disposed (though not necessarily collected) as soon as control leaves the block.
According to the docs for func (*Client) Do
:
"An error is returned if caused by client policy (such as CheckRedirect), or if there was an HTTP protocol error. A non-2xx response doesn't cause an error.
When err is nil, resp always contains a non-nil resp.Body."
Then looking at this code:
res, err := client.Do(req)
defer res.Body.Close()
if err != nil {
return nil, err
}
I'm guessing that err
is not nil
. You're accessing the .Close()
method on res.Body
before you check for the err
.
The defer
only defers the function call. The field and method are accessed immediately.
So instead, try checking the error immediately.
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
Your problem is that all chapters, whether they're in the appendix or not, default to starting on an odd-numbered page when you're in two-sided layout mode. A few possible solutions:
The simplest solution is to use the openany
option to your document class, which makes chapters start on the next page, irrespective of whether it's an odd or even numbered page. This is supported in the standard book documentclass, eg \documentclass[openany]{book}
. (memoir
also supports using this as a declaration \openany
which can be used in the middle of a document to change the behavior for subsequent pages.)
Another option is to try the \let\cleardoublepage\clearpage
command before your appendices to avoid the behavior.
Or, if you don't care using a two-sided layout, using the option oneside
to your documentclass
(eg \documentclass[oneside]{book}
) will switch to using a one-sided layout.
Spring Data JPA by default looks for an EntityManagerFactory named entityManagerFactory
. Check out this part of the Javadoc of EnableJpaRepositories
or Table 2.1
of the Spring Data JPA documentation.
That means that you either have to rename your emf
bean to entityManagerFactory
or change your Spring configuration to:
<jpa:repositories base-package="your.package" entity-manager-factory-ref="emf" />
(if you are using XML)
or
@EnableJpaRepositories(basePackages="your.package", entityManagerFactoryRef="emf")
(if you are using Java Config)
You can try this... put parameters as :
http://localhost:8080/WebApplication11/webresources/generic/getText?arg1=hello
in your browser...
package newpackage;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.QueryParam;
@Path("generic")
public class GenericResource {
@Context
private UriInfo context;
/**
* Creates a new instance of GenericResource
*/
public GenericResource() {
}
/**
* Retrieves representation of an instance of newpackage.GenericResource
* @return an instance of java.lang.String
*/
@GET
@Produces("text/plain")
@Consumes("text/plain")
@Path("getText/")
public String getText(@QueryParam("arg1")
@DefaultValue("") String arg1) {
return arg1 ; }
@PUT
@Consumes("text/plain")
public void putText(String content) {
}
}
Not sure if this is cheating or not:
window.say = function(a) { alert(a); };
var a = "say('hello')";
var p = /^([^(]*)\('([^']*)'\).*$/; // ["say('hello')","say","hello"]
var fn = window[p.exec(a)[1]]; // get function reference by name
if( typeof(fn) === "function")
fn.apply(null, [p.exec(a)[2]]); // call it with params
In response to: "How to convert Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México)) to dd-MM-yy in Java?", it was marked how duplicate
Try this:
With java.util.Date
, java.text.SimpleDateFormat
, it's a simple solution.
public static void main(String[] args) throws ParseException {
String fecha = "Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México))";
Date f = new Date(fecha);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("-5GMT"));
fecha = sdf.format(f);
System.out.println(fecha);
}
Wow! Mean this that you must learn a different programming language just to send two keys to the keyboard? There are simpler ways for you to achieve the same thing. :-)
The Batch file below is an example that start another program (cmd.exe in this case), send a command to it and then send an Up Arrow key, that cause to recover the last executed command. The Batch file is simple enough to be understand with no problems, so you may modify it to fit your needs.
@if (@CodeSection == @Batch) @then
@echo off
rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"
rem Start the other program in the same Window
start "" /B cmd
%SendKeys% "echo off{ENTER}"
set /P "=Wait and send a command: " < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "echo Hello, world!{ENTER}"
set /P "=Wait and send an Up Arrow key: [" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{UP}"
set /P "=] Wait and send an Enter key:" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{ENTER}"
%SendKeys% "exit{ENTER}"
goto :EOF
@end
// JScript section
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));
For a list of key names for SendKeys, see: http://msdn.microsoft.com/en-us/library/8c6yea83(v=vs.84).aspx
For example:
LEFT ARROW {LEFT}
RIGHT ARROW {RIGHT}
For a further explanation of this solution, see: GnuWin32 openssl s_client conn to WebSphere MQ server not closing at EOF, hangs
Ctrl+K,Ctrl+R opens the Object Browser in Visual Studio 2010. Find what you're looking for by searching and browsing and filtering the results. See also Ctrl+Alt+J. ^K ^R
is better because it puts your caret right in the search box, ready to type your new search, even when the Object Browser is already open.
Set the Browse list on the top left to where you want to look to get started. From there you can use the search box (2nd text box from the top, goes all the way across the Object Browser window) or you can just go through everything from the tree on the left. Searches are temporary but the "selected components" set by the Browse list persists. Set a custom set with the little "..." button just to the right of the list.
Objects, packages, namespaces, types, etc. on the left; fields, methods, constants, etc. on the top right, docstrings on the lower right.
The display mode of a pane can be changed by right-clicking in the empty space of the window; tree organized by assembly/container or by namespace and other preferences.
Items can be right-clicked to find, copy and filter.
For keyboard navigation, use Ctrl+K,Ctrl+R from anywhere to start a new search, Enter to execute the search you just typed or pasted and Ctrl+F6 to make the Object Browser close. ALT+<-- to go back and ALT+--> to go forward through the search history. More can be set; search for "ObjectBrowser" in the keyboard shortcut config.
If the key shortcuts above don't work, Object Browser should be in the View menu somewhere with a different shortcut. If all else fails, search for "ObjectBrowser" under Tools->Options->Environment->Keyboard->"Show commands containing".
Create a test.php file with the following code in a www folder:
<?php echo phpinfo();?>
When you navigate to that page/URL in the browser. You will see something similar if you have openssl enabled:
Note
Mutation events have been deprecated since this post was written, and may not be supported by all browsers. Instead, use a mutation observer.
Yes you can. DOM L2 Events module defines mutation events; one of them - DOMAttrModified is the one you need. Granted, these are not widely implemented, but are supported in at least Gecko and Opera browsers.
Try something along these lines:
document.documentElement.addEventListener('DOMAttrModified', function(e){
if (e.attrName === 'style') {
console.log('prevValue: ' + e.prevValue, 'newValue: ' + e.newValue);
}
}, false);
document.documentElement.style.display = 'block';
You can also try utilizing IE's "propertychange" event as a replacement to DOMAttrModified
. It should allow to detect style
changes reliably.
The Location directive system is
Like you want to forward all request which start /static
and your data present in /var/www/static
So a simple method is separated last folder from full path , that means
Full path : /var/www/static
Last Path : /static
and First path : /var/www
location <lastPath> {
root <FirstPath>;
}
So lets see what you did mistake and what is your solutions
Your Mistake :
location /static {
root /web/test.example.com/static;
}
Your Solutions :
location /static {
root /web/test.example.com;
}
If you are trying to center text on a TableRow in a TableLayout, here is how I achieved this:
<TableRow android:id="@+id/rowName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dip" >
<TextView android:id="@+id/lblSomeLabel"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:layout_width="0dp"
android:layout_weight="100"
android:text="Your Text Here" />
</TableRow>
This answer no longer works, and I cannot come up with anything better then the other answers (see below) listed here. Please review and up-vote them.
Convert.ToInt64("1100.25")
Method signature from MSDN:
public static long ToInt64(
string value
)
Simple Solution Solution Works Given: If your HEAD commit is in sync with remote commit.
The cherry-picked commit will only contain your latest changes, not the old changes. You can now just rename this commit.
In addition to advices from above I was getting error and found solution on following link http://blog.vanmeeuwen-online.nl/2012/12/error-value-2147942523-on-scheduled.html.
Also this can help:
In task scheduler, click on the scheduled job properties, then settings.
In the last listed option: "if the task is already running, the following rule applies:" Select "stop the existing instance" from the drop down list.
I know I'm late to answer this question, but for your issue you could look into the "joystick" package. I designed it for plotting a stream of data from the serial port, but it works for any stream. It also allows for interactive text logging or image plotting (in addition to graph plotting). No need to do your own loops in a separate thread, the package takes care of it, just give the update frequency you wish. Plus the terminal remains available for monitoring commands while plotting. See http://www.github.com/ceyzeriat/joystick/ or https://pypi.python.org/pypi/joystick (use pip install joystick to install)
Just replace np.random.random() by your real data point read from the serial port in the code below:
import joystick as jk
import numpy as np
import time
class test(jk.Joystick):
# initialize the infinite loop decorator
_infinite_loop = jk.deco_infinite_loop()
def _init(self, *args, **kwargs):
"""
Function called at initialization, see the doc
"""
self._t0 = time.time() # initialize time
self.xdata = np.array([self._t0]) # time x-axis
self.ydata = np.array([0.0]) # fake data y-axis
# create a graph frame
self.mygraph = self.add_frame(jk.Graph(name="test", size=(500, 500), pos=(50, 50), fmt="go-", xnpts=10000, xnptsmax=10000, xylim=(None, None, 0, 1)))
@_infinite_loop(wait_time=0.2)
def _generate_data(self): # function looped every 0.2 second to read or produce data
"""
Loop starting with the simulation start, getting data and
pushing it to the graph every 0.2 seconds
"""
# concatenate data on the time x-axis
self.xdata = jk.core.add_datapoint(self.xdata, time.time(), xnptsmax=self.mygraph.xnptsmax)
# concatenate data on the fake data y-axis
self.ydata = jk.core.add_datapoint(self.ydata, np.random.random(), xnptsmax=self.mygraph.xnptsmax)
self.mygraph.set_xydata(t, self.ydata)
t = test()
t.start()
t.stop()
Although it seems the previous solutions would work, if a single anomaly occurs in the document the output would go to pieces. Below is a bit safer.
sed -n '/KEY/{
N
s/\n/ /p
}' somefile.txt
You need to use font-url
in your @font-face block, not url
@font-face {
font-family: 'Inconsolata';
src:font-url('Inconsolata-Regular.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
as well as this line in application.rb, as you mentioned (for fonts in app/assets/fonts
config.assets.paths << Rails.root.join("app", "assets", "fonts")
As stated in the question:
To align flex items along the main axis there is one property:
justify-content
To align flex items along the cross axis there are three properties:
align-content
,align-items
andalign-self
.
The question then asks:
Why are there no
justify-items
andjustify-self
properties?
One answer may be: Because they're not necessary.
The flexbox specification provides two methods for aligning flex items along the main axis:
justify-content
keyword property, andauto
marginsjustify-content
The justify-content
property aligns flex items along the main axis of the flex container.
It is applied to the flex container but only affects flex items.
There are five alignment options:
flex-start
~ Flex items are packed toward the start of the line.
flex-end
~ Flex items are packed toward the end of the line.
center
~ Flex items are packed toward the center of the line.
space-between
~ Flex items are evenly spaced, with the first item aligned to one edge of the container and the last item aligned to the opposite edge. The edges used by the first and last items depends on flex-direction
and writing mode (ltr
or rtl
).
space-around
~ Same as space-between
except with half-size spaces on both ends.
With auto
margins, flex items can be centered, spaced away or packed into sub-groups.
Unlike justify-content
, which is applied to the flex container, auto
margins go on flex items.
They work by consuming all free space in the specified direction.
Scenario from the question:
making a group of flex items align-right (
justify-content: flex-end
) but have the first item align left (justify-self: flex-start
)Consider a header section with a group of nav items and a logo. With
justify-self
the logo could be aligned left while the nav items stay far right, and the whole thing adjusts smoothly ("flexes") to different screen sizes.
Other useful scenarios:
Scenario from the question:
- placing a flex item in a corner
.box { align-self: flex-end; justify-self: flex-end; }
margin: auto
is an alternative to justify-content: center
and align-items: center
.
Instead of this code on the flex container:
.container {
justify-content: center;
align-items: center;
}
You can use this on the flex item:
.box56 {
margin: auto;
}
This alternative is useful when centering a flex item that overflows the container.
A flex container aligns flex items by distributing free space.
Hence, in order to create equal balance, so that a middle item can be centered in the container with a single item alongside, a counterbalance must be introduced.
In the examples below, invisible third flex items (boxes 61 & 68) are introduced to balance out the "real" items (box 63 & 66).
Of course, this method is nothing great in terms of semantics.
Alternatively, you can use a pseudo-element instead of an actual DOM element. Or you can use absolute positioning. All three methods are covered here: Center and bottom-align flex items
NOTE: The examples above will only work – in terms of true centering – when the outermost items are equal height/width. When flex items are different lengths, see next example.
Scenario from the question:
in a row of three flex items, affix the middle item to the center of the container (
justify-content: center
) and align the adjacent items to the container edges (justify-self: flex-start
andjustify-self: flex-end
).Note that values
space-around
andspace-between
onjustify-content
property will not keep the middle item centered in relation to the container if the adjacent items have different widths (see demo).
As noted, unless all flex items are of equal width or height (depending on flex-direction
), the middle item cannot be truly centered. This problem makes a strong case for a justify-self
property (designed to handle the task, of course).
#container {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
background-color: lightyellow;_x000D_
}_x000D_
.box {_x000D_
height: 50px;_x000D_
width: 75px;_x000D_
background-color: springgreen;_x000D_
}_x000D_
.box1 {_x000D_
width: 100px;_x000D_
}_x000D_
.box3 {_x000D_
width: 200px;_x000D_
}_x000D_
#center {_x000D_
text-align: center;_x000D_
margin-bottom: 5px;_x000D_
}_x000D_
#center > span {_x000D_
background-color: aqua;_x000D_
padding: 2px;_x000D_
}
_x000D_
<div id="center">_x000D_
<span>TRUE CENTER</span>_x000D_
</div>_x000D_
_x000D_
<div id="container">_x000D_
<div class="box box1"></div>_x000D_
<div class="box box2"></div>_x000D_
<div class="box box3"></div>_x000D_
</div>_x000D_
_x000D_
<p>The middle box will be truly centered only if adjacent boxes are equal width.</p>
_x000D_
Here are two methods for solving this problem:
Solution #1: Absolute Positioning
The flexbox spec allows for absolute positioning of flex items. This allows for the middle item to be perfectly centered regardless of the size of its siblings.
Just keep in mind that, like all absolutely positioned elements, the items are removed from the document flow. This means they don't take up space in the container and can overlap their siblings.
In the examples below, the middle item is centered with absolute positioning and the outer items remain in-flow. But the same layout can be achieved in reverse fashion: Center the middle item with justify-content: center
and absolutely position the outer items.
Solution #2: Nested Flex Containers (no absolute positioning)
.container {_x000D_
display: flex;_x000D_
}_x000D_
.box {_x000D_
flex: 1;_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
}_x000D_
.box71 > span { margin-right: auto; }_x000D_
.box73 > span { margin-left: auto; }_x000D_
_x000D_
/* non-essential */_x000D_
.box {_x000D_
align-items: center;_x000D_
border: 1px solid #ccc;_x000D_
background-color: lightgreen;_x000D_
height: 40px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box box71"><span>71 short</span></div>_x000D_
<div class="box box72"><span>72 centered</span></div>_x000D_
<div class="box box73"><span>73 loooooooooooooooong</span></div>_x000D_
</div>
_x000D_
Here's how it works:
.container
) is a flex container..box
) is now a flex item..box
item is given flex: 1
in order to distribute container space equally.justify-content: center
.span
element is a centered flex item.auto
margins to shift the outer span
s left and right.You could also forgo justify-content
and use auto
margins exclusively.
But justify-content
can work here because auto
margins always have priority. From the spec:
8.1. Aligning with
auto
marginsPrior to alignment via
justify-content
andalign-self
, any positive free space is distributed to auto margins in that dimension.
justify-content: space-same (concept)
Going back to justify-content
for a minute, here's an idea for one more option.
space-same
~ A hybrid of space-between
and space-around
. Flex items are evenly spaced (like space-between
), except instead of half-size spaces on both ends (like space-around
), there are full-size spaces on both ends.This layout can be achieved with ::before
and ::after
pseudo-elements on the flex container.
(credit: @oriol for the code, and @crl for the label)
UPDATE: Browsers have begun implementing space-evenly
, which accomplishes the above. See this post for details: Equal space between flex items
PLAYGROUND (includes code for all examples above)
String parentPath = f.getPath().substring(0, f.getPath().length() - f.getName().length());
This would be my solution
For me the accepted answer did not yet work. I started off as suggested here:
ln -s /usr/bin/nodejs /usr/bin/node
After doing this I was getting the following error:
/usr/local/lib/node_modules/npm/bin/npm-cli.js:85 let notifier = require('update-notifier')({pkg}) ^^^
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:374:25) at Object.Module._extensions..js (module.js:417:10) at Module.load (module.js:344:32) at Function.Module._load (module.js:301:12) at Function.Module.runMain (module.js:442:10) at startup (node.js:136:18) at node.js:966:3
The solution was to download the most recent version of node from https://nodejs.org/en/download/ .
Then I did:
sudo tar -xf node-v10.15.0-linux-x64.tar.xz --directory /usr/local --strip-components 1
Now the update was finally successful: npm -v
changed from 3.2.1 to 6.4.1
(Meaning if your system: Chrome, Node.js, Firefox, etc supports Ecmascript 2019 or later)
Use the new yourString.matchAll( /your-regex/ )
.
If you have an older system, here's a function for easy copy and pasting
function findAll(regexPattern, sourceString) {
let output = []
let match
// make sure the pattern has the global flag
let regexPatternWithGlobal = RegExp(regexPattern,[...new Set("g"+regexPattern.flags)].join(""))
while (match = regexPatternWithGlobal.exec(sourceString)) {
// get rid of the string copy
delete match.input
// store the match data
output.push(match)
}
return output
}
example usage:
console.log( findAll(/blah/g,'blah1 blah2') )
outputs:
[ [ 'blah', index: 0 ], [ 'blah', index: 6 ] ]
Most universal way is to take value by name. It doesn't matter if its input or select form element type.
var value = $('[name="foo"]');
Why are you combining GET and POST? Use one or the other.
$.ajax({
type: 'post',
data: {
timestamp: timestamp,
uid: uid
...
}
});
php:
$uid =$_POST['uid'];
Or, just format your request properly (you're missing the ampersands for the get parameters).
url:"getdata.php?timestamp="+timestamp+"&uid="+id+"&uname="+name,
Here for commenting we have to write like below:
<!-- Your comment here -->
For Windows & Linux:
Shortcut for Commenting a single line:
Ctrl
+ /
Shortcut for Commenting multiple lines:
Ctrl
+ Shift
+ /
For Mac:
Shortcut for Commenting a single line:
cmnd
+ /
Shortcut for Commenting multiple lines:
cmnd
+ Shift
+ /
One thing you have to keep in mind that, you can't comment an attribute of an XML tag. For Example:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
<!--android:text="Hello.."-->
android:textStyle="bold" />
Here, TextView
is a XML Tag and text
is an attribute of that tag. You can't comment attributes of an XML Tag. You have to comment the full XML Tag. For Example:
<!--<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello.."
android:textStyle="bold" />-->
You can list the tags on remote repository with ls-remote
, and then check if it's there. Supposing the remote reference name is origin
in the following.
git ls-remote --tags origin
And you can list tags local with tag
.
git tag
You can compare the results manually or in script.
Instant.now()
The Answer by Damilola is correct in suggesting you use the java.time framework built into Java 8 and later. But that Answer uses the ZonedDateTime
class which is overkill if you just want UTC rather than any particular time zone.
The troublesome old date-time classes are now legacy, supplanted by the java.time classes.
Instant
The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Simple code:
Instant instant = Instant.now() ;
instant.toString(): 2016-11-29T23:18:14.604Z
You can think of Instant
as the building block to which you can add a time zone (ZoneID
) to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
\S
matches anything but a whitespace, according to this reference.
it doesn't work that way. the work around is to manually check the coordinates of the mouse click against the area occupied by each element.
area occupied by an element can found found by 1. getting the location of the element with respect to the top left of the page, and 2. the width and the height. a library like jQuery makes this pretty simple, although it can be done in plain js. adding an event handler for mousemove
on the document
object will provide continuous updates of the mouse position from the top and left of the page. deciding if the mouse is over any given object consists of checking if the mouse position is between the left, right, top and bottom edges of an element.
<div ng-hide="myvar == null"></div>
or
<div ng-show="myvar != null"></div>
The issue is caused because dataTable must calculate its width - but when used inside a tab, it's not visible, hence can't calculate the widths. The solution is to call 'fnAdjustColumnSizing' when the tab shows.
Preamble
This example shows how DataTables with scrolling can be used together with jQuery UI tabs (or indeed any other method whereby the table is in a hidden (display:none) element when it is initialised). The reason this requires special consideration, is that when DataTables is initialised and it is in a hidden element, the browser doesn't have any measurements with which to give DataTables, and this will require in the misalignment of columns when scrolling is enabled.
The method to get around this is to call the fnAdjustColumnSizing API function. This function will calculate the column widths that are needed based on the current data and then redraw the table - which is exactly what is needed when the table becomes visible for the first time. For this we use the 'show' method provided by jQuery UI tables. We check to see if the DataTable has been created or not (note the extra selector for 'div.dataTables_scrollBody', this is added when the DataTable is initialised). If the table has been initialised, we re-size it. An optimisation could be added to re-size only of the first showing of the table.
Initialisation code
$(document).ready(function() {
$("#tabs").tabs( {
"show": function(event, ui) {
var oTable = $('div.dataTables_scrollBody>table.display', ui.panel).dataTable();
if ( oTable.length > 0 ) {
oTable.fnAdjustColumnSizing();
}
}
} );
$('table.display').dataTable( {
"sScrollY": "200px",
"bScrollCollapse": true,
"bPaginate": false,
"bJQueryUI": true,
"aoColumnDefs": [
{ "sWidth": "10%", "aTargets": [ -1 ] }
]
} );
} );
See this for more info.
I read through all these, but wanted something a bit more elegant. Just to remove a certain number of characters from the end of a string:
string.Concat("hello".Reverse().Skip(3).Reverse());
output:
"he"
First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.
If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
'do something
End If
End If
As per official guidelines and from performance point of view they appear equivalent (ANisus answer), the s != "" would be better due to a syntactical advantage. s != "" will fail at compile time if the variable is not a string, while len(s) == 0 will pass for several other data types.
Using a DispatcherTimer:
var _activeTimer = new DispatcherTimer {
Interval = TimeSpan.FromMinutes(5)
};
_activeTimer.Tick += delegate (object sender, EventArgs e) {
YourMethod();
};
_activeTimer.Start();
We are developing Versile Python (VPy), an implementation for python 2.6+ and 3.x of a new ORB/RPC framework. Functional AGPL dev releases for review and testing are available. VPy has native python capabilities similar to PyRo and RPyC via a general native objects layer (code example). The product is designed for platform-independent remote object interaction for implementations of Versile Platform.
Full disclosure: I work for the company developing VPy.
It turns it into a bytes
literal (or str
in 2.x), and is valid for 2.6+.
The r
prefix causes backslashes to be "uninterpreted" (not ignored, and the difference does matter).
Use @temp tables whenever possible--that is, you only need one primary key and you do not need to access the data from a subordinate stored proc.
Use #temp tables if you need to access the data from a subordinate stored proc (it is an evil global variable to the stored proc call chain) and you have no other clean way to pass the data between stored procs. Also use it if you need a secondary index (although, really ask yourself if it is a #temp table if you need more than one index)
If you do this, always declare your #temp table at the top of the function. SQL will force a recompile of your stored proc when it sees the create table statement....so if you have the #temp table declaration in the middle of the stored proc, you stored proc must stop processing and recompile.
import React, { Component } from 'react';
import { Image, StyleSheet } from 'react-native';
export default class App extends Component {
render() {
return (
<Image source={{uri: 'http://i.imgur.com/IGlBYaC.jpg'}} style={s.backgroundImage} />
);
}
}
const s = StyleSheet.create({
backgroundImage: {
flex: 1,
width: null,
height: null,
}
});
You can try it at: https://sketch.expo.io/B1EAShDie (from: github.com/Dorian/sketch-reactive-native-apps)
Docs: https://facebook.github.io/react-native/docs/images.html#background-image-via-nesting
You just need to do:
#!/bin/bash
count=$(cat last_queries.txt | wc -l)
$(perl test.pl test2 $count)
However, if you want to call your Perl command later, and that's why you want to assign it to a variable, then:
#!/bin/bash
count=$(cat last_queries.txt | wc -l)
var="perl test.pl test2 $count" # You need double quotes to get your $count value substituted.
...stuff...
eval $var
As per Bash's help:
~$ help eval
eval: eval [arg ...]
Execute arguments as a shell command.
Combine ARGs into a single string, use the result as input to the shell,
and execute the resulting commands.
Exit Status:
Returns exit status of command or success if command is null.
As already mentioned, awk is the right tool for this. If you don't want to use awk, instead of parsing output of "ls -l" line by line, you could iterate over all files and do an "ls -l" for each individual file like this:
for x in * ; do echo `ls -ld $x` ; done
Swift 5.3, I believe.
The normal array wasvar myArray = ["Steve", "Bill", "Linus", "Bret"]
and you want to add "Tim"
to the array, then you can use myArray.insert("Tim", at=*index*)
so if you want to add it at the back of the array, then you can use myArray.append("Tim", at: 3)
$('#myCheckbox').change(function () {
if ($(this).prop("checked")) {
// checked
return;
}
// not checked
});
Note: In older versions of jquery it was OK to use attr
. Now it's suggested to use prop
to read the state.
In Xcode Beta 5, they no longer let you do:
var xyz : NSString?
if xyz {
// Do something using `xyz`.
}
This produces an error:
does not conform to protocol 'BooleanType.Protocol'
You have to use one of these forms:
if xyz != nil {
// Do something using `xyz`.
}
if let xy = xyz {
// Do something using `xy`.
}
No, you can't name the tuple members.
The in-between would be to use ExpandoObject instead of Tuple.
No, but you could have something like:
bool b;
b = b.YourExtensionMethod();
fetchTimeout (url,options,timeout=3000) {
return new Promise( (resolve, reject) => {
fetch(url, options)
.then(resolve,reject)
setTimeout(reject,timeout);
})
}
You can easily pass the path of the image to retrieve the base64 string
public static string ImageToBase64(string _imagePath)
{
string _base64String = null;
using (System.Drawing.Image _image = System.Drawing.Image.FromFile(_imagePath))
{
using (MemoryStream _mStream = new MemoryStream())
{
_image.Save(_mStream, _image.RawFormat);
byte[] _imageBytes = _mStream.ToArray();
_base64String = Convert.ToBase64String(_imageBytes);
return "data:image/jpg;base64," + _base64String;
}
}
}
Hope this will help.
You can convert list in string with elements seperated by space and split it based on number/char to be searched..
Will be clean and fast for large list..
>>>L = [2,1,1,2,1,3]
>>>strL = " ".join(str(x) for x in L)
>>>strL
2 1 1 2 1 3
>>>count=len(strL.split(" 1"))-1
>>>count
3
How about just Dir.mkdir('dir') rescue nil
?
Use JSON.stringify(<data>)
.
Change your code: data: sendInfo
to data: JSON.stringify(sendInfo)
.
Hope this can help you.
x
is used to print t pointer argument in hexadecimal.
A typical address when printed using %x
would look like bfffc6e4
and the sane address printed using %p
would be 0xbfffc6e4
Final(?) edit
Answer, wrapped up in a function, with annotated interactive session:
>>> import re
>>> def special_match(strg, search=re.compile(r'[^a-z0-9.]').search):
... return not bool(search(strg))
...
>>> special_match("")
True
>>> special_match("az09.")
True
>>> special_match("az09.\n")
False
# The above test case is to catch out any attempt to use re.match()
# with a `$` instead of `\Z` -- see point (6) below.
>>> special_match("az09.#")
False
>>> special_match("az09.X")
False
>>>
Note: There is a comparison with using re.match() further down in this answer. Further timings show that match() would win with much longer strings; match() seems to have a much larger overhead than search() when the final answer is True; this is puzzling (perhaps it's the cost of returning a MatchObject instead of None) and may warrant further rummaging.
==== Earlier text ====
The [previously] accepted answer could use a few improvements:
(1) Presentation gives the appearance of being the result of an interactive Python session:
reg=re.compile('^[a-z0-9\.]+$')
>>>reg.match('jsdlfjdsf12324..3432jsdflsdf')
True
but match() doesn't return True
(2) For use with match(), the ^
at the start of the pattern is redundant, and appears to be slightly slower than the same pattern without the ^
(3) Should foster the use of raw string automatically unthinkingly for any re pattern
(4) The backslash in front of the dot/period is redundant
(5) Slower than the OP's code!
prompt>rem OP's version -- NOTE: OP used raw string!
prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import
re;reg=re.compile(r'[^a-z0-9\.]')" "not bool(reg.search(t))"
1000000 loops, best of 3: 1.43 usec per loop
prompt>rem OP's version w/o backslash
prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import
re;reg=re.compile(r'[^a-z0-9.]')" "not bool(reg.search(t))"
1000000 loops, best of 3: 1.44 usec per loop
prompt>rem cleaned-up version of accepted answer
prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import
re;reg=re.compile(r'[a-z0-9.]+\Z')" "bool(reg.match(t))"
100000 loops, best of 3: 2.07 usec per loop
prompt>rem accepted answer
prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import
re;reg=re.compile('^[a-z0-9\.]+$')" "bool(reg.match(t))"
100000 loops, best of 3: 2.08 usec per loop
(6) Can produce the wrong answer!!
>>> import re
>>> bool(re.compile('^[a-z0-9\.]+$').match('1234\n'))
True # uh-oh
>>> bool(re.compile('^[a-z0-9\.]+\Z').match('1234\n'))
False
When you add the const
keyword to a method the this
pointer will essentially become a pointer to const
object, and you cannot therefore change any member data. (Unless you use mutable
, more on that later).
The const
keyword is part of the functions signature which means that you can implement two similar methods, one which is called when the object is const
, and one that isn't.
#include <iostream>
class MyClass
{
private:
int counter;
public:
void Foo()
{
std::cout << "Foo" << std::endl;
}
void Foo() const
{
std::cout << "Foo const" << std::endl;
}
};
int main()
{
MyClass cc;
const MyClass& ccc = cc;
cc.Foo();
ccc.Foo();
}
This will output
Foo
Foo const
In the non-const method you can change the instance members, which you cannot do in the const
version. If you change the method declaration in the above example to the code below you will get some errors.
void Foo()
{
counter++; //this works
std::cout << "Foo" << std::endl;
}
void Foo() const
{
counter++; //this will not compile
std::cout << "Foo const" << std::endl;
}
This is not completely true, because you can mark a member as mutable
and a const
method can then change it. It's mostly used for internal counters and stuff. The solution for that would be the below code.
#include <iostream>
class MyClass
{
private:
mutable int counter;
public:
MyClass() : counter(0) {}
void Foo()
{
counter++;
std::cout << "Foo" << std::endl;
}
void Foo() const
{
counter++; // This works because counter is `mutable`
std::cout << "Foo const" << std::endl;
}
int GetInvocations() const
{
return counter;
}
};
int main(void)
{
MyClass cc;
const MyClass& ccc = cc;
cc.Foo();
ccc.Foo();
std::cout << "Foo has been invoked " << ccc.GetInvocations() << " times" << std::endl;
}
which would output
Foo
Foo const
Foo has been invoked 2 times
This can also happen in safari if you try a selector with a missing ], for example
$('select[name="something"')
but interestingly, this same jquery selector with a missing bracket will work in chrome.
I'm late to the game here, but another approach could be:
1) create a branch from the tag ($ git checkout -b [new branch name] [tag name]
)
2) create a pull-request to merge with your new branch into the destination branch
I have JSONObject like this: {"status":[{"Response":"success"}]}
.
If I want to convert the JSONObject value, which is a JSONArray into JSONObject automatically without using any static value, here is the code for that.
JSONArray array=new JSONArray();
JSONObject obj2=new JSONObject();
obj2.put("Response", "success");
array.put(obj2);
JSONObject obj=new JSONObject();
obj.put("status",array);
Converting the JSONArray to JSON Object:
Iterator<String> it=obj.keys();
while(it.hasNext()){
String keys=it.next();
JSONObject innerJson=new JSONObject(obj.toString());
JSONArray innerArray=innerJson.getJSONArray(keys);
for(int i=0;i<innerArray.length();i++){
JSONObject innInnerObj=innerArray.getJSONObject(i);
Iterator<String> InnerIterator=innInnerObj.keys();
while(InnerIterator.hasNext()){
System.out.println("InnInnerObject value is :"+innInnerObj.get(InnerIterator.next()));
}
}
I can't be satisfied by the answers calling for a English-only solution based on manual formats. I've been looking for a proper solution for a while now and I finally found it.
You should be using RuleBasedNumberFormat. It works perfectly and it's respectful of the Locale.
For the benefit of searchers, there is another way you can produce this error message - by missing the $ off the script block name when calling it.
e.g. I had a script block like so:
$qa = {
param($question, $answer)
Write-Host "Question = $question, Answer = $answer"
}
I tried calling it using:
&qa -question "Do you like powershell?" -answer "Yes!"
But that errored. The correct way was:
&$qa -question "Do you like powershell?" -answer "Yes!"
To get rid of the if/else awkwardness you could use a using block:
@{
var count = 0;
foreach (var item in Model)
{
using(Html.TableRow(new { @class = (count++ % 2 == 0) ? "alt-row" : "" }))
{
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.Truncate(item.Details, 75)
</td>
<td>
<img src="@Url.Content("~/Content/Images/Projects/")@item.Images.Where(i => i.IsMain == true).Select(i => i.Name).Single()"
alt="@item.Images.Where(i => i.IsMain == true).Select(i => i.AltText).Single()" class="thumb" />
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ProjectId }) |
@Html.ActionLink("Details", "Details", new { id = item.ProjectId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ProjectId })
</td>
}
}
}
Reusable element that make it easier to add attributes:
//Block is take from http://www.codeducky.org/razor-trick-using-block/
public class TableRow : Block
{
private object _htmlAttributes;
private TagBuilder _tr;
public TableRow(HtmlHelper htmlHelper, object htmlAttributes) : base(htmlHelper)
{
_htmlAttributes = htmlAttributes;
}
public override void BeginBlock()
{
_tr = new TagBuilder("tr");
_tr.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(_htmlAttributes));
this.HtmlHelper.ViewContext.Writer.Write(_tr.ToString(TagRenderMode.StartTag));
}
protected override void EndBlock()
{
this.HtmlHelper.ViewContext.Writer.Write(_tr.ToString(TagRenderMode.EndTag));
}
}
Helper method to make razor syntax clearer:
public static TableRow TableRow(this HtmlHelper self, object htmlAttributes)
{
var tableRow = new TableRow(self, htmlAttributes);
tableRow.BeginBlock();
return tableRow;
}
It's showing asterisk server is not running.
You may type following commands at cli:
asterisk
asterisk -rvvvv
above commands worked for me!
first command starts asterisk
second command gets you to asterisk cli
css href link is incorrect. Use relative path instead:
<link href="../css/loginstyle.css" rel="stylesheet" type="text/css">
private makes the class accessible only to the class in which it is declared. If we make entire class private no one from outside can access the class and makes it useless.
Inner class can be made private because the outer class can access inner class where as it is not the case with if you make outer class private.
matrix = {}
You can define keys and values in two ways:
matrix[0,0] = value
or
matrix = { (0,0) : value }
Result:
[ value, value, value, value, value],
[ value, value, value, value, value],
...
Use vscode-solution-explorer
extension:
This extension adds a Visual Studio Solution File explorer panel in Visual Studio Code. Now you can navigate into your solution following the original Visual Studio structure.
https://github.com/fernandoescolar/vscode-solution-explorer
Thanks @fernandoescolar
There is no such font as “Calibri (Body)”. You probably saw this string in Microsoft Word font selection menu, but it’s not a font name (see e.g. the explanation Font: +body (in W07)).
So use just font-family: Calibri
or, better, font-family: Calibri, sans-serif
. (There is no adequate backup font for Calibri, but the odds are that when Calibri is not available, the browser’s default sans-serif font suits your design better than the browser’s default font, which is most often a serif font.)
You may have a try for https://github.com/cls1991/pef. It will remove package with its all dependencies.
Edit /var/lib/logrotate.status (or /var/lib/loglogrotate/logrotate.status) to reset the 'last rotated' date on the log file you want to test.
Then run logrotate YOUR_CONFIG_FILE
.
Or you can use the --force flag, but editing logrotate.status gives you more precision over what does and doesn't get rotated.
This answer is a complement to @shawalli's answer...
I wanted to reference an image within my jar too, but instead of having a BufferedImage, I simple did this:
JPanel jPanel = new JPanel();
jPanel.add(new JLabel(new ImageIcon(getClass().getClassLoader().getResource("resource/images/polygon.jpg"))));
Based on your question, I think that you may be a bit confused about the difference between a User and a Login. A Login is an account on the SQL Server as a whole - someone who is able to log in to the server and who has a password. A User is a Login with access to a specific database.
Creating a Login is easy and must (obviously) be done before creating a User account for the login in a specific database:
CREATE LOGIN NewAdminName WITH PASSWORD = 'ABCD'
GO
Here is how you create a User with db_owner privileges using the Login you just declared:
Use YourDatabase;
GO
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'NewAdminName')
BEGIN
CREATE USER [NewAdminName] FOR LOGIN [NewAdminName]
EXEC sp_addrolemember N'db_owner', N'NewAdminName'
END;
GO
Now, Logins are a bit more fluid than I make it seem above. For example, a Login account is automatically created (in most SQL Server installations) for the Windows Administrator account when the database is installed. In most situations, I just use that when I am administering a database (it has all privileges).
However, if you are going to be accessing the SQL Server from an application, then you will want to set the server up for "Mixed Mode" (both Windows and SQL logins) and create a Login as shown above. You'll then "GRANT" priviliges to that SQL Login based on what is needed for your app. See here for more information.
UPDATE: Aaron points out the use of the sp_addsrvrolemember to assign a prepared role to your login account. This is a good idea - faster and easier than manually granting privileges. If you google it you'll see plenty of links. However, you must still understand the distinction between a login and a user.
I had the same problem, thanks to @Jacob for giving information about it.
The Reason is - wrong entry for your project in config file applicationhost located at
C:\Users\(yourusername)\Documents\IISExpress\config
It worked for me and hope it should work for you also.
If it's in the same class with the equal number of parameters with the same types and order, then it is not possible for example:
int methoda(String a,int b) {
return b;
}
String methoda(String b,int c) {
return b;
}
if the number of parameters and their types is same but order is different then it is possible since it results in method overloading. It means if the method signature is same which includes method name with number of parameters and their types and the order they are defined.
It often ends up being easier to load your data into the database, even if it is only to run a quick query. Hard-coded data seems quick to enter, but it quickly becomes a pain if you start having to make changes.
However, if you want to code the names directly into your query, here is a cleaner way to do it:
with names (fname,lname) as (
values
('John','Smith'),
('Mary','Jones')
)
select city from user
inner join names on
fname=firstName and
lname=lastName;
The advantage of this is that it separates your data out of the query somewhat.
(This is DB2 syntax; it may need a bit of tweaking on your system).
If you are looking for a way to import all your images from the image
// Import all images in image folder
function importAll(r) {
let images = {};
r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
return images;
}
const images = importAll(require.context('../images', false, /\.(gif|jpe?g|svg)$/));
Then:
<img src={images['image-01.jpg']}/>
You can find the original thread here: Dynamically import images from a directory using webpack
This does not need jquery, you could set a variable inside the if and use it in html or pass it thru your template system if any
<?php
$showDivFlag=false
$query3 = mysql_query($query3);
$numrows = mysql_num_rows($query3);
if ($numrows > 0){
$fvisit = mysql_fetch_array($result3);
$showDivFlag=true;
}else {
}
?>
later in html
<div id="results" <?php if ($showDivFlag===false){?>style="display:none"<?php } ?>>
Simple code to send email with attachement.
source: http://www.coding-issues.com/2012/11/sending-email-with-attachments-from-c.html
using System.Net;
using System.Net.Mail;
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your [email protected]");
mail.To.Add("[email protected]");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("your [email protected]", "your password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
Dropping the table was not an option for me, since I'm keeping a running log. If every time I needed to insert I had to drop, the table would be meaningless.
My error was because I had a couple columns in the create table statement that were products of other columns, changing these fixed my problem. eg
create table foo (
field1 as int
,field2 as int
,field12 as field1 + field2 )
create table copyOfFoo (
field1 as int
,field2 as int
,field12 as field1 + field2) --this is the problem, should just be 'as int'
insert into copyOfFoo
SELECT * FROM foo
I did not find the -q1
option on my netcat. Instead I used the -w1
option. Below is the bash script I did to send an udp packet to any host and port:
#!/bin/bash
def_host=localhost
def_port=43211
HOST=${2:-$def_host}
PORT=${3:-$def_port}
echo -n "$1" | nc -4u -w1 $HOST $PORT
This is from a comment on the jQuery documentation page:
In older, pre-HTML5 browsers, "keyup" is definitely what you're looking for.
In HTML5 there is a new event, "input", which behaves exactly like you seem to think "change" should have behaved - in that it fires as soon as a key is pressed to enter information into a form.
$('element').bind('input',function);
Hey there's a useful tutorial on Dot Net pearls: http://www.dotnetperls.com/progressbar
In agreement with Peter, you need to use some amount of threading or the program will just hang, somewhat defeating the purpose.
Example that uses ProgressBar and BackgroundWorker: C#
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, System.EventArgs e)
{
// Start the BackgroundWorker.
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
// Wait 100 milliseconds.
Thread.Sleep(100);
// Report progress.
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Change the value of the ProgressBar to the BackgroundWorker progress.
progressBar1.Value = e.ProgressPercentage;
// Set the text.
this.Text = e.ProgressPercentage.ToString();
}
}
} //closing here
Note that a select list is posted as null, hence your error complains that the viewdata property cannot be found.
Always reinitialize your select list within a POST action.
For further explanation: Persist SelectList in model on Post
Here is an example of callbacks in C.
Let's say you want to write some code that allows registering callbacks to be called when some event occurs.
First define the type of function used for the callback:
typedef void (*event_cb_t)(const struct event *evt, void *userdata);
Now, define a function that is used to register a callback:
int event_cb_register(event_cb_t cb, void *userdata);
This is what code would look like that registers a callback:
static void my_event_cb(const struct event *evt, void *data)
{
/* do stuff and things with the event */
}
...
event_cb_register(my_event_cb, &my_custom_data);
...
In the internals of the event dispatcher, the callback may be stored in a struct that looks something like this:
struct event_cb {
event_cb_t cb;
void *data;
};
This is what the code looks like that executes a callback.
struct event_cb *callback;
...
/* Get the event_cb that you want to execute */
callback->cb(event, callback->data);
PYTHONPATH
is an environment variable those content is added to the sys.path
where Python looks for modules. You can set it to whatever you like.
However, do not mess with PYTHONPATH
. More often than not, you are doing it wrong and it will only bring you trouble in the long run. For example, virtual environments could do strange things…
I would suggest you learned how to package a Python module properly, maybe using this easy setup. If you are especially lazy, you could use cookiecutter to do all the hard work for you.
In case it helps somebody else, I got this error message after accidentally deleting .git/objects/
fatal: Not a git repository (or any of the parent directories): .git
Restoring it solved the problem.
Turns out I don't have enough reputation to put this as a comment, which would be a more appropriate place for this:
Re. AllBlackt's answer, if you prefer Ansible's multiline format you need to adjust the quoting for state
(I spent a few minutes working this out, so hopefully this speeds someone else up),
- stat:
path: "/etc/nologin"
register: p
- name: create fake 'nologin' shell
file:
path: "/etc/nologin"
owner: root
group: sys
mode: 0555
state: '{{ "file" if p.stat.exists else "touch" }}'
You cannot start a container from a Dockerfile.
The process goes like this:
Dockerfile =[
docker build
]=> Docker image =[docker run
]=> Docker container
To start (or run) a container you need an image. To create an image you need to build the Dockerfile[1].
[1]: you can also docker import
an image from a tarball or again docker load
.
std::wstring text = L"??????";
QString qstr = QString::fromStdWString(text);
QByteArray byteArray(qstr.toUtf8());
std::string str_std( byteArray.constData(), byteArray.length());
Some closure should deal with this;
var foo = function() {
var a = 5;
var b = 6;
var c = a + b;
return {
a: a,
b: b,
c: c
}
}();
All the variables declared within foo
are private to foo
, as you would expect with any function declaration and because they are all in scope, they all have access to each other without needing to refer to this
, just as you would expect with a function. The difference is that this function returns an object that exposes the private variables and assigns that object to foo
. In the end, you return just the interface you want to expose as an object with the return {}
statement.
The function is then executed at the end with the ()
which causes the entire foo object to be evaluated, all the variables within instantiated and the return object added as properties of foo()
.
I think that the difference is to insert html tag
in text()
you html tag do not functions
$('#output').html('You are registered'+'<br>' +' '
+ 'Mister'+' ' + name+' ' + sourname ); }
output :
You are registered <br> Mister name sourname
replacing text()
with html()
output
You are registered
Mister name sourname
then the tag <br>
works in html()
Adding another way of doing it exactly what the OP asked for, without using latest inbuilt methods:
public static String getDay(String inputDate) {
String dayOfWeek = null;
String[] days = new String[]{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
try {
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
Date dt1 = format1.parse(inputDate);
dayOfWeek = days[dt1.getDay() - 1];
} catch(Exception e) {
System.out.println(e);
}
return dayOfWeek;
}
No doubt that NLTK is the most suitable for the purpose. But getting started with NLTK is quite painful (But once you install it - you just reap the rewards)
So here is simple re based code available at http://pythonicprose.blogspot.com/2009/09/python-split-paragraph-into-sentences.html
# split up a paragraph into sentences
# using regular expressions
def splitParagraphIntoSentences(paragraph):
''' break a paragraph into sentences
and return a list '''
import re
# to split by multile characters
# regular expressions are easiest (and fastest)
sentenceEnders = re.compile('[.!?]')
sentenceList = sentenceEnders.split(paragraph)
return sentenceList
if __name__ == '__main__':
p = """This is a sentence. This is an excited sentence! And do you think this is a question?"""
sentences = splitParagraphIntoSentences(p)
for s in sentences:
print s.strip()
#output:
# This is a sentence
# This is an excited sentence
# And do you think this is a question
A sort of block comment uses an if statement:
if(FALSE) {
all your code
}
It works, but I almost always use the block comment options of my editors (RStudio, Kate, Kwrite).
Actually every object in javascript resolves to true if it has "a real value" as W3Cschools puts it. That means everything except ""
, NaN
, undefined
, null
or 0
.
Testing a number against a boolean with the ==
operator indeed is a tad weird, since the boolean gets converted into numerical 1 before comparing, which defies a little bit the logic behind the definition.
This gets even more confusing when you do something like this:
var fred = !!3; // will set fred to true _x000D_
var joe = !!0; // will set joe to false_x000D_
alert("fred = "+ fred + ", joe = "+ joe);
_x000D_
not everything in javascript makes a lot of sense ;)
Sure, the syntax is exactly the same as C - NewObj* pNew = (NewObj*)oldObj;
In this situation you may wish to consider supplying this list as a parameter to the constructor, something like:
// SelectionListViewController
-(id) initWith:(SomeListClass*)anItemList
{
self = [super init];
if ( self ) {
[self setList: anItemList];
}
return self;
}
Then use it like this:
myEditController = [[SelectionListViewController alloc] initWith: listOfItems];
A simpler approach would be:
Hope this helps!
Aggregation and composition are terms that most people in the OO world have acquired via UML. And UML does a very poor job at defining these terms, as has been demonstrated by, for example, Henderson-Sellers and Barbier ("What is This Thing Called Aggregation?", "Formalization of the Whole-Part Relationship in the Unified Modeling Language"). I don't think that a coherent definition of aggregation and composition can be given if you are interested in being UML-compliant. I suggest you look at the cited works.
Regarding dependency, that's a highly abstract relationship between types (not objects) that can mean almost anything.
You could try this
box-shadow:
progid:DXImageTransform.Microsoft.dropshadow(OffX=0, OffY=10, Color='#19000000'),
progid:DXImageTransform.Microsoft.dropshadow(OffX=10, OffY=20, Color='#19000000'),
progid:DXImageTransform.Microsoft.dropshadow(OffX=20, OffY=30, Color='#19000000'),
progid:DXImageTransform.Microsoft.dropshadow(OffX=30, OffY=40, Color='#19000000');
For a more robust solution i use something like the following. That way the temp dir will always be deleted after the script exits.
The cleanup function is executed on the EXIT
signal. That guarantees that the cleanup function is always called, even if the script aborts somewhere.
#!/bin/bash
# the directory of the script
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# the temp directory used, within $DIR
# omit the -p parameter to create a temporal directory in the default location
WORK_DIR=`mktemp -d -p "$DIR"`
# check if tmp dir was created
if [[ ! "$WORK_DIR" || ! -d "$WORK_DIR" ]]; then
echo "Could not create temp dir"
exit 1
fi
# deletes the temp directory
function cleanup {
rm -rf "$WORK_DIR"
echo "Deleted temp working directory $WORK_DIR"
}
# register the cleanup function to be called on the EXIT signal
trap cleanup EXIT
# implementation of script starts here
...
Directory of bash script from here.
Bash traps.
Easiest way for me is using Android Device Monitor to get the database file and SQLite DataBase Browser to view the file while still using Android Studio to program android.
1) Run and launch database app with Android emulator from Android Studio. (I inserted some data to database app to verify)
2) Run Android Device Monitor. How to run?; Go to [your_folder] > sdk >tools
. You can see monitor.bat in that folder. shift + right click
inside the folder and select "Open command window here
". This action will launch command prompt. type monitor
and Android Device Monitor will be launched.
3) Select the emulator that you are currently running. Then Go to data>data>[your_app_name]>databases
4) Click on the icon (located at top right corner) (hover on the icon and you will see "pull a file from the device") and save anywhere you like
5) Launch SQLite DataBase Browser. Drag and drop the file that you just saved into that Browser.
6) Go to Browse Data
tab and select your table to view.
i tried it worked tnx @Anastasiosyal i want to share it on this thread.
I'm not positive how the input fields did not trigger when I emptied the fields. But I managed to trigger each required field individually using:
$(".setting-p input").bind("change", function () {
//Seven.NetOps.validateSettings(Seven.NetOps.saveSettings);
/*$.validator.unobtrusive.parse($('#saveForm'));*/
$('#NodeZoomLevel').valid();
$('#ZoomLevel').valid();
$('#CenterLatitude').valid();
$('#CenterLongitude').valid();
$('#NodeIconSize').valid();
$('#SaveDashboard').valid();
$('#AutoRefresh').valid();
});
here's my view
@using (Html.BeginForm("SaveSettings", "Settings", FormMethod.Post, new {id = "saveForm"}))
{
<div id="sevenRightBody">
<div id="mapMenuitemPanel" class="setingsPanelStyle" style="display: block;">
<div class="defaultpanelTitleStyle">Map Settings</div>
Customize the map view upon initial navigation to the map view page.
<p class="setting-p">@Html.LabelFor(x => x.NodeZoomLevel)</p>
<p class="setting-p">@Html.EditorFor(x => x.NodeZoomLevel) @Html.ValidationMessageFor(x => x.NodeZoomLevel)</p>
<p class="setting-p">@Html.LabelFor(x => x.ZoomLevel)</p>
<p class="setting-p">@Html.EditorFor(x => x.ZoomLevel) @Html.ValidationMessageFor(x => x.ZoomLevel)</p>
<p class="setting-p">@Html.LabelFor(x => x.CenterLatitude)</p>
<p class="setting-p">@Html.EditorFor(x => x.CenterLatitude) @Html.ValidationMessageFor(x => x.CenterLatitude)</p>
<p class="setting-p">@Html.LabelFor(x => x.CenterLongitude)</p>
<p class="setting-p">@Html.EditorFor(x => x.CenterLongitude) @Html.ValidationMessageFor(x => x.CenterLongitude)</p>
<p class="setting-p">@Html.LabelFor(x => x.NodeIconSize)</p>
<p class="setting-p">@Html.SliderSelectFor(x => x.NodeIconSize) @Html.ValidationMessageFor(x => x.NodeIconSize)</p>
</div>
and my Entity
public class UserSetting : IEquatable<UserSetting>
{
[Required(ErrorMessage = "Missing Node Zoom Level.")]
[Range(200, 10000000, ErrorMessage = "Node Zoom Level must be between {1} and {2}.")]
[DefaultValue(100000)]
[Display(Name = "Node Zoom Level")]
public double NodeZoomLevel { get; set; }
[Required(ErrorMessage = "Missing Zoom Level.")]
[Range(200, 10000000, ErrorMessage = "Zoom Level must be between {1} and {2}.")]
[DefaultValue(1000000)]
[Display(Name = "Zoom Level")]
public double ZoomLevel { get; set; }
[Range(-90, 90, ErrorMessage = "Latitude degrees must be between {1} and {2}.")]
[Required(ErrorMessage = "Missing Latitude.")]
[DefaultValue(-200)]
[Display(Name = "Latitude")]
public double CenterLatitude { get; set; }
[Range(-180, 180, ErrorMessage = "Longitude degrees must be between {1} and {2}.")]
[Required(ErrorMessage = "Missing Longitude.")]
[DefaultValue(-200)]
[Display(Name = "Longitude")]
public double CenterLongitude { get; set; }
[Display(Name = "Save Dashboard")]
public bool SaveDashboard { get; set; }
.....
}
Yes, you need to write it like your second line. Java doesn't have the python style syntactic sugar of your first line.
Alternatively you could put your valid values into an array and check for the existence of symbol
in the array.
My issue turned out to be embarrassingly simple:
Restart command prompt and the new variables should update
The short answer is:
One thing to keep in mind is that the relevant path here is the path relative to the file system location of your class... in your case TestGameTable.class. It is not related to the location of the TestGameTable.java file.
I left a more detailed answer here... where is resource actually located
This can be caused by SELinux. If you don't want to disable SELinux completely, you need to set the db directory fcontext to httpd_sys_rw_content_t.
semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/railsapp/db(/.*)?"
restorecon -v /var/www/railsapp/db
If I understand you correctly, you should be able to do something along the lines of the following:
function clicked() {
var someVariable="<?php echo $phpVariable; ?>";
}
Your activity must have
public void insertIntoDb(View v) {
...
}
not Fragment .
If you don't want the above in activity. initialize button in fragment and set listener to the same.
<Button
android:id="@+id/btn_conferma" // + missing
Then
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_rssitem_detail,
container, false);
Button button = (Button) view.findViewById(R.id.btn_conferma);
button.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// do something
}
});
return view;
}
If you want to prevent the user from enter non-numeric values at the time of enter the information in the TextBox, you can use the Event OnKeyPress like this:
private void txtAditionalBatch_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar)) e.Handled = true; //Just Digits
if (e.KeyChar == (char)8) e.Handled = false; //Allow Backspace
if (e.KeyChar == (char)13) btnSearch_Click(sender, e); //Allow Enter
}
This solution doesn't work if the user paste the information in the TextBox using the mouse (right click / paste) in that case you should add an extra validation.
JSON
JSON (JavaScript Object Notation) is a convenient way to transport data between applications, especially when the destination is a JavaScript application.
Example:
Here is a minimal example that uses JSON as the transport for the server response. The client makes an Ajax request with the jQuery shorthand function $.getJSON. The server generates a hash, formats it as JSON and returns this to the client. The client formats this and puts it in a page element.
Server:
get '/json' do
content_type :json
content = { :response => 'Sent via JSON',
:timestamp => Time.now,
:random => rand(10000) }
content.to_json
end
Client:
var url = host_prefix + '/json';
$.getJSON(url, function(json){
$("#json-response").html(JSON.stringify(json, null, 2));
});
Output:
{
"response": "Sent via JSON",
"timestamp": "2014-06-18 09:49:01 +0000",
"random": 6074
}
JSONP (JSON with Padding)
JSONP is a simple way to overcome browser restrictions when sending JSON responses from different domains from the client.
The only change on the client side with JSONP is to add a callback parameter to the URL
Server:
get '/jsonp' do
callback = params['callback']
content_type :js
content = { :response => 'Sent via JSONP',
:timestamp => Time.now,
:random => rand(10000) }
"#{callback}(#{content.to_json})"
end
Client:
var url = host_prefix + '/jsonp?callback=?';
$.getJSON(url, function(jsonp){
$("#jsonp-response").html(JSON.stringify(jsonp, null, 2));
});
Output:
{
"response": "Sent via JSONP",
"timestamp": "2014-06-18 09:50:15 +0000",
"random": 364
}
A CRLF is two characters, of course, the CR and the LF. However, `n
consists of both. For example:
PS C:\> $x = "Hello
>> World"
PS C:\> $x
Hello
World
PS C:\> $x.contains("`n")
True
PS C:\> $x.contains("`r")
False
PS C:\> $x.replace("o`nW","o There`nThe W")
Hello There
The World
PS C:\>
I think you're running into problems with the `r
. I was able to remove the `r
from your example, use only `n
, and it worked. Of course, I don't know exactly how you generated the original string so I don't know what's in there.
I would like to compliment Ram Narasimhans answer with some tips I found on an Excel blog
Non-uniformly distributed data can be plotted in excel in
Just like Ram Narasimhan suggested, to have the points centered you will want the mid point but you don't need to move to a numeric format, you can stay in the time format.
1- Add the center point to your data series
+---------------+-------+------+
| Time | Time | Freq |
+---------------+-------+------+
| 08:00 - 09:00 | 08:30 | 12 |
| 09:00 - 10:00 | 09:30 | 13 |
| 10:00 - 11:00 | 10:30 | 10 |
| 13:00 - 14:00 | 13:30 | 5 |
| 14:00 - 15:00 | 14:30 | 14 |
+---------------+-------+------+
2- Create a Scatter Plot
3- Excel allows you to specify time values for the axis options. Time values are a parts per 1 of a 24-hour day. Therefore if we want to 08:00 to 15:00, then we Set the Axis options to:
Alternative Display:
To be able to represent these points as bars instead of just point we need to draw disjoint lines. Here is a way to go about getting this type of chart.
1- You're going to need to add several rows where we draw the line and disjoint the data
+-------+------+
| Time | Freq |
+-------+------+
| 08:30 | 0 |
| 08:30 | 12 |
| | |
| 09:30 | 0 |
| 09:30 | 13 |
| | |
| 10:30 | 0 |
| 10:30 | 10 |
| | |
| 13:30 | 0 |
| 13:30 | 5 |
| | |
| 14:30 | 0 |
| 14:30 | 14 |
+-------+------+
2- Plot an X Y (Scatter) Chart with Lines.
3- Now you can tweak the data series to have a fatter line, no markers, etc.. to get a bar/column type chart with non-uniformly distributed data.
If you use Express (high-performance, high-class web development for Node.js), you can do this:
HTML:
<form method="post" action="/">
<input type="text" name="user[name]">
<input type="text" name="user[email]">
<input type="submit" value="Submit">
</form>
API client:
fetch('/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
user: {
name: "John",
email: "[email protected]"
}
})
});
Node.js: (since Express v4.16.0)
// Parse URL-encoded bodies (as sent by HTML forms)
app.use(express.urlencoded());
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
// Access the parse results as request.body
app.post('/', function(request, response){
console.log(request.body.user.name);
console.log(request.body.user.email);
});
Node.js: (for Express <4.16.0)
const bodyParser = require("body-parser");
/** bodyParser.urlencoded(options)
* Parses the text as URL encoded data (which is how browsers tend to send form data from regular forms set to POST)
* and exposes the resulting object (containing the keys and values) on req.body
*/
app.use(bodyParser.urlencoded({
extended: true
}));
/**bodyParser.json(options)
* Parses the text as JSON and exposes the resulting object on req.body.
*/
app.use(bodyParser.json());
app.post("/", function (req, res) {
console.log(req.body.user.name)
});
In Javascript you can do the following:
Object.keys(ahash)[0];
The patch.exe utility from the Git installation works on Windows 10.
Install Git for Windows then use the "C:\Program Files\Git\usr\bin\patch.exe"
command to apply a patch.
If any error message like a Hunk #1 FAILED at 1 (different line endings).
had been got on the output during applying a patch, try to add the -l
(that is a shortcut for the --ignore-whitespace
) or the --binary
switches to the command line.
One of the weird behaviour and spec in Javascript is the typeof Array is Object
.
You can check if the variable is an array in couple of ways:
var isArr = data instanceof Array;
var isArr = Array.isArray(data);
But the most reliable way is:
isArr = Object.prototype.toString.call(data) == '[object Array]';
Since you tagged your question with jQuery, you can use jQuery isArray
function:
var isArr = $.isArray(data);
Updating for latest release:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.14</version>
</dependency>
Hope it helps!
The time and space complexities are not related to each other. They are used to describe how much space/time your algorithm takes based on the input.
For example when the algorithm has space complexity of:
O(1)
- constant - the algorithm uses a fixed (small) amount of space which doesn't depend on the input. For every size of the input the algorithm will take the same (constant) amount of space. This is the case in your example as the input is not taken into account and what matters is the time/space of the print
command.O(n)
, O(n^2)
, O(log(n))
... - these indicate that you create additional objects based on the length of your input. For example creating a copy of each object of v
storing it in an array and printing it after that takes O(n)
space as you create n
additional objects.In contrast the time complexity describes how much time your algorithm consumes based on the length of the input. Again:
O(1)
- no matter how big is the input it always takes a constant time - for example only one instruction. Like
function(list l) {
print("i got a list");
}
O(n)
, O(n^2)
, O(log(n))
- again it's based on the length of the input. For example
function(list l) {
for (node in l) {
print(node);
}
}
Note that both last examples take O(1)
space as you don't create anything. Compare them to
function(list l) {
list c;
for (node in l) {
c.add(node);
}
}
which takes O(n)
space because you create a new list whose size depends on the size of the input in linear way.
Your example shows that time and space complexity might be different. It takes v.length * print.time
to print all the elements. But the space is always the same - O(1)
because you don't create additional objects. So, yes, it is possible that an algorithm has different time and space complexity, as they are not dependent on each other.
<div>{{modal.title | slice: 0: 20}}</div>
The first thing that comes to my mind is a one-liner regex:
var pageNum = $("#specificLink").attr("href").match(/page=([0-9]+)/)[1];
You can get equal height columns in CSS by applying bottom padding of a large amount, bottom negative margin of the same amount and surrounding the columns with a div that has overflow hidden. Vertically centering the text is a little trickier but this should help you on the way.
#container {_x000D_
overflow: hidden;_x000D_
width: 100%;_x000D_
}_x000D_
#left-col {_x000D_
float: left;_x000D_
width: 50%;_x000D_
background-color: orange;_x000D_
padding-bottom: 500em;_x000D_
margin-bottom: -500em;_x000D_
}_x000D_
#right-col {_x000D_
float: left;_x000D_
width: 50%;_x000D_
margin-right: -1px; /* Thank you IE */_x000D_
border-left: 1px solid black;_x000D_
background-color: red;_x000D_
padding-bottom: 500em;_x000D_
margin-bottom: -500em;_x000D_
}
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"_x000D_
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">_x000D_
_x000D_
<head></head>_x000D_
_x000D_
<body>_x000D_
<div id="container">_x000D_
<div id="left-col">_x000D_
<p>Test content</p>_x000D_
<p>longer</p>_x000D_
</div>_x000D_
<div id="right-col">_x000D_
<p>Test content</p>_x000D_
</div>_x000D_
</div>_x000D_
</body>
_x000D_
I think it worth mentioning that the previous answer by streetpc has invalid html, the doctype is XHTML and there are single quotes around the attributes. Also worth noting is that you dont need an extra element with clear
on in order to clear the internal floats of the container. If you use overflow hidden this clears the floats in all non-IE browsers and then just adding something to give hasLayout such as width or zoom:1 will cause IE to clear its internal floats.
I have tested this in all modern browsers FF3+ Opera9+ Chrome Safari 3+ and IE6/7/8. It may seem like an ugly trick but it works well and I use it in production a lot.
I hope this helps.
Have you tried using Unix style slashes (/ instead of \)?
\ is often an escape or command character, and may be the source of confusion. I have never had issues with this, but I also do not have Windows, so I cannot test it.
Additionally, the permissions may be based on the user running psql, or maybe the user executing the postmaster service, check that both have read to that file in that directory.
for i=1:length(list)
elm = list(i);
//do something with elm.
First, open a file:
with open("filename") as fileobj:
for line in fileobj:
for ch in line:
print(ch)
This goes through every line in the file and then every character in that line.
I would perform a Null check before converting to set.
if(myList != null){
Set<Foo> foo = new HashSet<Foo>(myList);
}
There are multiple ways of doing this, since state update is a async operation, so to update the state object, we need to use updater function with setState
.
1- Simplest one:
First create a copy of jasper
then do the changes in that:
this.setState(prevState => {
let jasper = Object.assign({}, prevState.jasper); // creating copy of state variable jasper
jasper.name = 'someothername'; // update the name property, assign a new value
return { jasper }; // return new object jasper object
})
Instead of using Object.assign
we can also write it like this:
let jasper = { ...prevState.jasper };
2- Using spread syntax:
this.setState(prevState => ({
jasper: { // object that we want to update
...prevState.jasper, // keep all other key-value pairs
name: 'something' // update the value of specific key
}
}))
Note: Object.assign
and Spread Operator
creates only shallow copy, so if you have defined nested object or array of objects, you need a different approach.
Assume you have defined state as:
this.state = {
food: {
sandwich: {
capsicum: true,
crackers: true,
mayonnaise: true
},
pizza: {
jalapeno: true,
extraCheese: false
}
}
}
To update extraCheese of pizza object:
this.setState(prevState => ({
food: {
...prevState.food, // copy all other key-value pairs of food object
pizza: { // specific object of food object
...prevState.food.pizza, // copy all pizza key-value pairs
extraCheese: true // update value of specific key
}
}
}))
Lets assume you have a todo app, and you are managing the data in this form:
this.state = {
todoItems: [
{
name: 'Learn React Basics',
status: 'pending'
}, {
name: 'Check Codebase',
status: 'pending'
}
]
}
To update the status of any todo object, run a map on the array and check for some unique value of each object, in case of condition=true
, return the new object with updated value, else same object.
let key = 2;
this.setState(prevState => ({
todoItems: prevState.todoItems.map(
el => el.key === key? { ...el, status: 'done' }: el
)
}))
Suggestion: If object doesn't have a unique value, then use array index.
The method takes a regular expression, not a string, and the dot has a special meaning in regular expressions. Escape it like so split("\\.")
. You need a double backslash, the second one escapes the first.
I think,The better way At the command line
python manage.py createsuperuser
The idea of MD5 is that is a one-way hashing, so it can't be once the original value has been passed through the hashing algorithm (if at all).
You could (potentially) create a database table with a pairing of the original and the MD5 values but I guess that's highly impractical and poses a major security risk.
This code snippet worked for me. I have an issue with the parsing batch of XML files. I had to encode them to 'iso-8859-5'
import xml.etree.ElementTree as ET
tree = ET.parse(filename, parser = ET.XMLParser(encoding = 'iso-8859-5'))
use:
opener.document.<id of document>.innerHTML = xmlhttp.responseText;
Yes - just do it this way:
WITH DependencedIncidents AS
(
....
),
lalala AS
(
....
)
You don't need to repeat the WITH
keyword
Supporting historical data directly within an operational system will make your application much more complex than it would otherwise be. Generally, I would not recommend doing it unless you have a hard requirement to manipulate historical versions of a record within the system.
If you look closely, most requirements for historical data fall into one of two categories:
Audit logging: This is better off done with audit tables. It's fairly easy to write a tool that generates scripts to create audit log tables and triggers by reading metadata from the system data dictionary. This type of tool can be used to retrofit audit logging onto most systems. You can also use this subsystem for changed data capture if you want to implement a data warehouse (see below).
Historical reporting: Reporting on historical state, 'as-at' positions or analytical reporting over time. It may be possible to fulfil simple historical reporting requirements by quering audit logging tables of the sort described above. If you have more complex requirements then it may be more economical to implement a data mart for the reporting than to try and integrate history directly into the operational system.
Slowly changing dimensions are by far the simplest mechanism for tracking and querying historical state and much of the history tracking can be automated. Generic handlers aren't that hard to write. Generally, historical reporting does not have to use up-to-the-minute data, so a batched refresh mechanism is normally fine. This keeps your core and reporting system architecture relatively simple.
If your requirements fall into one of these two categories, you are probably better off not storing historical data in your operational system. Separating the historical functionality into another subsystem will probably be less effort overall and produce transactional and audit/reporting databases that work much better for their intended purpose.
Here you can also find more examples for values that data-toggle
can have assigned. Just visit the page and then CTRL+F
to search for data-toggle
.
http://php.net/ereg_replace says:
Note: As of PHP 5.3.0, the regex extension is deprecated in favor of the PCRE extension.
Thus, preg_replace is in every way better choice. Note there are some differences in pattern syntax though.
If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8
into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.
While using regex is typically less performant than non-regex techniques, I do appreciate the control and flexibility that it affords.
In my snippet, I will set the pattern to be case-insensitive (\i
, although my sample input will not challenge this rule) and include word boundaries (\b
, although they were not explicitly called for).
I am also going to use the \K
metacharacter to reset the fullstring match so that no capture groups / backreferences are needed.
Code: (Demo)
$search = 'The';
$replace = 'A';
$subject = "The Quick Brown Fox Jumps Over The Lazy Dog's Thermos!";
echo preg_replace(
'/.*\K\b' . preg_quote($search, '/') . '\b/i',
$replace,
$subject
);
Output:
The Quick Brown Fox Jumps Over A Lazy Dog's Thermos!
# ^^^ ^ ^^^
# not replaced replaced not replaced
Without word boundaries: (Demo)
echo preg_replace(
'/.*\K' . preg_quote($search, '/') . '/i',
$replace,
$subject
);
Output:
The Quick Brown Fox Jumps Over The Lazy Dog's Armos!
# ^^^ ^^^ ^
# not replaced not replaced replaced
Use a function like this:
public static string FlattenException(Exception exception)
{
var stringBuilder = new StringBuilder();
while (exception != null)
{
stringBuilder.AppendLine(exception.Message);
stringBuilder.AppendLine(exception.StackTrace);
exception = exception.InnerException;
}
return stringBuilder.ToString();
}
Then you can call it like this:
try
{
// invoke code above
}
catch(MyCustomException we)
{
Debug.Writeline(FlattenException(we));
}
When you use setcookie
, you can either set the expiration time to 0
or simply omit the parametre - the cookie will then expire at the end of session (ie, when you close the browser).
In my case, I was downloading a library with sample code of keycloak implementation by mattorg from GITHUB: https://github.com/mattmorg55/Owin.Security.Keycloak/tree/dev/samples
The solution was quite easy, as I used .Net Framework 4.6.1, but the project begged me in the beginning to use 4.6.2. Although I downloaded it, it was first actively chosen, when restartet all instances of Visual Studion (or better close all instances). The project was manipulated to 4.6.1 (although I wished not and chose so).
So after I chose the configuration again to choose .Net Framework 4.6.1 the error vanished immediately.
Rather give names of the column on which you want to merge:
exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)
you need /q at the end
MsiExec.exe /x {2F808931-D235-4FC7-90CD-F8A890C97B2F} /q
It is in the dist folder inside of the project, but only if "Compress WAR File" in the project settings dialog ( build / packaging) ist checked. Before I checked this checkbox there was no dist folder.
The NSURLErrorDomain
error codes are listed here https://developer.apple.com/documentation/foundation/1508628-url_loading_system_error_codes
However, 400 is just the http status code (http://www.w3.org/Protocols/HTTP/HTRESP.html) being returned which means you've got something wrong with your request.
I use this little method that outputs the trace and line number of the method that called it.
Log.d(TAG, "Where did i put this debug code again? " + Utils.lineOut());
Double click the output to go to that source code line!
You might need to adjust the level value depending on where you put your code.
public static String lineOut() {
int level = 3;
StackTraceElement[] traces;
traces = Thread.currentThread().getStackTrace();
return (" at " + traces[level] + " " );
}