You can check the total number of arguments which are passed in command line with "$#
"
Say for Example my shell script name is hello.sh
sh hello.sh hello-world
# I am passing hello-world as argument in command line which will b considered as 1 argument
if [ $# -eq 1 ]
then
echo $1
else
echo "invalid argument please pass only one argument "
fi
Output will be hello-world
It worked using PSCP. Instructions:
set PATH=<path to the pscp.exe file>
pscp
use the following command to copy file form remote server to the local system
pscp [options] [user@]host:source target
So to copy the file /etc/hosts
from the server example.com
as user fred
to the file
c:\temp\example-hosts.txt
, you would type:
pscp [email protected]:/etc/hosts c:\temp\example-hosts.txt
Yes, you can actually with CSS 2D Transforms. This is supported in almost all modern browsers, including IE9+. Here's an example.
HTML
<p>I feel like <span class="stretch">stretching</span>.</p>
CSS
span.stretch {
display:inline-block;
-webkit-transform:scale(2,1); /* Safari and Chrome */
-moz-transform:scale(2,1); /* Firefox */
-ms-transform:scale(2,1); /* IE 9 */
-o-transform:scale(2,1); /* Opera */
transform:scale(2,1); /* W3C */
}
TIP: You may need to add margin to your stretched text to prevent text collisions.
Java is platform independent in aspect of java developer,but this is not the case for the end-user, who need to have platform dependent JVM to run java code. Basically, when java code is compiled, a bytecode is generated which is typically platform independent. Thus, the developer has to have write a single code for entire platform series. But, this benefit comes with a headache for end-user who need to install JVM in order to run this compiled code. This JVM is differnt for every platform. Thus, dependency comes into effect only for end-user.
I thought I would put a note here that explains a basic misconception for a lot of people who are using these Text Editors... Sublime Text in particular (or at least that's the one I use, so I don't know how it works for other editors):
There are "Themes" and there are "Color Schemes". They are similar but affect different things. "Themes" actively change the entire UI, and can include a Color Scheme if you set it up that way. This typically includes the sidebar, and can also include options for the file tabs, and some even include icons for the sidebar as well. And then we have "Color Schemes" which only change the coding windows and nothing else... not the Sidebar, nor the File tabs, etc.
The confusion happens because some people call Color Schemes "Themes" which makes folks think that their "Theme" is going to change everything.... when technically, it's just a color scheme.
And an additional note: Themes don't automatically install for all users. When I install a Theme, I have to open my User preferences (under "preferences > Settings - User"), and then you have to add the line which says something like:
"theme": "Theme-Name.sublime-theme"
(where "Theme-Name" is the name of your theme).
This is different than just activating a color scheme. If you've chosen a color scheme via the dropdown menus in Sublime Text, you will see a line in there like this:
"color_scheme": "Packages/Color-Scheme-Name.tmTheme"
(where "Color-Scheme-Name" is the name of your color scheme).
Sometimes all it takes to get a EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
is a missing return
statement.
It certainly was my case.
If you're using Matplotlib interactively, for example in a web application, (e.g. ipython) you maybe looking for
plt.show()
instead of plt.close()
or plt.clf()
.
Based on answers suggested by many authors, I created a JsPref test scenario. https://jsperf.com/array2object82364
Below are the screenshots of performance. It is a little shocking to me to see, chrome result is in contrast to firefox and edge, even after running it several times.
import numpy as np
arr_float = np.arange(10, dtype=np.float32)
arr_int = arr_float.view(np.float32)
use view() and parameter 'dtype' to change the array in place.
For people using jQuery, there is an excellent plugin for handling key events:
For capturing ?+S and Ctrl+S I'm using this:
$(window).bind('keydown.ctrl_s keydown.meta_s', function(event) {
event.preventDefault();
// Do something here
});
You can use the ui
object provided to the events, specifically you want the stop
event, the ui.item
property and .index()
, like this:
$("#sortable").sortable({
stop: function(event, ui) {
alert("New position: " + ui.item.index());
}
});
You can see a working demo here, remember the .index()
value is zero-based, so you may want to +1 for display purposes.
Reply to MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in IE
In the Model you need to have following type of declaration:
[DataType(DataType.Date)]
public DateTime? DateXYZ { get; set; }
OR
[DataType(DataType.Date)]
public Nullable<System.DateTime> DateXYZ { get; set; }
You don't need to use following attribute:
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
At the Date.cshtml use this template:
@model Nullable<DateTime>
@using System.Globalization;
@{
DateTime dt = DateTime.Now;
if (Model != null)
{
dt = (System.DateTime)Model;
}
if (Request.Browser.Type.ToUpper().Contains("IE") || Request.Browser.Type.Contains("InternetExplorer"))
{
@Html.TextBox("", String.Format("{0:d}", dt.ToShortDateString()), new { @class = "datefield", type = "date" })
}
else
{
//Tested in chrome
DateTimeFormatInfo dtfi = CultureInfo.CreateSpecificCulture("en-US").DateTimeFormat;
dtfi.DateSeparator = "-";
dtfi.ShortDatePattern = @"yyyy/MM/dd";
@Html.TextBox("", String.Format("{0:d}", dt.ToString("d", dtfi)), new { @class = "datefield", type = "date" })
}
}
Have fun! Regards, Blerton
Please use Homebrew Formulae page to see the list of installable packages. https://formulae.brew.sh/formula/
To install any package => command to use is :
brew install node
This is worked for me successfully.
"C:\Program Files\Java\jdk1.6.0_26\bin\keytool.exe" -exportcert -alias sociallisting -keystore "D:\keystore\SocialListing" | "C:\cygwin\bin\openssl.exe" sha1 -binary | "C:\cygwin\bin\openssl.exe" base64
Be careful with below path :
If command successfully work then you will see this command :
Enter keystore password : typeyourpassword
Encryptedhashkey**
I've finally managed to do it. Answer in code snippet below:
var querystring = require('querystring');
var request = require('request');
var form = {
username: 'usr',
password: 'pwd',
opaque: 'opaque',
logintype: '1'
};
var formData = querystring.stringify(form);
var contentLength = formData.length;
request({
headers: {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded'
},
uri: 'http://myUrl',
body: formData,
method: 'POST'
}, function (err, res, body) {
//it works!
});
user.dir
is the "User working directory" according to the Java Tutorial, System Properties
More than code in C, I think that an english definition could be enough:
Given a class Base of which there is a derived class Derived, dynamic_cast
will convert a Base pointer to a Derived pointer if and only if the actual object pointed at is in fact a Derived object.
class Base { virtual ~Base() {} };
class Derived : public Base {};
class Derived2 : public Base {};
class ReDerived : public Derived {};
void test( Base & base )
{
dynamic_cast<Derived&>(base);
}
int main() {
Base b;
Derived d;
Derived2 d2;
ReDerived rd;
test( b ); // throw: b is not a Derived object
test( d ); // ok
test( d2 ); // throw: d2 is not a Derived object
test( rd ); // ok: rd is a ReDerived, and thus a derived object
}
In the example, the call to test
binds different objects to a reference to Base
. Internally the reference is downcasted to a reference to Derived
in a typesafe way: the downcast will succeed only for those cases where the referenced object is indeed an instance of Derived
.
Set the property of your DataGridView:
Anchor: Top,Left
AutoSizeColumn: Fill
Dock: Fill
Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
In R the equivalent function is seq
and you can use it with the option by
:
seq(from = 5, to = 100, by = 5)
# [1] 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100
In addition to by
you can also have other options such as length.out
and along.with
.
length.out: If you want to get a total of 10 numbers between 0 and 1, for example:
seq(0, 1, length.out = 10)
# gives 10 equally spaced numbers from 0 to 1
along.with: It takes the length of the vector you supply as input and provides a vector from 1:length(input).
seq(along.with=c(10,20,30))
# [1] 1 2 3
Although, instead of using the along.with
option, it is recommended to use seq_along
in this case. From the documentation for ?seq
seq
is generic, and only the default method is described here. Note that it dispatches on the class of the first argument irrespective of argument names. This can have unintended consequences if it is called with just one argument intending this to be taken as along.with: it is much better to useseq_along
in that case.
seq_along: Instead of seq(along.with(.))
seq_along(c(10,20,30))
# [1] 1 2 3
Hope this helps.
this will also work, if you like
xcopy C:\Test\Log "c:\Test\Backup-%date:~4,2%-%date:~7,2%-%date:~10,4%_%time:~0,2%%time:~3,2%" /s /i
del C:\Test\Log
Here is the formula
create a new rule in conditional formating based on a formula. Use the following formula and apply it to $A:$A
=NOT(ISERROR(MATCH(A1,$B$1:$B$1000,0)))
here is the example sheet to download if you encounter problems
UPDATE
here is @pnuts's suggestion which works perfect as well:
=MATCH(A1,B:B,0)>0
Sometimes that problem occurs if you already have a branch with the base name.
I tried this:
git checkout -b features/aName origin/features/aName
Unfortunately, I already had a branch named features
, and I got the exception of the question asker.
Removing the branch features
resolved the problem, the above command worked.
If you mean an equal number of lines, split
has an option for this:
split --lines=75
If you need to know what that 75
should really be for N
equal parts, its:
lines_per_part = int(total_lines + N - 1) / N
where total lines can be obtained with wc -l
.
See the following script for an example:
#!/usr/bin/bash
# Configuration stuff
fspec=qq.c
num_files=6
# Work out lines per file.
total_lines=$(wc -l <${fspec})
((lines_per_file = (total_lines + num_files - 1) / num_files))
# Split the actual file, maintaining lines.
split --lines=${lines_per_file} ${fspec} xyzzy.
# Debug information
echo "Total lines = ${total_lines}"
echo "Lines per file = ${lines_per_file}"
wc -l xyzzy.*
This outputs:
Total lines = 70
Lines per file = 12
12 xyzzy.aa
12 xyzzy.ab
12 xyzzy.ac
12 xyzzy.ad
12 xyzzy.ae
10 xyzzy.af
70 total
More recent versions of split
allow you to specify a number of CHUNKS
with the -n/--number
option. You can therefore use something like:
split --number=l/6 ${fspec} xyzzy.
(that's ell-slash-six
, meaning lines
, not one-slash-six
).
That will give you roughly equal files in terms of size, with no mid-line splits.
I mention that last point because it doesn't give you roughly the same number of lines in each file, more the same number of characters.
So, if you have one 20-character line and 19 1-character lines (twenty lines in total) and split to five files, you most likely won't get four lines in every file.
upgrade numpy to the latest version
pip install numpy --upgrade
In your particular case the issue seem to be with accessing the site from non-canonical url (www.site.com vs. site.com).
Instead of fixing CORS issue (which may require writing proxy to server fonts with proper CORS headers depending on service provider) you can normalize your Urls to always server content on canonical Url and simply redirect if one requests page without "www.".
Alternatively you can upload fonts to different server/CDN that is known to have CORS headers configured or you can easily do so.
I would like to answer your question, as there are various methods - here I’ll talk about the code that is widely used.
So, for hiding the sheet:
Sub try()
Worksheets("Sheet1").Visible = xlSheetHidden
End Sub
There are other methods also if you want to learn all Methods Click here
I am having a similar issue now and I believe the problem in my case as well as the original poster is because of the redirect. By default a Response.Redirect causes an exception which immediately bubbles up until it is caught and the redirect is immediately executed, I am guessing that this is preventing the modified cookie collection from being passed down to the client. If you modify your code to use:
Response.Redirect("url", false);
This prevents the exception and seems to allow the cookie to be properly sent back to the client.
use .val()
, it will return the value of the <input>
$("#spa").val().length > 0
And you had a typo, length
not lenght
.
You are not using Oracle, so you should be using the modulus operator:
SELECT * FROM Orders where OrderID % 2 = 0;
The MOD()
function exists in Oracle, which is the source of your confusion.
Have a look at this SO question which discusses your problem.
There's the built-in trim function that is perfect for the purpose.
SELECT trim(both 'ag' from 'asdfg');
btrim
-------
sdf
(1 riga)
http://www.postgresql.org/docs/8.1/static/functions-string.html
These are the two ways to do it:
SELECT `from` FROM TableName
SELECT TableName.from FROM TableName
I have always just used the os feature of Current Working Directory, or CWD. This is part of the standard library, and is very easy to implement. Here is an example:
import os
base_directory = os.getcwd()
You can use the Boolean constants - Boolean.TRUE
and Boolean.FALSE
instead of 0
and 1
. You can create your variable as of type boolean
if primitive is what you are after. This way you won't have to create new Boolean
objects.
This works:
SELECT STR_TO_DATE(dateColumn, '%c/%e/%Y %r') FROM tabbleName WHERE 1
How I do it with openpyxl lib:
import csv
from openpyxl import Workbook
def convert_csv_to_xlsx(self):
wb = Workbook()
sheet = wb.active
CSV_SEPARATOR = "#"
with open("my_file.csv") as f:
reader = csv.reader(f)
for r, row in enumerate(reader):
for c, col in enumerate(row):
for idx, val in enumerate(col.split(CSV_SEPARATOR)):
cell = sheet.cell(row=r+1, column=idx+1)
cell.value = val
wb.save("my_file.xlsx")
In Python 3.x the raw_input()
of Python 2.x has been replaced by input()
function. However in both the cases you cannot input multi-line strings, for that purpose you would need to get input from the user line by line and then .join()
them using \n
, or you can also take various lines and concatenate them using +
operator separated by \n
To get multi-line input from the user you can go like:
no_of_lines = 5
lines = ""
for i in xrange(no_of_lines):
lines+=input()+"\n"
print(lines)
Or
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
text = '\n'.join(lines)
Agree completely with Bryan and others.
Instead, consider using multiple sections in your email that you can jump to using links and anchors (the 'a' tag). I think that you can emulate the behavior you want by including multiple copies of the text further down in your email. This is a bet messy though, so you could just have sets of anchors that link to each other and allow you to move back in forth between the 'summary' section and the 'expanded' one.
Example:
<a href="#section1">Jump to section!</a>
<p>A bunch of content</p>
<h2 id="section1">An anchor!</h2>
Clicking on the first link will move focus to the sub-section.
This is what worked for me (Windows 10) :
Tip : You can pin mysql.exe to Start Menu so you don't always have to search for this folder
You are populating your dictionaries with references to a single list so when you update it, the update is reflected across all the references. Try a dictionary comprehension instead. See Create a dictionary with list comprehension in Python
d = {k : v for k in blah blah blah}
Console.WriteLine won't work. Only Debug.WriteLine() or Trace.WriteLine() will work, in debug mode.
I do the following: include using System.Diagnostics in the test module. Then, use Debug.WriteLine for my output, right click on the test, choose Debug Selected Tests. The result output will now appear in the Output window below. I use Visual Studio 2017 vs 15.8.1, with the default unit test framework VS provides.
Directory.GetParent
is probably a better answer, but for completeness there's a different method that takes string and returns string: Path.GetDirectoryName
.
string parent = System.IO.Path.GetDirectoryName(str_directory);
Starting from Angular 9 localization process changed. Check out official doc.
Follow the steps below:
ng add @angular/localize
The Angular repository includes common locales. You can change your app's source locale for the build by setting the source locale in the sourceLocale field of your app's workspace configuration file (angular.json). The build process (described in Merge translations into the app in this guide) uses your app's angular.json file to automatically set the LOCALE_ID token and load the locale data.
so set locale in angular.json
like this (list of available locales can be found here):
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"test-app": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"prefix": "app",
"i18n": {
"sourceLocale": "es"
},
....
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
...
"configurations": {
"production": {
...
},
"ru": {
"localize": ["ru"]
},
"es": {
"localize": ["es"]
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "test-app:build"
},
"configurations": {
"production": {
"browserTarget": "test-app:build:production"
},
"ru":{
"browserTarget": "test-app:build:ru"
},
"es": {
"browserTarget": "test-app:build:es"
}
}
},
...
}
},
...
"defaultProject": "test-app"
}
Basically you need to define sourceLocale
in i18n
section and add build configuration with specific locale like "localize": ["es"]
. Optionally you can add it so serve
section
build
or serve
: ng serve --configuration=es
Set the svn:ignore property. Most UI svn tools have a way to do this as well as the command line discussion in the link.
You should change/add in your PostController: (and change PostsController to PostController)
public function create()
{
$categories = Category::all();
return view('create',compact('categories'));
}
public function store(Request $request)
{
$post = new Posts;
$post->title = $request->get('title'); // CHANGE THIS
$post->body = $request->get('body'); // CHANGE THIS
$post->save(); // ADD THIS
$post->categories()->attach($request->get('categories_id')); // CHANGE THIS
return redirect()->route('posts.index'); // PS ON THIS ONE
}
PS: using route() means you have named your route as such
Route::get('example', 'ExampleController@getExample')->name('getExample');
UPDATE
The comments above are also right, change your 'Posts' Model to 'Post'
Well, the API for Integer.valueOf(String)
does indeed say that the String
is interpreted exactly as if it were given to Integer.parseInt(String)
. However, valueOf(String)
returns a new
Integer()
object whereas parseInt(String)
returns a primitive int
.
If you want to enjoy the potential caching benefits of Integer.valueOf(int)
, you could also use this eyesore:
Integer k = Integer.valueOf(Integer.parseInt("123"))
Now, if what you want is the object and not the primitive, then using valueOf(String)
may be more attractive than making a new object out of parseInt(String)
because the former is consistently present across Integer
, Long
, Double
, etc.
parseInt() or parseFloat() are functions in JavaScript which can help you convert the values into integers or floats respectively.
parseInt(string, radix);
parseFloat(string);
var x = prompt("Enter a Value", "0");
var y = prompt("Enter a Value", "0");
var num1 = parseInt(x);
var num2 = parseInt(y);
After this you can perform which ever calculations you want on them.
Would something like this do what you need?
class Test(object):
def _decorator(foo):
def magic( self ) :
print "start magic"
foo( self )
print "end magic"
return magic
@_decorator
def bar( self ) :
print "normal call"
test = Test()
test.bar()
This avoids the call to self to access the decorator and leaves it hidden in the class namespace as a regular method.
>>> import stackoverflow
>>> test = stackoverflow.Test()
>>> test.bar()
start magic
normal call
end magic
>>>
edited to answer question in comments:
How to use the hidden decorator in another class
class Test(object):
def _decorator(foo):
def magic( self ) :
print "start magic"
foo( self )
print "end magic"
return magic
@_decorator
def bar( self ) :
print "normal call"
_decorator = staticmethod( _decorator )
class TestB( Test ):
@Test._decorator
def bar( self ):
print "override bar in"
super( TestB, self ).bar()
print "override bar out"
print "Normal:"
test = Test()
test.bar()
print
print "Inherited:"
b = TestB()
b.bar()
print
Output:
Normal:
start magic
normal call
end magic
Inherited:
start magic
override bar in
start magic
normal call
end magic
override bar out
end magic
In C++ the stack memory is where local variables get stored/constructed. The stack is also used to hold parameters passed to functions.
The stack is very much like the std::stack class: you push parameters onto it and then call a function. The function then knows that the parameters it expects can be found on the end of the stack. Likewise, the function can push locals onto the stack and pop them off it before returning from the function. (caveat - compiler optimizations and calling conventions all mean things aren't this simple)
The stack is really best understood from a low level and I'd recommend Art of Assembly - Passing Parameters on the Stack. Rarely, if ever, would you consider any sort of manual stack manipulation from C++.
Generally speaking, the stack is preferred as it is usually in the CPU cache, so operations involving objects stored on it tend to be faster. However the stack is a limited resource, and shouldn't be used for anything large. Running out of stack memory is called a Stack buffer overflow. It's a serious thing to encounter, but you really shouldn't come across one unless you have a crazy recursive function or something similar.
Heap memory is much as rskar says. In general, C++ objects allocated with new, or blocks of memory allocated with the likes of malloc end up on the heap. Heap memory almost always must be manually freed, though you should really use a smart pointer class or similar to avoid needing to remember to do so. Running out of heap memory can (will?) result in a std::bad_alloc.
SIMPLE SOLUTION (tested on Red Hat):
run command: curl -sS https://getcomposer.org/installer | php
to use it: php composer.phar
SYSTEM WIDE SOLLUTION (tested on Red Hat):
run command: mv composer.phar /usr/local/bin/composer
to use it: composer update
now you can call composer from any directory.
Source: http://www.agix.com.au/install-composer-on-centosredhat/
You can use phpMyAdmin Style:
/**
* block attempts to directly run this script
*/
if (getcwd() == dirname(__FILE__)) {
die('Attack stopped');
}
I came across System.Runtime.InteropServices.COMException
while opening a project solution. Sometimes user doesn't have enough priveleges to run some COM
Methods. I ran Visual Studio as Administrator and the exception was gone.
When MS-DOS and Windows 3.1 operated in 16-bit mode, an Intel 8086 word was 16 bits, a Microsoft WORD was 16 bits, a Microsoft DWORD was 32 bits, and a typical compiler's unsigned int was 16 bits.
When Windows NT operated in 32-bit mode, an Intel 80386 word was 32 bits, a Microsoft WORD was 16 bits, a Microsoft DWORD was 32 bits, and a typical compiler's unsigned int was 32 bits. The names WORD and DWORD were no longer self-descriptive but they preserved the functionality of Microsoft programs.
When Windows operates in 64-bit mode, an Intel word is 64 bits, a Microsoft WORD is 16 bits, a Microsoft DWORD is 32 bits, and a typical compiler's unsigned int is 32 bits. The names WORD and DWORD are no longer self-descriptive, AND an unsigned int no longer conforms to the principle of least surprises, but they preserve the functionality of lots of programs.
I don't think WORD or DWORD will ever change.
For Eclipse Mars (I've just verified that) you to do this (assuming that C:\eclipseMarsEE is root folder of your Eclipse):
You can only close a window using javascript that was opened using javascript, i.e. when the window was opened using :
window.open
then
window.close
will work. Or else not.
This simple problem can cause a real headache!
I can see your controller EDIT
(PUT
) method expects 2 parameters: a) an int id, and b) a department object.
It is the default code when you generate this from VS > add controller with read/write options. However, you have to remember to consume this service using the two parameters, otherwise you will get the error 405.
In my case, I did not need the id parameter for PUT
, so I just dropped it from the header... after a few hours of not noticing it there! If you keep it there, then the name must also be retained as id, unless you go on to make necessary changes to your configurations.
If you need this in derived classes, you can put that code in the base class:
protected string GetThisClassName() { return this.GetType().Name; }
Then, you can reach the name in the derived class. Returns derived class name. Of course, when using the new keyword "nameof", there will be no need like this variety acts.
Besides you can define this:
public static class Extension
{
public static string NameOf(this object o)
{
return o.GetType().Name;
}
}
And then use like this:
public class MyProgram
{
string thisClassName;
public MyProgram()
{
this.thisClassName = this.NameOf();
}
}
Try moving the order by
after group by
:
var groupByReference = (from m in context.Measurements
group m by new { m.Reference } into g
order by g.Avg(i => i.CreationTime)
select g).Take(numOfEntries).ToList();
Instead of naming my invoking class, I started using the following:
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
In this way, I can use the same line of code in every class that uses log4net without having to remember to change code when I copy and paste. Alternatively, i could create a logging class, and have every other class inherit from my logging class.
You can have a static field to store this kind of state. Or put it to the resource Bundle and restore from there on onCreate(Bundle savedInstanceState). Just make sure you entirely understand Android app managed lifecycle (e.g. why login() gets called on keyboard orientation change).
In Oracle 12c, you can now specify the CURRVAL and NEXTVAL sequence pseudocolumns as default values for a column. Alternatively, you can use Identity columns; see:
E.g.,
CREATE SEQUENCE t1_seq;
CREATE TABLE t1 (
id NUMBER DEFAULT t1_seq.NEXTVAL,
description VARCHAR2(30)
);
In VS2008, the doc entry that seems the most useful is:
Windows Presentation Foundation Building a WPF Application (WPF)
ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/wpf_conceptual/html/a58696fd-bdad-4b55-9759-136dfdf8b91c.htm
ApplicationDefinition Identifies the XAML markup file that contains the application definition (a XAML markup file whose root element is Application). ApplicationDefinition is mandatory when Install is true and OutputType is winexe. A WPF application and, consequently, an MSBuild project can only have one ApplicationDefinition.
Page Identifies a XAML markup file whose content is converted to a binary format and compiled into an assembly. Page items are typically implemented in conjunction with a code-behind class.
The most common Page items are XAML files whose top-level elements are one of the following:
Window (System.Windows..::.Window).
Page (System.Windows.Controls..::.Page).
PageFunction (System.Windows.Navigation..::.PageFunction<(Of <(T>)>)).
ResourceDictionary (System.Windows..::.ResourceDictionary).
FlowDocument (System.Windows.Documents..::.FlowDocument).
UserControl (System.Windows.Controls..::.UserControl).
Resource Identifies a resource file that is compiled into an application assembly. As mentioned earlier, UICulture processes Resource items.
Content Identifies a content file that is distributed with an application. Metadata that describes the content file is compiled into the application (using AssemblyAssociatedContentFileAttribute).
As far as I can remember, the first versions of C only allowed to return a value that could fit into a processor register, which means that you could only return a pointer to a struct. The same restriction applied to function arguments.
More recent versions allow to pass around larger data objects like structs. I think this feature was already common during the eighties or early nineties.
Arrays, however, can still be passed and returned only as pointers.
I believe you're not fully understanding how pointers work.
When you have a pointer pointing to some memory there are three different things you must understand:
- there is "what is pointed" by the pointer (the memory)
- this memory address
- not all pointers need to have their memory deleted: you only need to delete memory that was dynamically allocated (used new
operator).
Imagine:
int *ptr = new int;
// ptr has the address of the memory.
// at this point, the actual memory doesn't have anything.
*ptr = 8;
// you're assigning the integer 8 into that memory.
delete ptr;
// you are only deleting the memory.
// at this point the pointer still has the same memory address (as you could
// notice from your 2nd test) but what inside that memory is gone!
When you did
ptr = NULL;
// you didn't delete the memory
// you're only saying that this pointer is now pointing to "nowhere".
// the memory that was pointed by this pointer is now lost.
C++ allows that you try to delete
a pointer that points to null
but it doesn't actually do anything, just doesn't give any error.
SELECT *
FROM table_name
ORDER BY id DESC
LIMIT 1
This works in Linux & Windows:
Python 3.x
>>> import sys
>>> print(sys.executable)
C:\path\to\python.exe
Python 2.x
>>> import sys
>>> print sys.executable
/usr/bin/python
Simple solution
myDivObj = document.getElementById("myDivID")
let myDivObjBgColor = window.getComputedStyle(myDivObj).backgroundColor;
Now the background color is stored in the new variable.
Take a look at Generic Lists.
You can create a local computer policy on Windows. See the TechNet at http://technet.microsoft.com/en-us/magazine/dd630947
gpedit.msc
to open the Group Policy Editor,You cal also do this
SELECT SUM(amnt) `value`,DATE_FORMAT(dtrg,'%m-%y') AS label FROM rentpay GROUP BY YEAR(dtrg) DESC, MONTH(dtrg) DESC LIMIT 12
to order by year and month. Lets say you want to order from this year and this month all the way back to 12 month
This one is valid HTML5 and it is absolutely fine without closing it. It is a so-called void element:
<img src='stackoverflow.png'>
The following are valid XHTML tags. They have to be closed. The later one is also fine in HTML 5:
<img src='stackoverflow.png'></img>
<img src='stackoverflow.png' />
We recently had some experience with this. We have ported from Solaris (x86-64 Version 5.10) to Linux (RedHat x86-64) recently and have realized that we have less memory available for a 32 bit JVM process on Linux than Solaris.
For Solaris this almost comes around to 4GB (http://www.oracle.com/technetwork/java/hotspotfaq-138619.html#gc_heap_32bit).
We ran our app with -Xms2560m -Xmx2560m -XX:MaxPermSize=512m -XX:PermSize=512m with no issues on Solaris for past couple of years. Tried to move it to linux and we had issues with random out of memory errors on start up. We could only get it to consistently start up on -Xms2300 -Xmx2300. Then we were advised of this by support.
A 32 bit process on Linux has a maximum addressable address space of 3gb (3072mb) whereas on Solaris it is the full 4gb (4096mb).
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
<param name="Threshold" value="INFO" />
<param name="File" value="sample.log"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p [%c{1}] %m %n" />
</layout>
</appender>
<root>
<priority value ="debug" />
<appender-ref ref="fileAppender" />
</root>
</log4j:configuration>
Log4j can be a bit confusing. So lets try to understand what is going on in this file: In log4j you have two basic constructs appenders and loggers.
Appenders define how and where things are appended. Will it be logged to a file, to the console, to a database, etc.? In this case you are specifying that log statements directed to fileAppender will be put in the file sample.log
using the pattern specified in the layout tags. You could just as easily create a appender for the console or the database. Where the console appender would specify things like the layout on the screen and the database appender would have connection details and table names.
Loggers respond to logging events as they bubble up. If an event catches the interest of a specific logger it will invoke its attached appenders. In the example below you have only one logger the root logger - which responds to all logging events by default. In addition to the root logger you can specify more specific loggers that respond to events from specific packages. These loggers can have their own appenders specified using the appender-ref
tags or will otherwise inherit the appenders from the root logger. Using more specific loggers allows you to fine tune the logging level on specific packages or to direct certain packages to other appenders.
So what this file is saying is:
The net out is that if you have a logger.debug("blah blah")
in your code it will get ignored. A logger.info("Blah blah");
will output to sample.log.
The snippet below could be added to the file above with the log4j tags. This logger would inherit the appenders from <root>
but would limit the all logging events from the package org.springframework
to those logged at level info
or above.
<!-- Example Package level Logger -->
<logger name="org.springframework">
<level value="info"/>
</logger>
You could use Enumerable.Max
:
new [] { 1, 2, 3 }.Max();
You can do this:
select t2.*
from t1
join t2 on t2.url = 'site.com/path/' + CAST(t1.id AS VARCHAR(10)) + '/more'
where t1.id > 9000
Pay attention to CAST(t1.id AS VARCHAR(10))
.
This is a special case, but if you're starting with a predefined hash that you want to grab and make a copy of, you can create a method that returns a hash:
def johns
{ "John"=>"Adams","Thomas"=>"Jefferson","Johny"=>"Appleseed"}
end
h1 = johns
The particular scenario that I had was I had a collection of JSON-schema hashes where some hashes built off others. I was initially defining them as class variables and ran into this copy issue.
Maybe you are out of inodes. Try df -i
2591792 136322 2455470 6% /home
/dev/sdb1 1887488 1887488 0 100% /data
Disk used 6% but inode table full.
You can use Process.GetProcesses()
to get the currently running processes, then Process.Kill()
to kill a process.
You need use Stream to send file (archive) in a response, what is more you have to use appropriate Content-type in your response header.
There is an example function that do it:
const fs = require('fs');
// Where fileName is name of the file and response is Node.js Reponse.
responseFile = (fileName, response) => {
const filePath = "/path/to/archive.rar" // or any file format
// Check if file specified by the filePath exists
fs.exists(filePath, function(exists){
if (exists) {
// Content-type is very interesting part that guarantee that
// Web browser will handle response in an appropriate manner.
response.writeHead(200, {
"Content-Type": "application/octet-stream",
"Content-Disposition": "attachment; filename=" + fileName
});
fs.createReadStream(filePath).pipe(response);
} else {
response.writeHead(400, {"Content-Type": "text/plain"});
response.end("ERROR File does not exist");
}
});
}
}
The purpose of the Content-Type field is to describe the data contained in the body fully enough that the receiving user agent can pick an appropriate agent or mechanism to present the data to the user, or otherwise deal with the data in an appropriate manner.
"application/octet-stream" is defined as "arbitrary binary data" in RFC 2046, purpose of this content-type is to be saved to disk - it is what you really need.
"filename=[name of file]" specifies name of file which will be downloaded.
For more information please see this stackoverflow topic.
The other answers are preferable, but for a pure Bash solution, I've modified the script in my answer here to be able to output a continuous stream of hex characters representing the contents of a file. (Its normal mode is to emulate hexdump -C
.)
Just for fun I did this:
function getMonthFromString(mon){
return new Date(Date.parse(mon +" 1, 2012")).getMonth()+1
}
Bonus: it also supports full month names :-D Or the new improved version that simply returns -1 - change it to throw the exception if you want (instead of returning -1):
function getMonthFromString(mon){
var d = Date.parse(mon + "1, 2012");
if(!isNaN(d)){
return new Date(d).getMonth() + 1;
}
return -1;
}
Sry for all the edits - getting ahead of myself
var elems = document.querySelectorAll('.one');_x000D_
_x000D_
for (var i = 0; i < elems.length; i++) {_x000D_
elems[i].innerHTML = 'content';_x000D_
};
_x000D_
Usually you make the thing you don't want duplicates of unique, and allow the database itself to refuse the insert.
Otherwise, you can use INSERT INTO, see How to avoid duplicates in INSERT INTO SELECT query in SQL Server?
The DataTable.Clone()
method works great when you want to create a completely new DataTable, but there might be cases where you would want to add the schema columns from one DataTable to another existing DataTable.
For example, if you've derived a new subclass from DataTable, and want to import schema information into it, you couldn't use Clone().
E.g.:
public class CoolNewTable : DataTable {
public void FillFromReader(DbDataReader reader) {
// We want to get the schema information (i.e. columns) from the
// DbDataReader and
// import it into *this* DataTable, NOT a new one.
DataTable schema = reader.GetSchemaTable();
//GetSchemaTable() returns a DataTable with the columns we want.
ImportSchema(this, schema); // <--- how do we do this?
}
}
The answer is just to create new DataColumns in the existing DataTable using the schema table's columns as templates.
I.e. the code for ImportSchema would be something like this:
void ImportSchema(DataTable dest, DataTable source) {
foreach(var c in source.Columns)
dest.Columns.Add(c);
}
or, if you're using Linq:
void ImportSchema(DataTable dest, DataTable source) {
var cols = source.Columns.Cast<DataColumn>().ToArray();
dest.Columns.AddRange(cols);
}
This was just one example of a situation where you might want to copy schema/columns from one DataTable into another one without using Clone() to create a completely new DataTable. I'm sure I've come across several others as well.
How do I split a column of dictionaries into separate columns with pandas?
pd.DataFrame(df['val'].tolist())
is the canonical method for exploding a column of dictionariesHere's your proof using a colorful graph.
Benchmarking code for reference.
Note that I am only timing the explosion since that's the most interesting part of answering this question - other aspects of result construction (such as whether to use pop
or drop
) are tangential to the discussion and can be ignored (it should be noted however that using pop
avoids the followup drop
call, so the final solution is a bit more performant, but we are still listifying the column and passing it to pd.DataFrame
either way).
Additionally, pop
destructively mutates the input DataFrame, making it harder to run in benchmarking code which assumes the input is not changed across test runs.
df['val'].apply(pd.Series)
is extremely slow for large N as pandas constructs Series objects for each row, then proceeds to construct a DataFrame from them. For larger N the performance dips to the order of minutes or hours.
pd.json_normalize(df['val']))
is slower simply because json_normalize
is meant to work with a much more complex input data - particularly deeply nested JSON with multiple record paths and metadata. We have a simple flat dict for which pd.DataFrame
suffices, so use that if your dicts are flat.
Some answers suggest df.pop('val').values.tolist()
or df.pop('val').to_numpy().tolist()
. I don't think it makes much of a difference whether you listify the series or the numpy array. It's one operation less to listify the series directly and really isn't slower so I'd recommend avoiding generating the numpy array in the intermediate step.
I've just had some of the similar problems with scrollTop
described here.
In the end I got around this on Firefox and IE by using the selector $('*').scrollTop(0);
Not perfect if you have elements you don't want to effect but it gets around the Document, Body, HTML and Window disparity. If it helps...
You might like to try this password breaker.
http://maxcamillo.github.io/android-keystore-password-recover/index.html
I was using the Dictionary Attack method. It worked for me because there were only a few combinations to my password that I could think of.
In SQL, this problem could be solved by several methods:
select * from df1 where exists (select * from df2 where df2.user_id = df1.user_id)
union all
select * from df2 where exists (select * from df1 where df1.user_id = df2.user_id)
or join and then unpivot (possible in SQL server)
select
df1.user_id,
c.rating
from df1
inner join df2 on df2.user_i = df1.user_id
outer apply (
select df1.rating union all
select df2.rating
) as c
Second one could be written in pandas with something like:
>>> df1 = pd.DataFrame({"user_id":[1,2,3], "rating":[10, 15, 20]})
>>> df2 = pd.DataFrame({"user_id":[3,4,5], "rating":[30, 35, 40]})
>>>
>>> df4 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df = pd.merge(df1, df2, on='user_id', suffixes=['_1', '_2'])
>>> df3 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df4 = df[['user_id', 'rating_2']].rename(columns={'rating_2':'rating'})
>>> pd.concat([df3, df4], axis=0)
user_id rating
0 3 20
0 3 30
I believe it would be like this
takedata.match(/(\[.+\])/g);
the g
at the end means global, so it doesn't stop at the first match.
why do you ever want to use out?
To let others know that the variable will be initialized when it returns from the called method!
As mentioned above: "for an out parameter, the calling method is required to assign a value before the method returns."
example:
Car car;
SetUpCar(out car);
car.drive(); // You know car is initialized.
You can use MERGE
Statement, This statement is used to insert data if not exist or update if does exist.
MERGE INTO Employee AS e
using EmployeeUpdate AS eu
ON e.EmployeeID = eu.EmployeeID`
Another option for detecting whether all keys are in a dict:
dict_to_test = { ... } # dict
keys_sought = { "key_sought_1", "key_sought_2", "key_sought_3" } # set
if keys_sought & dict_to_test.keys() == keys_sought:
# True -- dict_to_test contains all keys in keys_sought
# code_here
pass
If post data is malformed, $_POST will not contain anything. Yet, php://input will have the malformed string.
For example there is some ajax applications, that do not form correct post key-value sequence for uploading a file, and just dump all the file as post data, without variable names or anything. $_POST will be empty, $_FILES empty also, and php://input will contain exact file, written as a string.
If you are very unlucky you have used about 100% of all inodes and can't create the scipt.
You can check this with df -ih
.
Then this bash command may help you:
sudo find . -xdev -type f | cut -d "/" -f 2 | sort | uniq -c | sort -n
And yes, this will take time, but you can locate the directory with the most files.
Instead of letting the business layer decide how it’s best to fetch all the associations that are needed by the View layer, OSIV (Open Session in View) forces the Persistence Context to stay open so that the View layer can trigger the Proxy initialization, as illustrated by the following diagram.
OpenSessionInViewFilter
calls the openSession
method of the underlying SessionFactory
and obtains a new Session
.Session
is bound to the TransactionSynchronizationManager
.OpenSessionInViewFilter
calls the doFilter
of the javax.servlet.FilterChain
object reference and the request is further processedDispatcherServlet
is called, and it routes the HTTP request to the underlying PostController
.PostController
calls the PostService
to get a list of Post
entities.PostService
opens a new transaction, and the HibernateTransactionManager
reuses the same Session
that was opened by the OpenSessionInViewFilter
.PostDAO
fetches the list of Post
entities without initializing any lazy association.PostService
commits the underlying transaction, but the Session
is not closed because it was opened externally.DispatcherServlet
starts rendering the UI, which, in turn, navigates the lazy associations and triggers their initialization.OpenSessionInViewFilter
can close the Session
, and the underlying database connection is released as well.At first glance, this might not look like a terrible thing to do, but, once you view it from a database perspective, a series of flaws start to become more obvious.
The service layer opens and closes a database transaction, but afterward, there is no explicit transaction going on. For this reason, every additional statement issued from the UI rendering phase is executed in auto-commit mode. Auto-commit puts pressure on the database server because each transaction issues a commit at end, which can trigger a transaction log flush to disk. One optimization would be to mark the Connection
as read-only which would allow the database server to avoid writing to the transaction log.
There is no separation of concerns anymore because statements are generated both by the service layer and by the UI rendering process. Writing integration tests that assert the number of statements being generated requires going through all layers (web, service, DAO) while having the application deployed on a web container. Even when using an in-memory database (e.g. HSQLDB) and a lightweight webserver (e.g. Jetty), these integration tests are going to be slower to execute than if layers were separated and the back-end integration tests used the database, while the front-end integration tests were mocking the service layer altogether.
The UI layer is limited to navigating associations which can, in turn, trigger N+1 query problems. Although Hibernate offers @BatchSize
for fetching associations in batches, and FetchMode.SUBSELECT
to cope with this scenario, the annotations are affecting the default fetch plan, so they get applied to every business use case. For this reason, a data access layer query is much more suitable because it can be tailored to the current use case data fetch requirements.
Last but not least, the database connection is held throughout the UI rendering phase which increases connection lease time and limits the overall transaction throughput due to congestion on the database connection pool. The more the connection is held, the more other concurrent requests are going to wait to get a connection from the pool.
Unfortunately, OSIV (Open Session in View) is enabled by default in Spring Boot, and OSIV is really a bad idea from a performance and scalability perspective.
So, make sure that in the application.properties
configuration file, you have the following entry:
spring.jpa.open-in-view=false
This will disable OSIV so that you can handle the LazyInitializationException
the right way.
Starting with version 2.0, Spring Boot issues a warning when OSIV is enabled by default, so you can discover this problem long before it affects a production system.
you can also use this:
SELECT DATEADD(day, DATEDIFF(day, 0, WeddingDate) /7*7, 0) AS weekstart,
DATEADD(day, DATEDIFF(day, 6, WeddingDate-1) /7*7 + 7, 6) AS WeekEnd
The following worked for me against a SQL Azure backend (using SQL Server Management Studio), so YMMV, but, if it works for you, it's waaaaay simpler than the other solutions.
ALTER TABLE MyTable
DROP CONSTRAINT FK_MyColumn
CONSTRAINT DK_MyColumn
-- etc...
COLUMN MyColumn
GO
Shortest way:
(new Image()).src = "http:/track.me/image.gif";
Something you can try is using the bind method, I think this achieves what you were asking for. If nothing else, it's still very useful.
function doClick(elem, func) {
var diffElem = document.getElementById('some_element'); //could be the same or different element than the element in the doClick argument
diffElem.addEventListener('click', func.bind(diffElem, elem))
}
function clickEvent(elem, evt) {
console.log(this);
console.log(elem);
// 'this' and elem can be the same thing if the first parameter
// of the bind method is the element the event is being attached to from the argument passed to doClick
console.log(evt);
}
var elem = document.getElementById('elem_to_do_stuff_with');
doClick(elem, clickEvent);
I think that your model #2 is fine, however you can take a look at the more complex model which stores questions and pre-made answers (offered answers) and allows them to be re-used in different surveys.
- One survey can have many questions; one question can be (re)used in many surveys.
- One (pre-made) answer can be offered for many questions. One question can have many answers offered. A question can have different answers offered in different surveys. An answer can be offered to different questions in different surveys. There is a default "Other" answer, if a person chooses other, her answer is recorded into Answer.OtherText.
- One person can participate in many surveys, one person can answer specific question in a survey only once.
Unfortunately although the Array.join approach mentioned here is terse, it is about 10X slower than a string-concatenation-based implementation. It performs especially badly on large strings. See below for full performance details.
On Firefox, Chrome, Node.js MacOS, Node.js Ubuntu, and Safari, the fastest implementation I tested was:
function repeatChar(count, ch) {
if (count == 0) {
return "";
}
var count2 = count / 2;
var result = ch;
// double the input until it is long enough.
while (result.length <= count2) {
result += result;
}
// use substring to hit the precise length target without
// using extra memory
return result + result.substring(0, count - result.length);
};
This is verbose, so if you want a terse implementation you could go with the naive approach; it still performs betweeb 2X to 10X better than the Array.join approach, and is also faster than the doubling implementation for small inputs. Code:
// naive approach: simply add the letters one by one
function repeatChar(count, ch) {
var txt = "";
for (var i = 0; i < count; i++) {
txt += ch;
}
return txt;
}
Further information:
I was need to save the start position and the end position. this work to me:
$('.object').draggable({
stop: function(ev, ui){
var position = ui.position;
var originalPosition = ui.originalPosition;
}
});
curl -s http://google.com > temp.html
works for curl version 7.19.5 on Ubuntu 9.10 (no progress bar). But if for some reason that does not work on your platform, you could always redirect stderr to /dev/null:
curl http://google.com 2>/dev/null > temp.html
Since git 1.8.2, Resources/** !Resources/**/*.foo
works.
Acoustics answer works, on windows it would be File --> Settings --> Editor --> Colors & Fonts then save as, name it something then you can edit all the fields you want.
In general I fully agree with Jason's use of css selector, but in some cases you may not want to change the css, e.g. when using a 3rd party css-template, and rather prefer to add/remove a class on the element.
The following sample shows a simple way of adding/removing a class on ng-mouseenter/mouseleave:
<div ng-app>
<div
class="italic"
ng-class="{red: hover}"
ng-init="hover = false"
ng-mouseenter="hover = true"
ng-mouseleave="hover = false">
Test 1 2 3.
</div>
</div>
with some styling:
.red {
background-color: red;
}
.italic {
font-style: italic;
color: black;
}
See running example here: jsfiddle sample
Styling on hovering is a view concern. Although the solution above sets a "hover" property in the current scope, the controller does not need to be concerned about this.
I had a similar issue and could not "compromise" with background images. I came up with this.
<div class="container">
<img src="http://lorempixel.com/800x600/nature">
</div>
.container {
position: relative;
width: 25%; /* whatever width you want. I was implementing this in a 4 tile grid pattern. I used javascript to set height equal to width */
border: 2px solid #fff; /* just to separate the images */
overflow: hidden; /* "crop" the image */
background: #000; /* incase the image is wider than tall/taller than wide */
}
.container img {
position: absolute;
display: block;
height: 100%; /* all images at least fill the height */
top: 50%; /* top, left, transform trick to vertically and horizontally center image */
left: 50%;
transform: translate3d(-50%,-50%,0);
}
//assuming you're using jQuery
var h = $('.container').outerWidth();
$('.container').css({height: h + 'px'});
Hope this helps!
Example: https://jsfiddle.net/cfbuwxmr/1/
Jelly Bean adds support for this with the ActivityOptions.makeCustomAnimation() method. Of course, since it's only on Jelly Bean, it's pretty much worthless for practical purposes.
DO this :
Create libs folder under the application folder. Add .jar files to libs folder. Then add .jar files to app's build.gradle dependency. Finally Sync project with Gradle files.
v15.8.0
, LTS v14.15.4
, and v12.20.1
--- Feb 2021Async method (Unix):
'use strict';
const { spawn } = require( 'child_process' );
const ls = spawn( 'ls', [ '-lh', '/usr' ] );
ls.stdout.on( 'data', ( data ) => {
console.log( `stdout: ${ data }` );
} );
ls.stderr.on( 'data', ( data ) => {
console.log( `stderr: ${ data }` );
} );
ls.on( 'close', ( code ) => {
console.log( `child process exited with code ${ code }` );
} );
Async method (Windows):
'use strict';
const { spawn } = require( 'child_process' );
// NOTE: Windows Users, this command appears to be differ for a few users.
// You can think of this as using Node to execute things in your Command Prompt.
// If `cmd` works there, it should work here.
// If you have an issue, try `dir`:
// const dir = spawn( 'dir', [ '.' ] );
const dir = spawn( 'cmd', [ '/c', 'dir' ] );
dir.stdout.on( 'data', ( data ) => console.log( `stdout: ${ data }` ) );
dir.stderr.on( 'data', ( data ) => console.log( `stderr: ${ data }` ) );
dir.on( 'close', ( code ) => console.log( `child process exited with code ${code}` ) );
Sync:
'use strict';
const { spawnSync } = require( 'child_process' );
const ls = spawnSync( 'ls', [ '-lh', '/usr' ] );
console.log( `stderr: ${ ls.stderr.toString() }` );
console.log( `stdout: ${ ls.stdout.toString() }` );
From Node.js v15.8.0 Documentation
The same goes for Node.js v14.15.4 Documentation and Node.js v12.20.1 Documentation
In app.config file (or .exe.config) you can add or change the "receiveTimeout" property in binding. like this
<binding name="WebServiceName" receiveTimeout="00:00:59" />
You can also "prepend" the environment variable setting by using 'environment' command:
run.doFirst { environment 'SPARK_LOCAL_IP', 'localhost' }
There's a jQuery selector for that:
// Get all form fields that are hidden
var hidden_fields = $( this ).find( 'input:hidden' );
// Filter those which have a specific type
hidden_fields.attr( 'text' );
Will give you all hidden input fields and filter by those with a specific type=""
.
This worked for me:
tar -zcvf target.tar.gz target/ --exclude="target/backups" --exclude="target/cache"
What i came up with is :
1) Make a position:fixed
<div>
with width:100%
(id=zoomdiv)
2) when the page loads :
zoomlevel=$("#zoomdiv").width()*1.0 / screen.availWidth
And it worked for me for ctrl+
and ctrl-
zooms.
or i can add the line to a $(window).onresize()
event to get the active zoom level
Code:
<script>
var zoom=$("#zoomdiv").width()*1.0 / screen.availWidth;
$(window).resize(function(){
zoom=$("#zoomdiv").width()*1.0 / screen.availWidth;
alert(zoom);
});
</script>
<body>
<div id=zoomdiv style="width:100%;position:fixed;"></div>
</body>
P.S. : this is my first post, pardon any mistakes
I could do this (demo):
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
</head>
<body>
<form >
<input type="file" id="f" data-max-size="32154" />
<input type="submit" />
</form>
<script>
$(function(){
$('form').submit(function(){
var isOk = true;
$('input[type=file][data-max-size]').each(function(){
if(typeof this.files[0] !== 'undefined'){
var maxSize = parseInt($(this).attr('max-size'),10),
size = this.files[0].size;
isOk = maxSize > size;
return isOk;
}
});
return isOk;
});
});
</script>
</body>
</html>
Kotlin version:
var current = ""
editText.addTextChangedListener(object: TextWatcher {
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val stringText = s.toString()
if(stringText != current) {
editText.removeTextChangedListener(this)
val locale: Locale = Locale.UK
val currency = Currency.getInstance(locale)
val cleanString = stringText.replace("[${currency.symbol},.]".toRegex(), "")
val parsed = cleanString.toDouble()
val formatted = NumberFormat.getCurrencyInstance(locale).format(parsed / 100)
current = formatted
editText.setText(formatted)
editText.setSelection(formatted.length)
editText.addTextChangedListener(this)
}
}
})
if (substr_count($this->content,'<p>') == 1)
{
$this->content = preg_replace('/<\/?p>/i', '', $this->content);
}
On Linux/OS X/Unix to display the groups to which you (or the optionally specified user) belong, use:
id -Gn [user]
which is equivalent to groups [user]
utility which has been obsoleted on Unix.
On OS X/Unix, the command id -p [user]
is suggested for normal interactive.
Explanation on the parameters:
-G
,--groups
- print all group IDs
-n
,--name
- print a name instead of a number, for-ugG
-p
- Make the output human-readable.
IEnumerable<Control> Ctrls = from Control ctrl in Me.Controls where ctrl is TextBox | ctrl is GroupBox select ctr;
Lambda Expressions
IEnumerable<Control> Ctrls = Me.Controls.Cast<Control>().Where(c => c is Button | c is GroupBox);
I'm on OSX 10.10.2, and succeeded in using JPype.
Ran into installation problems with Jnius (others have too), Javabridge installed but gave mysterious errors when I tried to use it, PyJ4 has this inconvenience of having to start a Gateway server in Java first, JCC wouldn't install. Finally, JPype ended up working. There's a maintained fork of JPype on Github. It has the major advantages that (a) it installs properly and (b) it can very efficiently convert java arrays to numpy array (np_arr = java_arr[:]
)
The installation process was:
git clone https://github.com/originell/jpype.git
cd jpype
python setup.py install
And you should be able to import jpype
The following demo worked:
import jpype as jp
jp.startJVM(jp.getDefaultJVMPath(), "-ea")
jp.java.lang.System.out.println("hello world")
jp.shutdownJVM()
When I tried calling my own java code, I had to first compile (javac ./blah/HelloWorldJPype.java
), and I had to change the JVM path from the default (otherwise you'll get inexplicable "class not found" errors). For me, this meant changing the startJVM command to:
jp.startJVM('/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/MacOS/libjli.dylib', "-ea")
c = jp.JClass('blah.HelloWorldJPype')
# Where my java class file is in ./blah/HelloWorldJPype.class
...
There's a really good paper by Microsoft Research called To Blob or Not To Blob.
Their conclusion after a large number of performance tests and analysis is this:
if your pictures or document are typically below 256KB in size, storing them in a database VARBINARY column is more efficient
if your pictures or document are typically over 1 MB in size, storing them in the filesystem is more efficient (and with SQL Server 2008's FILESTREAM attribute, they're still under transactional control and part of the database)
in between those two, it's a bit of a toss-up depending on your use
If you decide to put your pictures into a SQL Server table, I would strongly recommend using a separate table for storing those pictures - do not store the employee photo in the employee table - keep them in a separate table. That way, the Employee table can stay lean and mean and very efficient, assuming you don't always need to select the employee photo, too, as part of your queries.
For filegroups, check out Files and Filegroup Architecture for an intro. Basically, you would either create your database with a separate filegroup for large data structures right from the beginning, or add an additional filegroup later. Let's call it "LARGE_DATA".
Now, whenever you have a new table to create which needs to store VARCHAR(MAX) or VARBINARY(MAX) columns, you can specify this file group for the large data:
CREATE TABLE dbo.YourTable
(....... define the fields here ......)
ON Data -- the basic "Data" filegroup for the regular data
TEXTIMAGE_ON LARGE_DATA -- the filegroup for large chunks of data
Check out the MSDN intro on filegroups, and play around with it!
Using Gradle Task Graph we can check/switch build type.
The basic idea is to increment the versionCode on each build. On Each build a counter stored in the version.properties file. It will be keep updated on every new APK build and replace versionCode string in the build.gradle file with this incremented counter value.
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion '25.0.2'
def versionPropsFile = file('version.properties')
def versionBuild
/*Setting default value for versionBuild which is the last incremented value stored in the file */
if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
versionBuild = versionProps['VERSION_BUILD'].toInteger()
} else {
throw new FileNotFoundException("Could not read version.properties!")
}
/*Wrapping inside a method avoids auto incrementing on every gradle task run. Now it runs only when we build apk*/
ext.autoIncrementBuildNumber = {
if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
versionBuild = versionProps['VERSION_BUILD'].toInteger() + 1
versionProps['VERSION_BUILD'] = versionBuild.toString()
versionProps.store(versionPropsFile.nminSdkVersion 14
targetSdkVersion 21
versionCode 1ewWriter(), null)
} else {
throw new FileNotFoundException("Could not read version.properties!")
}
}
defaultConfig {
minSdkVersion 16
targetSdkVersion 21
versionCode 1
versionName "1.0.0." + versionBuild
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
// Hook to check if the release/debug task is among the tasks to be executed.
//Let's make use of it
gradle.taskGraph.whenReady {taskGraph ->
if (taskGraph.hasTask(assembleDebug)) { /* when run debug task */
autoIncrementBuildNumber()
} else if (taskGraph.hasTask(assembleRelease)) { /* when run release task */
autoIncrementBuildNumber()
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.3.1'
}
Place the above script inside your build.gradle file of main module.
Reference Website: http://devdeeds.com/auto-increment-build-number-using-gradle-in-android/
Thanks & Regards!
I know it's a little late for an answer, but I've created a polyfill for the .live() method. I've tested it in jQuery 1.11, and it seems to work pretty well. I know that we're supposed to implement the .on() method wherever possible, but in big projects, where it's not possible to convert all .live() calls to the equivalent .on() calls for whatever reason, the following might work:
if(jQuery && !jQuery.fn.live) {
jQuery.fn.live = function(evt, func) {
$('body').on(evt, this.selector, func);
}
}
Just include it after you load jQuery and before you call live().
I hope this explaination gives a more intuitive appeal to dependency than the answers previously given.
An analysis of dependency operates on the attribute level, i.e. one or more attribute is determined by another attribute, it comes before the concept of keys. 'The role of a key is based on the concept of determination. 'Determination is the state in which knowing the value of one attribute makes it possible to determine the value of another.' Database Systems 12ed
Functional dependency is when one or more attributes determine one or more attributes. For instance:
Social Security Number -> First Name, Last Name.
However, by definition of functional dependency:
(SSN, First Name) -> Last Name
This is also a valid functional dependency. The determinants (The attribute that which determines another attribution) are called super key.
Thus, as a subset of functional dependency, there is the concept of full functional dependency, where the bare minimal determinant is considered. We refer those bare minimal determinants collectively as one candidate key (weird linguistic quirk in my opinion, like the concept of vector).
However, sometimes one of the attributes in the candidate key is sufficient to determine another attribute(s), BUT not all, in a relation (a table with no rows). That, is when you have a partial functional dependency within a relation.
Also, consider to use a repository manager such as Nexus and configure all your repositories there.
I just answered a similar question here
IMHO, if your FTP server is able to communicate with Fabric please us Fabric. It is far better than doing raw ftp
.
I have an FTP account from dotgeek.com
so I am not sure if this will work for other FTP accounts.
#!/usr/bin/python
from fabric.api import run, env, sudo, put
env.user = 'username'
env.hosts = ['ftp_host_name',] # such as ftp.google.com
def copy():
# assuming i have wong_8066.zip in the same directory as this script
put('wong_8066.zip', '/www/public/wong_8066.zip')
save the file as fabfile.py
and run fab copy
locally.
yeukhon@yeukhon-P5E-VM-DO:~$ fab copy2
[1.ai] Executing task 'copy2'
[1.ai] Login password:
[1.ai] put: wong_8066.zip -> /www/public/wong_8066.zip
Done.
Disconnecting from 1.ai... done.
Once again, if you don't want to input password all the time, just add
env.password = 'my_password'
worked for me too:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date parsed = null;
try {
parsed = sdf.parse("02/01/2014");
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.sql.Date data = new java.sql.Date(parsed.getTime());
contato.setDataNascimento( data);
// Contato DataNascimento era Calendar
//contato.setDataNascimento(Calendar.getInstance());
// grave nessa conexão!!!
ContatoDao dao = new ContatoDao("mysql");
// método elegante
dao.adiciona(contato);
System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());
If you build your libraries with gradle, you can attach sources to the jars you create and then eclipse will automatically use them. See the answer by @MichaelOryl How to build sources jar with gradle.
Copied here for your reference:
jar {
from sourceSets.main.allSource
}
The solution shown is for use with the gradle java plugin. Mileage may vary if you're not using that plugin.
called_from
must be null
. Add a test against that condition like
if (called_from != null && called_from.equalsIgnoreCase("add")) {
or you could use Yoda conditions (per the Advantages in the linked Wikipedia article it can also solve some types of unsafe null
behavior they can be described as placing the constant portion of the expression on the left side of the conditional statement)
if ("add".equalsIgnoreCase(called_from)) { // <-- safe if called_from is null
My solution might not be the cleanest but it should work with no problems.
The logic is simply to create a static variable to store your data on the Service
and update your view each second on your Activity
.
Let's say that you have a String
on your Service
that you want to send it to a TextView
on your Activity
. It should look like this
Your Service:
public class TestService extends Service {
public static String myString = "";
// Do some stuff with myString
Your Activty:
public class TestActivity extends Activity {
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
setContentView(tv);
update();
Thread t = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
update();
}
});
}
} catch (InterruptedException ignored) {}
}
};
t.start();
startService(new Intent(this, TestService.class));
}
private void update() {
// update your interface here
tv.setText(TestService.myString);
}
}
This is backwards from what Bootstrap is designed for, but you can do this:
<div class="row">
<div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
<div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
<div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
</div>
This will make each element 33.3% wide on small and extra small devices but 100% wide on medium and larger devices.
JSFiddle: http://jsfiddle.net/jdwire/sggt8/embedded/result/
I think you're looking for the visible-xs
and/or visible-sm
classes. These will let you make certain elements only visible to small screen devices.
For example, if you want a element to only be visible to small and extra-small devices, do this:
<div class="visible-xs visible-sm">You're using a fairly small device.</div>
To show it only for larger screens, use this:
<div class="hidden-xs hidden-sm">You're probably not using a phone.</div>
See http://getbootstrap.com/css/#responsive-utilities-classes for more information.
I prefer to process collections functionally rather than mutate them in place. That avoids this kind of problem altogether, as well as aliasing issues and other tricky sources of bugs.
So, I would implement it like:
List<Thing> expand(List<Thing> inputs) {
List<Thing> expanded = new ArrayList<Thing>();
for (Thing thing : inputs) {
expanded.add(thing);
if (needsSomeMoreThings(thing)) {
addMoreThingsTo(expanded);
}
}
return expanded;
}
In python 3 you can do this to print on the same line:
print('', end='\r')
Especially useful to keep track of the latest update and progress.
I would also recommend tqdm from here if one wants to see the progress of a loop. It prints the current iteration and total iterations as a progression bar with an expected time of finishing. Super useful and quick. Works for python2 and python3.
<div>
<div class="a">
A
</div>
</div>?
$(window).scroll(function() {
if ($(this).scrollTop() > 0) {
$('.a').fadeOut();
} else {
$('.a').fadeIn();
}
});
This problem arises due to incompatible JDK version. Download and install latest JDK(currently its 8) from java official site in case you are using previous versions. Then in Android Studio go to File->Project Structure->SDK location -> JDK location and set it to 'C:\Program Files\Java\jdk1.8.0_121' (Default location of JDK). Gradle sync your project and you are all set...
A simple return
statement will 'stop' or return the function; in precise terms, it 'returns' function execution to the point at which the function was called - the function is terminated without further action.
That means you could have a number of places throughout your function where it might return. Like this:
def player():
# do something here
check_winner_variable = check_winner() # check something
if check_winner_variable == '1':
return
second_test_variable = second_test()
if second_test_variable == '1':
return
# let the computer do something
computer()
It's just the syntax. '<' is a binary operation, and most languages don't make it transitive. They could have made it like the way you say, but then somebody would be asking why you can't do other operations in trinary as well. "if (12 < x != 5)"?
Syntax is always a trade-off between complexity, expressiveness and readability. Different language designers make different choices. For instance, SQL has "x BETWEEN y AND z", where x, y, and z can individually or all be columns, constants, or bound variables. And I'm happy to use it in SQL, and I'm equally happy not to worry about why it's not in Java.
I don't know what your use case was, however in addition to other answers here another (lazy) option is to still sort in ascending order as you indicate but then iterate in reverse order instead.
I've used sortUsingFunction:: in some of my projects:
int SortPlays(id a, id b, void* context)
{
Play* p1 = a;
Play* p2 = b;
if (p1.score<p2.score)
return NSOrderedDescending;
else if (p1.score>p2.score)
return NSOrderedAscending;
return NSOrderedSame;
}
...
[validPlays sortUsingFunction:SortPlays context:nil];
ng-if="select.name.indexOf('?') !== -1"
There is also http://appyframework.org/pod.html which takes a LibreOffice or OpenOffice document as template and can generate pdf, rtf, odt ... To generate pdf it requires a headless OOo on some server. Documentation is concise but relatively complete. http://appyframework.org/podWritingTemplates.html If you need advice, the author is rather helpful.
After implementing a classic pattern like
class Singleton {
private instance: Singleton;
private constructor() {}
public getInstance() {
if (!this.instance) {
this.instance = new Singleton();
}
return this.instance;
}
}
I realized it's pretty useless in case you want some other class to be a singleton too. It's not extendable. You have to write that singleton stuff for every class you want to be a singleton.
Decorators for the rescue.
@singleton
class MyClassThatIsSingletonToo {}
You can write decorator by yourself or take some from npm. I found this proxy-based implementation from @keenondrums/singleton package neat enough.
int
(including Python2's long
) can be converted to bytes
using following function:
import codecs
def int2bytes(i):
hex_value = '{0:x}'.format(i)
# make length of hex_value a multiple of two
hex_value = '0' * (len(hex_value) % 2) + hex_value
return codecs.decode(hex_value, 'hex_codec')
The reverse conversion can be done by another one:
import codecs
import six # should be installed via 'pip install six'
long = six.integer_types[-1]
def bytes2int(b):
return long(codecs.encode(b, 'hex_codec'), 16)
Both functions work on both Python2 and Python3.
I wrote a method (see below) which extracts a url's domain name and which uses simple String matching. What it actually does is extract the bit between the first "://"
(or index 0
if there's no "://"
contained) and the first subsequent "/"
(or index String.length()
if there's no subsequent "/"
). The remaining, preceding "www(_)*."
bit is chopped off. I'm sure there'll be cases where this won't be good enough but it should be good enough in most cases!
Mike Samuel's post above says that the java.net.URI
class could do this (and was preferred to the java.net.URL
class) but I encountered problems with the URI
class. Notably, URI.getHost()
gives a null value if the url does not include the scheme, i.e. the "http(s)"
bit.
/**
* Extracts the domain name from {@code url}
* by means of String manipulation
* rather than using the {@link URI} or {@link URL} class.
*
* @param url is non-null.
* @return the domain name within {@code url}.
*/
public String getUrlDomainName(String url) {
String domainName = new String(url);
int index = domainName.indexOf("://");
if (index != -1) {
// keep everything after the "://"
domainName = domainName.substring(index + 3);
}
index = domainName.indexOf('/');
if (index != -1) {
// keep everything before the '/'
domainName = domainName.substring(0, index);
}
// check for and remove a preceding 'www'
// followed by any sequence of characters (non-greedy)
// followed by a '.'
// from the beginning of the string
domainName = domainName.replaceFirst("^www.*?\\.", "");
return domainName;
}
There is an official Python receipe for the more generalized case of splitting an array into smaller arrays of size n
.
from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
This code snippet is from the python itertools doc page.
I have run into the same error entries in LogCat. In my case it's caused by the 3rd party keyboard I am using. When I change it back to Android keyboard, the error entry does not show up any more.
Are you trying to drop the FK constraint or the column itself?
To drop the constraint:
alter table company drop constraint Company_CountryID_FK
You won't be able to drop the column until you drop the constraint.
In newer versions of Excel (2013 and up) flash fill might be a simple and quick solution see: Using Flash Fill in Excel .
I recommend always using a named range (as you have suggested you are doing) because if any columns or rows are added or deleted, the name reference will update, whereas if you hard code the cell reference (eg "H1" as suggested in one of the responses) in VBA, then it will not update and will point to the wrong cell.
So
Range("RefNo") = InputBox("....")
is safer than
Range("H1") = InputBox("....")
You can set the value of several cells, too.
Range("Results").Resize(10,3) = arrResults()
where arrResults is an array of at least 10 rows & 3 columns (and can be any type). If you use this, put this
Option Base 1
at the top of the VBA module, otherwise VBA will assume the array starts at 0 and put a blank first row and column in the sheet. This line makes all arrays start at 1 as a default (which may be abnormal in most languages but works well with spreadsheets).
I solved it myself for the time being. The original value has only 2 sub-properties. I reformed a new object with the properties from a
and then assigned it to b
. Now my event handler updates only b
, and my original a
stays as it is.
var a = { key1: 'value1', key2: 'value2' },
b = a;
$('#revert').on('click', function(e){
//FAIL!
b = a;
//WIN
b = { key1: a.key1, key2: a.key2 };
});
This works fine. I have not changed a single line anywhere in my code except for the above, and it works just how I wanted it to. So, trust me, nothing else was updating a
.
Just noticed that quick search has been included into eclipse 4.13 as a built-in function by typing Ctrl+Alt+Shift+L (or Cmd+Alt+Shift+L on Mac)
https://www.eclipse.org/eclipse/news/4.13/platform.php#quick-text-search
To exit a script you can use,
import sys
sys.exit()
You can also provide an exit status value, usually an integer.
import sys
sys.exit(0)
Exits with zero, which is generally interpreted as success. Non-zero codes are usually treated as errors. The default is to exit with zero.
import sys
sys.exit("aa! errors!")
Prints "aa! errors!" and exits with a status code of 1.
There is also an _exit() function in the os module. The sys.exit() function raises a SystemExit exception to exit the program, so try statements and cleanup code can execute. The os._exit() version doesn't do this. It just ends the program without doing any cleanup or flushing output buffers, so it shouldn't normally be used.
The Python docs indicate that os._exit() is the normal way to end a child process created with a call to os.fork(), so it does have a use in certain circumstances.
Move to front by transform:TranslateZ
Warning: Only works in FireFox
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 160" style="width:160px; height:160px;">
<g style="transform-style: preserve-3d;">
<g id="one" style="transform-style: preserve-3d;">
<circle fill="green" cx="100" cy="105" r="20" style="transform:TranslateZ(1px);"></circle>
</g>
<g id="two" style="transform-style: preserve-3d;">
<circle fill="orange" cx="100" cy="95" r="20"></circle>
</g>
</g>
</svg>
_x000D_
But to make sure that your new row is accessible in the new table, you need to close the table:
DataTable destination = new DataTable(source.TableName);
destination = source.Clone();
DataRow sourceRow = source.Rows[0];
destination.ImportRow(sourceRow);
Regex.Replace(strInput, strToken.Replace("$", "[$]"), strReplaceWith, RegexOptions.IgnoreCase);
Great answers. I also had a problem with NULLS and managed to solve it by including a COALESCE inside of the GROUP_CONCAT. Example as follows:
SELECT id, GROUP_CONCAT(COALESCE(name,'') SEPARATOR ' ')
FROM table
GROUP BY id;
Hope this helps someone else
I had a similar issue with a ~400MB file. Setting low_memory=False
did the trick for me. Do the simple things first,I would check that your dataframe isn't bigger than your system memory, reboot, clear the RAM before proceeding. If you're still running into errors, its worth making sure your .csv
file is ok, take a quick look in Excel and make sure there's no obvious corruption. Broken original data can wreak havoc...
//Check xml element value if exists using XmlReader
using (XmlReader xmlReader = XmlReader.Create(new StringReader("XMLSTRING")))
{
if (xmlReader.ReadToFollowing("XMLNODE"))
{
string nodeValue = xmlReader.ReadElementString("XMLNODE");
}
}
<a target="_blank" title="Share this page" href="http://www.sharethis.com/share?url=[INSERT URL]&title=[INSERT TITLE]&summary=[INSERT SUMMARY]&img=[INSERT IMAGE URL]&pageInfo=%7B%22hostname%22%3A%22[INSERT DOMAIN NAME]%22%2C%22publisher%22%3A%22[INSERT PUBLISHERID]%22%7D"><img width="86" height="25" alt="Share this page" src="http://w.sharethis.com/images/share-classic.gif"></a>
Instructions
First, insert these lines wherever you want within your newsletter code. Then:
If you are using this on an email newsletter, make sure you add our sharing buttons to the destination page. This will ensure that you get complete sharing analytics for your page. Make sure you replace "INSERT PUBLISHERID" with your own.
for get week number in jalai calendar you can use this:
$weeknumber = date("W"); //number week in year
$dayweek = date("w"); //number day in week
if ($dayweek == "6")
{
$weeknumberint = (int)$weeknumber;
$date2int++;
$weeknumber = (string)$date2int;
}
echo $date2;
result:
15
week number change in saturday
Try to run this command if you are using nohup -
nohup npm start 2>/dev/null 1>/dev/null&
You can also use forever to start server
forever start -c "npm start" ./
PM2 also supports npm start
pm2 start npm -- start
But again main doubt why TextView resource id it needs?
Look at the constructor and the params.
public ArrayAdapter (Context context, int resource, int textViewResourceId, T[] objects)
Added in API level 1 Constructor
Parameters
context
The current context.
resource
The resource ID for a layout file containing a layout to use when instantiating views.
textViewResourceId
The id of the TextView within the layout resource to be populated objects The objects to represent in theListView
.
android.R.id.text1
refers to the id of text in android resource. So you need not have the one in your activity.
Here's the full list
http://developer.android.com/reference/android/R.id.html
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
this
refers to activity context
android.R.layout.simple_list_item_1
simple_list_item_1 is the layout in android.R.layout.
android.R.id.text1
refers to the android resource id.
values
is a string array from the link you provided
http://developer.android.com/reference/android/R.layout.html
This will do the job:
<div style="position:absolute; right:0;">Hello world</div>
_x000D_
Tables work differently; sometimes counter-intuitively.
The solution is to use width
on the table cells instead of max-width
.
Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.
I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.
table {_x000D_
width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
border: 0;_x000D_
border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
min-width: 10px;_x000D_
width: 20px;_x000D_
max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
min-width: 40px;_x000D_
width: 45px;_x000D_
max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
<tr>_x000D_
<td class="a">A</td>_x000D_
<td class="b">B</td>_x000D_
<td class="c">C</td>_x000D_
</tr>_x000D_
</table>
_x000D_
You could just have <hr style="border-top: dotted 1px;" />
. That should work.
If a linked server is not allowed by your dba, you can use OPENROWSET. Books Online will provide the syntax you need.
New Python users on Windows often forget to add Python's \Scripts directory to the PATH variable during the installation. I recommend to use the Python launcher and execute pip as a script with the -m
switch. Then you can install the wheels for a specific Python version (if more than one are installed) and the Scripts directory doesn't have to be in the PATH. So open the command line, navigate (with the cd
command) to the folder where the .whl file is located and enter:
py -3.6 -m pip install your_whl_file.whl
Replace 3.6
by your Python version or just enter -3
if the desired Python version appears first in the PATH. And with an active virtual environment: py -m pip install your_whl_file.whl
.
Of course you can also install packages from PyPI in this way, e.g.
py -3.6 -m pip install pygame
There's nothing on the Documentation that mentions about anything like that.
Here's a quote:
-Dproperty=value Set a system property value. If value is a string that contains spaces, you must enclose the string in double quotes:
java -Dfoo="some string" SomeClass
A StaticResource will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored.
A DynamicResource assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.
Below grep with regex is also working,
>pwd | grep -o "\w*-*$"
export PATH=/usr/local/bin:$PATH
brew update
brew install vim && brew install macvim
brew link macvim
You now have the latest versions of vim and macvim managed by brew. Run brew update && brew upgrade
every once in a while to upgrade them.
This includes the installation of the CLI mvim
and the mac application (which both point to the same thing).
I use this setup and it works like a charm. Brew even takes care of installing vim with the preferable options.
The solution is in the link that you provided in your question:
datetime.combine(date.today(), time()) + timedelta(hours=1)
Full example:
from datetime import date, datetime, time, timedelta
dt = datetime.combine(date.today(), time(23, 55)) + timedelta(minutes=30)
print dt.time()
Output:
00:25:00
I was getting the same error but it's sorted now. In my case, I had columns with the heading "Key1", "Key2", and "Key3". I have changed the column names to something else and it's sorted.
It seems that these are reserved keywords.
Regards, Mahesh
Three ways to pass model data to partial view (there may be more)
This is view page
Method One Populate at view
@{
PartialViewTestSOl.Models.CountryModel ctry1 = new PartialViewTestSOl.Models.CountryModel();
ctry1.CountryName="India";
ctry1.ID=1;
PartialViewTestSOl.Models.CountryModel ctry2 = new PartialViewTestSOl.Models.CountryModel();
ctry2.CountryName="Africa";
ctry2.ID=2;
List<PartialViewTestSOl.Models.CountryModel> CountryList = new List<PartialViewTestSOl.Models.CountryModel>();
CountryList.Add(ctry1);
CountryList.Add(ctry2);
}
@{
Html.RenderPartial("~/Views/PartialViewTest.cshtml",CountryList );
}
Method Two Pass Through ViewBag
@{
var country = (List<PartialViewTestSOl.Models.CountryModel>)ViewBag.CountryList;
Html.RenderPartial("~/Views/PartialViewTest.cshtml",country );
}
Method Three pass through model
@{
Html.RenderPartial("~/Views/PartialViewTest.cshtml",Model.country );
}
You could just write it out in multiline like this,
$ cat dict.go
package main
import "fmt"
func main() {
items := map[string]interface{}{
"foo": map[string]int{
"strength": 10,
"age": 2000,
},
"bar": map[string]int{
"strength": 20,
"age": 1000,
},
}
for key, value := range items {
fmt.Println("[", key, "] has items:")
for k,v := range value.(map[string]int) {
fmt.Println("\t-->", k, ":", v)
}
}
}
And the output:
$ go run dict.go
[ foo ] has items:
--> strength : 10
--> age : 2000
[ bar ] has items:
--> strength : 20
--> age : 1000
A recursive CTE solution was suggested, but no code was provided. The code below is an example of a recursive CTE. Note that although the results match the question, the data doesn't quite match the given description, as I assume that you really want to be doing this on groups of rows, not all rows in the table. Changing it to match all rows in the table is left as an exercise for the reader.
;WITH basetable AS (
SELECT
id,
CAST(name AS VARCHAR(MAX)) name,
ROW_NUMBER() OVER (Partition BY id ORDER BY seq) rw,
COUNT(*) OVER (Partition BY id) recs
FROM (VALUES
(1, 'Johnny', 1),
(1, 'M', 2),
(2, 'Bill', 1),
(2, 'S.', 4),
(2, 'Preston', 5),
(2, 'Esq.', 6),
(3, 'Ted', 1),
(3, 'Theodore', 2),
(3, 'Logan', 3),
(4, 'Peter', 1),
(4, 'Paul', 2),
(4, 'Mary', 3)
) g (id, name, seq)
),
rCTE AS (
SELECT recs, id, name, rw
FROM basetable
WHERE rw = 1
UNION ALL
SELECT b.recs, r.ID, r.name +', '+ b.name name, r.rw + 1
FROM basetable b
INNER JOIN rCTE r ON b.id = r.id AND b.rw = r.rw + 1
)
SELECT name
FROM rCTE
WHERE recs = rw AND ID=4
1 use eclipse bar to install a Mat plug-in to analyze, is a good choice. Studio Memory provides the Monitor 2.Android studio to display the memory occupancy of the application in real time.
getdate()
or getutcdate()
.
Try the following command sequence:
$ git fetch origin <copy/past commit sha1 here>
$ git checkout FETCH_HEAD
$ git push origin master
You can do the following, which is referred to as a recursive query:
WITH y
AS
(
SELECT x, y, z
FROM MyTable
WHERE [base_condition]
UNION ALL
SELECT x, y, z
FROM MyTable M
INNER JOIN y ON M.[some_other_condition] = y.[some_other_condition]
)
SELECT *
FROM y
You may not need this functionality. I've done the following just to organize my queries better:
WITH y
AS
(
SELECT *
FROM MyTable
WHERE [base_condition]
),
x
AS
(
SELECT *
FROM y
WHERE [something_else]
)
SELECT *
FROM x
The tag is not closed:
$form.append("<input type=button value=button");
Should be:
$form.append('<input type="button" value="button">');
Remove all the texts in android/settings.gradle and paste the below code
rootProject.name = '****Your Project Name****'
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'
This issue will usually happen when you migrate from react-native < 0.60 to react-native >0.60. If you create a new project in react-native >0.60 you will see the same settings as above mentioned
I had the same issue, but came up with a different solution:
If you make the column or the whole grid "Read Only" so that when the user clicks the checkbox it doesn't change value.
Fortunately, the DataGridView.CellClick
event is still fired.
In my case I do the following in the cellClick
event:
if (jM_jobTasksDataGridView.Columns[e.ColumnIndex].CellType.Name == "DataGridViewCheckBoxCell")
But you could check the column name if you have more than one checkbox column.
I then do all the modification / saving of the dataset myself.
While jball's answer is an excellent description of content insets, it doesn't answer the question of when to use it. I'll borrow from his diagrams:
_|?_cW_?_|_?_
| |
---------------
|content| ?
? |content| contentInset.top
cH |content|
? |content| contentInset.bottom
|content| ?
---------------
|content|
-------------?-
That's what you get when you do it, but the usefulness of it only shows when you scroll:
_|?_cW_?_|_?_
|content| ? content is still visible
---------------
|content| ?
? |content| contentInset.top
cH |content|
? |content| contentInset.bottom
|content| ?
---------------
_|_______|___
?
That top row of content will still be visible because it's still inside the frame of the scroll view. One way to think of the top offset is "how much to shift the content down the scroll view when we're scrolled all the way to the top"
To see a place where this is actually used, look at the build-in Photos app on the iphone. The Navigation bar and status bar are transparent, and the contents of the scroll view are visible underneath. That's because the scroll view's frame extends out that far. But if it wasn't for the content inset, you would never be able to have the top of the content clear that transparent navigation bar when you go all the way to the top.
Declare them before the while loop.
$hn = "";
$pid = "";
$datereg = "";
$prefix = "";
$fname = "";
$lname = "";
$age = "";
$sex = "";
You are getting the notice because the variables are declared and assigned inside the loop.
Russian.
Month
.MAY
.getDisplayName(
TextStyle.FULL_STANDALONE ,
new Locale( "ru" , "RU" )
)
???
English in the United States.
Month
.MAY
.getDisplayName(
TextStyle.FULL_STANDALONE ,
Locale.US
)
May
See this code run live at IdeOne.com.
Here’s the modern answer. When this question was asked in 2011, Calendar
and GregorianCalendar
were commonly used for dates and times even though they were always poorly designed. That’s 8 years ago now, and those classes are long outdated. Assuming you are not yet on API level 26, my suggestion is to use the ThreeTenABP library, which contains an Android adapted backport of java.time, the modern Java date and time API. java.time is so much nicer to work with.
Depending on your exact needs and situation there are two options:
Month
and its getDisplayName
method.DateTimeFormatter
. Locale desiredLanguage = Locale.ENGLISH;
Month m = Month.MAY;
String monthName = m.getDisplayName(TextStyle.FULL, desiredLanguage);
System.out.println(monthName);
Output from this snippet is:
May
In a few languages it will make a difference whether you use TextStyle.FULL
or TextStyle.FULL_STANDALONE
. You will have to see, maybe check with your users, which of the two fits into your context.
If you’ve got a date with or without time of day, I find a DateTimeFormatter
more practical. For example:
DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMMM", desiredLanguage);
ZonedDateTime dateTime = ZonedDateTime.of(2019, 5, 31, 23, 49, 51, 0, ZoneId.of("America/Araguaina"));
String monthName = dateTime.format(monthFormatter);
I am showing the use of a ZonedDateTime
, the closest replacement for the old Calendar
class. The above code will work for a LocalDate
, a LocalDateTime
, MonthDay
, OffsetDateTime
and a YearMonth
too.
What if you got a Calendar
from a legacy API not yet upgraded to java.time? Convert to a ZonedDateTime
and proceed as above:
Calendar c = getCalendarFromLegacyApi();
ZonedDateTime dateTime = DateTimeUtils.toZonedDateTime(c);
The rest is the same as before.
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).If following symbolic links is not important, you can also use the os.lstat
builtin.
>>> os.lstat("2048.py")
posix.stat_result(st_mode=33188, st_ino=4172202, st_dev=16777218L, st_nlink=1, st_uid=501, st_gid=20, st_size=2078, st_atime=1423378041, st_mtime=1423377552, st_ctime=1423377553)
>>> os.lstat("2048.py").st_atime
1423378041.0
Many in the community would prefer no limit with warnings about performance, see this comment for a well reasoned argument: https://jira.mongodb.org/browse/SERVER-431?focusedCommentId=22283&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-22283
My take, the lead developers are stubborn about this issue because they decided it was an important "feature" early on. They're not going to change it anytime soon because their feelings are hurt that anyone questioned it. Another example of personality and politics detracting from a product in open source communities but this is not really a crippling issue.
You can add org.apache.http
by using below code in app:Build gradle
dependencies {
compile 'org.apache.httpcomponents:httpclient:4.5'
}
This solved my issue.
Including following dependencies in your POM.xml and run Maven -> Update also fixed my issue.
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.19.1</version>
</dependency>
<dependency>
<groupId>com.owlike</groupId>
<artifactId>genson</artifactId>
<version>0.99</version>
</dependency>
What about: b - delta < a && a < b + delta
To view the file, run:
xxd filename | less
To use Vim as a hex editor:
:%!xxd
(transform buffer to hex):%!xxd -r
(reverse transformation)I need to add that, if the Module name and the sub name is the same you have such issue. Consider change the Module name to mod_Test instead of "Test" which is the same as the sub.
Another way to continue with the example @nfreeze used is this validation method:
UserModel.schema.path('name').validate(function (value, res) {
UserModel.findOne({name: value}, 'id', function(err, user) {
if (err) return res(err);
if (user) return res(false);
res(true);
});
}, 'already exists');
Pre-compiling the regex increases the speed. Re-using the Matcher gives you another slight speedup. If the method gets called frequently say gets called within a loop, the overall performace will certainly go up.
In H2, what works for me is:
I code, starting the server like:
server = Server.createTcpServer().start();
That starts the server on localhost
port 9092.
Then, in code, establish a DB connection on the following JDBC URL:
jdbc:h2:tcp://localhost:9092/mem:test;DB_CLOSE_DELAY=-1;MODE=MySQL
While debugging, as a client to inspect the DB I use the one provided by H2, which is good enough, to launch it you just need to launch the following java main separately
org.h2.tools.Console
This will start a web server with an app on 8082, launch a browser on localhost:8082
And then you can enter the previous URL to see the DB
You need to understand java generics. You have a list of ClientThread
but trying to get String
. You have other errors, but this one is very basic.
myApp.controller('mainController', ['$scope', '$log', function($scope, $log) {
$scope.person = {
name:"sangeetha PH",
address:"first Block"
}
}]);
myApp.directive('searchResult',function(){
return{
restrict:'AECM',
templateUrl:'directives/search.html',
replace: true,
scope:{
personName:"@",
personAddress:"@"
}
}
});
USAGE
File :directives/search.html
content:
<h1>{{personName}} </h1>
<h2>{{personAddress}}</h2>
the File where we use directive
<search-result person-name="{{person.name}}" person-address="{{person.address}}"></search-result>