It looks like mysql service is either not working or stopped. you can start it by using below command (in Ubuntu):
service mysql start
It should work! If you are using any other operating system than Ubuntu then use appropriate way to start mysql
Just change the port to 8081
and following virtual host will work:
<VirtualHost *:8081>
ServerName comm-app.local
DocumentRoot "C:/xampp/htdocs/CommunicationApp/public"
SetEnv APPLICATION_ENV "development"
<Directory "C:/xampp/htdocs/CommunicationApp/public">
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
The Other Issue I have seen on this is when nesting arrays this tends to throw the warning, consider the following:
$data = [
"rs" => null
]
this above will work absolutely fine when used like:
$data["rs"] = 5;
But the below will throw a warning ::
$data = [
"rs" => [
"rs1" => null;
]
]
..
$data[rs][rs1] = 2; // this will throw the warning unless assigned to an array
This can happen due to too many connection same time or many chat at same time. Also it can happen due too many session.
The best way to sort out this issue is restart MySQL.
service mysqld restart
or
service mysql restart
or
/etc/init.d/mysqld restart
A convenient solution in your case would be to include the configs in a yaml file named
**your_config_name.yml**
which would look like this:
path1: "D:\test1\first"
path2: "D:\test2\second"
path3: "D:\test2\third"
In your python code you can then load the config params into a dictionary by doing this:
import yaml
with open('your_config_name.yml') as stream:
config = yaml.safe_load(stream)
You then access e.g. path1 like this from your dictionary config:
config['path1']
To import yaml you first have to install the package as such: pip install pyyaml
into your chosen virtual environment.
This is one way to do it:
Fiddle here: http://jsfiddle.net/4Mvan/1/
HTML:
<div class='container'>
<a href='#'>
<img class='resize_fit_center'
src='http://i.imgur.com/H9lpVkZ.jpg' />
</a>
</div>
CSS:
.container {
margin: 10px;
width: 115px;
height: 115px;
line-height: 115px;
text-align: center;
border: 1px solid red;
}
.resize_fit_center {
max-width:100%;
max-height:100%;
vertical-align: middle;
}
def solve(s):
for i in s[:].split():
s = s.replace(i, i.capitalize())
return s
This is the actual code for work. .title() will not work at '12name' case
In my case there was no DEFINER
or root@localhost
mentioned in my SQL file. Actually I was trying to import and run SQL file into SQLYog from Database
->Import
->Execute SQL Script
menu. That was giving error.
Then I copied all the script from SQL file and ran in SQLYog query editor. That worked perfectly fine.
Change the signature of the CreateFile
method to expect a SupportedPermissions
value instead of plain Enum.
public string CreateFile(string id, string name, string description, SupportedPermissions supportedPermissions)
{
file = new File
{
Name = name,
Id = id,
Description = description,
SupportedPermissions = supportedPermissions
};
return file.Id;
}
Then when you call your method you pass the SupportedPermissions
value to your method
var basicFile = CreateFile(myId, myName, myDescription, SupportedPermissions.basic);
The return false
prevents the page from being navigated and unwanted scrolling of a window to the top or bottom.
onclick="return false"
RealVNC 5.0.x now offers a VNCViewer that will do dual displays on Windows without having to buy a license. (Licensing now covers the SERVER portion of their tools).
The fix for me was to set property HorizontalAlignment="Stretch"
on ItemsPresenter
inside ScrollViewe
r..
Hope this helps someone...
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBox">
<ScrollViewer x:Name="ScrollViewer" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Foreground="{TemplateBinding Foreground}" Padding="{TemplateBinding Padding}" HorizontalAlignment="Stretch">
<ItemsPresenter Height="252" HorizontalAlignment="Stretch"/>
</ScrollViewer>
</ControlTemplate>
</Setter.Value>
</Setter>
Yeah, when ASP.NET web.config gets updated, the whole application gets restarted which means the web.config gets reloaded.
The problem is how 100% height is being calculated. Two ways to deal with this.
Add 20px to the body padding-bottom
body {
padding-bottom: 20px;
}
or add a transparent border to body
body {
border: 1px solid transparent;
}
Both worked for me in firebug
Below are some comments regarding the correctness of my answer to this question. These kinds of discussions are exactly why stackoverflow is so great. Many different people have different opinions on how best to solve the problem. I've learned some incredible coding style that I would not have thought of myself. And I've been told that readers have learned something from my style from time to time. Social coding has really encouraged me to be a better programmer.
Social coding can, at times, be disturbing. I hate it when I spend 30 minutes flushing out an answer with a jsfiddle and detailed explanation only to submit and find 10 other answers all saying the same thing in less detail. And the author accepts someone else's answer. How frustrating! I think that this has happend to my fellow contributors–in particular thirtydot.
Thirtydot's answer is completely legit. The p
around the script
is the culprit in this problem. Remove it and the space goes away. It also is a good answer to this question.
But why? Shouldn't the p
tag's height, padding and margin be calculated into the height of the body?
And it is! If you remove the padding-bottom style that I've suggested and then set the body's background to black, you will see that the body's height includes this extra p
space accurately (you see the strip at the bottom turn to black). But the gradient fails to include it when finding where to start. This is the real problem.
The two solutions that I've offered are ways to tell the browser to calculate the gradient properly. In fact, the padding-bottom could just be 1px. The value isn't important, but the setting is. It makes the browser take a look at where the body ends. Setting the border will have the same effect.
In my opinion, a padding setting of 20px looks the best for this page and that is why I answered it this way. It is addressing the problem of where the gradient starts.
Now, if I were building this page. I would have avoided wrapping the script in a p tag. But I must assume that author of the page either can't change it or has a good reason for putting it in there. I don't know what that script does. Will it write something that needs a p tag? Again, I would avoid this practice and it is fine to question its presence, but also I accept that there are cases where it must be there.
My hope in writing this "defense" is that the people who marked down this answer might consider that decision. My answer is thought out, purposeful, and relevant. The author thought so. However, in this social environment, I respect that you disagree and have a right to degrade my answer. I just hope that your choice is motivated by disagreement with my answer and not that author chose mine over yours.
In my case, the problem was I didn't had a Tomcat server separately installed in my eclipse. I assumed my Springboot will start the server automatically within itself.
Since my main class extends SpringBootServletInitializer
and override configure
method, I definitely need a Tomcat server installed in my IDE.
To install, first download Apachce Tomcat (version 9 in my case) and create server using Servers tab.
After installation, run the main class on server.
Run As -> Run on Server
It is actually very easy. But there is no way you can achieve it directly. You need to select a service side technology. You can use anything for this part. And this is what we call a RESTful API or a SOAP API. It depends on you what to select. I have done many project with both. I would prefer REST. So what will happen you will have some scripts in your web server, and you know the URLs. For example we need to make a user registration. And for this we have
mydomain.com/v1/userregister.php
Now from the android side you will send an HTTP request to the above URL. And the above URL will handle the User Registration and will give you a response that whether the operation succeed or not.
For a complete detailed explanation of the above concept. You can visit the following link.
infile = open('filename.txt', 'r')
firstLine = infile.readline()
See String Formatting Operations:
%d
is the format code for an integer. %f
is the format code for a float.
%s
prints the str()
of an object (What you see when you print(object)
).
%r
prints the repr()
of an object (What you see when you print(repr(object))
.
For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:
>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
1.12
$result2 is resource link not a string to echo
it or to replace some of its parts with str_replace()
.
Consider the Switch Function as an alternative to multiple IIf()
expressions. It will return the value from the first expression/value pair where the expression evaluates as True, and ignore any remaining pairs. The concept is similar to the SELECT ... CASE
approach you referenced but which is not available in Access SQL.
If you want to display a calculated field as commission
:
SELECT
Switch(
OpeningBalance < 5001, 20,
OpeningBalance < 10001, 30,
OpeningBalance < 20001, 40,
OpeningBalance >= 20001, 50
) AS commission
FROM YourTable;
If you want to store that calculated value to a field named commission
:
UPDATE YourTable
SET commission =
Switch(
OpeningBalance < 5001, 20,
OpeningBalance < 10001, 30,
OpeningBalance < 20001, 40,
OpeningBalance >= 20001, 50
);
Either way, see whether you find Switch()
easier to understand and manage. Multiple IIf()s
can become mind-boggling as the number of conditions grows.
The easiest and the most correct (and legal) way is to use graph api.
Just perform the request: http://graph.facebook.com/4
which returns
{
"id": "4",
"name": "Mark Zuckerberg",
"first_name": "Mark",
"last_name": "Zuckerberg",
"link": "http://www.facebook.com/zuck",
"username": "zuck",
"gender": "male",
"locale": "en_US"
}
and take the link
key.
You can also reduce the traffic by using fields
parameter: http://graph.facebook.com/4?fields=link to get only what you need:
{
"link": "http://www.facebook.com/zuck",
"id": "4"
}
curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2
You are using a very old version of curl. My guess is that you run into the bug described 6 years ago. Fix is to update your curl.
In Swift 3.0 you can get the appdelegate
reference by
let appDelegate = UIApplication.shared.delegate as! AppDelegate
This is definitely help. Working. but set separator "none" from attribute inspector. Write following code in cellForRowAtIndexPath method
UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0,
cell.contentView.frame.size.height - 1.0,
cell.contentView.frame.size.width, 1)];
lineView.backgroundColor = [UIColor blackColor];
[cell.contentView addSubview:lineView];
As you are expecting it to know using the Javascript, I believe you want to know the JRE versioned being used in your browser. Hence you can include Java version tester applet which can exactly tell you the version of the current browser.
import java.applet.*;
import java.awt.*;
public class JavaVersionDisplayApplet extends Applet
{
private Label m_labVersionVendor;
public JavaVersionDisplayApplet() // Constructor
{
Color colFrameBackground = Color.pink;
this.setBackground(colFrameBackground);
m_labVersionVendor = new Label (" Java Version: " +
System.getProperty("java.version") +
" from "+System.getProperty("java.vendor"));
this.add(m_labVersionVendor);
}
}
I got the same error using:
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,700,700i,900,900i" type="text/css" media="all">
But once I added https: in the beginning of the href the error disappeared.
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,700,700i,900,900i" type="text/css" media="all">
The current C++ standard does not have hash maps, but the coming C++0x standard does, and these are already supported by g++ in the shape of "unordered maps":
#include <unordered_map>
#include <iostream>
#include <string>
using namespace std;
int main() {
unordered_map <string, int> m;
m["foo"] = 42;
cout << m["foo"] << endl;
}
In order to get this compile, you need to tell g++ that you are using C++0x:
g++ -std=c++0x main.cpp
These maps work pretty much as std::map does, except that instead of providing a custom operator<()
for your own types, you need to provide a custom hash function - suitable functions are provided for types like integers and strings.
status=canceled may happen also on ajax requests on JavaScript events:
<script>
$("#call_ajax").on("click", function(event){
$.ajax({
...
});
});
</script>
<button id="call_ajax">call</button>
The event successfully sends the request, but is is canceled then (but processed by the server). The reason is, the elements submit forms on click events, no matter if you make any ajax requests on the same click event.
To prevent request from being cancelled, JavaScript event.preventDefault(); have to be called:
<script>
$("#call_ajax").on("click", function(event){
event.preventDefault();
$.ajax({
...
});
});
</script>
This issue boiled down to how I was building my select2 select box. In one javascript file I had...
$(function(){
$(".select2").select2();
});
And in another js file an override...
$(function(){
var employerStateSelector =
$("#registration_employer_state").select2("destroy");
employerStateSelector.select2({
placeholder: 'Select a State...'
});
});
Moving the second override into a window load event resolved the issue.
$( window ).load(function() {
var employerStateSelector =
$("#registration_employer_state").select2("destroy");
employerStateSelector.select2({
placeholder: 'Select a State...'
});
});
This issue blossomed inside a Rails application
Have you looked into ZXING? I've been using it successfully to create barcodes. You can see a full working example in the bitcoin application src
// this is a small sample use of the QRCodeEncoder class from zxing
try {
// generate a 150x150 QR code
Bitmap bm = encodeAsBitmap(barcode_content, BarcodeFormat.QR_CODE, 150, 150);
if(bm != null) {
image_view.setImageBitmap(bm);
}
} catch (WriterException e) { //eek }
if you want same string output then try below else use without double quotes for proper output
$str = '20130814';
echo date('"F Y"', strtotime($str));
//output : "August 2013"
If you want to find a specific user's home directory, I don't believe you can do it directly.
When I've needed to do this before from Java I had to write some JNI native code that wrapped the UNIX getpwXXX()
family of calls.
If you want or don't mind having all the leading and trailing whitespace from your string removed you can use the strip
method.
" hello ".strip #=> "hello"
"\tgoodbye\r\n".strip #=> "goodbye"
as mentioned here.
edit The original title for this question was different. My answer is for the original question.
Jack M. is right. Do it this way:
>>> class City:
... def __init__(self, city=None):
... self.city = city
... def __repr__(self):
... if self.city: return self.city
... return ''
...
>>> c = City('Berlin')
>>> print c
Berlin
>>> c = City()
>>> print c
>>>
check if this works for you,
public <T,S,K,V> ResponseObject<Collection<ResponseObject<T>>> runOnScheduler(ThreadPoolExecutor threadPoolExecutor,
int parallelismLevel, TimeUnit timeUnit, int timeToCompleteEachTask, Collection<S> collection,
Map<K,V> context, Task<T,S,K,V> someTask){
if(threadPoolExecutor==null){
return ResponseObject.<Collection<ResponseObject<T>>>builder().errorCode("500").errorMessage("threadPoolExecutor can not be null").build();
}
if(someTask==null){
return ResponseObject.<Collection<ResponseObject<T>>>builder().errorCode("500").errorMessage("Task can not be null").build();
}
if(CollectionUtils.isEmpty(collection)){
return ResponseObject.<Collection<ResponseObject<T>>>builder().errorCode("500").errorMessage("input collection can not be empty").build();
}
LinkedBlockingQueue<Callable<T>> callableLinkedBlockingQueue = new LinkedBlockingQueue<>(collection.size());
collection.forEach(value -> {
callableLinkedBlockingQueue.offer(()->someTask.perform(value,context)); //pass some values in callable. which can be anything.
});
LinkedBlockingQueue<Future<T>> futures = new LinkedBlockingQueue<>();
int count = 0;
while(count<parallelismLevel && count < callableLinkedBlockingQueue.size()){
Future<T> f = threadPoolExecutor.submit(callableLinkedBlockingQueue.poll());
futures.offer(f);
count++;
}
Collection<ResponseObject<T>> responseCollection = new ArrayList<>();
while(futures.size()>0){
Future<T> future = futures.poll();
ResponseObject<T> responseObject = null;
try {
T response = future.get(timeToCompleteEachTask, timeUnit);
responseObject = ResponseObject.<T>builder().data(response).build();
} catch (InterruptedException e) {
future.cancel(true);
} catch (ExecutionException e) {
future.cancel(true);
} catch (TimeoutException e) {
future.cancel(true);
} finally {
if (Objects.nonNull(responseObject)) {
responseCollection.add(responseObject);
}
futures.remove(future);//remove this
Callable<T> callable = getRemainingCallables(callableLinkedBlockingQueue);
if(null!=callable){
Future<T> f = threadPoolExecutor.submit(callable);
futures.add(f);
}
}
}
return ResponseObject.<Collection<ResponseObject<T>>>builder().data(responseCollection).build();
}
private <T> Callable<T> getRemainingCallables(LinkedBlockingQueue<Callable<T>> callableLinkedBlockingQueue){
if(callableLinkedBlockingQueue.size()>0){
return callableLinkedBlockingQueue.poll();
}
return null;
}
you can restrict the no of thread uses from scheduler as well as put timeout on the task.
You probably don't have the INTERNET
permission. Try adding this to your AndroidManifest.xml
file, right before </manifest>
:
<uses-permission android:name="android.permission.INTERNET" />
Note: the above doesn't have to be right before the </manifest>
tag, but that is a good / correct place to put it.
Note: if this answer doesn't help in your case, read the other answers!
since xcode5 organizer no longer team section exists. but the bold sentence was the answer for me. God thanks there is another mac to restore and import to problemmatic mac. now all is ok.
If you want to print decimal variables:
wchar_t text_buffer[20] = { 0 }; //temporary buffer
swprintf(text_buffer, _countof(text_buffer), L"%d", your.variable); // convert
OutputDebugString(text_buffer); // print
You can do it using mysqldump tool in command-line:
mysqldump your_database_name > script.sql
This creates a file with database create statements together with insert statements.
More info about options for mysql dump: https://dev.mysql.com/doc/refman/5.7/en/mysqldump-sql-format.html
A solution whithout imports for dates after 1700/1/1
def weekDay(year, month, day):
offset = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
week = ['Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday']
afterFeb = 1
if month > 2: afterFeb = 0
aux = year - 1700 - afterFeb
# dayOfWeek for 1700/1/1 = 5, Friday
dayOfWeek = 5
# partial sum of days betweem current date and 1700/1/1
dayOfWeek += (aux + afterFeb) * 365
# leap year correction
dayOfWeek += aux / 4 - aux / 100 + (aux + 100) / 400
# sum monthly and day offsets
dayOfWeek += offset[month - 1] + (day - 1)
dayOfWeek %= 7
return dayOfWeek, week[dayOfWeek]
print weekDay(2013, 6, 15) == (6, 'Saturday')
print weekDay(1969, 7, 20) == (0, 'Sunday')
print weekDay(1945, 4, 30) == (1, 'Monday')
print weekDay(1900, 1, 1) == (1, 'Monday')
print weekDay(1789, 7, 14) == (2, 'Tuesday')
I've seen where you can do something like this, assuming "NewWindow.cshtml" is in your "Home" folder:
string url = "/Home/NewWindow";
return JavaScript(string.Format("window.open('{0}', '_blank', 'left=100,top=100,width=500,height=500,toolbar=no,resizable=no,scrollable=yes');", url));
or
return Content("/Home/NewWindow");
If you just want to open views in tabs, you could use JavaScript click events to render your partial views. This would be your controller method for NewWindow.cshtml:
public ActionResult DisplayNewWindow(NewWindowModel nwm) {
// build model list based on its properties & values
nwm.Name = "John Doe";
nwm.Address = "123 Main Street";
return PartialView("NewWindow", nwm);
}
Your markup on your page this is calling it would go like this:
<input type="button" id="btnNewWin" value="Open Window" />
<div id="newWinResults" />
And the JavaScript (requires jQuery):
var url = '@Url.Action("NewWindow", "Home")';
$('btnNewWin').on('click', function() {
var model = "{ 'Name': 'Jane Doe', 'Address': '555 Main Street' }"; // you must build your JSON you intend to pass into the "NewWindowModel" manually
$('#newWinResults').load(url, model); // may need to do JSON.stringify(model)
});
Note that this JSON would overwrite what is in that C# function above. I had it there for demonstration purposes on how you could hard-code values, only.
(Adapted from Rendering partial view on button click in ASP.NET MVC)
If you only want find missing values in b, you can do:
List toReturn = new ArrayList(a);
toReturn.removeAll(b);
return toReturn;
If you want to find out values which are present in either list you can execute upper code twice. With changed lists.
This is working for me in .NET 2005 -
' * if the mouse button is down, do not run the select all.
If MouseButtons = Windows.Forms.MouseButtons.Left Then
Exit Sub
End If
' * OTHERWISE INVOKE THE SELECT ALL AS DISCUSSED.
You can use input text with "list" attribute, which refers to the datalist of values.
<input type="text" name="city" list="cityname">_x000D_
<datalist id="cityname">_x000D_
<option value="Boston">_x000D_
<option value="Cambridge">_x000D_
</datalist>
_x000D_
This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist
DateTime itself contains no real timezone information. It may know if it's UTC or local, but not what local really means.
DateTimeOffset is somewhat better - that's basically a UTC time and an offset. However, that's still not really enough to determine the timezone, as many different timezones can have the same offset at any one point in time. This sounds like it may be good enough for you though, as all you've got to work with when parsing the date/time is the offset.
The support for time zones as of .NET 3.5 is a lot better than it was, but I'd really like to see a standard "ZonedDateTime" or something like that - a UTC time and an actual time zone. It's easy to build your own, but it would be nice to see it in the standard libraries.
EDIT: Nearly four years later, I'd now suggest using Noda Time which has a rather richer set of date/time types. I'm biased though, as the main author of Noda Time :)
In Angular 2, change detection is automatic... $scope.$watch()
and $scope.$digest()
R.I.P.
Unfortunately, the Change Detection section of the dev guide is not written yet (there is a placeholder near the bottom of the Architecture Overview page, in section "The Other Stuff").
Here's my understanding of how change detection works:
setTimeout()
inside our components rather than something like $timeout
... because setTimeout()
is monkey patched.ChangeDetectorRef
.) These change detectors are created when Angular creates components. They keep track of the state of all of your bindings, for dirty checking. These are, in a sense, similar to the automatic $watches()
that Angular 1 would set up for {{}}
template bindings.onPush
change detection strategy on any of your components), every component in the tree is examined once (TTL=1)... from the top, in depth-first order. (Well, if you're in dev mode, change detection runs twice (TTL=2). See ApplicationRef.tick() for more about this.) It performs dirty checking on all of your bindings, using those change detector objects.
ngOnChanges()
to be notified of changes. ngDoCheck()
(see this SO answer for more on this). Other references to learn more:
onPush
.Use numpy.concatenate(list1 , list2)
or numpy.append()
Look into the thread at Append a NumPy array to a NumPy array.
It sounds like you would benefit from using an automation utility. If you were using a windows PC I would recommend AutoHotkey. I haven't used automation utilities on a Mac, but this Ask Different post has several suggestions, though none appear to be free.
This is not a VBA solution. These macros run outside of Excel and can interact with programs using keyboard strokes, mouse movements and clicks.
Basically you record or write a simple automation macro that waits for the Excel "Save As" dialogue box to become active, hits enter/return to complete the save action and then waits for the "Save As" window to close. You can set it to run in a continuous loop until you manually end the macro.
Here's a simple version of a Windows AutoHotkey script that would accomplish what you are attempting to do on a Mac. It should give you an idea of the logic involved.
; ' Infinite loop. End the macro by closing the program from the Windows taskbar.
Loop {
; ' Wait for ANY "Save As" dialogue box in any program.
; ' BE CAREFUL!
; ' Ignore the "Confirm Save As" dialogue if attempt is made
; ' to overwrite an existing file.
WinWait, Save As,,, Confirm Save As
IfWinNotActive, Save As,,, Confirm Save As
WinActivate, Save As,,, Confirm Save As
WinWaitActive, Save As,,, Confirm Save As
sleep, 250 ; ' 0.25 second delay
Send, {ENTER} ; ' Save the Excel file.
; ' Wait for the "Save As" dialogue box to close.
WinWaitClose, Save As,,, Confirm Save As
}
The spring configuration precedence is as follows.
So your configuration will be overridden at the command-line if you wish to do that. But the recommendation is to avoid overriding, though you can use multiple profiles.
<div :style="{'background-image': 'url(' + require('./assets/media/img.jpg') + ')'}"></div>
You can pass it as Action<string>
- which means it is a method with a single parameter of type string
that doesn't return anything (void) :
public void DoRequest(string request, Action<string> callback)
{
// do stuff....
callback("asdf");
}
You can use a function which I have created.
def method_finder(classname):
non_magic_class = []
class_methods = dir(classname)
for m in class_methods:
if m.startswith('__'):
continue
else:
non_magic_class.append(m)
return non_magic_class
method_finder(list)
Output:
['append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']
This method does the same thing but a little more simply and possibly a little more performant and in the event you are using reflection, it skips those frames automatically. The only issue is it may not be present in non-Sun JVMs, although it is included in the runtime classes of JRockit 1.4-->1.6. (Point is, it is not a public class).
sun.reflect.Reflection
/** Returns the class of the method <code>realFramesToSkip</code>
frames up the stack (zero-based), ignoring frames associated
with java.lang.reflect.Method.invoke() and its implementation.
The first frame is that associated with this method, so
<code>getCallerClass(0)</code> returns the Class object for
sun.reflect.Reflection. Frames associated with
java.lang.reflect.Method.invoke() and its implementation are
completely ignored and do not count toward the number of "real"
frames skipped. */
public static native Class getCallerClass(int realFramesToSkip);
As far as what the realFramesToSkip
value should be, the Sun 1.5 and 1.6 VM versions of java.lang.System
, there is a package protected method called getCallerClass() which calls sun.reflect.Reflection.getCallerClass(3)
, but in my helper utility class I used 4 since there is the added frame of the helper class invocation.
The CASE
is just a "switch" to return a value - not to execute a whole code block.
You need to change your code to something like this:
SELECT
@selectoneCount = CASE @Temp
WHEN 1 THEN @selectoneCount + 1
WHEN 2 THEN @selectoneCount + 1
END
If @temp
is set to none of those values (1 or 2), then you'll get back a NULL
Try this...
Give the element an ID, and also a class Name. Then you can nest the #IDName.className in your CSS.
Here's a better explanation https://css-tricks.com/multiple-class-id-selectors/
How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:
Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.
An abbreviated version of your code worked for me,
class Remote: NSObject {
var data = NSMutableData()
func connect(query:NSString) {
var url = NSURL.URLWithString("http://www.google.com")
var request = NSURLRequest(URL: url)
var conn = NSURLConnection(request: request, delegate: self, startImmediately: true)
}
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
println("didReceiveResponse")
}
func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {
self.data.appendData(conData)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
println(self.data)
}
deinit {
println("deiniting")
}
}
This is the code I used in the calling class,
class ViewController: UIViewController {
var remote = Remote()
@IBAction func downloadTest(sender : UIButton) {
remote.connect("/apis")
}
}
You didn't specify in your question where you had this code,
var remote = Remote()
remote.connect("/apis")
If var is a local variable, then the Remote class will be deallocated right after the connect(query:NSString) method finishes, but before the data returns. As you can see by my code, I usually implement reinit (or dealloc up to now) just to make sure when my instances go away. You should add that to your Remote class to see if that's your problem.
for names not present in the working copy or repo:
echo /globpattern >> .gitignore
or for an existing file (sh type command line):
echo /$(ls -1 file) >> .gitignore # I use tab completion to select the file to be ignored
git rm -r --cached file # if already checked in, deletes it on next commit
You're missing service name:
SQL> connect username/password@hostname:port/SERVICENAME
EDIT
If you can connect to the database from other computer try running there:
select sys_context('USERENV','SERVICE_NAME') from dual
and
select sys_context('USERENV','SID') from dual
Different Browsers enable different security measures when the HTTPOnly flag is set. For instance Opera and Safari do not prevent javascript from writing to the cookie. However, reading is always forbidden on the latest version of all major browsers.
But more importantly why do you want to read an HTTPOnly
cookie? If you are a developer, just disable the flag and make sure you test your code for xss. I recommend that you avoid disabling this flag if at all possible. The HTTPOnly
flag and "secure flag" (which forces the cookie to be sent over https) should always be set.
If you are an attacker, then you want to hijack a session. But there is an easy way to hijack a session despite the HTTPOnly
flag. You can still ride on the session without knowing the session id. The MySpace Samy worm did just that. It used an XHR to read a CSRF token and then perform an authorized task. Therefore, the attacker could do almost anything that the logged user could do.
People have too much faith in the HTTPOnly
flag, XSS can still be exploitable. You should setup barriers around sensitive features. Such as the change password filed should require the current password. An admin's ability to create a new account should require a captcha, which is a CSRF prevention technique that cannot be easily bypassed with an XHR.
None of the answers worked for me (I am using Ubuntu 16.04 and Python 3.6). So I finally solved the issue as following:
1- connect to the FTP of the server
2- go to the folder "/usr/lib/python3/dist-packages/"
3- duplicate the file "apt_pkg.cpython-35m-x86_64-linux-gnu.so"
4- rename this duplicated file to "apt_pkg.cpython-36m-x86_64-linux-gnu.so"
That's it!
Nowadays you can convert a standard JS object into an iterable object just by adding a Symbol.iterator method. Then you can use a for of
loop and acceess its values directly or even can use a spread operator on the object too. Cool. Let's see how we can make it:
var o = {a:1,b:2,c:3},_x000D_
a = [];_x000D_
o[Symbol.iterator] = function*(){_x000D_
var ok = Object.keys(this);_x000D_
i = 0;_x000D_
while (i < ok.length) yield this[ok[i++]];_x000D_
};_x000D_
for (var value of o) console.log(value);_x000D_
// or you can even do like_x000D_
a = [...o];_x000D_
console.log(a);
_x000D_
I eventually stumbled upon an example of the usage I was looking for - to assign an error to the Model in general, rather than one of it's properties, as usual you call:
ModelState.AddModelError(string key, string errorMessage);
but use an empty string for the key:
ModelState.AddModelError(string.Empty, "There is something wrong with Foo.");
The error message will present itself in the <%: Html.ValidationSummary() %>
as you'd expect.
<em>
element - from W3C (HTML5 reference)YES! There is a clear difference.
The <em>
element represents stress emphasis of its contents. The level of emphasis that a particular piece of content has is given by its number of ancestor <em>
elements.
<strong> = important content
<em> = stress emphasis of its contents
The placement of emphasis changes the meaning of the sentence. The element thus forms an integral part of the content. The precise way in which emphasis is used in this way depends on the language.
The <em>
element also isnt intended to convey importance; for that
purpose, the <strong>
element is more appropriate.
The <em>
element isn't a generic "italics" element. Sometimes, text
is intended to stand out from the rest of the paragraph, as if it was
in a different mood or voice. For this, the i
element is more
appropriate.
Reference (examples): See W3C Reference
use html5
's new attribute srcdoc
(srcdoc-polyfill) Docs
<iframe srcdoc="<html><body>Hello, <b>world</b>.</body></html>"></iframe>
Browser support - Tested in the following browsers:
Microsoft Internet Explorer
6, 7, 8, 9, 10, 11
Microsoft Edge
13, 14
Safari
4, 5.0, 5.1 ,6, 6.2, 7.1, 8, 9.1, 10
Google Chrome
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24.0.1312.5 (beta), 25.0.1364.5 (dev), 55
Opera
11.1, 11.5, 11.6, 12.10, 12.11 (beta) , 42
Mozilla FireFox
3.0, 3.6, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 (beta), 50
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(key1,value1);
cv.put(key2,value2); /*All values are your updated values, here you are
putting these values in a ContentValues object */
..................
..................
int val=myDB.update(TableName, cv, key_name +"=?", new String[]{value});
if(val>0)
//Successfully Updated
else
//Updation failed
In the interests of completeness you can also use the useNA
argument in table. For example table(df$col, useNA="always")
will count all of non NA
cases and the NA
ones.
Clear the cache and cookies and restart the browser .As the style is not suppose to change frequently for a website browser kinda store it .
Roland's answer is great for this specific problem, but I thought I would share a more generalized approach.
DF <- data.frame(x = letters[1:5], y = 1:5, z = LETTERS[1:5],
stringsAsFactors=FALSE)
str(DF)
# 'data.frame': 5 obs. of 3 variables:
# $ x: chr "a" "b" "c" "d" ...
# $ y: int 1 2 3 4 5
# $ z: chr "A" "B" "C" "D" ...
## The conversion
DF[sapply(DF, is.character)] <- lapply(DF[sapply(DF, is.character)],
as.factor)
str(DF)
# 'data.frame': 5 obs. of 3 variables:
# $ x: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
# $ y: int 1 2 3 4 5
# $ z: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
For the conversion, the left hand side of the assign (DF[sapply(DF, is.character)]
) subsets the columns that are character. In the right hand side, for that subset, you use lapply
to perform whatever conversion you need to do. R is smart enough to replace the original columns with the results.
The handy thing about this is if you wanted to go the other way or do other conversions, it's as simple as changing what you're looking for on the left and specifying what you want to change it to on the right.
Transform the sets into arrays, flatten them and finally the constructor will uniqify.
const union = (...sets) => new Set(sets.map(s => [...s]).flat());
All Func delegates return something; all the Action delegates return void.
Func<TResult>
takes no arguments and returns TResult:
public delegate TResult Func<TResult>()
Action<T>
takes one argument and does not return a value:
public delegate void Action<T>(T obj)
Action
is the simplest, 'bare' delegate:
public delegate void Action()
There's also Func<TArg1, TResult>
and Action<TArg1, TArg2>
(and others up to 16 arguments). All of these (except for Action<T>
) are new to .NET 3.5 (defined in System.Core).
Active 1st tab
$("#workflowTab").tabs({ active: 0 });
Active last tab
$("#workflowTab").tabs({ active: -1 });
Active 2nd tab
$("#workflowTab").tabs({ active: 1 });
Its work like an array
Below styles will vertically center it for you.
p.event_desc {
font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;
line-height: 14px;
height: 35px;
display: table-cell;
vertical-align: middle;
margin: 0px;
}
You have to open database connection, not workbench file with schema. It looks a bit wierd, but it makes sense when you realize what you are editing.
So, go to home tab, double click database connection (create it if you don't have it yet) and have fun.
I stumbled over this thread searching for answer to similar case. Basically all answers are found, but it's still hard to extract the essentials from them.
Assume a class Foo probably derived from some other class(es) with probably more classes derived from it.
Then accessing
this.method()
this.property
Foo.method()
Foo.property
this.constructor.method()
this.constructor.property
this.method()
this.property
Foo.method()
Foo.property
Foo.prototype.method.call( this )
Object.getOwnPropertyDescriptor( Foo.prototype,"property" ).get.call(this);
Keep in mind that using
this
isn't working this way when using arrow functions or invoking methods/getters explicitly bound to custom value.
this
is referring to current instance.super
is basically referring to same instance, but somewhat addressing methods and getters written in context of some class current one is extending (by using the prototype of Foo's prototype).this.constructor
.this
is available to refer to the definition of current class directly.super
is not referring to some instance either, but to static methods and getters written in context of some class current one is extending.Try this code:
class A {_x000D_
constructor( input ) {_x000D_
this.loose = this.constructor.getResult( input );_x000D_
this.tight = A.getResult( input );_x000D_
console.log( this.scaledProperty, Object.getOwnPropertyDescriptor( A.prototype, "scaledProperty" ).get.call( this ) );_x000D_
}_x000D_
_x000D_
get scaledProperty() {_x000D_
return parseInt( this.loose ) * 100;_x000D_
}_x000D_
_x000D_
static getResult( input ) {_x000D_
return input * this.scale;_x000D_
}_x000D_
_x000D_
static get scale() {_x000D_
return 2;_x000D_
}_x000D_
}_x000D_
_x000D_
class B extends A {_x000D_
constructor( input ) {_x000D_
super( input );_x000D_
this.tight = B.getResult( input ) + " (of B)";_x000D_
}_x000D_
_x000D_
get scaledProperty() {_x000D_
return parseInt( this.loose ) * 10000;_x000D_
}_x000D_
_x000D_
static get scale() {_x000D_
return 4;_x000D_
}_x000D_
}_x000D_
_x000D_
class C extends B {_x000D_
constructor( input ) {_x000D_
super( input );_x000D_
}_x000D_
_x000D_
static get scale() {_x000D_
return 5;_x000D_
}_x000D_
}_x000D_
_x000D_
class D extends C {_x000D_
constructor( input ) {_x000D_
super( input );_x000D_
}_x000D_
_x000D_
static getResult( input ) {_x000D_
return super.getResult( input ) + " (overridden)";_x000D_
}_x000D_
_x000D_
static get scale() {_x000D_
return 10;_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
let instanceA = new A( 4 );_x000D_
console.log( "A.loose", instanceA.loose );_x000D_
console.log( "A.tight", instanceA.tight );_x000D_
_x000D_
let instanceB = new B( 4 );_x000D_
console.log( "B.loose", instanceB.loose );_x000D_
console.log( "B.tight", instanceB.tight );_x000D_
_x000D_
let instanceC = new C( 4 );_x000D_
console.log( "C.loose", instanceC.loose );_x000D_
console.log( "C.tight", instanceC.tight );_x000D_
_x000D_
let instanceD = new D( 4 );_x000D_
console.log( "D.loose", instanceD.loose );_x000D_
console.log( "D.tight", instanceD.tight );
_x000D_
you can also use gcc -v
command that works like gcc --version
and if you would like to now where gcc
is you can use whereis gcc
command
I hope it'll be usefull
This is the only one that actually worked for me in all the browsers
let newTab = window.open();
newTab.location.href = url;
You can create an autofield. Here is the documentation for the same
Please remember Django won't allow to have more than one AutoField in a model, In your model you already have one for your primary key (which is default). So you'll have to override model's save method and will probably fetch the last inserted record from the table and accordingly increment the counter and add the new record.
Please make that code thread safe because in case of multiple requests you might end up trying to insert same value for different new records.
What do you get when you do puts lines
? That will give you a clue.
By default File.open
opens the file in text mode, so your \r\n
characters will be automatically converted to \n
. Maybe that's the reason lines
are always equal to lines2
. To prevent Ruby from parsing the line ends use the rb
mode:
C:\> copy con lala.txt a file with many lines ^Z C:\> irb irb(main):001:0> text = File.open('lala.txt').read => "a\nfile\nwith\nmany\nlines\n" irb(main):002:0> bin = File.open('lala.txt', 'rb').read => "a\r\nfile\r\nwith\r\nmany\r\nlines\r\n" irb(main):003:0>
But from your question and code I see you simply need to open the file with the default modifier. You don't need any conversion and may use the shorter File.read
.
This works also:
for i in range(19):
plt.subplot(5,4,i+1)
It plots 19 total graphs on one page. The format is 5 down and 4 across..
If you don't wan't to use ng-model there is ng-value
you can try.
Here's the fiddle for this: http://jsfiddle.net/Rg9sG/1/
Check out Google's Gson: http://code.google.com/p/google-gson/
From their website:
Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2
You would just need to make a MyType class (renamed, of course) with all the fields in the json string. It might get a little more complicated when you're doing the arrays, if you prefer to do all of the parsing manually (also pretty easy) check out http://www.json.org/ and download the Java source for the Json parser objects.
public function outletAmenities()
{
return $this->hasMany(OutletAmenities::class,'outlet_id','id')
->join('amenity_master','amenity_icon_url','=','image_url')
->where('amenity_master.status',1)
->where('outlet_amenities.status',1);
}
If you are using git, this searches all of the tracked files:
git grep -L "foo"
and you can search in a subset of tracked files if you have ** subdirectory globbing turned on (shopt -s globstar
in .bashrc, see this):
git grep -L "foo" -- **/*.cpp
I followed below steps to install mcrypt for PHP7.2 using PECL.
apt-get install php-pecl
apt-get install libmcrypt-dev libreadline-dev
pecl install mcrypt-1.0.1
You should add "extension=mcrypt.so" to php.ini
Please comment below if you need any assistance. :-)
IMPORTANT !
According to php.net reference many (all) mcrypt functions have been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.
I used xsd.exe
in the Windows command prompt.
However, since my xml referenced several online xml's (in my case http://www.w3.org/1999/xlink.xsd
which references http://www.w3.org/2001/xml.xsd
) I had to also download those schematics, put them in the same directory as my xsd, and then list those files in the command:
"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\xsd.exe" /classes /language:CS your.xsd xlink.xsd xml.xsd
computed: {
fullName: (app)=> (salut)=> {
return salut + ' ' + this.firstName + ' ' + this.lastName
}
}
when you want use
<p>{{fullName('your salut')}}</p>
With EL 2 you can do the following:
#{'this'.concat(' is').concat(' a').concat(' test!')}
I tried Gaby's answer (+1) above but it only partially solved my problem. Instead I used the following CSS, where content-box was changed to border-box:
input, select {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
One thing that i do is df=df.reset_index()
then df=df.drop(['index'],axis=1)
Below command used to export collection to CSV format.
Note: naag
is database, employee1_json
is a collection.
mongoexport --db naag--collection employee1_json --type csv --out /home/orienit/work/mongodb/employee1_csv_op1
These are two ways of using a DLL file in Windows:
There is a stub library (.lib) with associated header files. When you link your executable with the lib-file it will automatically load the DLL file when starting the program.
Loading the DLL manually. This is typically what you want to do if you are developing a plugin system where there are many DLL files implementing a common interface. Check out the documentation for LoadLibrary and GetProcAddress for more information on this.
For Qt I would suspect there are headers and a static library available that you can include and link in your project.
I found that selecting a clob
column in CTE caused this explosion. ie
with cte as (
select
mytable1.myIntCol,
mytable2.myClobCol
from mytable1
join mytable2 on ...
)
select myIntCol, myClobCol
from cte
where ...
presumably because oracle can't handle a clob in a temporary table.
Because my values were longer than 4K, I couldn't use to_char()
.
My work around was to select it from the final select
, ie
with cte as (
select
mytable1.myIntCol
from mytable1
)
select myIntCol, myClobCol
from cte
join mytable2 on ...
where ...
Too bad if this causes a performance problem.
Hmm i was having some trouble with that part (yes still xD):
xl.Application.Run("excelsheet.xlsm!macroname.macroname")
cos im not using excel often (same with vb or macros, but i need it to use femap with python) so i finaly resolved it checking macro list:
Developer -> Macros:
there i saw that: this macroname.macroname
should be sheet_name.macroname
like in "Macros" list.
(i spend something like 30min-1h trying to solve it, so it may be helpful for noobs like me in excel) xD
There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.
This can not have a variable:
create function Func() returns table
as
return
select 10 as ColName
You have to do like this instead:
create function Func()
returns @T table(ColName int)
as
begin
declare @Var int
set @Var = 10
insert into @T(ColName) values (@Var)
return
end
var model = JSON.stringify({
'ID': 0,
'ProductID': $('#ID').val(),
'PartNumber': $('#part-number').val(),
'VendorID': $('#Vendors').val()
})
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/api/PartSourceAPI/",
data: model,
success: function (data) {
alert('success');
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});
var model = JSON.stringify({ 'ID': 0, ...': 5, 'PartNumber': 6, 'VendorID': 7 }) // output is "{"ID":0,"ProductID":5,"PartNumber":6,"VendorID":7}"
your data is something like this "{"model": "ID":0,"ProductID":6,"PartNumber":7,"VendorID":8}}" web api controller cannot bind it to Your model
Shutting down "some system process" may be tricky... you should rather edit the [Apache folder]/conf/httpd.conf as mentioned by @Sergey Maksimenko and if you want to configure virtual host, use the new port in [Apache folder]/conf/extra/httpd-vhosts.conf (I used 4900 instead of 80 and 4901 instead of 443 in [Apache folder]/conf/httpd-ssl.conf). And remember to use the port when accessing page on localhost (or your virtualhost), for example: localhost:4900/index.html
Use a pattern along these lines:
function getValue(file) {
return lookupValue(file);
}
getValue('myFile.txt').then(function(res) {
// do whatever with res here
});
(although this is a bit redundant, I'm sure your actual code is more complicated)
The only way to add headers to a request from inside a browser is use the XmlHttpRequest setRequestHeader method.
Using this with "GET" request will download the resource. The trick then is to access the resource in the intended way. Ostensibly you should be able to allow the GET response to be cacheable for a short period, hence navigation to a new URL or the creation of an IMG tag with a src url should use the cached response from the previous "GET". However that is quite likely to fail especially in IE which can be a bit of a law unto itself where the cache is concerned.
Ultimately I agree with Mehrdad, use of query string is easiest and most reliable method.
Another quirky alternative is use an XHR to make a request to a URL that indicates your intent to access a resource. It could respond with a session cookie which will be carried by the subsequent request for the image or link.
Step 1: fetch list of commits:
git log
You'll get list like in this example:
[Comp:Folder User$ git log
commit 54b11d42e12dc6e9f070a8b5095a4492216d5320
Author: author <[email protected]>
Date: Fri Jul 8 23:42:22 2016 +0300
This is last commit message
commit fd6cb176297acca4dbc69d15d6b7f78a2463482f
Author: author <[email protected]>
Date: Fri Jun 24 20:20:24 2016 +0300
This is previous commit message
commit ab0de062136da650ffc27cfb57febac8efb84b8d
Author: author <[email protected]>
Date: Thu Jun 23 00:41:55 2016 +0300
This is previous previous commit message
...
Step 2: copy needed commit hash and paste it for checkout:
git checkout fd6cb176297acca4dbc69d15d6b7f78a2463482f
That's all.
I definitely wouldn't use Block1. It doesn't seem right having the Error block in an IF statement unrelated to Errors.
Blocks 2,3 & 4 I guess are variations of a theme. I prefer the use of Blocks 3 & 4 over 2 only because of a dislike of the GOTO statement; I generally use the Block4 method. This is one example of code I use to check if the Microsoft ActiveX Data Objects 2.8 Library is added and if not add or use an earlier version if 2.8 is not available.
Option Explicit
Public booRefAdded As Boolean 'one time check for references
Public Sub Add_References()
Dim lngDLLmsadoFIND As Long
If Not booRefAdded Then
lngDLLmsadoFIND = 28 ' load msado28.tlb, if cannot find step down versions until found
On Error GoTo RefErr:
'Add Microsoft ActiveX Data Objects 2.8
Application.VBE.ActiveVBProject.references.AddFromFile _
Environ("CommonProgramFiles") + "\System\ado\msado" & lngDLLmsadoFIND & ".tlb"
On Error GoTo 0
Exit Sub
RefErr:
Select Case Err.Number
Case 0
'no error
Case 1004
'Enable Trust Centre Settings
MsgBox ("Certain VBA References are not available, to allow access follow these steps" & Chr(10) & _
"Goto Excel Options/Trust Centre/Trust Centre Security/Macro Settings" & Chr(10) & _
"1. Tick - 'Disable all macros with notification'" & Chr(10) & _
"2. Tick - 'Trust access to the VBA project objects model'")
End
Case 32813
'Err.Number 32813 means reference already added
Case 48
'Reference doesn't exist
If lngDLLmsadoFIND = 0 Then
MsgBox ("Cannot Find Required Reference")
End
Else
For lngDLLmsadoFIND = lngDLLmsadoFIND - 1 To 0 Step -1
Resume
Next lngDLLmsadoFIND
End If
Case Else
MsgBox Err.Number & vbCrLf & Err.Description, vbCritical, "Error!"
End
End Select
On Error GoTo 0
End If
booRefAdded = TRUE
End Sub
You can just use return
.
function myfunction() {
if(a == 'stop')
return;
}
This will send a return value of undefined
to whatever called the function.
var x = myfunction();
console.log( x ); // console shows undefined
Of course, you can specify a different return value. Whatever value is returned will be logged to the console using the above example.
return false;
return true;
return "some string";
return 12345;
In my particular case -g -march=armv7-a -mfloat-abi=hard -mfpu=neon -marm -mthumb-interwork
worked.
Do NOT use timestamp to make an unique URL as for every page you visit is cached in DOM by jquery mobile and you soon run into trouble of running out of memory on mobiles.
$jqm(document).bind('pagebeforeload', function(event, data) {
var url = data.url;
var savePageInDOM = true;
if (url.toLowerCase().indexOf("vacancies") >= 0) {
savePageInDOM = false;
}
$jqm.mobile.cache = savePageInDOM;
})
This code activates before page is loaded, you can use url.indexOf() to determine if the URL is the one you want to cache or not and set the cache parameter accordingly.
Do not use window.location = ""; to change URL otherwise you will navigate to the address and pagebeforeload will not fire. In order to get around this problem simply use window.location.hash = "";
Here the async version.
public static Task<BitmapSource> ToBitmapSourceAsync(this Bitmap bitmap)
{
return Task.Run(() =>
{
using (System.IO.MemoryStream memory = new System.IO.MemoryStream())
{
bitmap.Save(memory, ImageFormat.Png);
memory.Position = 0;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();
return bitmapImage as BitmapSource;
}
});
}
You can try Cactoos:
new LengthOf(new TeeInput(array, new File("a.txt"))).value();
More details: http://www.yegor256.com/2017/06/22/object-oriented-input-output-in-cactoos.html
In URL as UI Jakob Nielsen recommends:
the social interface to the Web relies on email when users want to recommend Web pages to each other, and email is the second-most common way users get to new sites (search engines being the most common): make sure that all URLs on your site are less than 78 characters long so that they will not wrap across a line feed.
This is not the maximum but I'd consider this a practical maximum if you want your URL to be shared.
Here is a slightly different approach to read-only properties, which perhaps should be called write-once properties since they do have to get initialized, don't they? For the paranoid among us who worry about being able to modify properties by accessing the object's dictionary directly, I've introduced "extreme" name mangling:
from uuid import uuid4
class ReadOnlyProperty:
def __init__(self, name):
self.name = name
self.dict_name = uuid4().hex
self.initialized = False
def __get__(self, instance, cls):
if instance is None:
return self
else:
return instance.__dict__[self.dict_name]
def __set__(self, instance, value):
if self.initialized:
raise AttributeError("Attempt to modify read-only property '%s'." % self.name)
instance.__dict__[self.dict_name] = value
self.initialized = True
class Point:
x = ReadOnlyProperty('x')
y = ReadOnlyProperty('y')
def __init__(self, x, y):
self.x = x
self.y = y
if __name__ == '__main__':
try:
p = Point(2, 3)
print(p.x, p.y)
p.x = 9
except Exception as e:
print(e)
Use OnClicklistener
or you can use android:onClick="myMethod"
in your button's xml code from which you going to open a new layout. So when that button is clicked your myMethod function will be called automatically. Your myMethod
function in class look like this.
public void myMethod(View v) {
Intent intent=new Intent(context,SecondActivty.class);
startActivity(intent);
}
And in that SecondActivity.class set new layout in contentview.
Call MimeMessage.saveChanges()
on the enclosing message, which will update the headers by cascading down the MIME structure into a call to MimeBodyPart.updateHeaders()
on your body part. It's this updateHeaders
call that transfers the content type from the DataHandler
to the part's MIME Content-Type
header.
When you set the content of a MimeBodyPart
, JavaMail internally (and not obviously) creates a DataHandler
object wrapping the object you passed in. The part's Content-Type
header is not updated immediately.
There's no straightforward way to do it in your test program, since you don't have a containing MimeMessage
and MimeBodyPart.updateHeaders()
isn't public
.
Here's a working example that illuminates expected and unexpected outputs:
public class MailTest {
public static void main( String[] args ) throws Exception {
Session mailSession = Session.getInstance( new Properties() );
Transport transport = mailSession.getTransport();
String text = "Hello, World";
String html = "<h1>" + text + "</h1>";
MimeMessage message = new MimeMessage( mailSession );
Multipart multipart = new MimeMultipart( "alternative" );
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText( text, "utf-8" );
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent( html, "text/html; charset=utf-8" );
multipart.addBodyPart( textPart );
multipart.addBodyPart( htmlPart );
message.setContent( multipart );
// Unexpected output.
System.out.println( "HTML = text/html : " + htmlPart.isMimeType( "text/html" ) );
System.out.println( "HTML Content Type: " + htmlPart.getContentType() );
// Required magic (violates principle of least astonishment).
message.saveChanges();
// Output now correct.
System.out.println( "TEXT = text/plain: " + textPart.isMimeType( "text/plain" ) );
System.out.println( "HTML = text/html : " + htmlPart.isMimeType( "text/html" ) );
System.out.println( "HTML Content Type: " + htmlPart.getContentType() );
System.out.println( "HTML Data Handler: " + htmlPart.getDataHandler().getContentType() );
}
}
You can store images in MySQL as blobs. However, this is problematic for a couple of reasons:
Instead, consider updating your table to add an image_path field. For example:
ALTER TABLE `your_table`
ADD COLUMN `image_path` varchar(1024)
Then store your images on disk, and update the table with the image path. When you need to use the images, retrieve them from disk using the path specified.
An advantageous side-effect of this approach is that the images do not necessarily be stored on disk; you could just as easily store a URL instead of an image path, and retrieve images from any internet-connected location.
I found a customer matcher here: https://raw.github.com/gist/917903/92d7101f643e07896659f84609c117c4c279dfad/have_content_type.rb
Put it in spec/support/matchers/have_content_type.rb and make sure to load stuff from support with something like this in you spec/spec_helper.rb
Dir[Rails.root.join('spec/support/**/*.rb')].each {|f| require f}
Here is the code itself, just in case it disappeared from the given link.
RSpec::Matchers.define :have_content_type do |content_type|
CONTENT_HEADER_MATCHER = /^(.*?)(?:; charset=(.*))?$/
chain :with_charset do |charset|
@charset = charset
end
match do |response|
_, content, charset = *content_type_header.match(CONTENT_HEADER_MATCHER).to_a
if @charset
@charset == charset && content == content_type
else
content == content_type
end
end
failure_message_for_should do |response|
if @charset
"Content type #{content_type_header.inspect} should match #{content_type.inspect} with charset #{@charset}"
else
"Content type #{content_type_header.inspect} should match #{content_type.inspect}"
end
end
failure_message_for_should_not do |model|
if @charset
"Content type #{content_type_header.inspect} should not match #{content_type.inspect} with charset #{@charset}"
else
"Content type #{content_type_header.inspect} should not match #{content_type.inspect}"
end
end
def content_type_header
response.headers['Content-Type']
end
end
There's also split_whitespace()
fn main() {
let words: Vec<&str> = " foo bar\t\nbaz ".split_whitespace().collect();
println!("{:?}", words);
// ["foo", "bar", "baz"]
}
I have found it helpful to add a custom exec script to my utilities that do this.
utilities.js
const { exec } = require('child_process')
module.exports.exec = (command) => {
const process = exec(command)
process.stdout.on('data', (data) => {
console.log('stdout: ' + data.toString())
})
process.stderr.on('data', (data) => {
console.log('stderr: ' + data.toString())
})
process.on('exit', (code) => {
console.log('child process exited with code ' + code.toString())
})
}
app.js
const { exec } = require('./utilities.js')
exec('coffee -cw my_file.coffee')
The reason for the error is that the host server for https://cw.na1.hgncloud.com has provided some HTTP headers to protect the document. One of which is that the frame ancestors must be from the same domain as the original content. It seems you are attempting to put the iframe at a domain location that is not the same as the content of the iframe - thus violating the Content Security Policy that the host has set.
Check out this link on Content Security Policy for more details.
The java instanceof
operator is used to test whether the object is an instance of the specified type (class or subclass or interface).
The instanceof in java is also known as type comparison operator
as it compares the instance with type. It returns either true
or false
. If we apply the instanceof
operator with any variable that has null
value, it returns false
.
From JDK 14+ which includes JEP 305 we can also do "Pattern Matching" for instanceof
Patterns basically test that a value has a certain type, and can extract information from the value when it has the matching type. Pattern matching allows a more clear and efficient expression of common logic in a system, namely the conditional removal of components from objects.
Before Java 14
if (obj instanceof String) {
String str = (String) obj; // need to declare and cast again the object
.. str.contains(..) ..
}else{
str = ....
}
Java 14 enhancements
if (!(obj instanceof String str)) {
.. str.contains(..) .. // no need to declare str object again with casting
} else {
.. str....
}
We can also combine the type check and other conditions together
if (obj instanceof String str && str.length() > 4) {.. str.contains(..) ..}
The use of pattern matching in instanceof
should reduce the overall number of explicit casts in Java programs.
PS: instanceOf
will only match when the object is not null, then only it can be assigned to str
.
I know this is late answer but I have to make a comment about most voted answer that says to use generate scripts option in SSMS.
Problem with that is this option doesn’t necessarily generate script in correct execution order because it doesn't take dependencies into account.
For small databases this is not an issue but for larger ones it certainly is because it requires to manually re-order that script. Try that on 500 object database ;)
Unfortunately in this case the only solution are third party tools.
I successfully used comparison tools from ApexSQL (Diff and Data Diff) for similar tasks but you can’t go wrong with any other already mentioned here, especially Red Gate.
http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1230935955 states:
By default, the Arduino IDE and libraries does not use the operator new and operator delete. It does support malloc() and free(). So the solution is to implement new and delete operators for yourself, to use these functions.
Code:
#include <stdlib.h> // for malloc and free void* operator new(size_t size) { return malloc(size); } void operator delete(void* ptr) { free(ptr); }
This let's you create objects, e.g.
C* c; // declare variable
c = new C(); // create instance of class C
c->M(); // call method M
delete(c); // free memory
Regards, tamberg
alternatively, SQL%ROWCOUNT
you can use this within the procedure without any need to declare a variable
sed
is a stream editor. It works with streams of characters on a per-line basis. It has a primitive programming language that includes goto-style loops and simple conditionals (in addition to pattern matching and address matching). There are essentially only two "variables": pattern space and hold space. Readability of scripts can be difficult. Mathematical operations are extraordinarily awkward at best.
There are various versions of sed
with different levels of support for command line options and language features.
awk
is oriented toward delimited fields on a per-line basis. It has much more robust programming constructs including if
/else
, while
, do
/while
and for
(C-style and array iteration). There is complete support for variables and single-dimension associative arrays plus (IMO) kludgey multi-dimension arrays. Mathematical operations resemble those in C. It has printf
and functions. The "K" in "AWK" stands for "Kernighan" as in "Kernighan and Ritchie" of the book "C Programming Language" fame (not to forget Aho and Weinberger). One could conceivably write a detector of academic plagiarism using awk
.
GNU awk
(gawk
) has numerous extensions, including true multidimensional arrays in the latest version. There are other variations of awk
including mawk
and nawk
.
Both programs use regular expressions for selecting and processing text.
I would tend to use sed
where there are patterns in the text. For example, you could replace all the negative numbers in some text that are in the form "minus-sign followed by a sequence of digits" (e.g. "-231.45") with the "accountant's brackets" form (e.g. "(231.45)") using this (which has room for improvement):
sed 's/-\([0-9.]\+\)/(\1)/g' inputfile
I would use awk
when the text looks more like rows and columns or, as awk
refers to them "records" and "fields". If I was going to do a similar operation as above, but only on the third field in a simple comma delimited file I might do something like:
awk -F, 'BEGIN {OFS = ","} {gsub("-([0-9.]+)", "(" substr($3, 2) ")", $3); print}' inputfile
Of course those are just very simple examples that don't illustrate the full range of capabilities that each has to offer.
This is called the "shape" in NumPy, and can be requested via the .shape
attribute:
>>> a = zeros((2, 5))
>>> a.shape
(2, 5)
If you prefer a function, you could also use numpy.shape(a)
.
After uncommenting disable_overscan=1 follow my lead. In the link, http://elinux.org/RPiconfig when you search for Video options, you'll also get hdmi_group and hdmi_mode. For, hdmi_group choose 1 if you're using you TV as an video output or choose 2 for monitors. Then in hdmi_mode, you can select the resolution you want from the list. I chose :- hdmi_group=2 hdmi_mode=23 And it worked.
If you want to avoid concatenating all commands into a single command with ;
or &&
you can also get true multi-line scripts using a heredoc:
command:
- sh
- "-c"
- |
/bin/bash <<'EOF'
# Normal script content possible here
echo "Hello world"
ls -l
exit 123
EOF
This is handy for running existing bash scripts, but has the downside of requiring both an inner and an outer shell instance for setting up the heredoc.
You have extra brackets in Hours property;
public object Hours { get; set; }}
Binary floating-point numbers have interesting precision characteristics, since the value is stored as a binary integer raised to a binary power. When dealing with sub-integer values (that is, values between 0 and 1), negative powers of two "round off" very differently than negative powers of ten.
For example, the number 0.1 can be represented by 1 x 10-1, but there is no combination of base-2 exponent and mantissa that can precisely represent 0.1 -- the closest you get is 0.10000000000000001.
So if you have an application where you are working with values like 0.1 or 0.01 a great deal, but where small (less than 0.000000000000001%) errors cannot be tolerated, then binary floating-point numbers are not for you.
Conversely, if powers of ten are not "special" to your application (powers of ten are important in currency calculations, but not in, say, most applications of physics), then you are actually better off using binary floating-point, since it's usually at least an order of magnitude faster, and it is much more memory efficient.
The article from the Python documentation on floating point issues and limitations does an excellent job of explaining this issue in an easy to understand form. Wikipedia also has a good article on floating point that explains the math behind the representation.
As an extension of accepted answer Oracle internally uses ROW_NUMBER/RANK
functions. OFFSET FETCH
syntax is a syntax sugar.
It could be observed by using DBMS_UTILITY.EXPAND_SQL_TEXT
procedure:
Preparing sample:
CREATE TABLE rownum_order_test (
val NUMBER
);
INSERT ALL
INTO rownum_order_test
SELECT level
FROM dual
CONNECT BY level <= 10;
COMMIT;
Query:
SELECT val
FROM rownum_order_test
ORDER BY val DESC
FETCH FIRST 5 ROWS ONLY;
is regular:
SELECT "A1"."VAL" "VAL"
FROM (SELECT "A2"."VAL" "VAL","A2"."VAL" "rowlimit_$_0",
ROW_NUMBER() OVER ( ORDER BY "A2"."VAL" DESC ) "rowlimit_$$_rownumber"
FROM "ROWNUM_ORDER_TEST" "A2") "A1"
WHERE "A1"."rowlimit_$$_rownumber"<=5 ORDER BY "A1"."rowlimit_$_0" DESC;
Fetching expanded SQL text:
declare
x VARCHAR2(1000);
begin
dbms_utility.expand_sql_text(
input_sql_text => '
SELECT val
FROM rownum_order_test
ORDER BY val DESC
FETCH FIRST 5 ROWS ONLY',
output_sql_text => x);
dbms_output.put_line(x);
end;
/
WITH TIES
is expanded as RANK
:
declare
x VARCHAR2(1000);
begin
dbms_utility.expand_sql_text(
input_sql_text => '
SELECT val
FROM rownum_order_test
ORDER BY val DESC
FETCH FIRST 5 ROWS WITH TIES',
output_sql_text => x);
dbms_output.put_line(x);
end;
/
SELECT "A1"."VAL" "VAL"
FROM (SELECT "A2"."VAL" "VAL","A2"."VAL" "rowlimit_$_0",
RANK() OVER ( ORDER BY "A2"."VAL" DESC ) "rowlimit_$$_rank"
FROM "ROWNUM_ORDER_TEST" "A2") "A1"
WHERE "A1"."rowlimit_$$_rank"<=5 ORDER BY "A1"."rowlimit_$_0" DESC
and offset:
declare
x VARCHAR2(1000);
begin
dbms_utility.expand_sql_text(
input_sql_text => '
SELECT val
FROM rownum_order_test
ORDER BY val
OFFSET 4 ROWS FETCH NEXT 4 ROWS ONLY',
output_sql_text => x);
dbms_output.put_line(x);
end;
/
SELECT "A1"."VAL" "VAL"
FROM (SELECT "A2"."VAL" "VAL","A2"."VAL" "rowlimit_$_0",
ROW_NUMBER() OVER ( ORDER BY "A2"."VAL") "rowlimit_$$_rownumber"
FROM "ROWNUM_ORDER_TEST" "A2") "A1"
WHERE "A1"."rowlimit_$$_rownumber"<=CASE WHEN (4>=0) THEN FLOOR(TO_NUMBER(4))
ELSE 0 END +4 AND "A1"."rowlimit_$$_rownumber">4
ORDER BY "A1"."rowlimit_$_0"
Though a bit late, there is :/
which is the dedicated notation to specify a commit (or revision) based on the commit message, just prefix the search string with :/
, e.g.:
git show :/keyword(s)
Here <keywords>
can be a single word, or a complex regex pattern consisting of whitespaces, so please make sure to quote/escape when necessary, e.g.:
git log -1 -p ":/a few words"
Alternatively, a start point can be specified, to find the closest commit reachable from a specific point, e.g.:
git show 'HEAD^{/fix nasty bug}'
See: git revisions manual.
In this case it is just coding style.
Use of var
is only necessary when dealing with anonymous types.
In other situations it's a matter of taste.
So you can use a library for pagination logic https://github.com/pagino/pagino-js
Good comparison tool can be found here: http://www.jpab.org/All/All/All.html
Notice also the Head to Head DBMS/JPA Comparisons
A workspace is just a text file with a (.code-workspace) extension. You can look at it by opening it with a text editor. I too was frustrated by the idea of a workspace and how it is implemented in Visual Studio Code. I found a method that suits me.
Start with a single "project" folder.
Open Visual Studio Code and close any open workspaces or files or folders. You should see only "OPEN EDITORS" and "NO FOLDER OPENED" in the EXPLORER.
From the menu bar* → File → Open Folder.... Navigate to where you want to put your folder and right click to open a new folder. Name it whatever you want, then click on "Select Folder". It will appear in the *Visual Studio Code explorer.
Now from menu File → Save Workspace As.... Name the workspace and save it wherever you want to keep all your workspaces, (not necessarily where your project folders are). I put all mine in a folder called "Visual Studio Code workspace".
It will be saved as a (.code-workspace
) file and is just an index to all the files and folders it contains (or points to) wherever they may be on your hard drive. You can look at it by opening it with a text editor. Close the folder you created and close Visual Studio Code.
Now find your workspace "file" and double click on it. This will open Visual Studio Code with the folder you created in your workspace. Or you can open Visual Studio Code and use "Open Workspace".
Any folders you create from within your Visual Studio Code workspace will be inside your first folder. If you want to add any more top level folders, create them first wherever you want them and then use "Add To Workspace.." from Visual Studio Code.
>>> x = 'lipsum'
>>> x.replace(x[:3], '')
'sum'
Try to remove ib_logfile0
and ib_logfile1
files and then run mysql again
rm /usr/local/var/mysql/ib_logfile0
rm /usr/local/var/mysql/ib_logfile1
It works for me.
The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc
A set of simple examples:
Using Gson:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class Gson {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
com.google.gson.Gson gson = new com.google.gson.Gson();
Response respuesta = gson.fromJson(json, Response.class);
System.out.println(respuesta.getExample());
System.out.println(respuesta.getFr());
} catch (IOException ex) {
}
return null;
}
public class Response{
private String example;
private String fr;
public String getExample() {
return example;
}
public void setExample(String example) {
this.example = example;
}
public String getFr() {
return fr;
}
public void setFr(String fr) {
this.fr = fr;
}
}
}
Using json-simple:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonSimple {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
try {
JSONParser parser = new JSONParser();
Object resultObject = parser.parse(json);
if (resultObject instanceof JSONArray) {
JSONArray array=(JSONArray)resultObject;
for (Object object : array) {
JSONObject obj =(JSONObject)object;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
}else if (resultObject instanceof JSONObject) {
JSONObject obj =(JSONObject)resultObject;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
} catch (Exception e) {
// TODO: handle exception
}
} catch (IOException ex) {
}
return null;
}
}
etc...
Write below code in your MainActivity.java file instead of your code.
public class MainActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mBtn1 = (Button) findViewById(R.id.mBtn1);
mBtn1.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View v) {
Log.i("clicks","You Clicked B1");
Intent i=new Intent(MainActivity.this, MainActivity2.class);
startActivity(i);
}
}
And Declare MainActivity2 into your Androidmanifest.xml file using below code.
<activity
android:name=".MainActivity2"
android:label="@string/title_activity_main">
</activity>
In addition to the Wikipedia Cyclic redundancy check and Computation of CRC articles, I found a paper entitled Reversing CRC - Theory and Practice* to be a good reference.
There are essentially three approaches for computing a CRC: an algebraic approach, a bit-oriented approach, and a table-driven approach. In Reversing CRC - Theory and Practice*, each of these three algorithms/approaches is explained in theory accompanied in the APPENDIX by an implementation for the CRC32 in the C programming language.
* PDF Link
Reversing CRC – Theory and Practice.
HU Berlin Public Report
SAR-PR-2006-05
May 2006
Authors:
Martin Stigge, Henryk Plötz, Wolf Müller, Jens-Peter Redlich
I'm sure all of these algorithms are great, but you cannot verify that a card number is valid just by running an algorithm on it.
Algorithms make sure the format is correct and its checksums are valid. However, they do not guarantee the bank will accept the card... For that, you need to actually pass the card number to your bank for approval.
SQL Server Express does not come with profiler, but you can use SQL Server 2005/2008 Express Profiler instead.
$("#myModal").draggable({
handle: ".modal-header"
});
it works for me. I got it from there. if you give me thanks please give 70% to Andres Ilich
Another way that does the trick by using import/export wizard, first create an empty database, then choose the source which is your server with the source database, and then in the destination choose the same server with the destination database (using the empty database you created at first), then hit finish
It will create all tables and transfer all the data into the new database,
maybe useful for somebody, I got next problem on windows 8, apache 2.4, php 7+.
php.ini conf>
extension_dir="C:/Server/PHP7/ext"
php on apache works ok but on cli problem with libs loading, as a result, I changed to
extension_dir="C:/server/PHP7/ext"
Do:
NSData *data = [yourString dataUsingEncoding:NSUTF8StringEncoding];
then feel free to proceed with NSJSONSerialization:JSONObjectWithData
.
Following the comments, official documentation, and verifications, this answer was updated regarding the removal of an alleged NULL terminator:
As documented by dataUsingEncoding::
Return Value
The result of invoking
dataUsingEncoding:allowLossyConversion:
with NO as the second argument
As documented by getCString:maxLength:encoding: and cStringUsingEncoding::
note that the data returned by
dataUsingEncoding:allowLossyConversion:
is not a strict C-string since it does not have a NULL terminator
I had the same problem. Here's what I figured out:
=BDP(A1&"@BGN Corp", "Issuer_parent_eqy_ticker")
A1 being the ISINs. This will return the ticker number. Then just use the ticker number to get the price.
While the syntax is certainly different between Razor (.cshtml
/.vbhtml
) and WebForms (.aspx
/.ascx
), (Razor's being the more concise and modern of the two), nobody has mentioned that while both can be used as View Engines / Templating Engines, traditional ASP.NET Web Forms controls can be used on any .aspx or .ascx files, (even in cohesion with an MVC architecture).
This is relevant in situations where long standing solutions to a problem have been established and packaged into a pluggable component (e.g. a large-file uploading control) and you want to use it in an MVC site. With Razor, you can't do this. However, you can execute all of the same backend-processing that you would use with a traditional ASP.NET architecture with a Web Form view.
Furthermore, ASP.NET web forms views can have Code-Behind files, which allows embedding logic into a separate file that is compiled together with the view. While the software development community is growing to be see tightly coupled architectures and the Smart Client pattern as bad practice, it used to be the main way of doing things and is still very much possible with .aspx/.ascx files. Razor, intentionally, has no such quality.
Because the condition is never true.
i.e. count !=100 never executes when you put count=count+3 or count =count+9.
try this out..while count<100
Python String rindex() Method
Description
Python string method rindex() returns the last index where the substring str is found, or raises an exception if no such index exists, optionally restricting the search to string[beg:end].
Syntax
Following is the syntax for rindex() method -
str.rindex(str, beg=0 end=len(string))
Parameters
str - This specifies the string to be searched.
beg - This is the starting index, by default its 0
len - This is ending index, by default its equal to the length of the string.
Return Value
This method returns last index if found otherwise raises an exception if str is not found.
Example
The following example shows the usage of rindex() method.
Live Demo
str1 = "this is string example....wow!!!";
str2 = "is";
print str1.rindex(str2)
print str1.index(str2)
When we run above program, it produces following result -
5
2
for your example:
{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}
you will have to do something of this effect:
JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");
this returns the array object.
Then iterating will be as follows:
int size = the_json_array.length();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
//Blah blah blah...
arrays.add(another_json_object);
}
//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
//The end...
You will have to determine if the data is an array (simply checking that charAt(0)
starts with [
character).
Hope this helps.
You have a truncated array representation. Let's look at a full example:
>>> a = np.zeros((2, 3, 4))
>>> a
array([[[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]],
[[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]]])
Arrays in NumPy are printed as the word array
followed by structure, similar to embedded Python lists. Let's create a similar list:
>>> l = [[[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]],
[[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]]]
>>> l
[[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]],
[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]]
The first level of this compound list l
has exactly 2 elements, just as the first dimension of the array a
(# of rows). Each of these elements is itself a list with 3 elements, which is equal to the second dimension of a
(# of columns). Finally, the most nested lists have 4 elements each, same as the third dimension of a
(depth/# of colors).
So you've got exactly the same structure (in terms of dimensions) as in Matlab, just printed in another way.
Some caveats:
Matlab stores data column by column ("Fortran order"), while NumPy by default stores them row by row ("C order"). This doesn't affect indexing, but may affect performance. For example, in Matlab efficient loop will be over columns (e.g. for n = 1:10 a(:, n) end
), while in NumPy it's preferable to iterate over rows (e.g. for n in range(10): a[n, :]
-- note n
in the first position, not the last).
If you work with colored images in OpenCV, remember that:
2.1. It stores images in BGR format and not RGB, like most Python libraries do.
2.2. Most functions work on image coordinates (x, y
), which are opposite to matrix coordinates (i, j
).
Yor $.post
has no data. You need to pass the form data. You can use serialize()
to post the form data. Try this
$("#post-btn").click(function(){
$.post("process.php", $('#reg-form').serialize() ,function(data){
alert(data);
});
});
urllib
is a standard library, you do not have to install it. Simply import urllib
Had the same problem. Seems like there is something wrong with the set up instructions or the initial tables that are being created. This is how I got mysqld running on my machine.
If the mysqld server is already running on your Mac, stop it first with:
launchctl unload -w ~/Library/LaunchAgents/com.mysql.mysqld.plist
Start the mysqld server with the following command which lets anyone log in with full permissions.
mysqld_safe --skip-grant-tables
Then run mysql -u root
which should now let you log in successfully without a password. The following command should reset all the root passwords.
UPDATE mysql.user SET Password=PASSWORD('NewPassword') WHERE User='root'; FLUSH PRIVILEGES;
Now if you kill the running copy of mysqld_safe and start it up again without the skip-grant-tables option, you should be able to log in with mysql -u root -p
and the new password you just set.
You might want indexOf
if (code.indexOf("ST1") >= 0) { ... }
else if (code.indexOf("ST2") >= 0) { ... }
It checks if contains
is anywhere in the string
variable code
. This requires code
to be a string. If you want this solution to be case-insensitive you have to change the case to all the same with either String.toLowerCase()
or String.toUpperCase()
.
You could also work with a switch
statement like
switch (true) {
case (code.indexOf('ST1') >= 0):
document.write('code contains "ST1"');
break;
case (code.indexOf('ST2') >= 0):
document.write('code contains "ST2"');
break;
case (code.indexOf('ST3') >= 0):
document.write('code contains "ST3"');
break;
}?
Better short cuts:
+new Date # Milliseconds since Linux epoch
+new Date / 1000 # Seconds since Linux epoch
Math.round(+new Date / 1000) #Seconds without decimals since Linux epoch
In file php.ini you should try this for all errors:
error_reporting = off
Android Emulator Shortcuts
Ctrl+F11 Switch layout orientation portrait/landscape backwards
Ctrl+F12 Switch layout orientation portrait/landscape forwards
Home Home Button
F2 Left Softkey / Menu / Settings button (or PgUp)
Shift+F2 Right Softkey / Star button (or PgDn)
Esc Back Button
F3 Call/ dial Button
F4 Hang up / end call button
F5 Search Button
Ctrl+F5 Volume up (or + on numeric keyboard with Num Lock off) Ctrl+F6 Volume down (or + on numeric keyboard with Num Lock off) F7 Power Button Ctrl+F3 Camera Button
Ctrl+F11Switch layout orientation portrait/landscape backwards
Ctrl+F12 Switch layout orientation portrait/landscape forwards
F8 Toggle cell network
F9 Toggle code profiling
Alt+Enter Toggle fullscreen mode
F6 Toggle trackball mode
I found all of the answers to use too much code. Here is an easy way to do it:
function to_xml(SimpleXMLElement $object, array $data)
{
foreach ($data as $key => $value) {
if (is_array($value)) {
$new_object = $object->addChild($key);
to_xml($new_object, $value);
} else {
// if the key is an integer, it needs text with it to actually work.
if ($key != 0 && $key == (int) $key) {
$key = "key_$key";
}
$object->addChild($key, $value);
}
}
}
Then it's a simple matter of sending the array into the function, which uses recursion, so it will handle a multi-dimensional array:
$xml = new SimpleXMLElement('<rootTag/>');
to_xml($xml, $my_array);
Now $xml contains a beautiful XML object based on your array exactly how you wrote it.
print $xml->asXML();
Int=Int32 --> Original long type
Int16 --> Original int
Int64 --> New data type become available after 64 bit systems
"int" is only available for backward compatibility. We should be really using new int types to make our programs more precise.
---------------
One more thing I noticed along the way is there is no class named Int
similar to Int16, Int32 and Int64. All the helpful functions like TryParse
for integer come from Int32.TryParse
.
I found the following command to run from command line:
vlc.exe --extraintf=http:logger --verbose=2 --file-logging --logfile=vlc-log.txt
a void*
is a pointer, but the type of what it points to is unspecified. When you pass a void pointer to a function you will need to know what its type was in order to cast it back to that correct type later in the function to use it. You will see examples in pthreads
that use functions with exactly the prototype in your example that are used as the thread function. You can then use the void*
argument as a pointer to a generic datatype of your choosing and then cast it back to that type to use within your thread function. You need to be careful when using void pointers though as unless you case back to a pointer of its true type you can end up with all sorts of problems.
You can write one liner using DataRow.Add(params object[] values) instead of four lines.
dt.Rows.Add("Ravi", "500");
As you create new DataTable
object, there seems no need to Clear
DataTable
in very next statement. You can also use DataTable.Columns.AddRange
to add columns with on statement. Complete code would be.
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("Name"), new DataColumn("Marks") });
dt.Rows.Add("Ravi", "500");
Simple way
@{
Model.CRN = ViewBag.CRN;
}
@Html.HiddenFor(x => x.CRN)
In my case where I had the problem I was referring to a module when I tried extending the class.
import logging
class UserdefinedLogging(logging):
If you look at the Documentation Info, you'll see "logging" displayed as module.
In this specific case I had to simply inherit the logging module to create an extra class for the logging.
From Activity#showDialog(int)
:
This method is deprecated.
Use the newDialogFragment
class withFragmentManager
instead; this is also available on older platforms through the Android compatibility package.
I test with below code and it is fine.
@echo off
set varEmpty=
if not "%varEmpty%"=="" (
echo varEmpty is not empty
) else (
echo varEmpty is empty
)
set varNotEmpty=hasValue
if not "%varNotEmpty%"=="" (
echo varNotEmpty is not empty
) else (
echo varNotEmpty is empty
)
Ok after 2 days of trying to figure out why I couldn't run the example from
http://www.tutorialspoint.com/testng/testng_environment.htm the following code did not work for me
C:\TestNG_WORKSPACE>java -cp "C:\TestNG_WORKSPACE" org.testng.TestNG testng.xml
The fix for it is as follows: I came to the following conclusion: First off install eclipse, and download the TestNG plugin. After that follow the instructions from the tutorial to create and compile the test class from cmd using javac, and add the testng.xml. To run the testng.xml on windows 10 cmd run the following line:
java -cp C:\Users\Lenovo\Desktop\eclipse\plugins\org.testng.eclipse_6.9.12.201607091356\lib\*;C:\Test org.testng.TestNG testng.xml
to clarify: C:\Users\Lenovo\Desktop\eclipse\plugins\org.testng.eclipse_6.9.12.201607091356\lib\*
The path above represents the location of jcommander.jar and testng.jar that you downloaded by installing the TESTNG plugin for eclipse. The path may vary so to be sure just open the installation location of eclipse, go to plugins and search for jcommander.jar. Then copy that location and after that add * to select all the necessary .jars.
C:\Test
The path above represents the location of the testing.xml in your project. After getting all the necessary paths, append them by using ";".
I hope I have been helpful to some of you guys :)
There's a lot of typedef
going on here. Personally I'm against "hiding the asterisk", i.e. typedef
:ing pointer types into something that doesn't look like a pointer. In C, pointers are quite important and really affect the code, there's a lot of difference between foo
and foo *
.
Many of the answers are also confused about this, I think.
Your allocation of an array of Chess
values, which are pointers to values of type chess
(again, a very confusing nomenclature that I really can't recommend) should be like this:
Chess *array = malloc(n * sizeof *array);
Then, you need to initialize the actual instances, by looping:
for(i = 0; i < n; ++i)
array[i] = NULL;
This assumes you don't want to allocate any memory for the instances, you just want an array of pointers with all pointers initially pointing at nothing.
If you wanted to allocate space, the simplest form would be:
for(i = 0; i < n; ++i)
array[i] = malloc(sizeof *array[i]);
See how the sizeof
usage is 100% consistent, and never starts to mention explicit types. Use the type information inherent in your variables, and let the compiler worry about which type is which. Don't repeat yourself.
Of course, the above does a needlessly large amount of calls to malloc()
; depending on usage patterns it might be possible to do all of the above with just one call to malloc()
, after computing the total size needed. Then you'd still need to go through and initialize the array[i]
pointers to point into the large block, of course.
Just restart Android Studio - Usually then everything works again. (Invalidate Caches + Restart is actually not required).
Cygwin uses a DLL, cygwin.dll, (or maybe a set of DLLs) to provide a POSIX-like runtime on Windows.
MinGW compiles to a native Win32 application.
If you build something with Cygwin, any system you install it to will also need the Cygwin DLL(s). A MinGW application does not need any special runtime.
If you would rather not use AngularStrap then this directive should do the trick!. This is a modification of https://stackoverflow.com/a/16231859/910764.
JavaScript
angular.module('myApp').directive('bsNavbar', ['$location', function ($location) {
return {
restrict: 'A',
link: function postLink(scope, element) {
scope.$watch(function () {
return $location.path();
}, function (path) {
angular.forEach(element.children(), (function (li) {
var $li = angular.element(li),
regex = new RegExp('^' + $li.attr('data-match-route') + '$', 'i'),
isActive = regex.test(path);
$li.toggleClass('active', isActive);
}));
});
}
};
}]);
HTML
<ul class="nav navbar-nav" bs-navbar>
<li data-match-route="/home"><a href="#/home">Home</a></li>
<li data-match-route="/about"><a href="#/about">About</a></li>
</ul>
Note: The above HTML classes assume you are using Bootstrap 3.x
I have a struct KeyValuePairSerializable
:
[Serializable]
public struct KeyValuePairSerializable<K, V>
{
public KeyValuePairSerializable(KeyValuePair<K, V> pair)
{
Key = pair.Key;
Value = pair.Value;
}
[XmlAttribute]
public K Key { get; set; }
[XmlText]
public V Value { get; set; }
public override string ToString()
{
return "[" + StringHelper.ToString(Key, "") + ", " + StringHelper.ToString(Value, "") + "]";
}
}
Then, the XML serialization of a Dictionary
property is by:
[XmlIgnore]
public Dictionary<string, string> Parameters { get; set; }
[XmlArray("Parameters")]
[XmlArrayItem("Pair")]
[DebuggerBrowsable(DebuggerBrowsableState.Never)] // not necessary
public KeyValuePairSerializable<string, string>[] ParametersXml
{
get
{
return Parameters?.Select(p => new KeyValuePairSerializable<string, string>(p)).ToArray();
}
set
{
Parameters = value?.ToDictionary(i => i.Key, i => i.Value);
}
}
Just the property must be the array, not the List.
A query of type MyEntity
is going to return MyEntity
. You want a query for a Long
.
CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(MyEntity.class)));
cq.where(/*your stuff*/);
return entityManager.createQuery(cq).getSingleResult();
Obviously you will want to build up your expression with whatever restrictions and groupings etc you skipped in the example.
I'm actually surprised no one provided my answer. This is what you do (this will work if you have at least 1 eligible device):
You should be able to get your App Preview in the desired resolution.
When an array is passed to a method or function in PHP, it is passed by value unless you explicitly pass it by reference, like so:
function test(&$array) {
$array['new'] = 'hey';
}
$a = $array(1,2,3);
// prints [0=>1,1=>2,2=>3]
var_dump($a);
test($a);
// prints [0=>1,1=>2,2=>3,'new'=>'hey']
var_dump($a);
In your second question, $b
is not a reference to $a
, but a copy of $a
.
Much like the first example, you can reference $a
by doing the following:
$a = array(1,2,3);
$b = &$a;
// prints [0=>1,1=>2,2=>3]
var_dump($b);
$b['new'] = 'hey';
// prints [0=>1,1=>2,2=>3,'new'=>'hey']
var_dump($a);
Here is good solution with less coding...
var y = "";
var arr = x.toString().split("");
for(var i=0; i<arr.length; i++)
{
y += arr[i];
if((arr.length-i-1)%3==0 && i<arr.length-1) y += ",";
}
You can use a GoTo
:
Do
'... do stuff your loop will be doing
' skip to the end of the loop if necessary:
If <condition-to-go-to-next-iteration> Then GoTo ContinueLoop
'... do other stuff if the condition is not met
ContinueLoop:
Loop
I just reset the device (erase all settings) and sync up with iTunes and now I can drag the app over to the phone library on iTunes (even though there is no apps tab). Once you sync. the app is then on the phone.
The correct command for exclude directory from compression is :
tar --exclude='./folder' --exclude='./upload/folder2' -zcvf backup.tar.gz backup/
Make sure to put --exclude before the source and destination items.
and you can check the contents of the tar.gz file without unzipping :
tar -tf backup.tar.gz
had same error and finally fix that when updated all packages and then mentioned the same node engine version and npm version in package.json
as it is in my local working system.
"engines": {
"node": "10.15.3",
"npm": "6.9.0"
}
i was getting this error when deploying on heroku.
for more checkout heroku support
var date = moment(new Date(), moment.ISO_8601);
console.log(date);
<activity android:name="[packagename optional].ActivityClassName"></activity>
Simply adding the activity which we want to switch to should be placed in the manifest file
For my indeterminate progressbar (spinner) I just set a color filter on the drawable. Works great and just one line.
Example where setting color to red:
ProgressBar spinner = new android.widget.ProgressBar(
context,
null,
android.R.attr.progressBarStyle);
spinner.getIndeterminateDrawable().setColorFilter(0xFFFF0000, android.graphics.PorterDuff.Mode.MULTIPLY);
Libman seems to be the tool preferred by Microsoft now. It is integrated in Visual Studio 2017(15.8).
This article describes how to use it and even how to set up a restore performed by the build process.
Bootstrap's documentation tells you what files you need in your project.
The following example should work as a configuration for libman.json.
{
"version": "1.0",
"defaultProvider": "cdnjs",
"libraries": [
{
"library": "[email protected]",
"destination": "wwwroot/lib/bootstrap",
"files": [
"js/bootstrap.bundle.js",
"css/bootstrap.min.css"
]
},
{
"library": "[email protected]",
"destination": "wwwroot/lib/jquery",
"files": [
"jquery.min.js"
]
}
]
}
As stated by user2246674, using success
and error
as parameter of the ajax function is valid.
To be consistent with precedent answer, reading the doc :
Deprecation Notice:
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks will be deprecated in jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
If you are using the callback-manipulation function (using method-chaining for example), use .done()
, .fail()
and .always()
instead of success()
, error()
and complete()
.
a=[[1,2] , [3,4] , [0,5,4]]
print(a.__contains__([0,5,4]))
It provides true output.
a=[[1,2] , [3,4] , [0,5,4]]
print(a.__contains__([1,3]))
It provides false output.
You can use varargs
public function yourFunction(Parameter... parameters)
See also
Try Calender. Use getInstance to get a Calender-Object. Then use setTime to set the required Date. Now you can use get(int field) with the appropriate constant like HOUR_OF_DAY or so to read the values you need.
http://java.sun.com/javase/6/docs/api/java/util/Calendar.html
The classpath setting of the compiler plugin are two args. Changed it like this and it worked for me:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<compilerArgs>
<arg>-cp</arg>
<arg>${cp}:${basedir}/lib/bad.jar</arg>
</compilerArgs>
</configuration>
I used the gmavenplus-plugin to read the path and create the property 'cp':
<plugin>
<!--
Use Groovy to read classpath and store into
file named value of property <cpfile>
In second step use Groovy to read the contents of
the file into a new property named <cp>
In the compiler plugin this is used to create a
valid classpath
-->
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>1.12.0</version>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<!-- any version of Groovy \>= 1.5.0 should work here -->
<version>3.0.6</version>
<type>pom</type>
<scope>runtime</scope>
</dependency>
</dependencies>
<executions>
<execution>
<id>read-classpath</id>
<phase>validate</phase>
<goals>
<goal>execute</goal>
</goals>
</execution>
</executions>
<configuration>
<scripts>
<script><![CDATA[
def file = new File(project.properties.cpfile)
/* create a new property named 'cp'*/
project.properties.cp = file.getText()
println '<<< Retrieving classpath into new property named <cp> >>>'
println 'cp = ' + project.properties.cp
]]></script>
</scripts>
</configuration>
</plugin>
If you don't want to calculate it using java's Calendar you can use Androids Time class It is supposed to be faster but I didn't notice much difference when i switched.
I could not find any pre-defined functions to determine time between 2 dates for an age in Android. There are some nice helper functions to get formatted time between dates in the DateUtils but that's probably not what you want.
This is what I've been using for development:
<?xml version="1.0" ?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>
This is a very liberal approach, but is fine for my application.
As others have pointed out below, beware the risks of this.
Try this:
List<Double> list = Arrays.asList(1.38, 2.56, 4.3);
which returns a fixed size list.
If you need an expandable list, pass this result to the ArrayList
constructor:
List<Double> list = new ArrayList<>(Arrays.asList(1.38, 2.56, 4.3));
Suggestions are (basically) based on the text in the current open file and any snippets or completions you have defined (ref). If you want more text suggestions, I'd recommend:
As a side note, I'd really recommend installing Package control to take full advantage of the Sublime community. Some of the options above use Package control. I'd also highly recommend the tutsplus Sublime tutorial videos, which include all sorts of information about improving your efficiency when using Sublime.
It seems that the struct
datatype is commonly used in SOAP:
var_dump($client->__getTypes());
array(52) {
[0] =>
string(43) "struct Bank {\n string Code;\n string Name;\n}"
}
This is not a native PHP datatype!
It seems that the properties of the struct
type referred to in SOAP can be accessed as a simple PHP stdClass
object:
$some_struct = $client->SomeMethod();
echo 'Name: ' . $some_struct->Name;
Volatile boolean vs AtomicBoolean
The Atomic* classes wrap a volatile primitive of the same type. From the source:
public class AtomicLong extends Number implements java.io.Serializable {
...
private volatile long value;
...
public final long get() {
return value;
}
...
public final void set(long newValue) {
value = newValue;
}
So if all you are doing is getting and setting a Atomic* then you might as well just have a volatile field instead.
What does AtomicBoolean do that a volatile boolean cannot achieve?
Atomic* classes give you methods that provide more advanced functionality such as incrementAndGet()
for numbers, compareAndSet()
for booleans, and other methods that implement multiple operations (get/increment/set, test/set) without locking. That's why the Atomic* classes are so powerful.
For example, if multiple threads are using the following code using ++
, there will be race conditions because ++
is actually: get, increment, and set.
private volatile value;
...
// race conditions here
value++;
However, the following code will work in a multi-threaded environment safely without locks:
private final AtomicLong value = new AtomicLong();
...
value.incrementAndGet();
It's also important to note that wrapping your volatile field using Atomic* class is a good way to encapsulate the critical shared resource from an object standpoint. This means that developers can't just deal with the field assuming it is not shared possibly injecting problems with a field++; or other code that introducing race conditions.
It gives out a string of max 200 characters OR 200 normal characters OR 200 characters followed by '...'
$ur_str= (strlen($ur_str) > 200) ? substr($ur_str,0,200).'...' :$ur_str;
You also need to include the Log4J JAR file in the classpath.
Note that slf4j-log4j12-1.6.4.jar
is only an adapter to make it possible to use Log4J via the SLF4J API. It does not contain the actual implementation of Log4J.
string testString1 = "2,457";
string testString2 = "2.457";
double testNum = 0.5;
char decimalSepparator;
decimalSepparator = testNum.ToString()[1];
Console.WriteLine(double.Parse(testString1.Replace('.', decimalSepparator).Replace(',', decimalSepparator)));
Console.WriteLine(double.Parse(testString2.Replace('.', decimalSepparator).Replace(',', decimalSepparator)));
Another use (not yet mentioned) is constexpr
constructors. This allows creating compile time constants which don't have to be initialized during runtime.
const std::complex<double> meaning_of_imagination(0, 42);
Pair that with user defined literals and you have full support for literal user defined classes.
3.14D + 42_i;
It depends on whether default path is set for data and log files or not.
If the path is set explicitly at Properties
=> Database Settings
=> Database default locations
then SQL server stores it at Software\Microsoft\MSSQLServer\MSSQLServer
in DefaultData
and DefaultLog
values.
However, if these parameters aren't set explicitly, SQL server uses Data and Log paths of master database.
Bellow is the script that covers both cases. This is simplified version of the query that SQL Management Studio runs.
Also, note that I use xp_instance_regread
instead of xp_regread
, so this script will work for any instance, default or named.
declare @DefaultData nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultData', @DefaultData output
declare @DefaultLog nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultLog', @DefaultLog output
declare @DefaultBackup nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory', @DefaultBackup output
declare @MasterData nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer\Parameters', N'SqlArg0', @MasterData output
select @MasterData=substring(@MasterData, 3, 255)
select @MasterData=substring(@MasterData, 1, len(@MasterData) - charindex('\', reverse(@MasterData)))
declare @MasterLog nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer\Parameters', N'SqlArg2', @MasterLog output
select @MasterLog=substring(@MasterLog, 3, 255)
select @MasterLog=substring(@MasterLog, 1, len(@MasterLog) - charindex('\', reverse(@MasterLog)))
select
isnull(@DefaultData, @MasterData) DefaultData,
isnull(@DefaultLog, @MasterLog) DefaultLog,
isnull(@DefaultBackup, @MasterLog) DefaultBackup
You can achieve the same result by using SMO. Bellow is C# sample, but you can use any other .NET language or PowerShell.
using (var connection = new SqlConnection("Data Source=.;Integrated Security=SSPI"))
{
var serverConnection = new ServerConnection(connection);
var server = new Server(serverConnection);
var defaultDataPath = string.IsNullOrEmpty(server.Settings.DefaultFile) ? server.MasterDBPath : server.Settings.DefaultFile;
var defaultLogPath = string.IsNullOrEmpty(server.Settings.DefaultLog) ? server.MasterDBLogPath : server.Settings.DefaultLog;
}
It is so much simpler in SQL Server 2012 and above, assuming you have default paths set (which is probably always a right thing to do):
select
InstanceDefaultDataPath = serverproperty('InstanceDefaultDataPath'),
InstanceDefaultLogPath = serverproperty('InstanceDefaultLogPath')
From the answer here, spark.sql.shuffle.partitions
configures the number of partitions that are used when shuffling data for joins or aggregations.
spark.default.parallelism
is the default number of partitions in RDD
s returned by transformations like join
, reduceByKey
, and parallelize
when not set explicitly by the user. Note that spark.default.parallelism
seems to only be working for raw RDD
and is ignored when working with dataframes.
If the task you are performing is not a join or aggregation and you are working with dataframes then setting these will not have any effect. You could, however, set the number of partitions yourself by calling df.repartition(numOfPartitions)
(don't forget to assign it to a new val
) in your code.
To change the settings in your code you can simply do:
sqlContext.setConf("spark.sql.shuffle.partitions", "300")
sqlContext.setConf("spark.default.parallelism", "300")
Alternatively, you can make the change when submitting the job to a cluster with spark-submit
:
./bin/spark-submit --conf spark.sql.shuffle.partitions=300 --conf spark.default.parallelism=300
Declare your TextView
not clickable / focusable by using android:clickable="false"
and android:focusable="false"
or v.setClickable(false)
and v.setFocusable(false)
. The click events should be dispatched to the TextView
's parent now.
Note:
In order to achieve this, you have to add click to its direct parent
. or set
android:clickable="false"
and android:focusable="false"
to its direct parent to pass listener to further parent.
The linefeed character \n
is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n
instead, then it'll both see the line-break with only \n
and \r\n
, I've never had any problems using it.
Also, you should look into using a StringBuilder
instead of concatenating the String
in the while-loop at BookCatalog.toString()
, it is a lot more effective. For instance:
public String toString() {
BookNode current = front;
StringBuilder sb = new StringBuilder();
while (current!=null){
sb.append(current.getData().toString()+"\r\n ");
current = current.getNext();
}
return sb.toString();
}