Just a cooler swift syntax for Nate's answer:
[UISwipeGestureRecognizerDirection.right,
UISwipeGestureRecognizerDirection.left,
UISwipeGestureRecognizerDirection.up,
UISwipeGestureRecognizerDirection.down].forEach({ direction in
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipe.direction = direction
self.view.addGestureRecognizer(swipe)
})
I managed to figure it out in the end, so if anyone is looking for the answer:
//Firefox
$('#elem').bind('DOMMouseScroll', function(e){
if(e.originalEvent.detail > 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
//IE, Opera, Safari
$('#elem').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta < 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
EXEC sp_MSforeachtable @command1="EXEC sp_spaceused '?'"
To disable bundling and minification just put this your .aspx file
(this will disable optimization even if debug=true
in web.config)
vb.net:
System.Web.Optimization.BundleTable.EnableOptimizations = false
c#.net
System.Web.Optimization.BundleTable.EnableOptimizations = false;
If you put EnableOptimizations = true
this will bundle and minify even if debug=true
in web.config
There is no CREATE TABLE IF NOT EXISTS... but you can write a simple procedure for that, something like:
CREATE OR REPLACE FUNCTION prc_create_sch_foo_table() RETURNS VOID AS $$
BEGIN
EXECUTE 'CREATE TABLE /* IF NOT EXISTS add for PostgreSQL 9.1+ */ sch.foo (
id serial NOT NULL,
demo_column varchar NOT NULL,
demo_column2 varchar NOT NULL,
CONSTRAINT pk_sch_foo PRIMARY KEY (id));
CREATE INDEX /* IF NOT EXISTS add for PostgreSQL 9.5+ */ idx_sch_foo_demo_column ON sch.foo(demo_column);
CREATE INDEX /* IF NOT EXISTS add for PostgreSQL 9.5+ */ idx_sch_foo_demo_column2 ON sch.foo(demo_column2);'
WHERE NOT EXISTS(SELECT * FROM information_schema.tables
WHERE table_schema = 'sch'
AND table_name = 'foo');
EXCEPTION WHEN null_value_not_allowed THEN
WHEN duplicate_table THEN
WHEN others THEN RAISE EXCEPTION '% %', SQLSTATE, SQLERRM;
END; $$ LANGUAGE plpgsql;
var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductID orderby od.OrderID select new { od.OrderID,
pd.ProductID,
pd.Name,
pd.UnitPrice,
od.Quantity,
od.Price,
}).ToList();
You can also get the text resize events, and the zoom factor by injecting a div containing at least a non-breakable space (possibly, hidden), and regularly checking its height. If the height changes, the text size has changed, (and you know how much - this also fires, incidentally, if the window gets zoomed in full-page mode, and you still will get the correct zoom factor, with the same height / height ratio).
This question doesn't really have anything to do with how require()
works. Basically, whatever you set module.exports
to in your module will be returned from the require()
call for it.
This would be equivalent to:
var square = function(width) {
return {
area: function() {
return width * width;
}
};
}
There is no need for the new
keyword when calling square
. You aren't returning the function instance itself from square
, you are returning a new object at the end. Therefore, you can simply call this function directly.
For more intricate arguments around new
, check this out: Is JavaScript's "new" keyword considered harmful?
If you get rid of your existing instance of Junit, and download JUnit 4.11 or greater in the build path, the following code will execute the test methods in the order of their names, sorted in ascending order:
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SampleTest {
@Test
public void testAcreate() {
System.out.println("first");
}
@Test
public void testBupdate() {
System.out.println("second");
}
@Test
public void testCdelete() {
System.out.println("third");
}
}
I came across this error where rather than a trailing comma or some such, this syntax had been used in a constants.js
var titles = {
[title.X]: 'X title',
[title.Y]: 'Y title'
}
IE 11 did not like this at all.
As previously mentioned though this was easily fixed by using
var titles = {
'title.X': 'X title',
'title.Y': 'Y title'
}
When you use the exec()
function, it is as though you have a cmd
terminal open and are typing commands straight to it.
Use single quotes like this $str = exec('start /B Path\to\batch.bat');
The /B
means the bat will be executed in the background so the rest of the php will continue after running that line, as opposed to $str = exec('start /B /C command', $result);
where command
is executed and then result
is stored for later use.
PS: It works for both Windows and Linux.
More details are here http://www.php.net/manual/en/function.exec.php :)
Here is what I ended up doing to work around the error.
First, I set up the database recovery model as SIMPLE. More information here.
Then, by deleting some old files I was able to make 5GB of free space which gave the log file more space to grow.
I reran the DELETE statement sucessfully without any warning.
I thought that by running the DELETE statement the database would inmediately become smaller thus freeing space in my hard drive. But that was not true. The space freed after a DELETE statement is not returned to the operating system inmediatedly unless you run the following command:
DBCC SHRINKDATABASE (MyDb, 0);
GO
More information about that command here.
As everyone else here has stated: You cannot upload just any file automatically with JavaScript.
HOWEVER! If you have access to the information you want to send in your code (i.e., not C:\passwords.txt
), then you can upload it as a blob-type, and then treat it as a file.
What the server will end up seeing will be indistinguishable from someone actually setting the value of <input type="file" />
. The trick, ultimately, is to begin a new XMLHttpRequest()
with the server...
function uploadFile (data) {
// define data and connections
var blob = new Blob([JSON.stringify(data)]);
var url = URL.createObjectURL(blob);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'myForm.php', true);
// define new form
var formData = new FormData();
formData.append('someUploadIdentifier', blob, 'someFileName.json');
// action after uploading happens
xhr.onload = function(e) {
console.log("File uploading completed!");
};
// do the uploading
console.log("File uploading started!");
xhr.send(formData);
}
// This data/text below is local to the JS script, so we are allowed to send it!
uploadFile({'hello!':'how are you?'});
So, what could you possibly use this for? I use it for uploading HTML5 canvas elements as jpg's. This saves the user the trouble of having to open a file
input
element, only to select the local, cached image that they just resized, modified, etc.. But it should work for any file type.
what about http://jsbin.com/esepal/2
$(document).bind("DOMSubtreeModified",function(){
console.log($('body').width() + ' x '+$('body').height());
})
This event has been deprecated in favor of the Mutation Observer API
If it helps anyone, I was having an issue where I wanted to treat an object as another type with a similar interface. I attempted the following:
Didn't pass linting
const x = new Obj(a as b);
The linter was complaining that a
was missing properties that existed on b
. In other words, a
had some properties and methods of b
, but not all. To work around this, I followed VS Code's suggestion:
Passed linting and testing
const x = new Obj(a as unknown as b);
Note that if your code attempts to call one of the properties that exists on type b
that is not implemented on type a
, you should realize a runtime fault.
You can set ini_set('display_errors',0);
in your script or define which errors you do want to display with error_reporting()
.
There is indeed a problem with using utcfromtimestamp and specifying time zones. A nice example/explanation is available on the following question:
How to specify time zone (UTC) when converting to Unix time? (Python)
If you think other answers were too hacky, this one is too, but there is no JavaScript injection involved.
When the button is off the screen, it breaks and scrolls to it, so retry it... ¯\_(?)_/¯
try
{
element.Click();
}
catch {
element.Click();
}
converting 'int' into 'byte' is like fitting big object into small box
if sign in -ve takes 2's complement
example 1: let number be 130
step 1:130 interms of bits =1000 0010
step 2:condider 1st 7 bits and 8th bit is sign(1=-ve and =+ve)
step 3:convert 1st 7 bits to 2's compliment
000 0010
-------------
111 1101
add 1
-------------
111 1110 =126
step 4:8th bit is "1" hence the sign is -ve
step 5:byte of 130=-126
Example2: let number be 500
step 1:500 interms of bits 0001 1111 0100
step 2:consider 1st 7 bits =111 0100
step 3: the remained bits are '11' gives -ve sign
step 4: take 2's compliment
111 0100
-------------
000 1011
add 1
-------------
000 1100 =12
step 5:byte of 500=-12
example 3: number=300
300=1 0010 1100
1st 7 bits =010 1100
remaining bit is '0' sign =+ve need not take 2's compliment for +ve sign
hence 010 1100 =44
byte(300) =44
In the aspx page load event, add an onkeypress
to the box.
this.TextBox1.Attributes.Add(
"onkeypress", "button_click(this,'" + this.Button1.ClientID + "')");
Then add this javascript to evaluate the key press, and if it is "enter," click the right button.
<script>
function button_click(objTextBox,objBtnID)
{
if(window.event.keyCode==13)
{
document.getElementById(objBtnID).focus();
document.getElementById(objBtnID).click();
}
}
</script>
Try Stretch="UniformToFill" on the Image
I just used the javascript console in Chrome to do this. I replaced some of your stuff with placeholders.
var temp= ['one', 'two', 'three']; //'${temp}';
//alert(options);
var $select = $('<select>'); //$('#down');
$select.find('option').remove();
$.each(temp, function(key, value) {
$('<option>').val(key).text(value).appendTo($select);
});
console.log($select.html());
Output:
<option value="0">one</option><option value="1">two</option><option value="2">three</option>
However it looks like your json is probably actually a string because the following will end up doing what you describe. So make your JSON actual JSON not a string.
var temp= "['one', 'two', 'three']"; //'${temp}';
//alert(options);
var $select = $('<select>'); //$('#down');
$select.find('option').remove();
$.each(temp, function(key, value) {
$('<option>').val(key).text(value).appendTo($select);
});
console.log($select.html());
A BLOB
can be 65535 bytes (64 KB) maximum.
If you need more consider using:
a MEDIUMBLOB
for 16777215 bytes (16 MB)
a LONGBLOB
for 4294967295 bytes (4 GB).
See Storage Requirements for String Types for more info.
You can make a hard distinction instead of linear gradient by putting the second color to 0%
For instance,
Gradient - background: linear-gradient(80deg, #ff0000 20%, #0000ff 80%);
Hard distinction - background: linear-gradient(80deg, #ff0000 20%, #0000ff 0%);
Here is how you can test which piece of code is faster:
% python -mtimeit "l=[]"
10000000 loops, best of 3: 0.0711 usec per loop
% python -mtimeit "l=list()"
1000000 loops, best of 3: 0.297 usec per loop
However, in practice, this initialization is most likely an extremely small part of your program, so worrying about this is probably wrong-headed.
Readability is very subjective. I prefer []
, but some very knowledgable people, like Alex Martelli, prefer list()
because it is pronounceable.
As he didn't specify which version of SQL server he uses (date
type isn't available in 2005), one could also use
SELECT CONVERT(VARCHAR(10),date_column,112),SUM(num_col) AS summed
FROM table_name
GROUP BY CONVERT(VARCHAR(10),date_column,112)
For mac users, this is the best way to solve, Download the chromedriver and then paste that chromedriver in this directory
/usr/local/bin
If this directory is not found to you then from finder click on go then select computer then press command+shift+. (this shows the hidden files in mac) then definitely you will see these directory easily
var a = [], b = {};
console.log(a.constructor.name == "Array");
console.log(b.constructor.name == "Object");
I don't know if this changed recently -- the answer given by Samuel did not apply to me even though that link seemed authoritative.
A couple of things
1) For some reason, the folder in the start menu is called Visual Studio 2013
, and not Microsoft Visual Studio 2013
. Using the win8 apps interface you might see the 2010 entry Microsoft Visual Studio 2010
, and since you don't see the new 2013 folder Microsoft Visual Studio 2013
next to it, you assume it isn't there. But it is.. Just a few page scrolls away..
2) It seems the Windows 8 (or 8.1 at least) cannot display sub-folders. I tried creating a folder underneath the Visual Studio 2013
folder with shortcuts, and the entire folder just didn't show.
3) Which is why what is installed is a shortcut. Not sure what the windows 7 behavior is with a shortcut in the start menu, but the apps menu just displays it like a folder. When you click on it, it brings you to the so-called missing shortcuts in explorer.
Final solution: under C:\ProgramData\Microsoft\Windows\Start Menu\Programs
, create a new folder called Microsoft Visual Studio 2013
. Copy the shortcuts from C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts
to that new folder. Then you'll have your icons using the windows 8 app interface under the heading which is the new folder name.
You'll also be able to just start typing from the start screen VS2013
, and the icons will now show up.
I do this using the TextMaskModule from 'angular2-text-mask'
Mine are split but you can get the idea
Package using NPM NodeJS
"dependencies": {
"angular2-text-mask": "8.0.0",
HTML
<input *ngIf="column?.type =='areaCode'" type="text" [textMask]="{mask: areaCodeMask}" [(ngModel)]="areaCodeModel">
<input *ngIf="column?.type =='phone'" type="text" [textMask]="{mask: phoneMask}" [(ngModel)]="phoneModel">
Inside Component
public areaCodeModel = '';
public areaCodeMask = ['(', /[1-9]/, /\d/, /\d/, ')'];
public phoneModel = '';
public phoneMask = [/\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];
If you have configured navigation property 1-n I would recommend you to use:
var query = db.Categories // source
.SelectMany(c=>c.CategoryMaps, // join
(c, cm) => new { Category = c, CategoryMaps = cm }) // project result
.Select(x => x.Category); // select result
Much more clearer to me and looks better with multiple nested joins.
Also make sure the value is not too large or too small for int like in my case.
My solution, in case someone finds it useful.
In Web.config:
<system.web>
<customErrors mode="On" defaultRedirect="Error" >
<error statusCode="404" redirect="~/Error/PageNotFound"/>
</customErrors>
...
</system.web>
In Controllers/ErrorController.cs
:
public class ErrorController : Controller
{
public ActionResult PageNotFound()
{
if(Request.IsAjaxRequest()) {
Response.StatusCode = (int)HttpStatusCode.NotFound;
return Content("Not Found", "text/plain");
}
return View();
}
}
Add a PageNotFound.cshtml
in the Shared
folder, and that's it.
@{ var result = string.Join(",", @user.UserRoles.Select(x => x.Role.RoleName));
@result
}
I used in MVC Razor View to evaluate and print all roles separated by commas.
If the user name that is in the connection string has access to more then one database you have to specify the database you want the connection string to connect to. If your user has only one database available then you are correct that it doesn't matter. But it is good practice to put this in your connection string.
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
I will start my answer saying that most of previous answers were perfectly good answers at the time of writing them. So, thank you to them who wrote them.
Now, you can also use String Interpolation for same solution.
Edit: Adding this explanation after receiving a perfectively valid constructive comment from Heretic Monkey. I have preferred to use .ToString whenever I had need to convert an integer to string and not add the result to any other string. And, I have preferred to use interpolation whenever I had need to combine string(s) and an integer, like in below examples.
i.ToString("00")
01
i.ToString("000")
001
i.ToString("0000")
0001
$"Prefix_{i:00}"
Prefix_01
$"Prefix_{i:000}"
Prefix_001
$"Prefix_{i:0000}_Suffix"
Prefix_0001_Suffix
This seemed to work best for me:
public static Date fromISO8601_( String string ) {
try {
return new SimpleDateFormat ( "yyyy-MM-dd'T'HH:mm:ssXXX").parse ( string );
} catch ( ParseException e ) {
return Exceptions.handle (Date.class, "Not a valid ISO8601", e);
}
}
I needed to convert to/fro JavaScript date strings to Java. I found the above works with the recommendation. There were some examples using SimpleDateFormat that were close but they did not seem to be the subset as recommended by:
http://www.w3.org/TR/NOTE-datetime
and supported by PLIST and JavaScript Strings and such which is what I needed.
This seems to be the most common form of ISO8601 string out there, and a good subset.
The examples they give are:
1994-11-05T08:15:30-05:00 corresponds
November 5, 1994, 8:15:30 am, US Eastern Standard Time.
1994-11-05T13:15:30Z corresponds to the same instant.
I also have a fast version:
final static int SHORT_ISO_8601_TIME_LENGTH = "1994-11-05T08:15:30Z".length ();
// 01234567890123456789012
final static int LONG_ISO_8601_TIME_LENGTH = "1994-11-05T08:15:30-05:00".length ();
public static Date fromISO8601( String string ) {
if (isISO8601 ( string )) {
char [] charArray = Reflection.toCharArray ( string );//uses unsafe or string.toCharArray if unsafe is not available
int year = CharScanner.parseIntFromTo ( charArray, 0, 4 );
int month = CharScanner.parseIntFromTo ( charArray, 5, 7 );
int day = CharScanner.parseIntFromTo ( charArray, 8, 10 );
int hour = CharScanner.parseIntFromTo ( charArray, 11, 13 );
int minute = CharScanner.parseIntFromTo ( charArray, 14, 16 );
int second = CharScanner.parseIntFromTo ( charArray, 17, 19 );
TimeZone tz ;
if (charArray[19] == 'Z') {
tz = TimeZone.getTimeZone ( "GMT" );
} else {
StringBuilder builder = new StringBuilder ( 9 );
builder.append ( "GMT" );
builder.append( charArray, 19, LONG_ISO_8601_TIME_LENGTH - 19);
String tzStr = builder.toString ();
tz = TimeZone.getTimeZone ( tzStr ) ;
}
return toDate ( tz, year, month, day, hour, minute, second );
} else {
return null;
}
}
...
public static int parseIntFromTo ( char[] digitChars, int offset, int to ) {
int num = digitChars[ offset ] - '0';
if ( ++offset < to ) {
num = ( num * 10 ) + ( digitChars[ offset ] - '0' );
if ( ++offset < to ) {
num = ( num * 10 ) + ( digitChars[ offset ] - '0' );
if ( ++offset < to ) {
num = ( num * 10 ) + ( digitChars[ offset ] - '0' );
if ( ++offset < to ) {
num = ( num * 10 ) + ( digitChars[ offset ] - '0' );
if ( ++offset < to ) {
num = ( num * 10 ) + ( digitChars[ offset ] - '0' );
if ( ++offset < to ) {
num = ( num * 10 ) + ( digitChars[ offset ] - '0' );
if ( ++offset < to ) {
num = ( num * 10 ) + ( digitChars[ offset ] - '0' );
if ( ++offset < to ) {
num = ( num * 10 ) + ( digitChars[ offset ] - '0' );
}
}
}
}
}
}
}
}
return num;
}
public static boolean isISO8601( String string ) {
boolean valid = true;
if (string.length () == SHORT_ISO_8601_TIME_LENGTH) {
valid &= (string.charAt ( 19 ) == 'Z');
} else if (string.length () == LONG_ISO_8601_TIME_LENGTH) {
valid &= (string.charAt ( 19 ) == '-' || string.charAt ( 19 ) == '+');
valid &= (string.charAt ( 22 ) == ':');
} else {
return false;
}
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4
// "1 9 9 4 - 1 1 - 0 5 T 0 8 : 1 5 : 3 0 - 0 5 : 0 0
valid &= (string.charAt ( 4 ) == '-') &&
(string.charAt ( 7 ) == '-') &&
(string.charAt ( 10 ) == 'T') &&
(string.charAt ( 13 ) == ':') &&
(string.charAt ( 16 ) == ':');
return valid;
}
I have not benchmarked it, but I am guess it will be pretty fast. It seems to work. :)
@Test
public void testIsoShortDate() {
String test = "1994-11-05T08:15:30Z";
Date date = Dates.fromISO8601 ( test );
Date date2 = Dates.fromISO8601_ ( test );
assertEquals(date2.toString (), date.toString ());
puts (date);
}
@Test
public void testIsoLongDate() {
String test = "1994-11-05T08:11:22-05:00";
Date date = Dates.fromISO8601 ( test );
Date date2 = Dates.fromISO8601_ ( test );
assertEquals(date2.toString (), date.toString ());
puts (date);
}
You can't do it with the layout alone, I've tried. I ended up writing a very simple class to handle it, you can check it out on github. SquareImage.java Its part of a larger project but nothing a little copy and paste can't fix (licensed under Apache 2.0)
Essentially you just need to set the height/width equal to the other dimension (depending on which way you want to scale it)
Note: You can make it square without a custom class using the scaleType
attribute but the view's bounds extend beyond the visible image, which makes it an issue if you are placing other views near it.
Consider:
Function GetFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
This code was adapted from Ozgrid
and as jkf points out, from Mr Excel
You need to remove the static
from your accessor methods - these methods need to be instance methods and access the instance variables
public class IDCard {
public String name, fileName;
public int id;
public IDCard(final String name, final String fileName, final int id) {
this.name = name;
this.fileName = fileName
this.id = id;
}
public String getName() {
return name;
}
}
You can the create an IDCard
and use the accessor like this:
final IDCard card = new IDCard();
card.getName();
Each time you call new
a new instance of the IDCard
will be created and it will have it's own copies of the 3 variables.
If you use the static
keyword then those variables are common across every instance of IDCard
.
A couple of things to bear in mind:
name
not Name
.This will give you a list.
List<Card> cardsList = Arrays.asList(hand);
If you want an arraylist, you can do
ArrayList<Card> cardsList = new ArrayList<Card>(Arrays.asList(hand));
Use btoa()
for encode and atob()
for decode
text_val:any="your encoding text";
Encoded Text: console.log(btoa(this.text_val)); //eW91ciBlbmNvZGluZyB0ZXh0
Decoded Text: console.log(atob("eW91ciBlbmNvZGluZyB0ZXh0")); //your encoding text
There are three scenarios (that I can think of) where you would call a method in a subclass where the method exits in the parent class:
Method is not overwritten by subclass, only exists in parent.
This is the same as your example, and generally it's better to use $this -> get_species();
You are right that in this case the two are effectively the same, but the method has been inherited by the subclass, so there is no reason to differentiate. By using $this
you stay consistent between inherited methods and locally declared methods.
Method is overwritten by the subclass and has totally unique logic from the parent.
In this case, you would obviously want to use $this -> get_species();
because you don't want the parent's version of the method executed. Again, by consistently using $this
, you don't need to worry about the distinction between this case and the first.
Method extends parent class, adding on to what the parent method achieves.
In this case, you still want to use `$this -> get_species();
when calling the method from other methods of the subclass. The one place you will call the parent method would be from the method that is overwriting the parent method. Example:
abstract class Animal {
function get_species() {
echo "I am an animal.";
}
}
class Dog extends Animal {
function __construct(){
$this->get_species();
}
function get_species(){
parent::get_species();
echo "More specifically, I am a dog.";
}
}
The only scenario I can imagine where you would need to call the parent method directly outside of the overriding method would be if they did two different things and you knew you needed the parent's version of the method, not the local. This shouldn't be the case, but if it did present itself, the clean way to approach this would be to create a new method with a name like get_parentSpecies()
where all it does is call the parent method:
function get_parentSpecies(){
parent::get_species();
}
Again, this keeps everything nice and consistent, allowing for changes/modifications to the local method rather than relying on the parent method.
I tend to use the second one to avoid a complicated constructor (or a useless one), also I don't really consider this as an initialization (even if it is an initialization), but more like giving a default value.
For example in your second snippet, you can remove the constructor and have a clearer code.
Do not use this return `${ pre }_${ new Date().getTime()}`;
. It's better to have the array index instead of that because, even though it's not ideal, that way you will at least get some consistency among the list components, with the new Date function you will get constant inconsistency. That means every new iteration of the function will lead to a new truly unique key.
The unique key doesn't mean that it needs to be globally unique, it means that it needs to be unique in the context of the component, so it doesn't run useless re-renders all the time. You won't feel the problem associated with new Date initially, but you will feel it, for example, if you need to get back to the already rendered list and React starts getting all confused because it doesn't know which component changed and which didn't, resulting in memory leaks, because, you guessed it, according to your Date key, every component changed.
Now to my answer. Let's say you are rendering a list of YouTube videos. Use the video id (arqTu9Ay4Ig) as a unique ID. That way, if that ID doesn't change, the component will stay the same, but if it does, React will recognize that it's a new Video and change it accordingly.
It doesn't have to be that strict, the little more relaxed variant is to use the title, like Erez Hochman already pointed out, or a combination of the attributes of the component (title plus category), so you can tell React to check if they have changed or not.
edited some unimportant stuff
If you are using MS Excel 2007, you could use the conditional formatting
on the Home
tab as shown in the screenshot below. You could either use the color scales
default option as I have done here or you can go ahead and create a new rule
based on your data set.
I just wanted to answer that question for Cocoa Swift programmers. This function returns NSImage with new size. You can use that function like this.
let sizeChangedImage = changeImageSize(image, ratio: 2)
// changes image size
func changeImageSize (image: NSImage, ratio: CGFloat) -> NSImage {
// getting the current image size
let w = image.size.width
let h = image.size.height
// calculating new size
let w_new = w / ratio
let h_new = h / ratio
// creating size constant
let newSize = CGSizeMake(w_new ,h_new)
//creating rect
let rect = NSMakeRect(0, 0, w_new, h_new)
// creating a image context with new size
let newImage = NSImage.init(size:newSize)
newImage.lockFocus()
// drawing image with new size in context
image.drawInRect(rect)
newImage.unlockFocus()
return newImage
}
$('#autoship_option').val('').trigger('liszt:updated');
and set the default option value to ''
.
It has to be used with chosen updated jQuery available at this link: https://raw.github.com/harvesthq/chosen/master/chosen/chosen.jquery.min.js.
I spent one full day to find out at the end that jquery.min
is different from chosen.jquery.min
Use the Java 8 solution. Note DatatypeConverter can still be used, but it is now within the java.xml.bind
module which will need to be included.
module org.example.foo {
requires java.xml.bind;
}
Java 8 now provides java.util.Base64
for encoding and decoding base64.
Encoding
byte[] message = "hello world".getBytes(StandardCharsets.UTF_8);
String encoded = Base64.getEncoder().encodeToString(message);
System.out.println(encoded);
// => aGVsbG8gd29ybGQ=
Decoding
byte[] decoded = Base64.getDecoder().decode("aGVsbG8gd29ybGQ=");
System.out.println(new String(decoded, StandardCharsets.UTF_8));
// => hello world
Since Java 6 the lesser known class javax.xml.bind.DatatypeConverter
can be used. This is part of the JRE, no extra libraries required.
Encoding
byte[] message = "hello world".getBytes("UTF-8");
String encoded = DatatypeConverter.printBase64Binary(message);
System.out.println(encoded);
// => aGVsbG8gd29ybGQ=
Decoding
byte[] decoded = DatatypeConverter.parseBase64Binary("aGVsbG8gd29ybGQ=");
System.out.println(new String(decoded, "UTF-8"));
// => hello world
function foo(x) {
// Function with other context
// Modify `x` property, increasing the value
x.value++;
}
// Initialize `ref` as object
var ref = {
// The `value` is inside `ref` variable object
// The initial value is `1`
value: 1
};
// Call function with object value
foo(ref);
// Call function with object value again
foo(ref);
console.log(ref.value); // Prints "3"
_x000D_
rvar
/**
* Aux function to create by-references variables
*/
function rvar(name, value, context) {
// If `this` is a `rvar` instance
if (this instanceof rvar) {
// Inside `rvar` context...
// Internal object value
this.value = value;
// Object `name` property
Object.defineProperty(this, 'name', { value: name });
// Object `hasValue` property
Object.defineProperty(this, 'hasValue', {
get: function () {
// If the internal object value is not `undefined`
return this.value !== undefined;
}
});
// Copy value constructor for type-check
if ((value !== undefined) && (value !== null)) {
this.constructor = value.constructor;
}
// To String method
this.toString = function () {
// Convert the internal value to string
return this.value + '';
};
} else {
// Outside `rvar` context...
// Initialice `rvar` object
if (!rvar.refs) {
rvar.refs = {};
}
// Initialize context if it is not defined
if (!context) {
context = window;
}
// Store variable
rvar.refs[name] = new rvar(name, value, context);
// Define variable at context
Object.defineProperty(context, name, {
// Getter
get: function () { return rvar.refs[name]; },
// Setter
set: function (v) { rvar.refs[name].value = v; },
// Can be overrided?
configurable: true
});
// Return object reference
return context[name];
}
}
// Variable Declaration
// Declare `test_ref` variable
rvar('test_ref_1');
// Assign value `5`
test_ref_1 = 5;
// Or
test_ref_1.value = 5;
// Or declare and initialize with `5`:
rvar('test_ref_2', 5);
// ------------------------------
// Test Code
// Test Function
function Fn1 (v) { v.value = 100; }
// Declare
rvar('test_ref_number');
// First assign
test_ref_number = 5;
console.log('test_ref_number.value === 5', test_ref_number.value === 5);
// Call function with reference
Fn1(test_ref_number);
console.log('test_ref_number.value === 100', test_ref_number.value === 100);
// Increase value
test_ref_number++;
console.log('test_ref_number.value === 101', test_ref_number.value === 101);
// Update value
test_ref_number = test_ref_number - 10;
console.log('test_ref_number.value === 91', test_ref_number.value === 91);
// Declare and initialize
rvar('test_ref_str', 'a');
console.log('test_ref_str.value === "a"', test_ref_str.value === 'a');
// Update value
test_ref_str += 'bc';
console.log('test_ref_str.value === "abc"', test_ref_str.value === 'abc');
// Declare other...
rvar('test_ref_number', 5);
test_ref_number.value === 5; // true
// Call function
Fn1(test_ref_number);
test_ref_number.value === 100; // true
// Increase value
test_ref_number++;
test_ref_number.value === 101; // true
// Update value
test_ref_number = test_ref_number - 10;
test_ref_number.value === 91; // true
test_ref_str.value === "a"; // true
// Update value
test_ref_str += 'bc';
test_ref_str.value === "abc"; // true
_x000D_
This is not an issue, this is a design of Android. See here:
You should design each fragment as a modular and reusable activity component. That is, because each fragment defines its own layout and its own behavior with its own lifecycle callbacks, you can include one fragment in multiple activities, so you should design for reuse and avoid directly manipulating one fragment from another fragment.
A possible workaround would be to do something like this in your MainActivity:
Fragment someFragment;
...onCreate etc instantiating your fragments
public void myClickMethod(View v){
someFragment.myClickMethod(v);
}
and then in your Fragment class:
public void myClickMethod(View v){
switch(v.getid()){
// Your code here
}
}
word-break: normal seems better to use than word-break: break-word because break-word breaks initials such as EN
word-break: normal
You can pass a C# Guid value directly to a SQL Stored Procedure by specifying SqlDbType.UniqueIdentifier
.
Your method may look like this (provided that your only parameter is the Guid):
public static void StoreGuid(Guid guid)
{
using (var cnx = new SqlConnection("YourDataBaseConnectionString"))
using (var cmd = new SqlCommand {
Connection = cnx,
CommandType = CommandType.StoredProcedure,
CommandText = "StoreGuid",
Parameters = {
new SqlParameter {
ParameterName = "@guid",
SqlDbType = SqlDbType.UniqueIdentifier, // right here
Value = guid
}
}
})
{
cnx.Open();
cmd.ExecuteNonQuery();
}
}
See also: SQL Server's uniqueidentifier
class flag:
## Store pseudo-global variables here
keys=False
sword=True
torch=False
## test the flag class
print('______________________')
print(flag.keys)
print(flag.sword)
print (flag.torch)
## now change the variables
flag.keys=True
flag.sword= not flag.sword
flag.torch=True
print('______________________')
print(flag.keys)
print(flag.sword)
print (flag.torch)
It looks much like a list of Django ORM model instances.
Why not sort them on query like this:
ut = Tag.objects.order_by('-count')
I found a solution in case you have installed Eclipse(Luna) with the SVN Client JavaHL(JNI) 1.8.13 and Tortoise:
Open Eclipse: First try to add the project / maven module to Version Control (Project -> Context Menu -> Team -> Add to Version Control)
You will see the following Eclipse error message:
org.apache.subversion.javahl.ClientException: Entry already exists svn: 'PathToYouProject' is already under version control
After that you have to open your workspace directory in your explorer, select your project and resolve it via Tortoise (Project -> Context Menu -> TortoiseSVN -> Resolve)
You will see the following message dialog: "File list is empty"
Press cancel and refresh the project in Eclipse. Your project should be under version control again.
Unfortunately it is not possible to resolve more the one project at the same time ... you don't have to delete anything but depending on the size of your project it could be a little bit laborious.
To complement the existing, helpful answers; tip of the hat to QZ Support for encouraging me to post a separate answer:
Two distinct mechanisms come into play here:
(a) whether cut
itself requires the delimiter (space, in this case) passed to the -d
option to be a separate argument or whether it's acceptable to append it directly to -d
.
(b) how the shell generally parses arguments before passing them to the command being invoked.
(a) is answered by a quote from the POSIX guidelines for utilities (emphasis mine)
If the SYNOPSIS of a standard utility shows an option with a mandatory option-argument [...] a conforming application shall use separate arguments for that option and its option-argument. However, a conforming implementation shall also permit applications to specify the option and option-argument in the same argument string without intervening characters.
In other words: In this case, because -d
's option-argument is mandatory, you can choose whether to specify the delimiter as:
-d
.Once you've chosen (s) or (d), it is the shell's string-literal parsing - (b) - that matters:
With approach (s), all of the following forms are EQUIVALENT:
-d ' '
-d " "
-d \<space> # <space> used to represent an actual space for technical reasons
With approach (d), all of the following forms are EQUIVALENT:
-d' '
-d" "
"-d "
'-d '
d\<space>
The equivalence is explained by the shell's string-literal processing:
All solutions above result in the exact same string (in each group) by the time cut
sees them:
(s): cut
sees -d
, as its own argument, followed by a separate argument that contains a space char - without quotes or \
prefix!.
(d): cut
sees -d
plus a space char - without quotes or \
prefix! - as part of the same argument.
The reason the forms in the respective groups are ultimately identical is twofold, based on how the shell parses string literals:
'...'
is taken literally and forms a single argument"..."
also forms a single argument, but is subject to interpolation (expands variable references such as $var
, command substitutions ($(...)
or `...`
), or arithmetic expansions ($(( ... ))
).\
-quoting of individual characters: a \
preceding a single character causes that character to be interpreted as a literal.'...'
or "..."
or \
instances) - thus, the command being invoked never sees the quote characters.First you need to download the latest support repository (17 by the time I write this) from internal SDK manager of Android Studio or from the stand alone SDK manager. Then you can add compile 'com.android.support:appcompat-v7:23.0.0'
or any other support library you want to your build.gradle file. (Don't forget the last .0
)
BigDecimal.ZERO.setScale(2).equals(new BigDecimal("0.00"));
As documentation says:
Raised when the part of a "multipart/form-data" request identified by its name cannot be found.
This may be because the request is not a multipart/form-data either because the part is not present in the request, or because the web application is not configured correctly for processing multipart requests -- e.g. no MultipartResolver.
For CURLOPT_POSTFIELDS
, the parameters can either be passed as a urlencoded string like para1=val1¶2=val2&..
or as an array with the field name as key and field data as value
Try the following format :
$data = json_encode(array(
"first" => "John",
"last" => "Smith"
));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);
In case you want to add the URL parameter in JavaScript, see this answer. As suggested there, you can use the URLSeachParams
API in modern browsers as follows:
<script>
function addUrlParameter(name, value) {
var searchParams = new URLSearchParams(window.location.search)
searchParams.set(name, value)
window.location.search = searchParams.toString()
}
</script>
<body>
...
<a onclick="addUrlParameter('like', 'like')">Like this page</a>
...
</body>
using System;
using System.Collections.Generic; (???????? ?????????? ?? ?? ?????
using System.Linq; ?????? PlayerScript.health =
using System.Text; 999999; ??? ?? ???? ??????)
using System.Threading.Tasks;
using UnityEngine;
namespace OneHack
{
public class One
{
public Rect RT_MainMenu = new Rect(0f, 100f, 120f, 100f); //Rect ??? ????????????????? ???? ?? x,y ? ??????, ??????.
public int ID_RTMainMenu = 1;
private bool MainMenu = true;
private void Menu_MainMenu(int id) //??????? ????
{
if (GUILayout.Button("???????? ????? ??????", new GUILayoutOption[0]))
{
if (GUILayout.Button("??????????", new GUILayoutOption[0]))
{
PlayerScript.health = 999999;//??? ??????? ?? ?????? ? ?????? ??????????????? ???????? 999999 //????? ???, ??????? ????? ??????????? ??? ??????? ?? ??? ??????
}
}
}
private void OnGUI()
{
if (this.MainMenu)
{
this.RT_MainMenu = GUILayout.Window(this.ID_RTMainMenu, this.RT_MainMenu, new GUI.WindowFunction(this.Menu_MainMenu), "MainMenu", new GUILayoutOption[0]);
}
}
private void Update() //????????? ??????????? ?????, ??? ??? ????? ????? ????????? ????? ??????????? ??????????
{
if (Input.GetKeyDown(KeyCode.Insert)) //?????? ?? ??????? ????? ??????????? ? ??????????? ????, ????? ????????? ??????
{
this.MainMenu = !this.MainMenu;
}
}
}
}
comment on the "private constructor" arguments: come on, developers are not that stupid; but they ARE lazy. creating an object then call static methods? not gonna happen.
don't spend too much time to make sure your class cannot be misused. have some faith for your colleagues. and there is always a way to misuse your class no matter how you protect it. the only thing that cannot be misused is a thing that is completely useless.
There could be multiple reasons, i fixed with following steps:
save changes and relaunch the eclipse..!! it should work.
You don't need two JScrollPanes
.
Example:
JTextArea ta = new JTextArea();
JScrollPane sp = new JScrollPane(ta);
// Add the scroll pane into the content pane
JFrame f = new JFrame();
f.getContentPane().add(sp);
You should take a look to a similar question in Default behavior of "git push" without a branch specified
Basically it explains how to set the default behavior to push your current branch just executing git push
. Probably what you need is:
git config --global push.default current
Other options:
Go to the file location where the POM is stored and open cmd. Then type "mvn --v" to check the maven version and java runtime provided. Check runtime attribute and if it is "C:\Program Files\Java\jre1.8.0_191" or even close to a JRE, go to environment variables and add a new "system variable" called "JAVA_HOME" with a value "C:\Program Files\Java\jdk1.8.0_191".
Reopen the cmd and then "clean install" the project.
For me the solution was cleaning and rebuilding the Test Project
Build > Clean
Build > Build
I haven't read that in the answers above, that's why I add it :)
You might also want to check your server configuration - sometimes the default for development type servers is to only accept connections from localhost.
Similarly to the approved answer. If you want to create an array from dictionary keys:
np.array( tuple(dict.keys()) )
If you want to create an array from dictionary values:
np.array( tuple(dict.values()) )
You can use res.render() or res.redirect() method to redirect to another page using node.js express
Eg:
var bodyParser = require('body-parser');
var express = require('express');
var navigator = require('web-midi-api');
var app = express();
app.use(express.static(__dirname + '/'));
app.use(bodyParser.urlencoded({extend:true}));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);
app.get('/', function(req, res){
res.render("index");
});
//This reponds a post request for the login page
app.post('/login', function (req, res) {
console.log("Got a POST request for the login");
var data = {
"email": req.body.email,
"password": req.body.password
};
console.log(data);
//Data insertion code
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("college");
var query = { email: data.email };
dbo.collection("user").find(query).toArray(function(err, result) {
if (err) throw err;
console.log(result);
if(result[0].password == data.password)
res.redirect('dashboard.html');
else
res.redirect('login-error.html');
db.close();
});
});
});
// This responds a POST request for the add user
app.post('/insert', function (req, res) {
console.log("Got a POST request for the add user");
var data = {
"first_name" : req.body.firstName,
"second_name" : req.body.secondName,
"organization" : req.body.organization,
"email": req.body.email,
"mobile" : req.body.mobile,
};
console.log(data);
**res.render('success.html',{email:data.email,password:data.password});**
});
//make sure that Service Workers are supported.
if (navigator.serviceWorker) {
navigator.serviceWorker.register('service-worker.js', {scope: '/'})
.then(function (registration) {
console.log(registration);
})
.catch(function (e) {
console.error(e);
})
} else {
console.log('Service Worker is not supported in this browser.');
}
// TODO add service worker code here
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('service-worker.js')
.then(function() { console.log('Service Worker Registered'); });
}
var server = app.listen(63342, function () {
var host = server.address().host;
var port = server.address().port;
console.log("Example app listening at http://localhost:%s", port)
});
Here in the login section, If the email and password matches in the database then the site is directed to dashbaord.html otherwise we will show page-error.html using res.redirect() method. Also you can use res.render() to render a page in node.js
I've checked DamienG's answer in LinqPad. Instead of
g.Group.Max(s => s.uid)
should be
g.Max(s => s.uid)
Thank you!
My favorite way to do this is with an extension function called 'Map':
public static void Map<T>(this IEnumerable<T> source, Action<T> func)
{
foreach (T i in source)
func(i);
}
Then you can add all the rows like so:
X.Map(item => this.dataGridView1.Rows.Add(item.ID, item.Name));
1) You can use standard java utility xjc - ([your java home dir]\bin\xjc.exe). But you need to create .bat (or .sh) script for using it.
e.g. generate.bat:
[your java home dir]\bin\xjc.exe %1 %2 %3
e.g. test-scheme.xsd:
<?xml version="1.0"?>
<xs:schema version="1.0"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
targetNamespace="http://myprojects.net/xsd/TestScheme"
xmlns="http://myprojects.net/xsd/TestScheme">
<xs:element name="employee" type="PersonInfoType"/>
<xs:complexType name="PersonInfoType">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
Run .bat file with parameters: generate.bat test-scheme.xsd -d [your src dir]
For more info use this documentation - http://docs.oracle.com/javaee/5/tutorial/doc/bnazg.html
and this - http://docs.oracle.com/javase/6/docs/technotes/tools/share/xjc.html
2) JAXB (xjc utility) is installed together with JDK6 by default.
The <button>
element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
<button type="button">
to override default submission behaviorevent.preventDefault()
in the onSubmit event to prevent form submissionInsert extra type
attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
In this improvement, we listen to the submit event emitted from the <form>
element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
.serialize()
to serialize your form, but remember to add name
attributes to your input:The name
attribute is required for .serialize()
to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
you can try this code to solve your problem
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/login_selected" /> <!-- pressed -->
<item android:state_focused="true"
android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
<item android:drawable="@drawable/login" /> <!-- default -->
</selector>
write this code in your drawable make a new resource and name it what you want and then write the name of this drwable in the button same as we refer to image src in android
In my case the database was running on non standard port. Check that the port you are connecting is the same as the port the database is running on. If there are more instances of SQL server, check the correct one.
I tried to improve the code a bit:
public T LoadEnum<T>(string value, T defaultValue = default(T)) where T : struct, IComparable, IFormattable, IConvertible
{
if (Enum.IsDefined(typeof(T), value))
{
return (T)Enum.Parse(typeof(T), value, true);
}
return defaultValue;
}
I will recommended best answer as
<?php
echo 'Hello ' . htmlspecialchars($_GET["name"]) . '!';
?>
Assuming the user entered http://example.com/?name=Hannes
The above example will output:
Hello Hannes!
An easy way to see all the properties on a particular DOM node in Chrome (I'm on v.69) is to right click on the element, select inspect, and then instead of viewing the "Style" tab click on "Properties".
Inside of the Properties tab you will see all the properties for your particular element.
I think you want this:
select *
from dbo.table
where DATALENGTH(column_name) = 3
To check if one or more columns all exist, you can use set.issubset
, as in:
if set(['A','C']).issubset(df.columns):
df['sum'] = df['A'] + df['C']
As @brianpck points out in a comment, set([])
can alternatively be constructed with curly braces,
if {'A', 'C'}.issubset(df.columns):
See this question for a discussion of the curly-braces syntax.
Or, you can use a list comprehension, as in:
if all([item in df.columns for item in ['A','C']]):
myList[1] is an element of myList and it's type is string.
myList[1] is str, you can not append to it. myList is a list, you should have been appending to it.
>>> myList = [1, 'from form', [1,2]]
>>> myList[1]
'from form'
>>> myList[2]
[1, 2]
>>> myList[2].append('t')
>>> myList
[1, 'from form', [1, 2, 't']]
>>> myList[1].append('t')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'
>>>
Please Note: The following answer only applied to WPF under the 3.5 Framework as NET 4.0 runtime has it's own datetime control.
By default WPF 3.5 does not come with a date time picker like winforms.
However a date picker has been added in the WPF tool kit produced by Microsoft which can be downloaded here. I guess it will become part of the framework in a future release.
It is simple to add a reference to the WPFToolkit.dll, see it in the tool box and distribute with your application by following the instructions on the website.
Before this was available other people had created 3rd party pickers (which you may prefer) or alternatively used the less ideal solution of using the winforms control in a WPF application.
Update: This so question is very similar this one which also has a link to a walk through for the datepicker along with other links.
Yes, once you have joined the iPhone Developer Program, and paid Apple $99, you can provision your applications on up to 100 iOS devices.
Detach
is unnecessary.
The answer (as of 2013) is simple:
$('#parentNode').append($('#childNode'));
According to http://api.jquery.com/append/
You can also select an element on the page and insert it into another:
$('.container').append($('h2'));
If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned).
To get ride of all Unnamed columns, you can also use regex such as df.drop(df.filter(regex="Unname"),axis=1, inplace=True)
Grinn / ThePirat solution works well.
I did not like that it new'd the Include method on bundle, and that it created temporary files in the content directory. (they ended up getting checked in, deployed, then the service wouldn't start!)
So to follow the design of Bundling, I elected to perform essentially the same code, but in an IBundleTransform implementation::
class StyleRelativePathTransform
: IBundleTransform
{
public StyleRelativePathTransform()
{
}
public void Process(BundleContext context, BundleResponse response)
{
response.Content = String.Empty;
Regex pattern = new Regex(@"url\s*\(\s*([""']?)([^:)]+)\1\s*\)", RegexOptions.IgnoreCase);
// open each of the files
foreach (FileInfo cssFileInfo in response.Files)
{
if (cssFileInfo.Exists)
{
// apply the RegEx to the file (to change relative paths)
string contents = File.ReadAllText(cssFileInfo.FullName);
MatchCollection matches = pattern.Matches(contents);
// Ignore the file if no match
if (matches.Count > 0)
{
string cssFilePath = cssFileInfo.DirectoryName;
string cssVirtualPath = context.HttpContext.RelativeFromAbsolutePath(cssFilePath);
foreach (Match match in matches)
{
// this is a path that is relative to the CSS file
string relativeToCSS = match.Groups[2].Value;
// combine the relative path to the cssAbsolute
string absoluteToUrl = Path.GetFullPath(Path.Combine(cssFilePath, relativeToCSS));
// make this server relative
string serverRelativeUrl = context.HttpContext.RelativeFromAbsolutePath(absoluteToUrl);
string quote = match.Groups[1].Value;
string replace = String.Format("url({0}{1}{0})", quote, serverRelativeUrl);
contents = contents.Replace(match.Groups[0].Value, replace);
}
}
// copy the result into the response.
response.Content = String.Format("{0}\r\n{1}", response.Content, contents);
}
}
}
}
And then wrapped this up in a Bundle Implemetation:
public class StyleImagePathBundle
: Bundle
{
public StyleImagePathBundle(string virtualPath)
: base(virtualPath)
{
base.Transforms.Add(new StyleRelativePathTransform());
base.Transforms.Add(new CssMinify());
}
public StyleImagePathBundle(string virtualPath, string cdnPath)
: base(virtualPath, cdnPath)
{
base.Transforms.Add(new StyleRelativePathTransform());
base.Transforms.Add(new CssMinify());
}
}
Sample Usage:
static void RegisterBundles(BundleCollection bundles)
{
...
bundles.Add(new StyleImagePathBundle("~/bundles/Bootstrap")
.Include(
"~/Content/css/bootstrap.css",
"~/Content/css/bootstrap-responsive.css",
"~/Content/css/jquery.fancybox.css",
"~/Content/css/style.css",
"~/Content/css/error.css",
"~/Content/validation.css"
));
Here is my extension method for RelativeFromAbsolutePath:
public static string RelativeFromAbsolutePath(this HttpContextBase context, string path)
{
var request = context.Request;
var applicationPath = request.PhysicalApplicationPath;
var virtualDir = request.ApplicationPath;
virtualDir = virtualDir == "/" ? virtualDir : (virtualDir + "/");
return path.Replace(applicationPath, virtualDir).Replace(@"\", "/");
}
By just entering swift command in the terminal, it will show the version, while logging to Swift console.(something like below)
System-IOSs-MacBook-Air:~ system$ swift
Welcome to Apple Swift version 5.1 (swiftlang-1100.0.270.13 clang-1100.0.33.7).
Type :help for assistance.
Memoization is keeping the results of expensive calculations and returning the cached result rather than continuously recalculating it.
Here's an example:
def doSomeExpensiveCalculation(self, input):
if input not in self.cache:
<do expensive calculation>
self.cache[input] = result
return self.cache[input]
A more complete description can be found in the wikipedia entry on memoization.
OK, here's my best pseudo math:
The equation for your line is:
Y = a + bX
Where:
b = (sum(x*y) - sum(x)sum(y)/n) / (sum(x^2) - sum(x)^2/n)
a = sum(y)/n - b(sum(x)/n)
Where sum(xy) is the sum of all x*y etc. Not particularly clear I concede, but it's the best I can do without a sigma symbol :)
... and now with added Sigma
b = (Σ(xy) - (ΣxΣy)/n) / (Σ(x^2) - (Σx)^2/n)
a = (Σy)/n - b((Σx)/n)
Where Σ(xy) is the sum of all x*y etc. and n is the number of points
the simple way I found out: add a "li" tag on the right side of an "a" tag List item
<li></span><a><span id="expand1"></span></a></li>
On CSS file create this below:
#expand1 {
padding-left: 40px;
}
Without any deep knowledge of the mySQL engine, I'd say this sounds like a memory saving strategy. I assume the reason is behind this paragraph from the docs:
Each BLOB or TEXT value is represented internally by a separately allocated object. This is in contrast to all other data types, for which storage is allocated once per column when the table is opened.
It seems like pre-filling these column types would lead to memory usage and performance penalties.
I think Regex is the most flexible and solid way:
var str = "This is my string"
let regex = try! NSRegularExpression(pattern: " ", options: [])
let output = regex.stringByReplacingMatchesInString(
str,
options: [],
range: NSRange(location: 0, length: str.characters.count),
withTemplate: "+"
)
// output: "This+is+my+string"
Ok, personal opinion here, but Append and Prepend imply precise positions in a set.
Push and Pop are really concepts that can be applied to either end of a set... Just as long as you're consistent... For some reason, to me, Push() seems like it should apply to the front of a set...
You can also limit the filter to only part of the ip address.
E.G. To filter 123.*.*.*
you can use ip.addr == 123.0.0.0/8
. Similar effects can be achieved with /16
and /24
.
See WireShark man pages (filters) and look for Classless InterDomain Routing (CIDR) notation.
... the number after the slash represents the number of bits used to represent the network.
Yes, c++ struct is very similar to c++ class, except the fact that everything is publicly inherited, ( single / multilevel / hierarchical inheritance, but not hybrid and multiple inheritance ) here is a code for demonstration
#include<bits/stdc++.h>
using namespace std;
struct parent
{
int data;
parent() : data(3){}; // default constructor
parent(int x) : data(x){}; // parameterized constructor
};
struct child : parent
{
int a , b;
child(): a(1) , b(2){}; // default constructor
child(int x, int y) : a(x) , b(y){};// parameterized constructor
child(int x, int y,int z) // parameterized constructor
{
a = x;
b = y;
data = z;
}
child(const child &C) // copy constructor
{
a = C.a;
b = C.b;
data = C.data;
}
};
int main()
{
child c1 ,
c2(10 , 20),
c3(10 , 20, 30),
c4(c3);
auto print = [](const child &c) { cout<<c.a<<"\t"<<c.b<<"\t"<<c.data<<endl; };
print(c1);
print(c2);
print(c3);
print(c4);
}
OUTPUT
1 2 3
10 20 3
10 20 30
10 20 30
_x000D_
https://paiza.io/projects/X1QjjBkA8mDo6oVh-J_63w
Check below code for converting json to array in PHP
,
If JSON is correct then json_decode()
works well, and will return an array,
But if malformed JSON, then It will return NULL
,
<?php
function jsonDecode1($json){
$arr = json_decode($json, true);
return $arr;
}
// In case of malformed JSON, it will return NULL
var_dump( jsonDecode1($json) );
If malformed JSON, and you are expecting only array, then you can use this function,
<?php
function jsonDecode2($json){
$arr = (array) json_decode($json, true);
return $arr;
}
// In case of malformed JSON, it will return an empty array()
var_dump( jsonDecode2($json) );
If malformed JSON, and you want to stop code execution, then you can use this function,
<?php
function jsonDecode3($json){
$arr = (array) json_decode($json, true);
if(empty(json_last_error())){
return $arr;
}
else{
throw new ErrorException( json_last_error_msg() );
}
}
// In case of malformed JSON, Fatal error will be generated
var_dump( jsonDecode3($json) );
You can use any function depends on your requirement,
Here is another REST-only working example for Google Service Accounts accessing G Suite Users and Groups, authenticating through JWT. This was only possible through reflection of Google libraries, since Google documentation of these APIs are beyond terrible. Anyone used to code in MS technologies will have a hard time figuring out how everything goes together in Google services.
$iss = "<name>@<serviceaccount>.iam.gserviceaccount.com"; # The email address of the service account.
$sub = "[email protected]"; # The user to impersonate (required).
$scope = "https://www.googleapis.com/auth/admin.directory.user.readonly https://www.googleapis.com/auth/admin.directory.group.readonly";
$certPath = "D:\temp\mycertificate.p12";
$grantType = "urn:ietf:params:oauth:grant-type:jwt-bearer";
# Auxiliary functions
function UrlSafeEncode([String] $Data) {
return $Data.Replace("=", [String]::Empty).Replace("+", "-").Replace("/", "_");
}
function UrlSafeBase64Encode ([String] $Data) {
return (UrlSafeEncode -Data ([Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Data))));
}
function KeyFromCertificate([System.Security.Cryptography.X509Certificates.X509Certificate2] $Certificate) {
$privateKeyBlob = $Certificate.PrivateKey.ExportCspBlob($true);
$key = New-Object System.Security.Cryptography.RSACryptoServiceProvider;
$key.ImportCspBlob($privateKeyBlob);
return $key;
}
function CreateSignature ([Byte[]] $Data, [System.Security.Cryptography.X509Certificates.X509Certificate2] $Certificate) {
$sha256 = [System.Security.Cryptography.SHA256]::Create();
$key = (KeyFromCertificate $Certificate);
$assertionHash = $sha256.ComputeHash($Data);
$sig = [Convert]::ToBase64String($key.SignHash($assertionHash, "2.16.840.1.101.3.4.2.1"));
$sha256.Dispose();
return $sig;
}
function CreateAssertionFromPayload ([String] $Payload, [System.Security.Cryptography.X509Certificates.X509Certificate2] $Certificate) {
$header = @"
{"alg":"RS256","typ":"JWT"}
"@;
$assertion = New-Object System.Text.StringBuilder;
$assertion.Append((UrlSafeBase64Encode $header)).Append(".").Append((UrlSafeBase64Encode $Payload)) | Out-Null;
$signature = (CreateSignature -Data ([System.Text.Encoding]::ASCII.GetBytes($assertion.ToString())) -Certificate $Certificate);
$assertion.Append(".").Append((UrlSafeEncode $signature)) | Out-Null;
return $assertion.ToString();
}
$baseDateTime = New-Object DateTime(1970, 1, 1, 0, 0, 0, [DateTimeKind]::Utc);
$timeInSeconds = [Math]::Truncate([DateTime]::UtcNow.Subtract($baseDateTime).TotalSeconds);
$jwtClaimSet = @"
{"scope":"$scope","email_verified":false,"iss":"$iss","sub":"$sub","aud":"https://oauth2.googleapis.com/token","exp":$($timeInSeconds + 3600),"iat":$timeInSeconds}
"@;
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certPath, "notasecret", [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable);
$jwt = CreateAssertionFromPayload -Payload $jwtClaimSet -Certificate $cert;
# Retrieve the authorization token.
$authRes = Invoke-WebRequest -Uri "https://oauth2.googleapis.com/token" -Method Post -ContentType "application/x-www-form-urlencoded" -UseBasicParsing -Body @"
assertion=$jwt&grant_type=$([Uri]::EscapeDataString($grantType))
"@;
$authInfo = ConvertFrom-Json -InputObject $authRes.Content;
$resUsers = Invoke-WebRequest -Uri "https://www.googleapis.com/admin/directory/v1/users?domain=<required_domain_name_dont_trust_google_documentation_on_this>" -Method Get -Headers @{
"Authorization" = "$($authInfo.token_type) $($authInfo.access_token)"
}
$users = ConvertFrom-Json -InputObject $resUsers.Content;
$users.users | ft primaryEmail, isAdmin, suspended;
If you have to check it out manually you can do int a = s.charAt(0)
If the value of a is between 65 to 90 it is upper case.
The WebClient class should be more than capable of handling the functionality you describe, for example:
System.Net.WebClient wc = new System.Net.WebClient();
byte[] raw = wc.DownloadData("http://www.yoursite.com/resource/file.htm");
string webData = System.Text.Encoding.UTF8.GetString(raw);
or (further to suggestion from Fredrick in comments)
System.Net.WebClient wc = new System.Net.WebClient();
string webData = wc.DownloadString("http://www.yoursite.com/resource/file.htm");
When you say it took 30 seconds, can you expand on that a little more? There are many reasons as to why that could have happened. Slow servers, internet connections, dodgy implementation etc etc.
You could go a level lower and implement something like this:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://www.yoursite.com/resource/file.htm");
using (StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream(), Encoding.UTF8))
{
streamWriter.Write(requestData);
}
string responseData = string.Empty;
HttpWebResponse httpResponse = (HttpWebResponse)webRequest.GetResponse();
using (StreamReader responseReader = new StreamReader(httpResponse.GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
}
However, at the end of the day the WebClient class wraps up this functionality for you. So I would suggest that you use WebClient and investigate the causes of the 30 second delay.
They're simply different schemes for representing Unicode characters.
Both are variable-length - UTF-16 uses 2 bytes for all characters in the basic multilingual plane (BMP) which contains most characters in common use.
UTF-8 uses between 1 and 3 bytes for characters in the BMP, up to 4 for characters in the current Unicode range of U+0000 to U+1FFFFF, and is extensible up to U+7FFFFFFF if that ever becomes necessary... but notably all ASCII characters are represented in a single byte each.
For the purposes of a message digest it won't matter which of these you pick, so long as everyone who tries to recreate the digest uses the same option.
See this page for more about UTF-8 and Unicode.
(Note that all Java characters are UTF-16 code points within the BMP; to represent characters above U+FFFF you need to use surrogate pairs in Java.)
The issue pointed in the comment is valid, so here is a different revision that's immune to that:
function show_alert() {
if(!confirm("Do you really want to do this?")) {
return false;
}
this.form.submit();
}
In Swift 2.0:
let date = NSDate()
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
let components = calendar.components([.Month, .Day], fromDate: date)
let (month, day) = (components.month, components.day)
Base URL in JavaScript
Here is simple function for your project to get base URL in JavaScript.
// base url
function base_url() {
var pathparts = location.pathname.split('/');
if (location.host == 'localhost') {
var url = location.origin+'/'+pathparts[1].trim('/')+'/'; // http://localhost/myproject/
}else{
var url = location.origin; // http://stackoverflow.com
}
return url;
}
If I understand you need following code. (passing expression lambda by parameter) The Method
public static void Method(Expression<Func<int, bool>> predicate) {
int[] number={1,2,3,4,5,6,7,8,9,10};
var newList = from x in number
.Where(predicate.Compile()) //here compile your clausuly
select x;
newList.ToList();//return a new list
}
Calling method
Method(v => v.Equals(1));
You can do the same in their class, see this is example.
public string Name {get;set;}
public static List<Class> GetList(Expression<Func<Class, bool>> predicate)
{
List<Class> c = new List<Class>();
c.Add(new Class("name1"));
c.Add(new Class("name2"));
var f = from g in c.
Where (predicate.Compile())
select g;
f.ToList();
return f;
}
Calling method
Class.GetList(c=>c.Name=="yourname");
I hope this is useful
import a_module
print(a_module.__file__)
Will actually give you the path to the .pyc file that was loaded, at least on Mac OS X. So I guess you can do:
import os
path = os.path.abspath(a_module.__file__)
You can also try:
path = os.path.dirname(a_module.__file__)
To get the module's directory.
For getting the directory 2 levels up:
import os.path as path
two_up = path.abspath(path.join(os.getcwd(),"../.."))
Since this question asked for non-Python versions, here's JavaScript:
a.methodname = function () { console.log("Yay, a new method!") }
I just wanted to point out that sometimes this error happens because a function has been used as a high order function (passed as an argument) and then the scope of this
got lost. In such cases, I would recommend passing such function bound to this
. E.g.
this.myFunction.bind(this);
Take selected value:
worksheet name = ordls
form control list box name = DEPDB1
selectvalue = ordls.Shapes("DEPDB1").ControlFormat.List(ordls.Shapes("DEPDB1").ControlFormat.Value)
// Initiate set interval and assign it to intervalListener
var intervalListener = self.setInterval(function () {someProcess()}, 1000);
function someProcess() {
console.log('someProcess() has been called');
// If some condition is true clear the interval
if (stopIntervalIsTrue) {
window.clearInterval(intervalListener);
}
}
consider $any()
<textarea (keyup)="emitWordCount($any($event))"></textarea>
If you want to upload multiple images at once you can add multiple
attribute to input.
upload multiple files: <input type="file" multiple accept='image/*'>
_x000D_
First thing to understand is that the RequestMapping#produces()
element in
@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
serves only to restrict the mapping for your request handlers. It does nothing else.
Then, given that your method has a return type of String
and is annotated with @ResponseBody
, the return value will be handled by StringHttpMessageConverter
which sets the Content-type
header to text/plain
. If you want to return a JSON string yourself and set the header to application/json
, use a return type of ResponseEntity
(get rid of @ResponseBody
) and add appropriate headers to it.
@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<String> bar() {
final HttpHeaders httpHeaders= new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>("{\"test\": \"jsonResponseExample\"}", httpHeaders, HttpStatus.OK);
}
Note that you should probably have
<mvc:annotation-driven />
in your servlet context configuration to set up your MVC configuration with the most suitable defaults.
You can never check and see if a process is running, you can only check to see if a process was running at some point in the recent past. A process is an entity that is not controlled by your application and can exit at any moment in time. There is no way to guaranteed that a process will not exit in between the check to see if it's running and the corresponding action.
The best approach is to just do the action required and catch the exception that would be thrown if the process was not running.
The DataGrid has an XAML property IsReadOnly
that you can set to true
:
<my:DataGrid
IsReadOnly="True"
/>
preferences -> mysql -> initialize database -> use legacy password encryption(instead of strong) -> entered same password
as my config.inc.php file, restarted the apache server and it worked. I was still suspicious about it so I stopped the apache and mysql server and started them again and now it's working.
You need to do two things:
ie
one.start();
one.join();
If you don't start()
it, nothing will happen - creating a Thread doesn't execute it.
If you don't join)
it, your main thread may finish and exit and the whole program exit before the other thread has been scheduled to execute. It's indeterminate whether it runs or not if you don't join it. The new thread may usually run, but may sometimes not run. Better to be certain.
This will work in Chrome
// get your input
var input = document.getElementById('txt206451');
// get it's (first) label
var label = input.labels[0];
// change it's content
label.textContent = 'thanks'
But after looking, labels doesn't seem to be widely supported..
You can use querySelector
// get txt206451's (first) label
var label = document.querySelector('label[for="txt206451"]');
// change it's content
label.textContent = 'thanks'
Cursor cursor = myDb.viewData();
if (cursor.moveToFirst()){
do {
String itemname=cursor.getString(cursor.getColumnIndex(myDb.col_2));
String price=cursor.getString(cursor.getColumnIndex(myDb.col_3));
String quantity=cursor.getString(cursor.getColumnIndex(myDb.col_4));
String table_no=cursor.getString(cursor.getColumnIndex(myDb.col_5));
}while (cursor.moveToNext());
}
cursor.requery();
This is exactly what you want
$(document).tooltip({ selector: "[title]",_x000D_
placement: "top",_x000D_
trigger: "focus",_x000D_
animation: false});
_x000D_
<form id="form">_x000D_
<label for="myinput1">Browser tooltip appears on hover but disappears on clicking the input field. But this one persists while user is typing within the field</label>_x000D_
<input id="myinput1" type="text" title="This tooltip persists" />_x000D_
<input id="myinput2" type="text" title="This one also" />_x000D_
</form>
_x000D_
[ref]
Another option, in addition to using OPENQUERY and xp_cmdshell, is to use SQLCLR (SQL Server's "CLR Integration" feature). Not only is the SQLCLR option more secure than those other two methods, but there is also the potential benefit of being able to call the stored procedure in the current session such that it would have access to any session-based objects or settings, such as:
This can be achieved by using "context connection = true;" as the ConnectionString. Just keep in mind that all other restrictions placed on T-SQL User-Defined Functions will be enforced (i.e. cannot have any side-effects).
If you use a regular connection (i.e. not using the context connection), then it will operate as an independent call, just like it does when using the OPENQUERY and xp_cmdshell methods.
HOWEVER, please keep in mind that if you will be using a function that calls a stored procedure (regardless of which of the 3 noted methods you use) in a statement that affects more than 1 row, then the behavior cannot be expected to run once per row. As @MartinSmith mentioned in a comment on @MatBailie's answer, the Query Optimizer does not guarantee either the timing or number of executions of functions. But if you are using it in a SET @Variable = function();
statement or SELECT * FROM function();
query, then it should be ok.
An example of using a .NET / C# SQLCLR user-defined function to execute a stored procedure is shown in the following article (which I wrote):
Stairway to SQLCLR Level 2: Sample Stored Procedure and Function
use this (in kotlin)
activity?.onBackPressedDispatcher?.addCallback(this, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
// in here you can do logic when backPress is clicked
}
})
i think this is the most elegant way to do it
Another option (just so you've seen it):
$(function () {
$(".inputs").click(function (e) {
alert(e.target.id);
});
});
HTH.
Assert allows you to assert a condition (post or pre) applies in your code. It's a way of documenting your intentions and having the debugger inform you with a dialog if your intention is not met.
Unlike a breakpoint, the Assert goes with your code and can be used to add additional detail about your intention.
As the whole thing is mixing up let's look at it function and code to simulate what it means consicely
The only way to get a row is via primary key
getRow(pk: PrimaryKey): Row
Primary key data structure can be this:
// If you decide your primary key is just the partition key.
class PrimaryKey(partitionKey: String)
// and in thids case
getRow(somePartitionKey): Row
However you can decide your primary key is partition key + sort key in this case:
// if you decide your primary key is partition key + sort key
class PrimaryKey(partitionKey: String, sortKey: String)
getRow(partitionKey, sortKey): Row
getMultipleRows(partitionKey): Row[]
So the bottom line:
Decided that your primary key is partition key only? get single row by partition key.
Decided that your primary key is partition key + sort key? 2.1 Get single row by (partition key, sort key) or get range of rows by (partition key)
In either way you get a single row by primary key the only question is if you defined that primary key to be partition key only or partition key + sort key
Building blocks are:
Think of Item as a row and of KV Attribute as cells in that row.
You can do (2) only if you decided that your PK is composed of (HashKey, SortKey).
More visually as its complex, the way I see it:
+----------------------------------------------------------------------------------+
|Table |
|+------------------------------------------------------------------------------+ |
||Item | |
||+-----------+ +-----------+ +-----------+ +-----------+ | |
|||primaryKey | |kv attr | |kv attr ...| |kv attr ...| | |
||+-----------+ +-----------+ +-----------+ +-----------+ | |
|+------------------------------------------------------------------------------+ |
|+------------------------------------------------------------------------------+ |
||Item | |
||+-----------+ +-----------+ +-----------+ +-----------+ +-----------+ | |
|||primaryKey | |kv attr | |kv attr ...| |kv attr ...| |kv attr ...| | |
||+-----------+ +-----------+ +-----------+ +-----------+ +-----------+ | |
|+------------------------------------------------------------------------------+ |
| |
+----------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------+
|1. Always get item by PrimaryKey |
|2. PK is (Hash,RangeKey), great get MULTIPLE Items by Hash, filter/sort by range |
|3. PK is HashKey: just get a SINGLE ITEM by hashKey |
| +--------------------------+|
| +---------------+ |getByPK => getBy(1 ||
| +-----------+ +>|(HashKey,Range)|--->|hashKey, > < or startWith ||
| +->|Composite |-+ +---------------+ |of rangeKeys) ||
| | +-----------+ +--------------------------+|
|+-----------+ | |
||PrimaryKey |-+ |
|+-----------+ | +--------------------------+|
| | +-----------+ +---------------+ |getByPK => get by specific||
| +->|HashType |-->|get one item |--->|hashKey ||
| +-----------+ +---------------+ | ||
| +--------------------------+|
+----------------------------------------------------------------------------------+
So what is happening above. Notice the following observations. As we said our data belongs to (Table, Item, KVAttribute). Then Every Item has a primary key. Now the way you compose that primary key is meaningful into how you can access the data.
If you decide that your PrimaryKey is simply a hash key then great you can get a single item out of it. If you decide however that your primary key is hashKey + SortKey then you could also do a range query on your primary key because you will get your items by (HashKey + SomeRangeFunction(on range key)). So you can get multiple items with your primary key query.
Note: I did not refer to secondary indexes.
The simplest way to install jq
and test that it works is through brew and then using the simplest filter that merely formats the JSON
brew
is the easiest way to manage packages on a mac:
brew install jq
Need brew
? Run the following command:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Failing that: instructions to install and use are on https://brew.sh/
The .
filter takes its input and produces it unchanged as output. This is the identity operator. (quote the docs)
echo '{ "name":"John", "age":31, "city":"New York" }' | jq .
The result should appear like so in your terminal:
{
"name": "John",
"age": 31,
"city": "New York"
}
Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.
In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:
CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
one int;
two int;
BEGIN
one := 1;
two := 2;
RETURN one + two;
END
$$;
SELECT somefuncname();
The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.
Since fall 2018, the subscription versions of Microsoft Excel (Office 365 / Microsoft 365 app) contain so called dynamic array functions (not yet available in Office 2016/2019 nonsubscription versions).
One of those functions is the UNIQUE
function that will deliver an array of unique values for the selected range.
Example
In the following example, the input values are in range A1:A6
. The UNIQUE
function is typed into cell C1
.
=UNIQUE(A1:A6)
As you can see, the UNIQUE
function will automatically spill over the necessary range of cells in order to show all unique values. This is indicated by the thin, blue frame around C1:C4
.
As the UNIQUE
function automatically spills over the necessary number of rows, you should leave enough space under the C1
. If there is not enough space, you will get a #SPILL
error.
If you want to reference the results of the UNIQUE
function, you can just reference the cell containing the UNIQUE
function and add a hash #
sign.
=C1#
It is also possible to check unique values in several columns. In this case, the UNIQUE function will deliver all rows where the combination of the cells within the row are unique:
If you wish to show unique columns instead of unique rows, you have to set the [by_col]
argument to TRUE
(default is FALSE
, meaning you will receive unique rows).
You can also show values that appear exactly once by setting the [exactly_once]
argument to TRUE
:
=UNIQUE(A1:A6;;TRUE)
These functions have been very helpful to me - especially in setting up subscription reports; however, I noticed when using the Last Day of Current Month function posted above, it works as long as the proceeding month has the same number of days as the current month. I have worked through and tested these modifications and hope they help other developers in the future:
Date Formulas: Find the First Day of Previous Month:
DateAdd("m", -1, DateSerial(Year(Today()), Month(Today()), 1))
Find Last Day of Previous Month:
DateSerial(Year(Today()), Month(Today()), 0)
Find First Day of Current Month:
DateSerial(Year(Today()),Month(Today()),1)
Find Last Day of Current Month:
DateSerial(Year(Today()),Month(DateAdd("m", 1, Today())),0)
Adding on to @Rob Hruska's sol, this setting in server.xml inside section works:
<Context path="" docBase="gateway" reloadable="true" override="true"> </Context>
Note: override="true" might be required in some cases.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script>
<script type="text/javascript" src="jquery-2.1.0.js"></script>
<script type="text/javascript" >
function openOnImageClick()
{
//alert("Jai Sh Raam");
// document.getElementById("images").src = "fruits.jpg";
var img = document.createElement('img');
img.setAttribute('src', 'tiger.jpg');
img.setAttribute('width', '200');
img.setAttribute('height', '150');
document.getElementById("images").appendChild(img);
}
</script>
</head>
<body>
<h1>Screen Shot View</h1>
<p>Click the Tiger to display the Image</p>
<div id="images" >
</div>
<img src="tiger.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick()" />
<img src="Logo1.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick()" />
</body>
</html>
I just found a way to get padding applied to the select input in chrome
select{
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
padding: 5px;
}
Seems to work in the current chrome 39.0.2171.71 (64-bit) and safari (I only tested this on a mac).
This seems to remove the default styling added to the select input (it also removed the drop down arrow), but allows you to then use your own styling without chrome overriding it.
I stumbled across this fix while using code from here: http://fettblog.eu/style-select-elements/
While that particular idiom is common, even more common is for people to use =
when they mean ==
. The convention when you really mean the =
is to use an extra layer of parentheses:
while ((list = list->next)) { // yes, it's an assignment
I had the same problem in Luna,
Suddenly my projects were gone in start-up.
I solved this by select Deselect working set option in the drop-down menu in Project Explorer.
Note: I post this answer even this is not a right answer for this question. Since I search for Luna and came here,while trying with discussed things I was find this solution. This may help others.
If t
is a matrix, you need to use the element-wise multiplication or exponentiation. Note the dot.
x = exp( -t.^2 )
or
x = exp( -t.*t )
An easy, loop-free alternative is to use the horizontalalignment
Text property as a keyword argument to xticks
[1]. In the below, at the commented line, I've forced the xticks
alignment to be "right".
n=5
x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Long ticklabel %i' % i for i in range(n)]
fig, ax = plt.subplots()
ax.plot(x,y, 'o-')
plt.xticks(
[0,1,2,3,4],
["this label extends way past the figure's left boundary",
"bad motorfinger", "green", "in the age of octopus diplomacy", "x"],
rotation=45,
horizontalalignment="right") # here
plt.show()
(yticks
already aligns the right edge with the tick by default, but for xticks
the default appears to be "center".)
[1] You find that described in the xticks documentation if you search for the phrase "Text properties".
Strings are immutable. string.replace
(python 2.x) or str.replace
(python 3.x) creates a new string. This is stated in the documentation:
Return a copy of string s with all occurrences of substring old replaced by new. ...
This means you have to re-allocate the set or re-populate it (re-allocating is easier with set comprehension):
new_set = {x.replace('.good', '').replace('.bad', '') for x in set1}
If you don't want to change your pattern you can use the Group Index and Length properties of a matched group.
var text = "example-123-example";
var pattern = @"-(\d+)-";
var regex = new RegEx(pattern);
var match = regex.Match(text);
var firstPart = text.Substring(0,match.Groups[1].Index);
var secondPart = text.Substring(match.Groups[1].Index + match.Groups[1].Length);
var fullReplace = firstPart + "AA" + secondPart;
A cookie is basically just an item in a dictionary. Each item has a key and a value. For authentication, the key could be something like 'username' and the value would be the username. Each time you make a request to a website, your browser will include the cookies in the request, and the host server will check the cookies. So authentication can be done automatically like that.
To set a cookie, you just have to add it to the response the server sends back after requests. The browser will then add the cookie upon receiving the response.
There are different options you can configure for the cookie server side, like expiration times or encryption. An encrypted cookie is often referred to as a signed cookie. Basically the server encrypts the key and value in the dictionary item, so only the server can make use of the information. So then cookie would be secure.
A browser will save the cookies set by the server. In the HTTP header of every request the browser makes to that server, it will add the cookies. It will only add cookies for the domains that set them. Example.com can set a cookie and also add options in the HTTP header for the browsers to send the cookie back to subdomains, like sub.example.com. It would be unacceptable for a browser to ever sends cookies to a different domain.
You could create a mutable wrapper of the primitive int and create a Set of those:
class MutableInteger
{
private int value;
public int getValue()
{
return value;
}
public void setValue(int value)
{
this.value = value;
}
}
class Test
{
public static void main(String[] args)
{
Set<MutableInteger> mySet = new HashSet<MutableInteger>();
// populate the set
// ....
for (MutableInteger integer: mySet)
{
integer.setValue(integer.getValue() + 1);
}
}
}
Of course if you are using a HashSet you should implement the hash, equals method in your MutableInteger but that's outside the scope of this answer.
I'm using mongojs, and i have this example:
db.users.findOne({'_id': db.ObjectId(user_id) }, function(err, user) {
if(err == null && user != null){
user._id.toHexString(); // I convert the objectId Using toHexString function.
}
})
I hope this help.
The 'Enter some junk value' answer didn't do the trick for me, my site was continuing to load despite the entered junk.
Instead I added the following line to the top of the .htaccess file:
deny from all
This will quickly let you know if .htaccess is being picked up or not. If the .htaccess is being used, the files in that folder won't load at all.
In PhpStorm 2019.1.3 You should add file type you want to make soft wrapping on it
go to Settings -> Editor -> General -> Soft-wrap files then add any types you want
pg_dump -t 'schema-name.table-name' --schema-only database-name
More info - in the manual.
Here's an answer, based on (and I think an improvement on) Tester101's answer, expressed as a subroutine, with the CopyFile line once instead of three times, and prepared to handle changing the file name as the copy is made (no hard-coded destination directory). I also found I had to delete the target file before copying to get this to work, but that might be a Windows 7 thing. The WScript.Echo statements are because I didn't have a debugger and can of course be removed if desired.
Sub CopyFile(SourceFile, DestinationFile)
Set fso = CreateObject("Scripting.FileSystemObject")
'Check to see if the file already exists in the destination folder
Dim wasReadOnly
wasReadOnly = False
If fso.FileExists(DestinationFile) Then
'Check to see if the file is read-only
If fso.GetFile(DestinationFile).Attributes And 1 Then
'The file exists and is read-only.
WScript.Echo "Removing the read-only attribute"
'Remove the read-only attribute
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes - 1
wasReadOnly = True
End If
WScript.Echo "Deleting the file"
fso.DeleteFile DestinationFile, True
End If
'Copy the file
WScript.Echo "Copying " & SourceFile & " to " & DestinationFile
fso.CopyFile SourceFile, DestinationFile, True
If wasReadOnly Then
'Reapply the read-only attribute
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
End If
Set fso = Nothing
End Sub
Just use = IF(A1="Bla*","YES","NO")
. When you insert the asterisk, it acts as a wild card for any amount of characters after the specified text.
I found a solution for my problem while writing my question !
Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)
I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)
So it seems the problem comes from the use of RDP (windows7 and 8)
Update 2017: Problem occurs on Windows 10 aswell.
Environment.ProcessorCount should give you the number of cores on the local machine.
If you only specify a literal, there is no difference. LEA has more abilities, though, and you can read about them here:
http://www.oopweb.com/Assembly/Documents/ArtOfAssembly/Volume/Chapter_6/CH06-1.html#HEADING1-136
dgg
will delete everything from your current line to the top of the file.
d
is the deletion command, and gg
is a movement command that says go to the top of the file, so when used together, it means delete from my current position to the top of the file.
Also
dG
will delete all lines at or below the current one
The first and the last, at least, are possible using the following syntax:
String.Format("{0,20}", "String goes here");
String.Format("{0,-20}", "String goes here");
you have to use the To_Date() function to convert the string to date ! http://www.techonthenet.com/oracle/functions/to_date.php
You can store images in MySQL as blobs. However, this is problematic for a couple of reasons:
Instead, consider updating your table to add an image_path field. For example:
ALTER TABLE `your_table`
ADD COLUMN `image_path` varchar(1024)
Then store your images on disk, and update the table with the image path. When you need to use the images, retrieve them from disk using the path specified.
An advantageous side-effect of this approach is that the images do not necessarily be stored on disk; you could just as easily store a URL instead of an image path, and retrieve images from any internet-connected location.
You'll normally be returning JSON either because:
A) You are building part / all of your application as a Single Page Application (SPA) and you need your client-side JavaScript to be able to pull in additional data without fully reloading the page.
or
B) You are building an API that third parties will be consuming and you have decided to use JSON to serialize your data.
Or, possibly, you are eating your own dogfood and doing both
In both cases render :json => some_data
will JSON-ify the provided data. The :callback
key in the second example needs a bit more explaining (see below), but it is another variation on the same idea (returning data in a way that JavaScript can easily handle.)
:callback
?JSONP (the second example) is a way of getting around the Same Origin Policy that is part of every browser's built-in security. If you have your API at api.yoursite.com
and you will be serving your application off of services.yoursite.com
your JavaScript will not (by default) be able to make XMLHttpRequest
(XHR - aka ajax) requests from services
to api
. The way people have been sneaking around that limitation (before the Cross-Origin Resource Sharing spec was finalized) is by sending the JSON data over from the server as if it was JavaScript instead of JSON). Thus, rather than sending back:
{"name": "John", "age": 45}
the server instead would send back:
valueOfCallbackHere({"name": "John", "age": 45})
Thus, a client-side JS application could create a script
tag pointing at api.yoursite.com/your/endpoint?name=John
and have the valueOfCallbackHere
function (which would have to be defined in the client-side JS) called with the data from this other origin.)
Here's an updated answer for Angular 4 & 5. TransformRequest and angular.identity were dropped. I've also included the ability to combine files with JSON data in one request.
Angular 5 Solution:
import {HttpClient} from '@angular/common/http';
uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
// Note that setting a content-type header
// for mutlipart forms breaks some built in
// request parsers like multer in express.
const options = {} as any; // Set any options you like
const formData = new FormData();
// Append files to the virtual form.
for (const file of files) {
formData.append(file.name, file)
}
// Optional, append other kev:val rest data to the form.
Object.keys(restObj).forEach(key => {
formData.append(key, restObj[key]);
});
// Send it.
return this.httpClient.post(uploadUrl, formData, options)
.toPromise()
.catch((e) => {
// handle me
});
}
Angular 4 Solution:
// Note that these imports below are deprecated in Angular 5
import {Http, RequestOptions} from '@angular/http';
uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
// Note that setting a content-type header
// for mutlipart forms breaks some built in
// request parsers like multer in express.
const options = new RequestOptions();
const formData = new FormData();
// Append files to the virtual form.
for (const file of files) {
formData.append(file.name, file)
}
// Optional, append other kev:val rest data to the form.
Object.keys(restObj).forEach(key => {
formData.append(key, restObj[key]);
});
// Send it.
return this.http.post(uploadUrl, formData, options)
.toPromise()
.catch((e) => {
// handle me
});
}
For python 3
First install module:
pip3 install gitpython
and later, code it :)
import os
from git.repo.base import Repo
Repo.clone_from("https://github.com/*****", "folderToSave")
I hope this helps you
In short:
Explanation:
Prebuilt OpenJDK (or distribution) — binaries, built from http://hg.openjdk.java.net/, provided as an archive or installer, offered for various platforms, with a possible support contract.
OpenJDK, the source repository (also called OpenJDK project) - is a Mercurial-based open source repository, hosted at http://hg.openjdk.java.net. The Java source code. The vast majority of Java features (from the VM and the core libraries to the compiler) are based solely on this source repository. Oracle have an alternate fork of this.
OpenJDK, the distribution (see the list of providers below) - is free as in beer and kind of free as in speech, but, you do not get to call Oracle if you have problems with it. There is no support contract. Furthermore, Oracle will only release updates to any OpenJDK (the distribution) version if that release is the most recent Java release, including LTS (long-term support) releases. The day Oracle releases OpenJDK (the distribution) version 12.0, even if there's a security issue with OpenJDK (the distribution) version 11.0, Oracle will not release an update for 11.0. Maintained solely by Oracle.
Some OpenJDK projects - such as OpenJDK 8 and OpenJDK 11 - are maintained by the OpenJDK community and provide releases for some OpenJDK versions for some platforms. The community members have taken responsibility for releasing fixes for security vulnerabilities in these OpenJDK versions.
AdoptOpenJDK, the distribution is very similar to Oracle's OpenJDK distribution (in that it is free, and it is a build produced by compiling the sources from the OpenJDK source repository). AdoptOpenJDK as an entity will not be backporting patches, i.e. there won't be an AdoptOpenJDK 'fork/version' that is materially different from upstream (except for some build script patches for things like Win32 support). Meaning, if members of the community (Oracle or others, but not AdoptOpenJDK as an entity) backport security fixes to updates of OpenJDK LTS versions, then AdoptOpenJDK will provide builds for those. Maintained by OpenJDK community.
OracleJDK - is yet another distribution. Starting with JDK12 there will be no free version of OracleJDK. Oracle's JDK distribution offering is intended for commercial support. You pay for this, but then you get to rely on Oracle for support. Unlike Oracle's OpenJDK offering, OracleJDK comes with longer support for LTS versions. As a developer you can get a free license for personal/development use only of this particular JDK, but that's mostly a red herring, as 'just the binary' is basically the same as the OpenJDK binary. I guess it means you can download security-patched versions of LTS JDKs from Oracle's websites as long as you promise not to use them commercially.
Note. It may be best to call the OpenJDK builds by Oracle the "Oracle OpenJDK builds".
Donald Smith, Java product manager at Oracle writes:
Ideally, we would simply refer to all Oracle JDK builds as the "Oracle JDK", either under the GPL or the commercial license, depending on your situation. However, for historical reasons, while the small remaining differences exist, we will refer to them separately as Oracle’s OpenJDK builds and the Oracle JDK.
---------------------------------------------------------------------------------------- | Provider | Free Builds | Free Binary | Extended | Commercial | Permissive | | | from Source | Distributions | Updates | Support | License | |--------------------------------------------------------------------------------------| | AdoptOpenJDK | Yes | Yes | Yes | No | Yes | | Amazon – Corretto | Yes | Yes | Yes | No | Yes | | Azul Zulu | No | Yes | Yes | Yes | Yes | | BellSoft Liberica | No | Yes | Yes | Yes | Yes | | IBM | No | No | Yes | Yes | Yes | | jClarity | No | No | Yes | Yes | Yes | | OpenJDK | Yes | Yes | Yes | No | Yes | | Oracle JDK | No | Yes | No** | Yes | No | | Oracle OpenJDK | Yes | Yes | No | No | Yes | | ojdkbuild | Yes | Yes | No | No | Yes | | RedHat | Yes | Yes | Yes | Yes | Yes | | SapMachine | Yes | Yes | Yes | Yes | Yes | ----------------------------------------------------------------------------------------
Free Builds from Source - the distribution source code is publicly available and one can assemble its own build
Free Binary Distributions - the distribution binaries are publicly available for download and usage
Extended Updates - aka LTS (long-term support) - Public Updates beyond the 6-month release lifecycle
Commercial Support - some providers offer extended updates and customer support to paying customers, e.g. Oracle JDK (support details)
Permissive License - the distribution license is non-protective, e.g. Apache 2.0
In the Sun/Oracle days, it was usually Sun/Oracle producing the proprietary downstream JDK distributions based on OpenJDK sources. Recently, Oracle had decided to do their own proprietary builds only with the commercial support attached. They graciously publish the OpenJDK builds as well on their https://jdk.java.net/ site.
What is happening starting JDK 11 is the shift from single-vendor (Oracle) mindset to the mindset where you select a provider that gives you a distribution for the product, under the conditions you like: platforms they build for, frequency and promptness of releases, how support is structured, etc. If you don't trust any of existing vendors, you can even build OpenJDK yourself.
Each build of OpenJDK is usually made from the same original upstream source repository (OpenJDK “the project”). However each build is quite unique - $free or commercial, branded or unbranded, pure or bundled (e.g., BellSoft Liberica JDK offers bundled JavaFX, which was removed from Oracle builds starting JDK 11).
If no environment (e.g., Linux) and/or license requirement defines specific distribution and if you want the most standard JDK build, then probably the best option is to use OpenJDK by Oracle or AdoptOpenJDK.
Additional information
Time to look beyond Oracle's JDK by Stephen Colebourne
Java Is Still Free by Java Champions community (published on September 17, 2018)
Java is Still Free 2.0.0 by Java Champions community (published on March 3, 2019)
Aleksey Shipilev about JDK updates interview by Opsian (published on June 27, 2019)
function slugify(text){
return text.toString().toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\u0100-\uFFFF\w\-]/g,'-') // Remove all non-word chars ( fix for UTF-8 chars )
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
}
*based on https://gist.github.com/mathewbyrne/1280286
now you can transform this string:
Barack_Obama ?????_????? ~!@#$%^&*()+/-+?><:";'{}[]\|`
into:
barack_obama-?????_?????
applying to your code:
$("#Restaurant_Name").keyup(function(){
var Text = $(this).val();
Text = slugify(Text);
$("#Restaurant_Slug").val(Text);
});
I referred a blog by Kim for doing this and its working fine for me. See the blog
The automated execution of macro can be accomplished with the help of a VB Script file which is being invoked by Windows Task Scheduler at specified times.
Remember to replace 'YourWorkbook' with the name of the workbook you want to open and replace 'YourMacro' with the name of the macro you want to run.
See the VB Script File (just named it RunExcel.VBS):
' Create a WshShell to get the current directory
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
' Create an Excel instance
Dim myExcelWorker
Set myExcelWorker = CreateObject("Excel.Application")
' Disable Excel UI elements
myExcelWorker.DisplayAlerts = False
myExcelWorker.AskToUpdateLinks = False
myExcelWorker.AlertBeforeOverwriting = False
myExcelWorker.FeatureInstall = msoFeatureInstallNone
' Tell Excel what the current working directory is
' (otherwise it can't find the files)
Dim strSaveDefaultPath
Dim strPath
strSaveDefaultPath = myExcelWorker.DefaultFilePath
strPath = WshShell.CurrentDirectory
myExcelWorker.DefaultFilePath = strPath
' Open the Workbook specified on the command-line
Dim oWorkBook
Dim strWorkerWB
strWorkerWB = strPath & "\YourWorkbook.xls"
Set oWorkBook = myExcelWorker.Workbooks.Open(strWorkerWB)
' Build the macro name with the full path to the workbook
Dim strMacroName
strMacroName = "'" & strPath & "\YourWorkbook" & "!Sheet1.YourMacro"
on error resume next
' Run the calculation macro
myExcelWorker.Run strMacroName
if err.number <> 0 Then
' Error occurred - just close it down.
End If
err.clear
on error goto 0
oWorkBook.Save
myExcelWorker.DefaultFilePath = strSaveDefaultPath
' Clean up and shut down
Set oWorkBook = Nothing
' Don’t Quit() Excel if there are other Excel instances
' running, Quit() will shut those down also
if myExcelWorker.Workbooks.Count = 0 Then
myExcelWorker.Quit
End If
Set myExcelWorker = Nothing
Set WshShell = Nothing
You can test this VB Script from command prompt:
>> cscript.exe RunExcel.VBS
Once you have the VB Script file and workbook tested so that it does what you want, you can then use Microsoft Task Scheduler (Control Panel-> Administrative Tools--> Task Scheduler) to execute ‘cscript.exe RunExcel.vbs’ automatically for you.
Please note the path of the macro should be in correct format and inside single quotes like:
strMacroName = "'" & strPath & "\YourWorkBook.xlsm'" &
"!ModuleName.MacroName"
It's not totally clear from your question, but I'm assuming you saying that you have a file where each line of that file is a filename. And each filename is something like this:
\u0048\u0065\u006C\u006C\u006F
In other words, the characters in the file of filenames are \
, u
, 0
, 0
, 4
, 8
and so on.
If so, what you're seeing is expected. Java only translates \uXXXX
sequences in string literals in source code (and when reading in stored Properties
objects). When you read the contents you file you will have a string consisting of the characters \
, u
, 0
, 0
, 4
, 8
and so on and not the string Hello
.
So you will need to parse that string to extract the 0048
, 0065
, etc. pieces and then convert them to char
s and make a string from those char
s and then pass that string to the routine that opens the file.
Use PHP Manual - parse_url() to get the parts you need.
Edit (example usage for @Navi Gamage)
You can use it like this:
<?php
function reconstruct_url($url){
$url_parts = parse_url($url);
$constructed_url = $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'];
return $constructed_url;
}
?>
Edit (second full example):
Updated function to make sure scheme will be attached and none notice msgs appear:
function reconstruct_url($url){
$url_parts = parse_url($url);
$constructed_url = $url_parts['scheme'] . '://' . $url_parts['host'] . (isset($url_parts['path'])?$url_parts['path']:'');
return $constructed_url;
}
$test = array(
'http://www.mydomian.com/myurl.html?unwan=abc',
'http://www.mydomian.com/myurl.html',
'http://www.mydomian.com',
'https://mydomian.com/myurl.html?unwan=abc&ab=1'
);
foreach($test as $url){
print_r(parse_url($url));
}
Will return:
Array
(
[scheme] => http
[host] => www.mydomian.com
[path] => /myurl.html
[query] => unwan=abc
)
Array
(
[scheme] => http
[host] => www.mydomian.com
[path] => /myurl.html
)
Array
(
[scheme] => http
[host] => www.mydomian.com
)
Array
(
[path] => mydomian.com/myurl.html
[query] => unwan=abc&ab=1
)
This is the output from passing example urls through parse_url() with no second parameter (for explanation only).
And this is the final output after constructing url using:
foreach($test as $url){
echo reconstruct_url($url) . '<br/>';
}
Output:
http://www.mydomian.com/myurl.html
http://www.mydomian.com/myurl.html
http://www.mydomian.com
https://mydomian.com/myurl.html
if (listView1.Items.Count > 0)
{
listView1.FocusedItem = listView1.Items[0];
listView1.Items[0].Selected = true;
listView1.Select();
}
Try this:
public static void main(String[] args) {
String str = "My name is Milan, people know me as Milan Vasic.";
Pattern p = Pattern.compile("(Milan)(?! Vasic)");
Matcher m = p.matcher(str);
StringBuffer sb = new StringBuffer();
while(m.find()) {
m.appendReplacement(sb, "Milan Vasic");
}
m.appendTail(sb);
System.out.println(sb);
}
I came across same issue. And my parameter was having null value. So I resolved by handling null value. If someone is not sure runtime value and want to handle null then simply use this. (And you don't want to change the SP/function.) E.g.
sp.Value = Template ?? (object)DBNull.Value;
First, we need GOPATH
The $GOPATH
is a folder (or set of folders) specified by its environment variable. We must notice that this is not the $GOROOT
directory where Go is installed.
export GOPATH=$HOME/gocode
export PATH=$PATH:$GOPATH/bin
We used ~/gocode
path in our computer to store the source of our application and its dependencies. The GOPATH
directory will also store the binaries of their packages.
Then check Go env
You system must have $GOPATH
and $GOROOT
, below is my Env:
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/elpsstu/gocode"
GORACE=""
GOROOT="/home/pravin/go"
GOTOOLDIR="/home/pravin/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"
Now, you run download go package:
go get [-d] [-f] [-fix] [-t] [-u] [build flags] [packages]
Get downloads and installs the packages named by the import paths, along with their dependencies. For more details you can look here.
Set the DataGridView property
gridView1.AutoGenerateColumns = true;
And make sure the list of objects your are binding, those object properties should be public.
This is known as a fork bomb. It keeps splitting itself until there is no option but to restart the system. http://en.wikipedia.org/wiki/Fork_bomb
I suposse this is the output you need:
title,intro,tagline
2.9,Gardena,CA
It can be done with this changes to your code:
import csv
import itertools
with open('log.txt', 'r') as in_file:
lines = in_file.read().splitlines()
stripped = [line.replace(","," ").split() for line in lines]
grouped = itertools.izip(*[stripped]*1)
with open('log.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('title', 'intro', 'tagline'))
for group in grouped:
writer.writerows(group)
In my case, I have two elements with the same id
. I could not notice the cause of problem for a long time, because the first such element was hidden.
By far the simplest solution:
if id -u "$user" >/dev/null 2>&1; then
echo 'user exists'
else
echo 'user missing'
fi
The >/dev/null 2>&1
can be shortened to &>/dev/null
in Bash.
To get a type that implements io.Reader
from a []byte
slice, you can use bytes.NewReader
in the bytes
package:
r := bytes.NewReader(byteData)
This will return a value of type bytes.Reader
which implements the io.Reader
(and io.ReadSeeker
) interface.
Don't worry about them not being the same "type". io.Reader
is an interface and can be implemented by many different types. To learn a little bit more about interfaces in Go, read Effective Go: Interfaces and Types.
<script type="text/javascript">
$(document).ready(function() {
$('#upload').bind("click",function()
{
var imgVal = $('#uploadImage').val();
if(imgVal=='')
{
alert("empty input file");
}
return false;
});
});
</script>
<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload" id="upload" class="send_upload" value="upload" />
var len = $('#your_form_id input:radio:checked').length;
if (!len) {
alert("None checked");
};
alert("checked: "+ len);
Then, we have a first big problem. This is a program:
f(x) = 2 * x
g(x,y) = x / y
How can we say what is to be executed first? How can we form an ordered sequence of functions (i.e. a program) using no more than functions?
Solution: compose functions. If you want first g
and then f
, just write f(g(x,y))
. OK, but ...
More problems: some functions might fail (i.e. g(2,0)
, divide by 0). We have no "exceptions" in FP. How do we solve it?
Solution: Let's allow functions to return two kind of things: instead of having g : Real,Real -> Real
(function from two reals into a real), let's allow g : Real,Real -> Real | Nothing
(function from two reals into (real or nothing)).
But functions should (to be simpler) return only one thing.
Solution: let's create a new type of data to be returned, a "boxing type" that encloses maybe a real or be simply nothing. Hence, we can have g : Real,Real -> Maybe Real
. OK, but ...
What happens now to f(g(x,y))
? f
is not ready to consume a Maybe Real
. And, we don't want to change every function we could connect with g
to consume a Maybe Real
.
Solution: let's have a special function to "connect"/"compose"/"link" functions. That way, we can, behind the scenes, adapt the output of one function to feed the following one.
In our case: g >>= f
(connect/compose g
to f
). We want >>=
to get g
's output, inspect it and, in case it is Nothing
just don't call f
and return Nothing
; or on the contrary, extract the boxed Real
and feed f
with it. (This algorithm is just the implementation of >>=
for the Maybe
type).
Many other problems arise which can be solved using this same pattern: 1. Use a "box" to codify/store different meanings/values, and have functions like g
that return those "boxed values". 2. Have composers/linkers g >>= f
to help connecting g
's output to f
's input, so we don't have to change f
at all.
Remarkable problems that can be solved using this technique are:
having a global state that every function in the sequence of functions ("the program") can share: solution StateMonad
.
We don't like "impure functions": functions that yield different output for same input. Therefore, let's mark those functions, making them to return a tagged/boxed value: IO
monad.
Total happiness !!!!
html code here
<input id="result" style="width:300px"/>some example text
<button onclick="copyToClipboard('result')">Copy P1</button>
<input type="text" style="width:400px" placeholder="Paste here for test" />
JS CODE:
function copyToClipboard(elementId) {
// Create a "hidden" input
var aux = document.createElement("input");
aux.setAttribute("value", document.getElementById(elementId).value);
// Append it to the body
document.body.appendChild(aux);
// Highlight its content
aux.select();
// Copy the highlighted text
document.execCommand("copy");
// Remove it from the body
document.body.removeChild(aux);
}
I got the desired result by using
android:maxLines="2"
android:minLines="2"
android:ellipsize="end"
The trick is set maxLines and minLines to the same value... and Not just android:lines = "2", dosen't do the trick. Also you are avoiding any deprecated attributes.
SELECT OBJECT_NAME(fk.parent_object_id) as ReferencingTable,
OBJECT_NAME(fk.constraint_object_id) as [FKContraint]
FROM sys.foreign_key_columns as fk
WHERE fk.referenced_object_id = OBJECT_ID('ReferencedTable', 'U')
This only shows the relationship if the are foreign key constraints. My database apparently predates the FK constraint.Some table use triggers to enforce referential integrity, and sometimes there's nothing but a similarly named column to indicate the relationship (and no referential integrity at all).
Fortunately, we do have a consistent naming scene so I am able to find referencing tables and views like this:
SELECT OBJECT_NAME(object_id) from sys.columns where name like 'client_id'
I used this select as the basis for generating a script the does what I need to do on the related tables.
If you are looking for a HTTP client library in C++ that is supported in multiple platforms (Linux, Windows and Mac) for consuming Restful web services. You can have below options.
Those documents are outdated. I'm guessing the 1.6 in the URL is for Docker 1.6, not Compose 1.6. Check out the correct syntax here: https://docs.docker.com/compose/compose-file/#network_mode. You are looking for network_mode
when using the v2 YAML format.
To convert a column into a string type (that will be an object column per se in pandas), use astype
:
df.zipcode = zipcode.astype(str)
If you want to get a Categorical
column, you can pass the parameter 'category'
to the function:
df.zipcode = zipcode.astype('category')
If you are looking for ad-hoc items rather than something that you would put into SSIS. From within SSMS simply highlight the results grid, copy, then paste into excel, it isn't elegant, but works. Then you can save as native .xls rather than .csv
You need the actual instance of the WindowSettings
that's open, not a new one.
Currently, you are creating a new instance of WindowSettings
and calling Close
on that. That doesn't do anything because that new instance never has been shown.
Instead, when showing DialogSettingsCancel
set the current instance of WindowSettings
as the parent.
Something like this:
In WindowSettings
:
private void showDialogSettings_Click(object sender, EventArgs e)
{
var dialogSettingsCancel = new DialogSettingsCancel();
dialogSettingsCancel.OwningWindowSettings = this;
dialogSettingsCancel.Show();
}
In DialogSettingsCancel
:
public WindowSettings OwningWindowSettings { get; set; }
private void button1_Click(object sender, EventArgs e)
{
this.Close();
if(OwningWindowSettings != null)
OwningWindowSettings.Close();
}
This approach takes into account, that a DialogSettingsCancel
could potentially be opened without a WindowsSettings
as parent.
If the two are always connected, you should instead use a constructor parameter:
In WindowSettings
:
private void showDialogSettings_Click(object sender, EventArgs e)
{
var dialogSettingsCancel = new DialogSettingsCancel(this);
dialogSettingsCancel.Show();
}
In DialogSettingsCancel
:
WindowSettings _owningWindowSettings;
public DialogSettingsCancel(WindowSettings owningWindowSettings)
{
if(owningWindowSettings == null)
throw new ArgumentNullException("owningWindowSettings");
_owningWindowSettings = owningWindowSettings;
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
_owningWindowSettings.Close();
}
Perhaps you can do some introspection on the db file. The protocol is relatively simple (yet not well documented), so you could write a parser for it to determine which individual keys are taking up a lot of space.
New suggestions:
Have you tried using MONITOR
to see what is being written, live? Perhaps you can find the issue with the data in motion.
.class {_x000D_
display: none;_x000D_
}_x000D_
@media (min-width:400px) and (max-width:900px) {_x000D_
.class {_x000D_
display: block; /* just an example display property */_x000D_
}_x000D_
}
_x000D_
On the anaconda prompt, do a
conda -V
or conda --version
to get the conda version.python -V
or python --version
to get the python version.conda list anaconda$
to get the Anaconda version.conda list
to get the Name, Version, Build & Channel details of all the packages installed (in the current environment).conda info
to get all the current environment details.conda info --envs
To see a list of all your environmentsODBC and OLE DB are two competing data access technologies. Specifically regarding SQL Server, Microsoft has promoted both of them as their Preferred Future Direction - though at different times.
ODBC is an industry-wide standard interface for accessing table-like data. It was primarily developed for databases and presents data in collections of records, each of which is grouped into a collection of fields. Each field has its own data type suitable to the type of data it contains. Each database vendor (Microsoft, Oracle, Postgres, …) supplies an ODBC driver for their database.
There are also ODBC drivers for objects which, though they are not database tables, are sufficiently similar that accessing data in the same way is useful. Examples are spreadsheets, CSV files and columnar reports.
OLE DB is a Microsoft technology for access to data. Unlike ODBC it encompasses both table-like and non-table-like data such as email messages, web pages, Word documents and file directories. However, it is procedure-oriented rather than object-oriented and is regarded as a rather difficult interface with which to develop access to data sources. To overcome this, ADO was designed to be an object-oriented layer on top of OLE DB and to provide a simpler and higher-level – though still very powerful – way of working with it. ADO’s great advantage it that you can use it to manipulate properties which are specific to a given type of data source, just as easily as you can use it to access those properties which apply to all data source types. You are not restricted to some unsatisfactory lowest common denominator.
While all databases have ODBC drivers, they don’t all have OLE DB drivers. There is however an interface available between OLE and ODBC which can be used if you want to access them in OLE DB-like fashion. This interface is called MSDASQL (Microsoft OLE DB provider for ODBC).
Since SQL Server is (1) made by Microsoft, and (2) the Microsoft database platform, both ODBC and OLE DB are a natural fit for it.
Since all other database platforms had ODBC interfaces, Microsoft obviously had to provide one for SQL Server. In addition to this, DAO, the original default technology in Microsoft Access, uses ODBC as the standard way of talking to all external data sources. This made an ODBC interface a sine qua non. The version 6 ODBC driver for SQL Server, released with SQL Server 2000, is still around. Updated versions have been released to handle the new data types, connection technologies, encryption, HA/DR etc. that have appeared with subsequent releases. As of 09/07/2018 the most recent release is v13.1 “ODBC Driver for SQL Server”, released on 23/03/2018.
This is Microsoft’s own technology, which they were promoting strongly from about 2002 – 2005, along with its accompanying ADO layer. They were evidently hoping that it would become the data access technology of choice. (They even made ADO the default method for accessing data in Access 2002/2003.) However, it eventually became apparent that this was not going to happen for a number of reasons, such as:
For these reasons and others, Microsoft actually deprecated OLE DB as a data access technology for SQL Server releases after v11 (SQL Server 2012). For a couple of years before this point, they had been producing and updating the SQL Server Native Client, which supported both ODBC and OLE DB technologies. In late 2012 however, they announced that they would be aligning with ODBC for native relational data access in SQL Server, and encouraged everybody else to do the same. They further stated that SQL Server releases after v11/SQL Server 2012 would actively not support OLE DB!
This announcement provoked a storm of protest. People were at a loss to understand why MS was suddenly deprecating a technology that they had spent years getting them to commit to. In addition, SSAS/SSRS and SSIS, which were MS-written applications intimately linked to SQL Server, were wholly or partly dependent on OLE DB. Yet another complaint was that OLE DB had certain desirable features which it seemed impossible to port back to ODBC – after all, OLE DB had many good points.
In October 2017, Microsoft relented and officially un-deprecated OLE DB. They announced the imminent arrival of a new driver (MSOLEDBSQL) which would have the existing feature set of the Native Client 11 and would also introduce multi-subnet failover and TLS 1.2 support. The driver was released in March 2018.
This answer improves on a couple above (please vote them up), assuming that in addition to creating the one commit (no-parents no-history), you also want to retain all of the commit-data of that commit:
Of course the commit-SHA of the new/single commit will change, because it represents a new (non-)history, becoming a parentless/root-commit.
This can be done by reading git log
and setting some variables for git commit-tree
. Assuming that you want to create a single commit from master
in a new branch one-commit
, retaining the commit-data above:
git checkout -b one-commit master ## create new branch to reset
git reset --hard \
$(eval "$(git log master -n1 --format='\
COMMIT_MESSAGE="%B" \
GIT_AUTHOR_NAME="%an" \
GIT_AUTHOR_EMAIL="%ae" \
GIT_AUTHOR_DATE="%ad" \
GIT_COMMITTER_NAME="%cn" \
GIT_COMMITTER_EMAIL="%ce" \
GIT_COMMITTER_DATE="%cd"')" 'git commit-tree master^{tree} <<COMMITMESSAGE
$COMMIT_MESSAGE
COMMITMESSAGE
')
It seems people mix a content encoding with a built files/resources encoding. Having only maven properties is not enough. Having -Dfile.encoding=UTF8
not effective. To avoid having issues with encoding you should follow the following simple rules
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
Always set encoding explicitly, when work with files, strings, IO in your code. If you do not follow this rule, your application depend on the environment. The -Dfile.encoding=UTF8
exactly is responsible for run-time environment configuration, but we should not depend on it. If you have thousands of clients, it takes more effort to configure systems and to find issues because of it. You just have an additional dependency on it which you can avoid by setting it explicitly. Most methods in Java that use a default encoding are marked as deprecated because of it.
Make sure the content, you are working with, also is in the same encoding, that you expect. If it is not, the previous steps do not matter! For instance a file will not be processed correctly, if its encoding is not UTF8 but you expect it. To check file encoding on Linux:
$ file --mime F_PRDAUFT.dsv
@Produces("application/json; charset=UTF-8") @Consumes("application/json; charset=UTF-8")
Hope this will be useful to someone.
Something like this in your form main. Double click the form in the visual editor to create the form load event.
Timer Clock=new Timer();
Clock.Interval=2700000; // not sure if this length of time will work
Clock.Start();
Clock.Tick+=new EventHandler(Timer_Tick);
Then add an event handler to do something when the timer fires.
public void Timer_Tick(object sender,EventArgs eArgs)
{
if(sender==Clock)
{
// do something here
}
}
Even though this thread is old, yet I would like to share my experience (recently started working with facebook), which seems to me straight:
To get the Development key for facebook integration, use the following command from the command line in windows:
keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%.android\debug.keystore | "C:\openssl\bin\openssl.exe" sha1 -binary | "C:\openssl\bin\openssl.exe" base64
NOTE!: please replace the path for openssl.exe (in this example it is "C:\openssl\bin\openssl.exe") with your own installation path.
Enter keystore password: android
Type android as password as shown above.
Thats it! You will be given a 28 character long key. Cheers!
Use the same procedure to get the Release key. Just replace the command with the following and use your release key alias.
keytool -exportcert -alias YOUR_RELEASE_KEY_ALIAS -keystore YOUR_RELEASE_KEY_PATH | "PATH FOR openssl.exe" sha1 -binary | openssl base64
This question already had a lot of answers. Unfortunately none worked for me. So for the sake of completenes I add what helped me:
I had multiple images with the same name - so I ordered them in sub folders. And I had the full path to the image file I wanted to show. With a full path imageNamed:
(as used in all solutions above) did not work and was the wrong method.
Instead I now use imageWithContentsOfFile:
like so:
self.myUIImage.image = [UIImage imageWithContentsOfFile:_currentWord.imageFileName];
Don't know, if anyone reads that far?
If so and this one helped you: please vote up. ;-)
As always, I recommend reading this article about date and time in Java so that you understand it.
The basic idea is that 'under the hood' everything is done in UTC milliseconds since the epoch. This means it is easiest if you operate without using time zones at all, with the exception of String formatting for the user.
Therefore I would skip most of the steps you have suggested.
Alternatively, you can use Joda time. I have heard it is a much more intuitive datetime API.
try this, it work for me
<IfModule mod_rewrite.c>
# Enable Rewrite Engine
# ------------------------------
RewriteEngine On
RewriteBase /
# Redirect index.php Requests
# ------------------------------
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteCond %{THE_REQUEST} !/system/.*
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,L]
# Standard ExpressionEngine Rewrite
# ------------------------------
RewriteCond $1 !\.(css|js|gif|jpe?g|png) [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>
_x000D_