Python does support "method overloading" as you present it. In fact, what you just describe is trivial to implement in Python, in so many different ways, but I would go with:
class Character(object):
# your character __init__ and other methods go here
def add_bullet(self, sprite=default, start=default,
direction=default, speed=default, accel=default,
curve=default):
# do stuff with your arguments
In the above code, default
is a plausible default value for those arguments, or None
. You can then call the method with only the arguments you are interested in, and Python will use the default values.
You could also do something like this:
class Character(object):
# your character __init__ and other methods go here
def add_bullet(self, **kwargs):
# here you can unpack kwargs as (key, values) and
# do stuff with them, and use some global dictionary
# to provide default values and ensure that ``key``
# is a valid argument...
# do stuff with your arguments
Another alternative is to directly hook the desired function directly to the class or instance:
def some_implementation(self, arg1, arg2, arg3):
# implementation
my_class.add_bullet = some_implementation_of_add_bullet
Yet another way is to use an abstract factory pattern:
class Character(object):
def __init__(self, bfactory, *args, **kwargs):
self.bfactory = bfactory
def add_bullet(self):
sprite = self.bfactory.sprite()
speed = self.bfactory.speed()
# do stuff with your sprite and speed
class pretty_and_fast_factory(object):
def sprite(self):
return pretty_sprite
def speed(self):
return 10000000000.0
my_character = Character(pretty_and_fast_factory(), a1, a2, kw1=v1, kw2=v2)
my_character.add_bullet() # uses pretty_and_fast_factory
# now, if you have another factory called "ugly_and_slow_factory"
# you can change it at runtime in python by issuing
my_character.bfactory = ugly_and_slow_factory()
# In the last example you can see abstract factory and "method
# overloading" (as you call it) in action
The answer to this is very needed today because not everyone wants to use cURL to consume web services. Also PHP does allow for this using the following code
function get_info()
{
$post_data = array(
'test' => 'foobar',
'okay' => 'yes',
'number' => 2
);
// Send a request to example.com
$result = $this->post_request('http://www.example.com/', $post_data);
if ($result['status'] == 'ok'){
// Print headers
echo $result['header'];
echo '<hr />';
// print the result of the whole request:
echo $result['content'];
}
else {
echo 'A error occured: ' . $result['error'];
}
}
function post_request($url, $data, $referer='') {
// Convert the data array into URL Parameters like a=b&foo=bar etc.
$data = http_build_query($data);
// parse the given URL
$url = parse_url($url);
if ($url['scheme'] != 'http') {
die('Error: Only HTTP request are supported !');
}
// extract host and path:
$host = $url['host'];
$path = $url['path'];
// open a socket connection on port 80 - timeout: 30 sec
$fp = fsockopen($host, 80, $errno, $errstr, 30);
if ($fp){
// send the request headers:
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
if ($referer != '')
fputs($fp, "Referer: $referer\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ". strlen($data) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);
$result = '';
while(!feof($fp)) {
// receive the results of the request
$result .= fgets($fp, 128);
}
}
else {
return array(
'status' => 'err',
'error' => "$errstr ($errno)"
);
}
// close the socket connection:
fclose($fp);
// split the result header from the content
$result = explode("\r\n\r\n", $result, 2);
$header = isset($result[0]) ? $result[0] : '';
$content = isset($result[1]) ? $result[1] : '';
// return as structured array:
return array(
'status' => 'ok',
'header' => $header,
'content' => $content);
}
Just for the sake of completeness, I invite you to think about it like this:
<p>
is a paragraph, an <li>
is a list item, etc., and we're supposed to use the right tag for the right purpose -- not like in the old days when we indented using <blockquote>
whether the content was a quote or not.<div>
and <span>
, because otherwise, people would go back to abusing the elements which do have meanings.Yes, that is normal behavior. You basically read to the end of the file the first time (you can sort of picture it as reading a tape), so you can't read any more from it unless you reset it, by either using f.seek(0)
to reposition to the start of the file, or to close it and then open it again which will start from the beginning of the file.
If you prefer you can use the with
syntax instead which will automatically close the file for you.
e.g.,
with open('baby1990.html', 'rU') as f:
for line in f:
print line
once this block is finished executing, the file is automatically closed for you, so you could execute this block repeatedly without explicitly closing the file yourself and read the file this way over again.
As of June 2016, the Download ZIP button is still under the <> Code tab, however it is now inside a button with two options clone or download:
Try this: if you need pass values between the activities you use this...
This is code for Main_Activity put the values to intent
String name="aaaa";
Intent intent=new Intent(Main_Activity.this,Other_Activity.class);
intent.putExtra("name", name);
startActivity(intent);
This code for Other_Activity and get the values form intent
Bundle b = new Bundle();
b = getIntent().getExtras();
String name = b.getString("name");
building on @ltamar's answer:
Use summary and munge the output into something useful!
library(tidyr)
library(dplyr)
df %>%
summary %>%
data.frame %>%
select(-Var1) %>%
separate(data=.,col=Freq,into = c('metric','value'),sep = ':') %>%
rename(column_name=Var2) %>%
mutate(value=as.numeric(value),
metric = trimws(metric,'both')
) %>%
filter(!is.na(value)) -> metrics
It's not pretty and it is certainly not fast but it gets the job done!
If you set it programmatically you can just call it like a variable (i.e. document.getElementById('image_1').style.top
). Otherwise, you can always use jQuery:
<html>
<body>
<div id="test" style="height: 100px;">Test</div>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
alert($("#test").css("height"));
</script>
</body>
</html>
Having the same issue in Flask, I had already a template that loaded JQuery, Popper and Bootstrap. I was extending that template into other template that I was using as a base to load the page that had the table.
For some reason in Flask apparently the files in the outer template load before the files in the tables above in the hierarchy (the ones you are extending) so JQuery was loading before the DataTables files causing the issue.
I had to create another template where I run all my imports of JS CDNs in the same place, that solved the issue.
Check your PrimeNumberModelTests
Target Settings.
If you can't see PrimeNumberModel.swift
file in Build Phases/Compile Sources
, add it.
You can get the actual height of called layout with this code:
public int getLayoutSize() {
// Get the layout id
final LinearLayout root = (LinearLayout) findViewById(R.id.mainroot);
final AtomicInteger layoutHeight = new AtomicInteger();
root.post(new Runnable() {
public void run() {
Rect rect = new Rect();
Window win = getWindow(); // Get the Window
win.getDecorView().getWindowVisibleDisplayFrame(rect);
// Get the height of Status Bar
int statusBarHeight = rect.top;
// Get the height occupied by the decoration contents
int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop();
// Calculate titleBarHeight by deducting statusBarHeight from contentViewTop
int titleBarHeight = contentViewTop - statusBarHeight;
Log.i("MY", "titleHeight = " + titleBarHeight + " statusHeight = " + statusBarHeight + " contentViewTop = " + contentViewTop);
// By now we got the height of titleBar & statusBar
// Now lets get the screen size
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int screenHeight = metrics.heightPixels;
int screenWidth = metrics.widthPixels;
Log.i("MY", "Actual Screen Height = " + screenHeight + " Width = " + screenWidth);
// Now calculate the height that our layout can be set
// If you know that your application doesn't have statusBar added, then don't add here also. Same applies to application bar also
layoutHeight.set(screenHeight - (titleBarHeight + statusBarHeight));
Log.i("MY", "Layout Height = " + layoutHeight);
// Lastly, set the height of the layout
FrameLayout.LayoutParams rootParams = (FrameLayout.LayoutParams)root.getLayoutParams();
rootParams.height = layoutHeight.get();
root.setLayoutParams(rootParams);
}
});
return layoutHeight.get();
}
For anyone who is looking a way to watch a specific file to exist in VBS:
Function bIsFileDownloaded(strPath, timeout)
Dim FSO, fileIsDownloaded
set FSO = CreateObject("Scripting.FileSystemObject")
fileIsDownloaded = false
limit = DateAdd("s", timeout, Now)
Do While Now < limit
If FSO.FileExists(strPath) Then : fileIsDownloaded = True : Exit Do : End If
WScript.Sleep 1000
Loop
Set FSO = Nothing
bIsFileDownloaded = fileIsDownloaded
End Function
Usage:
FileName = "C:\test.txt"
fileIsDownloaded = bIsFileDownloaded(FileName, 5) ' keep watching for 5 seconds
If fileIsDownloaded Then
WScript.Echo Now & " File is Downloaded: " & FileName
Else
WScript.Echo Now & " Timeout, file not found: " & FileName
End If
I realise this answer is not a direct response to the problem described by the OP, but I found this question as a result of searching for the same error message. I thought it worth posting my experience here just in case anybody is muddling over the same thing...
You can encounter the error in question as a result of a poorly formatted for
loop over an associative array. In a fit of bone-headedness, I was using -> instead of => in my for
statement:
foreach ($object->someArray as $key->$val) {
// do something
}
Of course, I should have had:
foreach ($object->someArray as $key=>$val) {
// do something
}
I confused myself at first, thinking the reported error was referring to the someArray property!
As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.
This is some pseudocodish JavaScript:
Client:
var websocket = new WebSocket("server address");
websocket.onmessage = function(str) {
console.log("Someone sent: ", str);
};
// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
id: "client1"
}));
// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
to: "client2",
data: "foo"
}));
Server:
var clients = {};
server.on("data", function(client, str) {
var obj = JSON.parse(str);
if("id" in obj) {
// New client, add it to the id/client object
clients[obj.id] = client;
} else {
// Send data to the client requested
clients[obj.to].send(obj.data);
}
});
This should work as well:
DELETE FROM [table]
INNER JOIN (
SELECT [id]
FROM (
SELECT [id]
FROM [table]
ORDER BY [id] DESC
LIMIT N
) AS Temp
) AS Temp2 ON [table].[id] = [Temp2].[id]
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = @"/c -sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer"
use /c as a cmd argument to close cmd.exe once its finish processing your commands
You are pointing to the source directory. You can run a build by running ant from that same directory, then add '\output\build' to the end of the installation directory path.
tolist()
works fine even if encountered a nested array, say a pandas DataFrame
;
my_list = [0,1,2,3,4,5,4,3,2,1,0]
my_dt = pd.DataFrame(my_list)
new_list = [i[0] for i in my_dt.values.tolist()]
print(type(my_list),type(my_dt),type(new_list))
Your function will return the size of a ResultSet, but its cursor will be set after last record, so without rewinding it by calling beforeFirst(), first() or previous() you won't be able to read its rows, and rewinding methods won't work with forward only ResultSet (you'll get the same exception you're getting in your second code fragment).
What worked for me was to import the project with "File -> New -> Project from Version Control" then choose your online source (GitHub for example). This way all the .gradle files were created in the import.
You may like to try something like this which covers all the bases, including not relying on whitespace after the number:
>>> import re
>>> numeric_const_pattern = r"""
... [-+]? # optional sign
... (?:
... (?: \d* \. \d+ ) # .1 .12 .123 etc 9.1 etc 98.1 etc
... |
... (?: \d+ \.? ) # 1. 12. 123. etc 1 12 123 etc
... )
... # followed by optional exponent part if desired
... (?: [Ee] [+-]? \d+ ) ?
... """
>>> rx = re.compile(numeric_const_pattern, re.VERBOSE)
>>> rx.findall(".1 .12 9.1 98.1 1. 12. 1 12")
['.1', '.12', '9.1', '98.1', '1.', '12.', '1', '12']
>>> rx.findall("-1 +1 2e9 +2E+09 -2e-9")
['-1', '+1', '2e9', '+2E+09', '-2e-9']
>>> rx.findall("current level: -2.03e+99db")
['-2.03e+99']
>>>
For easy copy-pasting:
numeric_const_pattern = '[-+]? (?: (?: \d* \. \d+ ) | (?: \d+ \.? ) )(?: [Ee] [+-]? \d+ ) ?'
rx = re.compile(numeric_const_pattern, re.VERBOSE)
rx.findall("Some example: Jr. it. was .23 between 2.3 and 42.31 seconds")
Removing the xml declaration solved it
<?xml version='1.0' encoding='utf-8'?>
public String reverse(String arg) {
char[] s = arg.toCharArray();
StringBuilder sb = new StringBuilder();
boolean reverse = false;
boolean isChar = false;
int insertPos = 0;
for (int i = 0; i < s.length; i++) {
isChar = Character.isAlphabetic(s[i]);
if (!reverse && isChar) {
sb.append(s[i]);
insertPos = i;
reverse = true;
} else if (reverse && isChar) {
sb.insert(insertPos, s[i]);
} else if (!reverse && !isChar) {
sb.append(s[i]);
} else if (reverse && !isChar) {
reverse = false;
sb.append(s[i]);
}
}
return sb.toString();
}
Android Cloud to Device Messaging Framework
Important: C2DM has been officially deprecated as of June 26, 2012. This means that C2DM has stopped accepting new users and quota requests. No new features will be added to C2DM. However, apps using C2DM will continue to work. Existing C2DM developers are encouraged to migrate to the new version of C2DM, called Google Cloud Messaging for Android (GCM). See the C2DM-to-GCM Migration document for more information. Developers must use GCM for new development.
Kindly check the following link:
The below method is the implementation of binary divide considering both numbers are positive. If subtraction is a concern we can implement that as well using binary operators.
-(int)binaryDivide:(int)numerator with:(int)denominator
{
if (numerator == 0 || denominator == 1) {
return numerator;
}
if (denominator == 0) {
#ifdef DEBUG
NSAssert(denominator == 0, @"denominator should be greater then 0");
#endif
return INFINITY;
}
// if (numerator <0) {
// numerator = abs(numerator);
// }
int maxBitDenom = [self getMaxBit:denominator];
int maxBitNumerator = [self getMaxBit:numerator];
int msbNumber = [self getMSB:maxBitDenom ofNumber:numerator];
int qoutient = 0;
int subResult = 0;
int remainingBits = maxBitNumerator-maxBitDenom;
if (msbNumber >= denominator) {
qoutient |=1;
subResult = msbNumber - denominator;
}
else {
subResult = msbNumber;
}
while (remainingBits>0) {
int msbBit = (numerator & (1 << (remainingBits-1)))>0 ? 1 : 0;
subResult = (subResult << 1) |msbBit;
if (subResult >= denominator) {
subResult = subResult-denominator;
qoutient = (qoutient << 1) | 1;
}
else {
qoutient = qoutient << 1;
}
remainingBits--;
}
return qoutient;
}
-(int)getMaxBit:(int)inputNumber
{
int maxBit =0;
BOOL isMaxBitSet = NO;
for (int i=0; i<sizeof(inputNumber)*8; i++) {
if (inputNumber & (1 << i) ) {
maxBit = i;
isMaxBitSet=YES;
}
}
if (isMaxBitSet) {
maxBit += 1;
}
return maxBit;
}
-(int)getMSB:(int)bits ofNumber:(int)number
{
int numbeMaxBit = [self getMaxBit:number];
return number >> (numbeMaxBit -bits);
}
$('#someid').attr('disabled', 'true');
In my case, this was happening because the android/gradlew file did not have execute permission. Once granted, this worked fine
For JUnit 4 users, System Lambda as suggested by Stefan Birkner is a great fit.
In case you are using JUnit 5, there is the JUnit Pioneer extension pack. It comes with @ClearEnvironmentVariable
and @SetEnvironmentVariable
. From the docs:
The
@ClearEnvironmentVariable
and@SetEnvironmentVariable
annotations can be used to clear, respectively, set the values of environment variables for a test execution. Both annotations work on the test method and class level, are repeatable as well as combinable. After the annotated method has been executed, the variables mentioned in the annotation will be restored to their original value or will be cleared if they didn't have one before. Other environment variables that are changed during the test, are not restored.
Example:
@Test
@ClearEnvironmentVariable(key = "SOME_VARIABLE")
@SetEnvironmentVariable(key = "ANOTHER_VARIABLE", value = "new value")
void test() {
assertNull(System.getenv("SOME_VARIABLE"));
assertEquals("new value", System.getenv("ANOTHER_VARIABLE"));
}
Inspired by VB.Net Generics List(Of Integer), I created my own module for that. Maybe you find it useful, too or you'd like to extend for additional methods e.g. to remove items again:
'Save module with name: ListOfInteger
Public Function ListLength(list() As Integer) As Integer
On Error Resume Next
ListLength = UBound(list) + 1
On Error GoTo 0
End Function
Public Sub ListAdd(list() As Integer, newValue As Integer)
ReDim Preserve list(ListLength(list))
list(UBound(list)) = newValue
End Sub
Public Function ListContains(list() As Integer, value As Integer) As Boolean
ListContains = False
Dim MyCounter As Integer
For MyCounter = 0 To ListLength(list) - 1
If list(MyCounter) = value Then
ListContains = True
Exit For
End If
Next
End Function
Public Sub DebugOutputList(list() As Integer)
Dim MyCounter As Integer
For MyCounter = 0 To ListLength(list) - 1
Debug.Print list(MyCounter)
Next
End Sub
You might use it as follows in your code:
Public Sub IntegerListDemo_RowsOfAllSelectedCells()
Dim rows() As Integer
Set SelectedCellRange = Excel.Selection
For Each MyCell In SelectedCellRange
If IsEmpty(MyCell.value) = False Then
If ListOfInteger.ListContains(rows, MyCell.Row) = False Then
ListAdd rows, MyCell.Row
End If
End If
Next
ListOfInteger.DebugOutputList rows
End Sub
If you need another list type, just copy the module, save it at e.g. ListOfLong and replace all types Integer by Long. That's it :-)
Though they operate the same way, however, the mouseenter
event only triggers when the mouse pointer enters the selected element. The mouseover
event is triggered if a mouse pointer enters any child elements as well.
That's not possible. localhost
always defaults to the loopback device on the local operating system.
As your virtual machine runs its own operating system it has its own loopback device which you cannot access from the outside.
If you want to access it e.g. in a browser, connect to it using the local IP instead:
http://192.168.180.1:8000
This is just an example of course, you can find out the actual IP by issuing an ifconfig
command on a shell in the guest operating system.
You can use the Java Geodesy Library for GPS, it uses the Vincenty's formulae which takes account of the earths surface curvature.
Implementation goes like this:
import org.gavaghan.geodesy.*;
...
GeodeticCalculator geoCalc = new GeodeticCalculator();
Ellipsoid reference = Ellipsoid.WGS84;
GlobalPosition pointA = new GlobalPosition(latitude, longitude, 0.0); // Point A
GlobalPosition userPos = new GlobalPosition(userLat, userLon, 0.0); // Point B
double distance = geoCalc.calculateGeodeticCurve(reference, userPos, pointA).getEllipsoidalDistance(); // Distance between Point A and Point B
The resulting distance is in meters.
A lot of these seem to be overcomplicated. I achieved what I wanted with just the following:
$(".ui-accordion-content").show();
Do something like this:
mkdir <your directory>/repos/test
svn cat http://svn.red-bean.com/repos/test/readme.txt > <your directory>/repos/test/readme.txt
Basically the idea is create the directory where you want to grab the file from SVN.
Use the svn cat
command and redirect the output to the same named file. By default, the cat will dump information on stdio.
I did this way:
Add this method to check whether email address is valid or not:
private boolean isValidEmailId(String email){
return Pattern.compile("^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
+ "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
+ "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$").matcher(email).matches();
}
Now check with String of EditText:
if(isValidEmailId(edtEmailId.getText().toString().trim())){
Toast.makeText(getApplicationContext(), "Valid Email Address.", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "InValid Email Address.", Toast.LENGTH_SHORT).show();
}
Done
You have to put div with single quotation around it. ' '
the Div
must be in the middle of single quotation . i'm gonna clear it with one example :
<?php
echo '<div id="output">'."Identify".'<br>'.'<br>';
echo 'Welcome '."$name";
echo "<br>";
echo 'Web Mail: '."$email";
echo "<br>";
echo 'Department of '."$dep";
echo "<br>";
echo "$maj";
'</div>'
?>
hope be useful.
Warning: this is an experimental feature that could dramatically change or even cease to exist in future releases
You can use ES7 statics:
npm install babel-preset-stage-0
And then add "stage-0"
to .babelrc presets:
{
"presets": ["es2015", "react", "stage-0"]
}
Afterwards, you go
class Component extends React.Component {
static foo = 'bar';
static baz = {a: 1, b: 2}
}
And then you use them like this:
Component.foo
"npm install" replaces all dependencies in your node_modules installed with "npm link" with versions from npmjs (specified in your package.json)
Well, I still find some room to answer.
In addition to answers from Rob and Nathan, I would add that having client-side validations matters. When you are applying validations on your webforms you must follow these guidelines:
Both types of validations play important roles in their respective scope but the most strongest is the server-side. If you receive 10k users at a single point of time then you would definitely end up filtering the number of requests coming to your webserver. If you find there was a single mistake like invalid email address then they post back the form again and ask your user to correct it which will definitely eat your server resources and bandwidth. So better you apply javascript validation. If javascript is disabled then your server side validation will come to rescue and i bet only a few users might have accidentlly disable it since 99.99% of websites use javascript and its already enabled by default in all modern browsers.
This below code just show the very basic use of delegate concept .. you name the variable and class as per your requirement.
First you need to declare a protocol:
Let's call it MyFirstControllerDelegate.h
@protocol MyFirstControllerDelegate
- (void) FunctionOne: (MyDataOne*) dataOne;
- (void) FunctionTwo: (MyDatatwo*) dataTwo;
@end
Import MyFirstControllerDelegate.h file and confirm your FirstController with protocol MyFirstControllerDelegate
#import "MyFirstControllerDelegate.h"
@interface FirstController : UIViewController<MyFirstControllerDelegate>
{
}
@end
In the implementation file, you need to implement both functions of protocol:
@implementation FirstController
- (void) FunctionOne: (MyDataOne*) dataOne
{
//Put your finction code here
}
- (void) FunctionTwo: (MyDatatwo*) dataTwo
{
//Put your finction code here
}
//Call below function from your code
-(void) CreateSecondController
{
SecondController *mySecondController = [SecondController alloc] initWithSomeData:.];
//..... push second controller into navigation stack
mySecondController.delegate = self ;
[mySecondController release];
}
@end
in your SecondController:
@interface SecondController:<UIViewController>
{
id <MyFirstControllerDelegate> delegate;
}
@property (nonatomic,assign) id <MyFirstControllerDelegate> delegate;
@end
In the implementation file of SecondController.
@implementation SecondController
@synthesize delegate;
//Call below two function on self.
-(void) SendOneDataToFirstController
{
[delegate FunctionOne:myDataOne];
}
-(void) SendSecondDataToFirstController
{
[delegate FunctionTwo:myDataSecond];
}
@end
Here is the wiki article on delegate.
nvl(value,defaultvalue) as Columnname
will set the missing values to defaultvalue specified
In your request options, try including the following:
var req = https.request({
host: '192.168.1.1',
port: 443,
path: '/',
method: 'GET',
rejectUnauthorized: false,
requestCert: true,
agent: false
},
Try this:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
</androidx.constraintlayout.widget.ConstraintLayout>
/>
_x000D_
All you need to do is to to use...
data-toggle="collapse"
data-target="#ElementToExpandOnClick"
...on the element you want to click to trigger the collapse/expand effect.
The element with data-toggle="collapse"
will be the element to trigger the effect.
The data-target
attribute indicates the element that will expand when the effect is triggered.
Optionally you can set the data-parent
if you want to create an accordion effect instead of independent collapsible, e.g.:
data-parent="#accordion"
I would also add the following CSS to the elements with data-toggle="collapse"
if they aren't <a>
tags, e.g.:
.panel-heading {
cursor: pointer;
}
Here's a jsfiddle with the modified html from the Bootstrap 3 documentation.
Quoting from nt.bas answer:
If you are using the newest version of Android Studio, you can let it assist you in this.
Note: I have tested this in Android Studio 3.0 only.
The procedure is as follows:
In the project view (this comes along with captures and structure on the left side of screen), select Project instead of Android.
The name of your project will be the top of the tree (alongside external libraries).
Select your project then go to Refactor -> Copy...
.
Android Studio will ask you the new name and where you want to copy the project. Provide the same.
After the copying is done, open your new project in Android Studio.
Packages will still be under the old project name.
That is the Java classes packages, application ID and everything else that was generated using the old package name.
We need to change that.
In the project view, select Android.
Open the java sub-directory and select the main package.
Then right click on it and go to Refactor
then Rename
.
Android Studio will give you a warning saying that multiple directories correspond to the package you are about to refactor.
Click on Rename package
and not Rename directory
.
After this step, your project is now completely under the new name.
Build -> Clean project
then Build -> Rebuild project
. Up to this point you only rename your whole project name. To rename packaging name you need to follow gnyrfta answer which was described as:
When refactoring the package name in Android Studio, you may need to click the little cogwheel up to the right by the package/android/project/etc - navigator and uncheck 'compact empty middle packages' in order to see each part of the package name as an own directory. Then for individual directories do refactor.
PS: If you're having an
Failed to finalize session : INSTALL_FAILED_INVALID_APK: Split lib_slice_0_apk was defined multiple times
Just delete build folder of appmodule and Rebuild the project!
This will fix the issue!
updated() should be what you're looking for:
Called after a data change causes the virtual DOM to be re-rendered and patched.
The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here.
{{ data.0 }}
should work.
Let's say you wrote data.obj
django tries data.obj
and data.obj()
. If they don't work it tries data["obj"]
. In your case data[0]
can be written as {{ data.0 }}
. But I recommend you to pull data[0]
in the view and send it as separate variable.
I resolved a similar issue by wrapping the query in another query...
Initial query was working find giving individual columns of output, with some of the columns coming from sub queries with Max or Sum function, and other with "distinct" or case substitutions and such.
I encountered the collation error after attempting to create a single field of output with...
select
rtrim(field1)+','+rtrim(field2)+','+...
The query would execute as I wrote it, but the error would occur after saving the sql and reloading it.
Wound up fixing it with something like...
select z.field1+','+z.field2+','+... as OUTPUT_REC
from (select rtrim(field1), rtrim(field2), ... ) z
Some fields are "max" of a subquery, with a case substitution if null and others are date fields, and some are left joins (might be NULL)...in other words, mixed field types. I believe this is the cause of the issue being caused by OS collation and Database collation being slightly different, but by converting all to trimmed strings before the final select, it sorts it out, all in the SQL.
I may be wrong here but I had the same problem, after spending more time than I'm proud of I realised I had set chrome to block all pop ups and hence kept reloading without showing me the alert box. So close your window and open the page again.
If that doesn't work then you problem might be something deeper because all the solutions already given should work.
public class IntergerParser {
public static void main(String[] args){
String number = "+123123";
System.out.println(parseInt(number));
}
private static int parseInt(String number){
char[] numChar = number.toCharArray();
int intValue = 0;
int decimal = 1;
for(int index = numChar.length ; index > 0 ; index --){
if(index == 1 ){
if(numChar[index - 1] == '-'){
return intValue * -1;
} else if(numChar[index - 1] == '+'){
return intValue;
}
}
intValue = intValue + (((int)numChar[index-1] - 48) * (decimal));
System.out.println((int)numChar[index-1] - 48+ " " + (decimal));
decimal = decimal * 10;
}
return intValue;
}
Please just write a static method somewhere and write:
if( isSizeBetween(orderBean.getFiles(), 0, 5) ){
// do your stuff
}
In Swift3:
let fileUrl = Foundation.URL(string: filePath)
I recently just figured out how to do this, and here's some example code from a current project of mine:
#Getting the random picture.
#First find all pictures:
import shlex, subprocess
cmd = 'find ../Pictures/ -regex ".*\(JPG\|NEF\|jpg\)" '
#cmd = raw_input("shell:")
args = shlex.split(cmd)
output,error = subprocess.Popen(args,stdout = subprocess.PIPE, stderr= subprocess.PIPE).communicate()
#Another way to get output
#output = subprocess.Popen(args,stdout = subprocess.PIPE).stdout
ber = raw_input("search complete, display results?")
print output
#... and on to the selection process ...
You now have the output of the command stored in the variable "output". "stdout = subprocess.PIPE" tells the class to create a file object named 'stdout' from within Popen. The communicate() method, from what I can tell, just acts as a convenient way to return a tuple of the output and the errors from the process you've run. Also, the process is run when instantiating Popen.
The whole thing to em is, that the size is relative to the base. So I would say you could keep the font sizes by altering the base.
Example: If you base is 16px, and p is .75em (which is 12px) you would have to raise the base to about 20px. In this case p would then equal about 15px which is the minimum I personally require for mobile phones.
I figured out that this behaves like a mousedown event:
button:active:hover {}
The OpenCV Android SDK has an example gradle.build file with helpful comments: https://github.com/opencv/opencv/blob/master/modules/java/android_sdk/build.gradle.in
//
// Notes about integration OpenCV into existed Android Studio application project are below (application 'app' module should exist).
//
// This file is located in <OpenCV-android-sdk>/sdk directory (near 'etc', 'java', 'native' subdirectories)
//
// Add module into Android Studio application project:
//
// - Android Studio way:
// (will copy almost all OpenCV Android SDK into your project, ~200Mb)
//
// Import module: Menu -> "File" -> "New" -> "Module" -> "Import Gradle project":
// Source directory: select this "sdk" directory
// Module name: ":opencv"
//
// - or attach library module from OpenCV Android SDK
// (without copying into application project directory, allow to share the same module between projects)
//
// Edit "settings.gradle" and add these lines:
//
// def opencvsdk='<path_to_opencv_android_sdk_rootdir>'
// // You can put declaration above into gradle.properties file instead (including file in HOME directory),
// // but without 'def' and apostrophe symbols ('): opencvsdk=<path_to_opencv_android_sdk_rootdir>
// include ':opencv'
// project(':opencv').projectDir = new File(opencvsdk + '/sdk')
//
//
//
// Add dependency into application module:
//
// - Android Studio way:
// "Open Module Settings" (F4) -> "Dependencies" tab
//
// - or add "project(':opencv')" dependency into app/build.gradle:
//
// dependencies {
// implementation fileTree(dir: 'libs', include: ['*.jar'])
// ...
// implementation project(':opencv')
// }
//
//
//
// Load OpenCV native library before using:
//
// - avoid using of "OpenCVLoader.initAsync()" approach - it is deprecated
// It may load library with different version (from OpenCV Android Manager, which is installed separatelly on device)
//
// - use "System.loadLibrary("opencv_java3")" or "OpenCVLoader.initDebug()"
// TODO: Add accurate API to load OpenCV native library
//
//
//
// Native C++ support (necessary to use OpenCV in native code of application only):
//
// - Use find_package() in app/CMakeLists.txt:
//
// find_package(OpenCV 3.4 REQUIRED java)
// ...
// target_link_libraries(native-lib ${OpenCV_LIBRARIES})
//
// - Add "OpenCV_DIR" and enable C++ exceptions/RTTI support via app/build.gradle
// Documentation about CMake options: https://developer.android.com/ndk/guides/cmake.html
//
// defaultConfig {
// ...
// externalNativeBuild {
// cmake {
// cppFlags "-std=c++11 -frtti -fexceptions"
// arguments "-DOpenCV_DIR=" + opencvsdk + "/sdk/native/jni" // , "-DANDROID_ARM_NEON=TRUE"
// }
// }
// }
//
// - (optional) Limit/filter ABIs to build ('android' scope of 'app/build.gradle'):
// Useful information: https://developer.android.com/studio/build/gradle-tips.html (Configure separate APKs per ABI)
//
// splits {
// abi {
// enable true
// reset()
// include 'armeabi-v7a' // , 'x86', 'x86_64', 'arm64-v8a'
// universalApk false
// }
// }
//
apply plugin: 'com.android.library'
println "OpenCV: " + project.buildscript.sourceFile
android {
compileSdkVersion 27
//buildToolsVersion "27.0.3" // not needed since com.android.tools.build:gradle:3.0.0
defaultConfig {
minSdkVersion 14
targetSdkVersion 21
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_6
targetCompatibility JavaVersion.VERSION_1_6
}
sourceSets {
main {
jniLibs.srcDirs = ['native/libs']
java.srcDirs = ['java/src']
aidl.srcDirs = ['java/src']
res.srcDirs = ['java/res']
manifest.srcFile 'java/AndroidManifest.xml'
}
}
}
dependencies {
}
Use the title
attribute while alt
is important for SEO stuff.
You need to correctly separate static data from instance data. In your code, onLoan
and setLoanItem()
are instance members. If you want to reference/call them you must do so via an instance. So you either want
public void loanItem() {
this.media.setLoanItem("Yes");
}
or
public void loanItem(Media object) {
object.setLoanItem("Yes");
}
depending on how you want to pass that instance around.
I AM USING HTML TO SOLVE THIS PROBLEM
Use:
<a href="page1.html"> Link </a>
*page1.html -> type the name of the file you are working on (your current HTML file)
A function name can become a variable name (and thus be passed as an argument) by dropping the parentheses. A variable name can become a function name by adding the parentheses.
In your example, equate the variable rules
to one of your functions, leaving off the parentheses and the mention of the argument. Then in your game()
function, invoke rules( v )
with the parentheses and the v
parameter.
if puzzle == type1:
rules = Rule1
else:
rules = Rule2
def Game(listA, listB, rules):
if rules( v ) == True:
do...
else:
do...
Ok, here's a simple box that follows the cursor
Doing the rest is a simple case of remembering the last cursor position and applying a formula to get the box to move other than exactly where the cursor is. A timeout would also be handy if the box has a limited acceleration and must catch up to the cursor after it stops moving. Replacing the box with an image is simple CSS (which can replace most of the setup code for the box). I think the actual thinking code in the example is about 8 lines.
Select the right image (use a sprite) to orientate the rocket.
Yeah, annoying as hell. :-)
function getMouseCoords(e) {
var e = e || window.event;
document.getElementById('container').innerHTML = e.clientX + ', ' +
e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}
var followCursor = (function() {
var s = document.createElement('div');
s.style.position = 'absolute';
s.style.margin = '0';
s.style.padding = '5px';
s.style.border = '1px solid red';
s.textContent = ""
return {
init: function() {
document.body.appendChild(s);
},
run: function(e) {
var e = e || window.event;
s.style.left = (e.clientX - 5) + 'px';
s.style.top = (e.clientY - 5) + 'px';
getMouseCoords(e);
}
};
}());
window.onload = function() {
followCursor.init();
document.body.onmousemove = followCursor.run;
}
_x000D_
#container {
width: 1000px;
height: 1000px;
border: 1px solid blue;
}
_x000D_
<div id="container"></div>
_x000D_
Try this
<div class="home-component"
[style.width.px]="width"
[style.height.px]="height">Some stuff in this div</div>
[Updated]: To set in % use
[style.height.%]="height">Some stuff in this div</div>
You can easily use this function to get the result:
function objetToArray($adminBar){
$reflector = new ReflectionObject($adminBar);
$nodes = $reflector->getProperties();
$out = [];
foreach ($nodes as $node) {
$nod = $reflector->getProperty($node->getName());
$nod->setAccessible(true);
$out[$node->getName()] = $nod->getValue($adminBar);
}
return $out;
}
Use PHP 5 or later.
I deal with this issue for some hours. Let's consider the request is Reactjs (javascript) and backend (API) is Asp .Net Core.
in the request, you must set in header Content-Type:
Axios({
method: 'post',
headers: { 'Content-Type': 'application/json'},
url: 'https://localhost:44346/Order/Order/GiveOrder',
data: order,
}).then(function (response) {
console.log(response);
});
and in backend (Asp .net core API) u must have some setting:
1. in Startup --> ConfigureServices:
#region Allow-Orgin
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});
#endregion
2. in Startup --> Configure before app.UseMvc() :
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
3. in controller before action:
[EnableCors("AllowOrigin")]
$ join -v 1 -t '' file1 file2
line2
line3
The -t
makes sure that it compares the whole line, if you had a space in some of the lines.
Is this what you are after? Just index the element and assign a new value.
A[2,1]=150
A
Out[345]:
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 150, 11, 12],
[13, 14, 15, 16]])
You can install the matplotlib package in python 3 by doing this
python3 -m pip install matplotlib --user
It's working for me.
here is your answer
String userName = "xxxx";
String password = "xxxx";
String url = "jdbc:sqlserver:xxx.xxx.xxx.xxx;databaseName=asdfzxcvqwer;integratedSecurity=true";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(url, userName, password);
} catch (Exception e)
{
e.printStackTrace();
}
setText
is changing the text content to exactly what you give it, not appending it.
Convert the String
from the field first, then apply it directly...
String value = "This Is A Test";
StringBuilder sb = new StringBuilder(value);
for (int index = 0; index < sb.length(); index++) {
char c = sb.charAt(index);
if (Character.isLowerCase(c)) {
sb.setCharAt(index, Character.toUpperCase(c));
} else {
sb.setCharAt(index, Character.toLowerCase(c));
}
}
SecondTextField.setText(sb.toString());
In your activity override this method.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
This will inflate your menu below:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_main_setting"
android:icon="@drawable/ic_settings"
android:orderInCategory="100"
app:showAsAction="always"
android:actionLayout="@layout/toolbar"
android:title="Setting" />
<item
android:id="@+id/menu_main_setting2"
android:icon="@drawable/ic_settings"
android:orderInCategory="200"
app:showAsAction="always"
android:actionLayout="@layout/toolbar"
android:title="Setting" />
</menu>
or:
using FileStream fileStream = File.Open(path, FileMode.Append);
using StreamWriter file = new StreamWriter(fileStream);
// ...
Example 4 columns of span3. For other span widths use new width = old width + gutter size. Use media queries to make it responsive.
css:
<style type="text/css">
@media (min-width: 1200px)
{
.nogutter .span3
{
margin-left: 0px; width:300px;
}
}
@media (min-width: 980px) and (max-width: 1199px)
{
.nogutter .span3
{
margin-left: 0px; width:240px;
}
}
@media (min-width: 768px) and (max-width: 979px)
{
.nogutter .span3
{
margin-left: 0px; width:186px;
}
}
</style>
html:
<div class="container">
<div class="row">
<div class="span3" style="background-color:red;">...</div>
<div class="span3" style="background-color:red;">...</div>
<div class="span3" style="background-color:red;">...</div>
<div class="span3" style="background-color:red;">...</div>
</div>
<br>
<div class="row nogutter">
<div class="span3" style="background-color:red;">...</div>
<div class="span3" style="background-color:red;">...</div>
<div class="span3" style="background-color:red;">...</div>
<div class="span3" style="background-color:red;">...</div>
</div>
</div>
update: or split a span12 div in 100/numberofcolumns % width parts floating left:
<div class="row">
<div class="span12">
<div style="background-color:green;width:25%;float:left;">...</div>
<div style="background-color:yellow;width:25%;float:left;">...</div>
<div style="background-color:red;width:25%;float:left;">...</div>
<div style="background-color:blue;width:25%;float:left;">...</div>
</div>
</div>
For both solutions see: http://bootply.com/61557
Adobe BrowserLab.
Conditionally perform a command several times.
syntax-FOR-Files
FOR %%parameter IN (set) DO command
syntax-FOR-Files-Rooted at Path
FOR /R [[drive:]path] %%parameter IN (set) DO command
syntax-FOR-Folders
FOR /D %%parameter IN (folder_set) DO command
syntax-FOR-List of numbers
FOR /L %%parameter IN (start,step,end) DO command
syntax-FOR-File contents
FOR /F ["options"] %%parameter IN (filenameset) DO command
or
FOR /F ["options"] %%parameter IN ("Text string to process") DO command
syntax-FOR-Command Results
FOR /F ["options"] %%parameter IN ('command to process') DO command
It
%%G
equal to some part of that dataIf you are using the FOR command at the command line rather than in a batch program, use just one percent sign: %G
instead of %%G
.
FOR Parameters
The first parameter has to be defined using a single character, for example the letter G.
FOR %%G IN
...
In each iteration of a FOR loop, the IN ( ....)
clause is evaluated and %%G
set to a different value
If this clause results in a single value then %%G is set equal to that value and the command is performed.
If the clause results in a multiple values then extra parameters are implicitly defined to hold each. These are automatically assigned in alphabetical order %%H %%I %%J
...(implicit parameter definition)
If the parameter refers to a file, then enhanced variable reference can be used to extract the filename/path/date/size.
You can of course pick any letter of the alphabet other than %%G
. but it is a good choice because it does not conflict with any of the pathname format letters (a, d, f, n, p, s, t, x) and provides the longest run of non-conflicting letters for use as implicit parameters.
Add: now you can use lambda to simplify your syntax. Requirement: Java 8+
public class A {
public static void main(String[] arg)
{
Thread th = new Thread(() -> {System.out.println("blah");});
th.start();
}
}
I think the answer you are after is implied (if not stated) by Vinko's answer, though it is not spelled out simply. To distinguish whether VAR is set but empty or not set, you can use:
if [ -z "${VAR+xxx}" ]; then echo VAR is not set at all; fi
if [ -z "$VAR" ] && [ "${VAR+xxx}" = "xxx" ]; then echo VAR is set but empty; fi
You probably can combine the two tests on the second line into one with:
if [ -z "$VAR" -a "${VAR+xxx}" = "xxx" ]; then echo VAR is set but empty; fi
However, if you read the documentation for Autoconf, you'll find that they do not recommend combining terms with '-a
' and do recommend using separate simple tests combined with &&
. I've not encountered a system where there is a problem; that doesn't mean they didn't used to exist (but they are probably extremely rare these days, even if they weren't as rare in the distant past).
You can find the details of these, and other related shell parameter expansions, the test
or [
command and conditional expressions in the Bash manual.
I was recently asked by email about this answer with the question:
You use two tests, and I understand the second one well, but not the first one. More precisely I don't understand the need for variable expansion
if [ -z "${VAR+xxx}" ]; then echo VAR is not set at all; fi
Wouldn't this accomplish the same?
if [ -z "${VAR}" ]; then echo VAR is not set at all; fi
Fair question - the answer is 'No, your simpler alternative does not do the same thing'.
Suppose I write this before your test:
VAR=
Your test will say "VAR is not set at all", but mine will say (by implication because it echoes nothing) "VAR is set but its value might be empty". Try this script:
(
unset VAR
if [ -z "${VAR+xxx}" ]; then echo JL:1 VAR is not set at all; fi
if [ -z "${VAR}" ]; then echo MP:1 VAR is not set at all; fi
VAR=
if [ -z "${VAR+xxx}" ]; then echo JL:2 VAR is not set at all; fi
if [ -z "${VAR}" ]; then echo MP:2 VAR is not set at all; fi
)
The output is:
JL:1 VAR is not set at all
MP:1 VAR is not set at all
MP:2 VAR is not set at all
In the second pair of tests, the variable is set, but it is set to the empty value. This is the distinction that the ${VAR=value}
and ${VAR:=value}
notations make. Ditto for ${VAR-value}
and ${VAR:-value}
, and ${VAR+value}
and ${VAR:+value}
, and so on.
As Gili points out in his answer, if you run bash
with the set -o nounset
option, then the basic answer above fails with unbound variable
. It is easily remedied:
if [ -z "${VAR+xxx}" ]; then echo VAR is not set at all; fi
if [ -z "${VAR-}" ] && [ "${VAR+xxx}" = "xxx" ]; then echo VAR is set but empty; fi
Or you could cancel the set -o nounset
option with set +u
(set -u
being equivalent to set -o nounset
).
closest()
selects the first element that matches the selector, up from the DOM tree. Begins from the current element and travels up.
parent()
selects one element up (single level up) the DOM tree.
parents()
method is similar toparent()
but selects all the matching elements up the DOM tree. Begins from the parent element and travels up.
Try this..
Dim S As String
S = "RAJAN"
Dim answer As Char
answer = S.Substring(0, 1)
var line = "<label onclick="alert(1)">aaa</label>";
app.filter('unsafe', function($sce) { return $sce.trustAsHtml; });
using (html):
<span ng-bind-html="line | unsafe"></span>
==>click `aaa` show alert box
include angular-sanitize.js
<script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
add ngSanitize
in root angular app
var app = angular.module("app", ["ngSanitize"]);
using (html):
<span ng-bind-html="line"></span>
==>click `aaa` nothing happen
Here is KeyboardHelper Class for hiding and showing keyboard
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
/**
* Created by khanhamza on 06-Mar-17.
*/
public class KeyboardHelper {
public static void hideSoftKeyboard(final Context context, final View view) {
if (context == null) {
return;
}
view.requestFocus();
view.postDelayed(new Runnable() {
@Override
public void run() {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}, 1000);
}
public static void hideSoftKeyboard(final Context context, final EditText editText) {
editText.requestFocus();
editText.postDelayed(new Runnable() {
@Override
public void run() {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
}, 1000);
}
public static void openSoftKeyboard(final Context context, final EditText editText) {
editText.requestFocus();
editText.postDelayed(new Runnable() {
@Override
public void run() {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
}, 1000);
}
}
pass the output to str() function and it will remove the convert the unicode output. also by printing the output it will remove the u'' tags from it.
This is what you can do:
SELECT *
FROM yourTable
PIVOT (MAX(xCount)
FOR Week in ([1],[2],[3],[4],[5],[6],[7])) AS pvt
Try this :
$i = 0;
while($row = mysqli_fetch_array($result)) {
$posts['post_id'] = $row[$i]['post_id'];
$posts['post_title'] = $row[$i]['post_title'];
$posts['type'] = $row[$i]['type'];
$posts['author'] = $row[$i]['author'];
}
$i++;
}
print_r($posts);
There is a problem with cordova version 6.4.0 and android 6.2.1 .so,please try with below compatible versions
cordova version must be 6.4.0
sudo npm install -g [email protected]
Install android in your project
sudo cordova platform add [email protected]
or
sudo ionic platform add [email protected]
If APEX_UTIL
is not available, you have a solution using REGEXP_SUBSTR()
.
Inspired from http://nuijten.blogspot.fr/2009/07/splitting-comma-delimited-string-regexp.html :
DECLARE
I INTEGER;
TYPE T_ARRAY_OF_VARCHAR IS TABLE OF VARCHAR2(2000) INDEX BY BINARY_INTEGER;
MY_ARRAY T_ARRAY_OF_VARCHAR;
MY_STRING VARCHAR2(2000) := '123,456,abc,def';
BEGIN
FOR CURRENT_ROW IN (
with test as
(select MY_STRING from dual)
select regexp_substr(MY_STRING, '[^,]+', 1, rownum) SPLIT
from test
connect by level <= length (regexp_replace(MY_STRING, '[^,]+')) + 1)
LOOP
DBMS_OUTPUT.PUT_LINE(CURRENT_ROW.SPLIT);
MY_ARRAY(MY_ARRAY.COUNT) := CURRENT_ROW.SPLIT;
END LOOP;
END;
/
You are looking for
MyList.Select(x=>x.Name).ToArray();
Since Select
is an Extension method make sure to add that namespace by adding a
using System.Linq
to your file - then it will show up with Intellisense.
I had the same problem. What I've done: add in my view hidden field with id of a model and in validator check the unique, only if I've get some id from view.
$this->validate(
$request,
[
'index' => implode('|', ['required', $request->input('id') ? '' : 'unique:members']),
'name' => 'required',
'surname' => 'required',
]
);
NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "functionHere", userInfo: nil, repeats: false)
This would call the function functionHere() with a 3 seconds delay
function return2tab (div)
{
document.addEventListener('keydown', function (ev) {
if (ev.key === "Enter" && ev.target.nodeName === 'INPUT') {
var focusableElementsString = 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex="0"], [contenteditable]';
let ol= div.querySelectorAll(focusableElementsString);
for (let i=0; i<ol.length; i++) {
if (ol[i] === ev.target) {
let o= i<ol.length-1? ol[i+1]: o[0];
o.focus(); break;
}
}
ev.preventDefault();
}
});
}
I have found problems when applying classes inside table elements when I had one class already applied to the whole table (for example, a color applied to the odd rows <myClass tbody tr:nth-child(even) td>
). It seems that when you inspect the element with Developer Tools, the element.style
has no style assigned. So instead of using ng-class
, I have tried using ng-style
, and in this case, the new CSS attribute does appear inside element.style
. This code works great for me:
<tr ng-repeat="element in collection">
[...amazing code...]
<td ng-style="myvar === 0 && {'background-color': 'red'} ||
myvar === 1 && {'background-color': 'green'} ||
myvar === 2 && {'background-color': 'yellow'}">{{ myvar }}</td>
[...more amazing code...]
</tr>
Myvar is what I am evaluating, and in each case I apply a style to each <td>
depending on myvar value, that overwrites the current style applied by the CSS class for the whole table.
UPDATE
If you want to apply a class to the table for example, when visiting a page or in other cases, you can use this structure:
<li ng-class="{ active: isActive('/route_a') || isActive('/route_b')}">
Basically, what we need to activate a ng-class is the class to apply and a true or false statement. True applies the class and false doesn't. So here we have two checks of the route of the page and an OR between them, so if we are in /route_a
OR we are in route_b
, the active class will be applied.
This works just having a logic function on the right that returns true or false.
So in the first example, ng-style is conditioned by three statements. If all of them are false, no style is applied, but following our logic, at least one is going to be applied, so, the logic expression will check which variable comparison is true and because a non empty array is always true, that will left an array as return and with only one true, considering we are using OR for the whole response, the style remaining will be applied.
By the way, I forgot to give you the function isActive():
$rootScope.isActive = function(viewLocation) {
return viewLocation === $location.path();
};
NEW UPDATE
Here you have something I find really useful. When you need to apply a class depending on the value of a variable, for example, an icon depending on the contents of the div
, you can use the following code (very useful in ng-repeat
):
<i class="fa" ng-class="{ 'fa-github' : type === 0,
'fa-linkedin' : type === 1,
'fa-skype' : type === 2,
'fa-google' : type === 3 }"></i>
Icons from Font Awesome
You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start()
. The headers will be sent automatically when any HTML is output.
Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.
Move the session_start()
to the top of your document :
<?php session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php'; // more PHP code here.
As soon as question is about dynamic array you may want not just to create array with variable size, but also to change it's size during runtime. Here is an example with memcpy
, you can use memcpy_s
or std::copy
as well. Depending on compiler, <memory.h>
or <string.h>
may be required. When using this functions you allocate new memory region, copy values of original memory regions to it and then release them.
// create desired array dynamically
size_t length;
length = 100; //for example
int *array = new int[length];
// now let's change is's size - e.g. add 50 new elements
size_t added = 50;
int *added_array = new int[added];
/*
somehow set values to given arrays
*/
// add elements to array
int* temp = new int[length + added];
memcpy(temp, array, length * sizeof(int));
memcpy(temp + length, added_array, added * sizeof(int));
delete[] array;
array = temp;
You may use constant 4 instead of sizeof(int)
.
Another option to do it is:
this.httpClient.get('path', {
params: Object.entries(data).reduce(
(params, [key, value]) => params.set(key, value), new HttpParams());
});
How to write literal boolean value in SQL Server?
select * from SomeTable where PSEUDO_TRUE
There is no such thing.
You have to compare the value with something using = < > like ...
. The closest you get a boolean value in SQL Server is the bit. And that is an integer that can have the values null
, 0
and 1
.
You can use the JsonTextReader
to read the JSON and iterate over the tokens:
using (var reader = new JsonTextReader(new StringReader(jsonText)))
{
while (reader.Read())
{
Console.WriteLine("{0} - {1} - {2}",
reader.TokenType, reader.ValueType, reader.Value);
}
}
What is wrong with List.Find ??
I think we need more information on what you've done, and why it fails, before we can provide truly helpful answers.
I have to restart my kernels and remove all the packages that I have installed previously(during the first installation), please make sure to delete all the packages, even after removing packages by command below
sudo apt-get --purge remove "nvidia"
the packages like "libtinfo6:i386" doesn't get removed
I'm using Ubuntu 20.04 and Nvidia-driver-440 for that you have to remove all the packages shown below image
List of all the packages that need to be remove:
as shown in the image, make sure that the package you're installing is of the correct size that is 207 Mb for Nvidia-driver-440, if it's less it means you haven't removed all the packages.
As an administrator working on other people's profile and you need to get the Id of the profile you are working on, you can use a ViewBag to capture the Id e.g ViewBag.UserId = userId; while userId is the string Parameter of the method you are working on.
[HttpGet]
public async Task<IActionResult> ManageUserRoles(string userId)
{
ViewBag.UserId = userId;
var user = await userManager.FindByIdAsync(userId);
if (user == null)
{
ViewBag.ErrorMessage = $"User with Id = {userId} cannot be found";
return View("NotFound");
}
var model = new List<UserRolesViewModel>();
foreach (var role in roleManager.Roles)
{
var userRolesViewModel = new UserRolesViewModel
{
RoleId = role.Id,
RoleName = role.Name
};
if (await userManager.IsInRoleAsync(user, role.Name))
{
userRolesViewModel.IsSelected = true;
}
else
{
userRolesViewModel.IsSelected = false;
}
model.Add(userRolesViewModel);
}
return View(model);
}
If you are using a SpringBoot application it's as simple as
ScheduledProcess
@Log
@Component
public class ScheduledProcess {
@Scheduled(fixedRate = 5000)
public void run() {
log.info("this runs every 5 seconds..");
}
}
Application.class
@SpringBootApplication
// ADD THIS ANNOTATION TO YOUR APPLICATION CLASS
@EnableScheduling
public class SchedulingTasksApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulingTasksApplication.class);
}
}
The first answer does't work anymore.
This worked for me:
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium import webdriver
options = FirefoxOptions()
options.add_argument("--headless")
driver = webdriver.Firefox(options=options)
driver.get("http://google.com")
It seems from your question that you would like to simply increment the year of your given date rather than worry about leap year implications. You can use the date class to do this by accessing its member year.
from datetime import date
startDate = date(2012, 12, 21)
# reconstruct date fully
endDate = date(startDate.year + 1, startDate.month, startDate.day)
# replace year only
endDate = startDate.replace(startDate.year + 1)
If you're having problems creating one given your format, let us know.
In my case I was using a parent pom (not sure it was the real cause since I was running against the clock), maven 2.x and java 1.6 were used, for some reason above solutions didn't work, so I added the following profile and managed it to make it run:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>myapp</artifactId>
<packaging>war</packaging>
<name>myapp</name>
<version>0.0.1-SNAPSHOT</version>
<description>My App</description>
<parent>
<groupId>com.mycompany</groupId>
<artifactId>parent-artifact</artifactId>
<version>0.0.1</version>
</parent>
<profiles>
<profile>
<id>doclint-java6-disable</id>
<activation>
<jdk>[1.6,)</jdk>
</activation>
<properties>
<additionalparam>--allow-script-in-comments</additionalparam>
</properties>
</profile>
</profiles>
</project>
You seem to just have begun using mysql.
Simple answer: for now use
mysql -u root -p password
Password is usually root by default. You may use other usernames if you have created other user using create user in mysql. For details use "help, help manage accounts, help create users" etc. If you dont want your password to be shown in open just press return key after "-p" and you will be prompted for password next. Hope this resolves the issue.
Use the dist()
function, but you need to form a matrix from the two inputs for the first argument to dist()
:
dist(rbind(x1, x2))
For the input in the OP's question we get:
> dist(rbind(x1, x2))
x1
x2 7.94821
a single value that is the Euclidean distance between x1
and x2
.
You can simply add a FontAwesome icon to your select dropdown as text. You only need a few things in CSS only, the FontAwesome CSS and the unicode. For example 
:
select {_x000D_
font-family: 'FontAwesome', 'Second Font name'_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<select>_x000D_
<option>Hi, </option>_x000D_
<option>Hi, </option>_x000D_
<option>Hi, </option>_x000D_
<option>Hi, </option>_x000D_
<option>Hi, </option>_x000D_
</select>
_x000D_
The unicodes can be found when you click on an icon: Fontawesome
According to the comment below and issue on Github, the unicode in select elements won't work on OSX (yet).
Update: from the Github issue, adding multiple
attribute to select
element makes it work on:
OSX El Capitan 10.11.4
select{_x000D_
font-family: FontAwesome, sans-serif;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<select multiple>_x000D_
<option> 500px</option>_x000D_
<option> Adjust</option>_x000D_
<option> Adn</option>_x000D_
<option> Align-center</option>_x000D_
<option> Align-justify</option>_x000D_
<option> Align-left</option>_x000D_
<option> Align-right</option>_x000D_
</select>
_x000D_
Foole's code worked perfectly for me, but in .NET 4.0, don't forget to check if Proxy is NULL, which means no proxy configured (outside corporate environment)
So here's the code that solved my problem with our corporate proxy
WebClient web = new WebClient();
if (web.Proxy != null)
web.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
The easiest way according to me will be using SDWebImage
Add this to your pod file
pod 'SDWebImage', '~> 4.0'
Run pod install
Now import SDWebImage
import SDWebImage
Now for setting image from url
imageView.sd_setImage(with: URL(string: "http://www.domain/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))
It will show placeholder image but when image is downloaded it will show the image from url .Your app will never crash
This are the main feature of SDWebImage
Categories for UIImageView, UIButton, MKAnnotationView adding web image and cache management
An asynchronous image downloader
An asynchronous memory + disk image caching with automatic cache expiration handling
A background image decompression
A guarantee that the same URL won't be downloaded several times
A guarantee that bogus URLs won't be retried again and again
A guarantee that main thread will never be blocked Performances!
Use GCD and ARC
To know more https://github.com/rs/SDWebImage
NOTE: In 2016, you can probably use
flexbox
to solve this problem easier.
This method works correctly IE7+ and all major browsers, it's been tried and tested in a number of complex viewport-based web applications.
<style>
.container {
font-size: 0;
}
.ie7 .column {
font-size: 16px;
display: inline;
zoom: 1;
}
.ie8 .column {
font-size:16px;
}
.ie9_and_newer .column {
display: inline-block;
width: 50%;
font-size: 1rem;
}
</style>
<div class="container">
<div class="column">text that can wrap</div>
<div class="column">text that can wrap</div>
</div>
Live demo: http://output.jsbin.com/sekeco/2
The only downside to this method for IE7/8, is relying on body {font-size:??px}
as basis for em/%-based font-sizing.
IE7/IE8 specific CSS could be served using IE's Conditional comments
Just do (int)myLongValue
. It'll do exactly what you want (discarding MSBs and taking LSBs) in unchecked
context (which is the compiler default). It'll throw OverflowException
in checked
context if the value doesn't fit in an int
:
int myIntValue = unchecked((int)myLongValue);
Finally, I got the mistake and the reason was I need to stringify the JSON data I was sending. I have to set the content type and datatype in XHR object. So the correct version is here:
$.ajax({
type: 'POST',
url: "http://localhost:8080/project/server/rest/subjects",
data: JSON.stringify({
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work", "facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
}),
error: function(e) {
console.log(e);
},
dataType: "json",
contentType: "application/json"
});
May be it will help someone else.
public async Task<List<TimeAndAttendanceShift>> FindEntitiesByExpression(Expression<Func<TimeAndAttendanceShift, bool>> predicate)
{
IList<TimeAndAttendanceShift> result = await _dbContext.Set<TimeAndAttendanceShift>().Where(predicate).ToListAsync<TimeAndAttendanceShift>();
return result.ToList<TimeAndAttendanceShift>();
}
O (n log n) is famously the upper bound on how fast you can sort an arbitrary set (assuming a standard and not highly parallel computing model).
As you have found out there is no such thing as a single "local IP address". Here's how to find out the local address that can be sent out to a specific host.
I know this is old but it is still relevant. You can take advantage of reshape2::melt to change the dataframe into a more friendly structure for ggplot2.
Advantages:
Disadvantage:
For example:
jobsAFAM1 <- data.frame(
data_date = seq.Date(from = as.Date('2017-01-01'),by = 'day', length.out = 100),
Percent.Change = runif(5,1,100)
)
jobsAFAM2 <- data.frame(
data_date = seq.Date(from = as.Date('2017-01-01'),by = 'day', length.out = 100),
Percent.Change = runif(5,1,100)
)
jobsAFAM <- merge(jobsAFAM1, jobsAFAM2, by="data_date")
jobsAFAMMelted <- reshape2::melt(jobsAFAM, id.var='data_date')
ggplot(jobsAFAMMelted, aes(x=data_date, y=value, col=variable)) + geom_line()
Wikipedia has a comprehensive list of unit testing frameworks, with tables that identify features supported or not.
Just ask yourself how many statements need to execute for F(n)
to complete.
For F(1)
, the answer is 1
(the first part of the conditional).
For F(n)
, the answer is F(n-1) + F(n-2)
.
So what function satisfies these rules? Try an (a > 1):
an == a(n-1) + a(n-2)
Divide through by a(n-2):
a2 == a + 1
Solve for a
and you get (1+sqrt(5))/2 = 1.6180339887
, otherwise known as the golden ratio.
So it takes exponential time.
This works in Chrome, Firefox, doesn't work in Safari :(, haven't tested in other browsers
delete window.document.referrer;
window.document.__defineGetter__('referrer', function () {
return "yoururl.com";
});
Saw that here https://gist.github.com/papoms/3481673
Regards
test case: https://jsfiddle.net/bez3w4ko/ (so you can easily test several browsers) and here is a test with iframes https://jsfiddle.net/2vbfpjp1/1/
<script type="text/javascript">
function lnkLogout_Confirm()
{
var bResponse = confirm('Are you sure you want to exit?');
if (bResponse === true) {
////console.log("lnkLogout_Confirm clciked.");
var url = '@Url.Action("Login", "Login")';
window.location.href = url;
}
return bResponse;
}
</script>
I would be very concerned about putting the load of sending e-mails on my database server (small though it may be). I might suggest one of these alternatives:
The ioctl
function is useful for implementing a device driver to set the configuration on the device. e.g. a printer that has configuration options to check and set the font family, font size etc. ioctl
could be used to get the current font as well as set the font to a new one. A user application uses ioctl
to send a code to a printer telling it to return the current font or to set the font to a new one.
int ioctl(int fd, int request, ...)
fd
is file descriptor, the one returned by open
;request
is request code. e.g GETFONT
will get the current font from the printer, SETFONT
will set the font on the printer;void *
. Depending on the second argument, the third may or may not be present,
e.g. if the second argument is SETFONT
, the third argument can be the font name such as "Arial"
;int request
is not just a macro. A user application is required to generate a request code and the device driver module to determine which configuration on device must be played with. The application sends the request code using ioctl
and then uses the request code in the device driver module to determine which action to perform.
A request code has 4 main parts
1. A Magic number - 8 bits
2. A sequence number - 8 bits
3. Argument type (typically 14 bits), if any.
4. Direction of data transfer (2 bits).
If the request code is SETFONT
to set font on a printer, the direction for data transfer will be from user application to device driver module (The user application sends the font name "Arial"
to the printer).
If the request code is GETFONT
, direction is from printer to the user application.
In order to generate a request code, Linux provides some predefined function-like macros.
1._IO(MAGIC, SEQ_NO)
both are 8 bits, 0 to 255, e.g. let us say we want to pause printer.
This does not require a data transfer. So we would generate the request code as below
#define PRIN_MAGIC 'P'
#define NUM 0
#define PAUSE_PRIN __IO(PRIN_MAGIC, NUM)
and now use ioctl
as
ret_val = ioctl(fd, PAUSE_PRIN);
The corresponding system call in the driver module will receive the code and pause the printer.
__IOW(MAGIC, SEQ_NO, TYPE)
MAGIC
and SEQ_NO
are the same as above, and TYPE
gives the type of the next argument, recall the third argument of ioctl
is void *
. W in __IOW
indicates that the data flow is from user application to driver module. As an example,
suppose we want to set the printer font to "Arial"
.#define PRIN_MAGIC 'S'
#define SEQ_NO 1
#define SETFONT __IOW(PRIN_MAGIC, SEQ_NO, unsigned long)
further,
char *font = "Arial";
ret_val = ioctl(fd, SETFONT, font);
Now font
is a pointer, which means it is an address best represented as unsigned long
, hence the third part of _IOW
mentions type as such. Also, this address of font is passed to corresponding system call implemented in device driver module as unsigned long
and we need to cast it to proper type before using it. Kernel space can access user space and hence this works. other two function-like macros are __IOR(MAGIC, SEQ_NO, TYPE)
and __IORW(MAGIC, SEQ_NO, TYPE)
where the data flow will be from kernel space to user space and both ways respectively.
Please let me know if this helps!
WAI-ARIA is a spec defining support for accessible web apps. It defines bunch of markup extensions (mostly as attributes on HTML5 elements), which can be used by the web app developer to provide additional information about the semantics of the various elements to assistive technologies like screen readers. Of course, for ARIA to work, the HTTP user agent that interprets the markup needs to support ARIA, but the spec is created in such a way, as to allow down-level user agents to ignore the ARIA-specific markup safely without affecting the web app's functionality.
Here's an example from the ARIA spec:
<ul role="menubar">
<!-- Rule 2A: "File" label via aria-labelledby -->
<li role="menuitem" aria-haspopup="true" aria-labelledby="fileLabel"><span id="fileLabel">File</span>
<ul role="menu">
<!-- Rule 2C: "New" label via Namefrom:contents -->
<li role="menuitem" aria-haspopup="false">New</li>
<li role="menuitem" aria-haspopup="false">Open…</li>
...
</ul>
</li>
...
</ul>
Note the role
attribute on the outer <ul>
element. This attribute does not affect in any way how the markup is rendered on the screen by the browser; however, browsers that support ARIA will add OS-specific accessibility information to the rendered UI element, so that the screen reader can interpret it as a menu and read it aloud with enough context for the end-user to understand (for example, an explicit "menu" audio hint) and is able to interact with it (for example, voice navigation).
Yes, you can configure the Spring servlet context xml file to define your beans (i.e., classes), so that it can do the automatic injection for you. However, do note, that you have to do other configurations to have Spring up and running and the best way to do that, is to follow a tutorial ground up.
Once you have your Spring configured probably, you can do the following in your Spring servlet context xml file for Example 1 above to work (please replace the package name of com.movies to what the true package name is and if this is a 3rd party class, then be sure that the appropriate jar file is on the classpath) :
<beans:bean id="movieFinder" class="com.movies.MovieFinder" />
or if the MovieFinder class has a constructor with a primitive value, then you could something like this,
<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
<beans:constructor-arg value="100" />
</beans:bean>
or if the MovieFinder class has a constructor expecting another class, then you could do something like this,
<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
<beans:constructor-arg ref="otherBeanRef" />
</beans:bean>
...where 'otherBeanRef' is another bean that has a reference to the expected class.
If you are storing values via any programming language
Here is an example in C#
To store date you have to convert it first and then store it
insert table1 (foodate)
values (FooDate.ToString("MM/dd/yyyy"));
FooDate is datetime variable which contains your date in your format.
As noted by CommonsWare in this question https://stackoverflow.com/a/16064418/1319061, this error can also occur if you are creating an anonymous subclass of a Fragment, since anonymous classes cannot have constructors.
Don't make anonymous subclasses of Fragment :-)
function checkTime(i) {_x000D_
if (i < 10) {_x000D_
i = "0" + i;_x000D_
}_x000D_
return i;_x000D_
}_x000D_
_x000D_
function startTime() {_x000D_
var today = new Date();_x000D_
var h = today.getHours();_x000D_
var m = today.getMinutes();_x000D_
var s = today.getSeconds();_x000D_
// add a zero in front of numbers<10_x000D_
m = checkTime(m);_x000D_
s = checkTime(s);_x000D_
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;_x000D_
t = setTimeout(function() {_x000D_
startTime()_x000D_
}, 500);_x000D_
}_x000D_
startTime();
_x000D_
<div id="time"></div>
_x000D_
DEMO using javaScript only
Update
(function () {
function checkTime(i) {
return (i < 10) ? "0" + i : i;
}
function startTime() {
var today = new Date(),
h = checkTime(today.getHours()),
m = checkTime(today.getMinutes()),
s = checkTime(today.getSeconds());
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
}
startTime();
})();
@Column(name = Columns.COLUMN_NAME, columnDefinition = "NVARCHAR(MAX)")
max
indicates that the maximum storage size is 2^31-1 bytes (2 GB)
<select name="aa" onchange="report(this.value)">
<option value="">Please select</option>
<option value="daily">daily</option>
<option value="monthly">monthly</option>
</select>
using
function report(period) {
if (period=="") return; // please select - possibly you want something else here
const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
loadXMLDoc(report,'responseTag');
document.getElementById('responseTag').style.visibility='visible';
document.getElementById('list_report').style.visibility='hidden';
document.getElementById('formTag').style.visibility='hidden';
}
Unobtrusive version:
<select id="aa" name="aa">
<option value="">Please select</option>
<option value="daily">daily</option>
<option value="monthly">monthly</option>
</select>
using
window.addEventListener("load",function() {
document.getElementById("aa").addEventListener("change",function() {
const period = this.value;
if (period=="") return; // please select - possibly you want something else here
const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
loadXMLDoc(report,'responseTag');
document.getElementById('responseTag').style.visibility='visible';
document.getElementById('list_report').style.visibility='hidden';
document.getElementById('formTag').style.visibility='hidden';
});
});
jQuery version - same select with ID
$(function() {
$("#aa").on("change",function() {
const period = this.value;
if (period=="") return; // please select - possibly you want something else here
var report = "script/"+((period == "daily")?"d":"m")+"_report.php";
loadXMLDoc(report,'responseTag');
$('#responseTag').show();
$('#list_report').hide();
$('#formTag').hide();
});
});
You can multiply the variable by 1 to force JavaScript to convert the variable to a number for you and then add it to your other value. This works because multiplication isn't overloaded as addition is. Some may say that this is less clear than parseInt, but it is a way to do it and it hasn't been mentioned yet.
If you're using angularJS or some variant of the Q promise library, then you have a .all()
method that solves this exact problem.
var savePromises = [];
angular.forEach(models, function(model){
savePromises.push(
model.saveToServer()
)
});
$q.all(savePromises).then(
function success(results){...},
function failed(results){...}
);
see the full API:
https://github.com/kriskowal/q/wiki/API-Reference#promiseall
The problem is already in the language:
the idea to differentiate the output based on limited placeholder like '[name]' defines limitations.
I like the core functionality of webpack, but the usage requires a rewrite with abstract definitions which are based on logic and simplicity... the hardest thing in software-development... logic and simplicity.
All this could be solved by just providing a list of input/output definitions... A LIST INPUT/OUTPUT DEFINITIONS.
Although this comment doesn't help much but we can learn from our mistakes by pointing at them.
Vinod Kumar: Good workaround, its:
module.exports = {
plugins: [
new FileManagerPlugin({
events: {
onEnd: {
copy: [
{source: 'www', destination: './vinod test 1/'},
{source: 'www', destination: './vinod testing 2/'},
{source: 'www', destination: './vinod testing 3/'},
],
},
}
}),
],
};
BTW. this is my first comment on stackoverflow (after 10 years as a programmer) and stackoverflow sucks in usability, like why is there so much text everywhere ? my eyes are bleeding.
From angular 6 you can run the command below to fix that issue
npm install --save-dev @angular-devkit/build-angular
OR
yarn add @angular-devkit/build-angular --dev
If your you still can not resolve issues, you can see other option from an unhandled exception occurred: cannot find module '@angular-devkit/build-angular/package.json'
Here's a code snippet showing how to insert a GUID using a parameterised query:
using(SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using(SqlTransaction trans = conn.BeginTransaction())
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.Transaction = trans;
cmd.CommandText = @"INSERT INTO [MYTABLE] ([GuidValue]) VALUE @guidValue;";
cmd.Parameters.AddWithValue("@guidValue", Guid.NewGuid());
cmd.ExecuteNonQuery();
trans.Commit();
}
}
If you're displaying a user-readable file name, you do not want to use lastPathComponent
. Instead, pass the full path to NSFileManager's displayNameAtPath:
method. This basically does does the same thing, only it correctly localizes the file name and removes the extension based on the user's preferences.
startService(new Intent(this, MyService.class));
Just writing this line was not sufficient for me. Service still did not work. Everything had worked only after registering service at manifest
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
...
<service
android:name=".MyService"
android:label="My Service" >
</service>
</application>
Try to capitalize 'app' like
const App = props => {...}
export default App;
In React, components need to be capitalized, and custom hooks need to start with use
.
I found that you can detect the command key in the latest version of Safari (7.0: 9537.71) if it is pressed in conjunction with another key. For example, if you want to detect ?+x:, you can detect the x key AND check if event.metaKey is set to true. For example:
var key = event.keyCode || event.charCode || 0;
console.log(key, event.metaKey);
When pressing x on it's own, this will output 120, false
. When pressing ?+x, it will output 120, true
This only seems to work in Safari - not Chrome
Just a note that as of Ruby 2.0 there is no need to add # encoding: utf-8
. UTF-8 is automatically detected.
git revert -m
allows to un-merge still keeping the history of both merge and un-do operation. Might be good for documenting probably.
You can use a lambda expression, e.g:
sales['time_hour'] = sales.timestamp.apply(lambda x: x.hour)
aspirinemaga, just replace:
$this->db->set('time', 'NOW()', FALSE);
$this->db->insert('mytable', $data);
for it:
$this->db->set('time', 'NOW() + INTERVAL 1 DAY', FALSE);
$this->db->insert('mytable', $data);
This might be just a requirement of PyMySql in Python, but I found that I had to name the exact table that I wanted the ID for:
In:
cnx = pymysql.connect(host='host',
database='db',
user='user',
password='pass')
cursor = cnx.cursor()
update_batch = """insert into batch set type = "%s" , records = %i, started = NOW(); """
second_query = (update_batch % ( "Batch 1", 22 ))
cursor.execute(second_query)
cnx.commit()
batch_id = cursor.execute('select last_insert_id() from batch')
cursor.close()
batch_id
Out:
5
... or whatever the correct Batch_ID value actually is
Try encodeURIComponent.
Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).
Example:
var encoded = encodeURIComponent(str);
Objective-C is not Java. In Objective-C exceptions are what they are called. Exceptions! Don’t use them for error handling. It’s not their proposal. Just check the length of the string before using characterAtIndex and everything is fine....
Use convert with style 101.
select convert(datetime, Remarks, 101)
If your column is really text
you need to convert to varchar before converting to datetime
select convert(datetime, convert(varchar(30), Remarks), 101)
Just use the event-handler. Something like this should work:
$('.js-my-element').bind('contextmenu', function(e) {
e.preventDefault();
alert('The eventhandler will make sure, that the contextmenu dosn't appear.');
});
As the other answers have mentioned, the int
operation will crash if the string input is not convertible to an int (such as a float or characters). What you can do is use a little helper method to try and interpret the string for you:
def interpret_string(s):
if not isinstance(s, basestring):
return str(s)
if s.isdigit():
return int(s)
try:
return float(s)
except ValueError:
return s
So it will take a string and try to convert it to int, then float, and otherwise return string. This is more just a general example of looking at the convertible types. It would be an error for your value to come back out of that function still being a string, which you would then want to report to the user and ask for new input.
Maybe a variation that returns None
if its neither float nor int:
def interpret_string(s):
if not isinstance(s, basestring):
return None
if s.isdigit():
return int(s)
try:
return float(s)
except ValueError:
return None
val=raw_input("> ")
how_much=interpret_string(val)
if how_much is None:
# ask for more input? Error?
Sorry for only commenting in the first place, but i'm posting almost every day a similar comment since many people think that it would be smart to encapsulate ADO.NET functionality into a DB-Class(me too 10 years ago). Mostly they decide to use static/shared objects since it seems to be faster than to create a new object for any action.
That is neither a good idea in terms of peformance nor in terms of fail-safety.
There's a good reason why ADO.NET internally manages the underlying Connections to the DBMS in the ADO-NET Connection-Pool:
In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.
Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.
So obviously there's no reason to avoid creating,opening or closing connections since actually they aren't created,opened and closed at all. This is "only" a flag for the connection pool to know when a connection can be reused or not. But it's a very important flag, because if a connection is "in use"(the connection pool assumes), a new physical connection must be openend to the DBMS what is very expensive.
So you're gaining no performance improvement but the opposite. If the maximum pool size specified (100 is the default) is reached, you would even get exceptions(too many open connections ...). So this will not only impact the performance tremendously but also be a source for nasty errors and (without using Transactions) a data-dumping-area.
If you're even using static connections you're creating a lock for every thread trying to access this object. ASP.NET is a multithreading environment by nature. So theres a great chance for these locks which causes performance issues at best. Actually sooner or later you'll get many different exceptions(like your ExecuteReader requires an open and available Connection).
Conclusion:
using-statement
to dispose and close(in case of Connections) implicitelyThat's true not only for Connections(although most noticable). Every object implementing IDisposable
should be disposed(simplest by using-statement
), all the more in the System.Data.SqlClient
namespace.
All the above speaks against a custom DB-Class which encapsulates and reuse all objects. That's the reason why i commented to trash it. That's only a problem source.
Edit: Here's a possible implementation of your retrievePromotion
-method:
public Promotion retrievePromotion(int promotionID)
{
Promotion promo = null;
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
var queryString = "SELECT PromotionID, PromotionTitle, PromotionURL FROM Promotion WHERE PromotionID=@PromotionID";
using (var da = new SqlDataAdapter(queryString, connection))
{
// you could also use a SqlDataReader instead
// note that a DataTable does not need to be disposed since it does not implement IDisposable
var tblPromotion = new DataTable();
// avoid SQL-Injection
da.SelectCommand.Parameters.Add("@PromotionID", SqlDbType.Int);
da.SelectCommand.Parameters["@PromotionID"].Value = promotionID;
try
{
connection.Open(); // not necessarily needed in this case because DataAdapter.Fill does it otherwise
da.Fill(tblPromotion);
if (tblPromotion.Rows.Count != 0)
{
var promoRow = tblPromotion.Rows[0];
promo = new Promotion()
{
promotionID = promotionID,
promotionTitle = promoRow.Field<String>("PromotionTitle"),
promotionUrl = promoRow.Field<String>("PromotionURL")
};
}
}
catch (Exception ex)
{
// log this exception or throw it up the StackTrace
// we do not need a finally-block to close the connection since it will be closed implicitely in an using-statement
throw;
}
}
}
return promo;
}
Another approach to this would put a span element with a display:block style inside the p element each time you need the content to break. It would only be useful when your p content is static.
<p>this is a not-dynamic text and I want to put<span style="display:block">the following words in the next line</span>and these other words in a third one</p>
It would output:
This is a not-dynamic text and I want to put
the following words in the next line
and these others in a third one
This allows you to change your text line-breaks in different viewports without JS.
I tried 600 level of permission for my private key and it worked for me. chmod 600 privateKey [dev]$ ssh -i privateKey user@ip worked
chmod 755 privateKey [dev]$ ssh -i privateKey user@ip it was giving below issue: Permissions 0755 for 'privateKey' are too open. It is required that your private key files are NOT accessible by others. This private key will be ignored. Load key "privateKey": bad permissions
If you want to be able to choose from different solutions, in addition to the given answers...
An alternative method is to give the container a width of 0 and to make sure overflow is visible. Then each word will overflow out of it and will be on its own line.
div {_x000D_
width: 0;_x000D_
overflow: visible;_x000D_
}
_x000D_
<div>Short Word</div>_x000D_
<hr>_x000D_
<div>Gargantuan Word</div>
_x000D_
Or you can use one of those newly proposed width
values, provided those still exist by the time you read this.
div {_x000D_
width: min-intrinsic; /* old Chrome, Safari */_x000D_
width: -webkit-min-content; /* less old Chrome, Safari */_x000D_
width: -moz-min-content; /* current Firefox */_x000D_
width: min-content; /* current Chrome, Safari; not IE or Edge */_x000D_
}
_x000D_
<div>Short Word</div>_x000D_
<hr>_x000D_
<div>Gargantuan Word</div>
_x000D_
Check if the manifest is a valid xml file. I had the same problem by doing a DOS copy command at the end of the build, and it turns out that for some reason I can not understand "copy" was adding a strange character (->) at the end of the manifest files. The problem was solved by adding "/b" switch to force binary copy.
You can use Contains()
for that. It will feel a little backwards when you're really trying to produce an IN
clause, but this should do it:
var userProfiles = _dataContext.UserProfile
.Where(t => idList.Contains(t.Id));
I'm also assuming that each UserProfile
record is going to have an int
Id
field. If that's not the case you'll have to adjust accordingly.
Try:
$('#myModal').on('show.bs.modal', function () {
$('.modal-content').css('height',$( window ).height()*0.8);
});
The @Transactional
annotation takes a timeout parameter where you can specify timeout in seconds for a specific method in the @RestController
@RequestMapping(value = "/method",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@Transactional(timeout = 120)
Another problem solved by the rubber duck:
The css is right but you still have to remember that the HTML elements order matters: the div has to come before the header. http://jsfiddle.net/Fq2Na/1/
Change your HTML code to have the div before the header:
<section>
<div><button>button</button></div>
<h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>
</section>
And keep your CSS to the simple div { float: right; }
.
Here's another version, and it's arguably a bit simpler.
multipetal <- function(df, n) {
varname <- paste("petal", n, sep=".")
df<-mutate_(df, .dots=setNames(paste0("Petal.Width*",n), varname))
df
}
for(i in 2:5) {
iris <- multipetal(df=iris, n=i)
}
> head(iris)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species petal.2 petal.3 petal.4 petal.5
1 5.1 3.5 1.4 0.2 setosa 0.4 0.6 0.8 1
2 4.9 3.0 1.4 0.2 setosa 0.4 0.6 0.8 1
3 4.7 3.2 1.3 0.2 setosa 0.4 0.6 0.8 1
4 4.6 3.1 1.5 0.2 setosa 0.4 0.6 0.8 1
5 5.0 3.6 1.4 0.2 setosa 0.4 0.6 0.8 1
6 5.4 3.9 1.7 0.4 setosa 0.8 1.2 1.6 2
Running any shell command inside $(...)
will help to store the output in a variable. So using that we can convert the files to array with IFS
.
IFS=' ' read -r -a array <<< $(ls /path/to/dir)
Use calendar.monthrange
:
>>> from calendar import monthrange
>>> monthrange(2011, 2)
(1, 28)
Just to be clear, monthrange
supports leap years as well:
>>> from calendar import monthrange
>>> monthrange(2012, 2)
(2, 29)
As @mikhail-pyrev mentions in a comment:
First number is weekday of first day of the month, second number is number of days in said month.
Here's a compact way to do something different in all four cases:
if(empty($youtube)) {
if(empty($link)) {
# both empty
} else {
# only $youtube not empty
}
} else {
if(empty($link)) {
# only $link empty
} else {
# both not empty
}
}
If you want to use an expression instead, you can use ?:
instead:
echo empty($youtube) ? ( empty($link) ? 'both empty' : 'only $youtube not empty' )
: ( empty($link) ? 'only $link empty' : 'both not empty' );
Change both Project and Package Properties ProtectionLevel to "DontSaveSensitive"
To complete the previous answers, one may need a collection of objects from his CSV File, either parsed by the TextFieldParser
or the string.Split
method, and then each line converted to an object via Reflection. You obviously first need to define a class that matches the lines of the CSV file.
I used the simple CSV Serializer from Michael Kropat found here: Generic class to CSV (all properties) and reused his methods to get the fields and properties of the wished class.
I deserialize my CSV file with the following method:
public static IEnumerable<T> ReadCsvFileTextFieldParser<T>(string fileFullPath, string delimiter = ";") where T : new()
{
if (!File.Exists(fileFullPath))
{
return null;
}
var list = new List<T>();
var csvFields = GetAllFieldOfClass<T>();
var fieldDict = new Dictionary<int, MemberInfo>();
using (TextFieldParser parser = new TextFieldParser(fileFullPath))
{
parser.SetDelimiters(delimiter);
bool headerParsed = false;
while (!parser.EndOfData)
{
//Processing row
string[] rowFields = parser.ReadFields();
if (!headerParsed)
{
for (int i = 0; i < rowFields.Length; i++)
{
// First row shall be the header!
var csvField = csvFields.Where(f => f.Name == rowFields[i]).FirstOrDefault();
if (csvField != null)
{
fieldDict.Add(i, csvField);
}
}
headerParsed = true;
}
else
{
T newObj = new T();
for (int i = 0; i < rowFields.Length; i++)
{
var csvFied = fieldDict[i];
var record = rowFields[i];
if (csvFied is FieldInfo)
{
((FieldInfo)csvFied).SetValue(newObj, record);
}
else if (csvFied is PropertyInfo)
{
var pi = (PropertyInfo)csvFied;
pi.SetValue(newObj, Convert.ChangeType(record, pi.PropertyType), null);
}
else
{
throw new Exception("Unhandled case.");
}
}
if (newObj != null)
{
list.Add(newObj);
}
}
}
}
return list;
}
public static IEnumerable<MemberInfo> GetAllFieldOfClass<T>()
{
return
from mi in typeof(T).GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
where new[] { MemberTypes.Field, MemberTypes.Property }.Contains(mi.MemberType)
let orderAttr = (ColumnOrderAttribute)Attribute.GetCustomAttribute(mi, typeof(ColumnOrderAttribute))
orderby orderAttr == null ? int.MaxValue : orderAttr.Order, mi.Name
select mi;
}
My team moved away from Bower and migrated to npm because:
For more details, see "Why my team uses npm instead of bower".
you can do this by setting the date of expiry to yesterday.
My new set of posts about cookies in JavaScript could help you.
http://www.markusnordhaus.de/2012/01/20/using-cookies-in-javascript-part-1/
If the error is thrown inside a closure that defines self
as unowned
, you may be limited in what you can access and will get this error code in certain situations. Especially while debugging. If this is the case for you try changing [unowned self]
to [weak self]
As of npm version 3.8.6, you can use
npm install --prefix ./install/here <package>
to install in the specified directory. NPM automatically creates node_modules
folder even when a node_modules
directory already exists in the higher up hierarchy.
You can also have a package.json
in the current directory and then install it in the specified directory using --prefix
option:
npm install --prefix ./install/here
As of npm 6.0.0, you can use
npm install --prefix ./install/here ./
to install the package.json in current directory to "./install/here" directory. There is one thing that I have noticed on Mac that it creates a symlink to parent folder inside the node_modules directory. But, it still works.
NOTE: NPM honours the path that you've specified through the --prefix
option. It resolves as per npm documentation on folders, only when npm install
is used without the --prefix
option.
NOTE: This answer talks about the Entity Framework's
DbContext
, but it is applicable to any sort of Unit of Work implementation, such as LINQ to SQL'sDataContext
, and NHibernate'sISession
.
Let start by echoing Ian: Having a single DbContext
for the whole application is a Bad Idea. The only situation where this makes sense is when you have a single-threaded application and a database that is solely used by that single application instance. The DbContext
is not thread-safe and and since the DbContext
caches data, it gets stale pretty soon. This will get you in all sorts of trouble when multiple users/applications work on that database simultaneously (which is very common of course). But I expect you already know that and just want to know why not to just inject a new instance (i.e. with a transient lifestyle) of the DbContext
into anyone who needs it. (for more information about why a single DbContext
-or even on context per thread- is bad, read this answer).
Let me start by saying that registering a DbContext
as transient could work, but typically you want to have a single instance of such a unit of work within a certain scope. In a web application, it can be practical to define such a scope on the boundaries of a web request; thus a Per Web Request lifestyle. This allows you to let a whole set of objects operate within the same context. In other words, they operate within the same business transaction.
If you have no goal of having a set of operations operate inside the same context, in that case the transient lifestyle is fine, but there are a few things to watch:
_context.SaveChanges()
(otherwise changes would get lost). This can complicate your code, and adds a second responsibility to the code (the responsibility of controlling the context), and is a violation of the Single Responsibility Principle.DbContext
] never leave the scope of such a class, because they can't be used in the context instance of another class. This can complicate your code enormously, because when you need those entities, you need to load them again by id, which could also cause performance problems.DbContext
implements IDisposable
, you probably still want to Dispose all created instances. If you want to do this, you basically have two options. You need to dispose them in the same method right after calling context.SaveChanges()
, but in that case the business logic takes ownership of an object it gets passed on from the outside. The second option is to Dispose all created instances on the boundary of the Http Request, but in that case you still need some sort of scoping to let the container know when those instances need to be Disposed.Another option is to not inject a DbContext
at all. Instead, you inject a DbContextFactory
that is able to create a new instance (I used to use this approach in the past). This way the business logic controls the context explicitly. If might look like this:
public void SomeOperation()
{
using (var context = this.contextFactory.CreateNew())
{
var entities = this.otherDependency.Operate(
context, "some value");
context.Entities.InsertOnSubmit(entities);
context.SaveChanges();
}
}
The plus side of this is that you manage the life of the DbContext
explicitly and it is easy to set this up. It also allows you to use a single context in a certain scope, which has clear advantages, such as running code in a single business transaction, and being able to pass around entities, since they originate from the same DbContext
.
The downside is that you will have to pass around the DbContext
from method to method (which is termed Method Injection). Note that in a sense this solution is the same as the 'scoped' approach, but now the scope is controlled in the application code itself (and is possibly repeated many times). It is the application that is responsible for creating and disposing the unit of work. Since the DbContext
is created after the dependency graph is constructed, Constructor Injection is out of the picture and you need to defer to Method Injection when you need to pass on the context from one class to the other.
Method Injection isn't that bad, but when the business logic gets more complex, and more classes get involved, you will have to pass it from method to method and class to class, which can complicate the code a lot (I've seen this in the past). For a simple application, this approach will do just fine though.
Because of the downsides, this factory approach has for bigger systems, another approach can be useful and that is the one where you let the container or the infrastructure code / Composition Root manage the unit of work. This is the style that your question is about.
By letting the container and/or the infrastructure handle this, your application code is not polluted by having to create, (optionally) commit and Dispose a UoW instance, which keeps the business logic simple and clean (just a Single Responsibility). There are some difficulties with this approach. For instance, were do you Commit and Dispose the instance?
Disposing a unit of work can be done at the end of the web request. Many people however, incorrectly assume that this is also the place to Commit the unit of work. However, at that point in the application, you simply can't determine for sure that the unit of work should actually be committed. e.g. If the business layer code threw an exception that was caught higher up the callstack, you definitely don't want to Commit.
The real solution is again to explicitly manage some sort of scope, but this time do it inside the Composition Root. Abstracting all business logic behind the command / handler pattern, you will be able to write a decorator that can be wrapped around each command handler that allows to do this. Example:
class TransactionalCommandHandlerDecorator<TCommand>
: ICommandHandler<TCommand>
{
readonly DbContext context;
readonly ICommandHandler<TCommand> decorated;
public TransactionCommandHandlerDecorator(
DbContext context,
ICommandHandler<TCommand> decorated)
{
this.context = context;
this.decorated = decorated;
}
public void Handle(TCommand command)
{
this.decorated.Handle(command);
context.SaveChanges();
}
}
This ensures that you only need to write this infrastructure code once. Any solid DI container allows you to configure such a decorator to be wrapped around all ICommandHandler<T>
implementations in a consistent manner.
No jQuery Needed
if (str.match(/[a-z]/i)) {
// alphabet letters found
}
I also came across the same error. Here is the fix: If you are using Cmake-GUI:
If you missed the 3rd step:
*** No rule to make target `install'. Stop.
error will occur.
This works without needing jQuery:
var textArea = document.getElementById("my-text-area");
var arrayOfLines = textArea.value.split("\n"); // arrayOfLines is array where every element is string of one line
I built on a previous answer and have this, some extra padding just to be able to conveniently join all the output:
SELECT
CONCAT('SELECT ''',A.TABLE_NAME, '-' ,A.COLUMN_NAME,''' FROM ', A.TABLE_SCHEMA, '.', A.TABLE_NAME,
' WHERE ', A.COLUMN_NAME, ' LIKE \'%Value%\' UNION')
FROM INFORMATION_SCHEMA.COLUMNS A
WHERE
A.TABLE_SCHEMA != 'mysql'
AND A.TABLE_SCHEMA != 'innodb'
AND A.TABLE_SCHEMA != 'performance_schema'
AND A.TABLE_SCHEMA != 'information_schema'
UNION SELECT 'SELECT '''
-- for exact match use: A.COLUMN_NAME, ' LIKE \'Value\' instead
First you run this, then paste in and run the result (no editing) and it will display all the table names and columns where the value is used.
I elaborated on dream83619 answer to make it handle nested Hibernate @Fetch
annotations. I used recursive method to find annotations in nested associated classes.
So you have to implement custom repository and override getQuery(spec, domainClass, sort)
method.
Unfortunately you also have to copy all referenced private methods :(.
Here is the code, copied private methods are omitted.
EDIT: Added remaining private methods.
@NoRepositoryBean
public class EntityGraphRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> {
private final EntityManager em;
protected JpaEntityInformation<T, ?> entityInformation;
public EntityGraphRepositoryImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
this.em = entityManager;
this.entityInformation = entityInformation;
}
@Override
protected <S extends T> TypedQuery<S> getQuery(Specification<S> spec, Class<S> domainClass, Sort sort) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<S> query = builder.createQuery(domainClass);
Root<S> root = applySpecificationToCriteria(spec, domainClass, query);
query.select(root);
applyFetchMode(root);
if (sort != null) {
query.orderBy(toOrders(sort, root, builder));
}
return applyRepositoryMethodMetadata(em.createQuery(query));
}
private Map<String, Join<?, ?>> joinCache;
private void applyFetchMode(Root<? extends T> root) {
joinCache = new HashMap<>();
applyFetchMode(root, getDomainClass(), "");
}
private void applyFetchMode(FetchParent<?, ?> root, Class<?> clazz, String path) {
for (Field field : clazz.getDeclaredFields()) {
Fetch fetch = field.getAnnotation(Fetch.class);
if (fetch != null && fetch.value() == FetchMode.JOIN) {
FetchParent<?, ?> descent = root.fetch(field.getName(), JoinType.LEFT);
String fieldPath = path + "." + field.getName();
joinCache.put(path, (Join) descent);
applyFetchMode(descent, field.getType(), fieldPath);
}
}
}
/**
* Applies the given {@link Specification} to the given {@link CriteriaQuery}.
*
* @param spec can be {@literal null}.
* @param domainClass must not be {@literal null}.
* @param query must not be {@literal null}.
* @return
*/
private <S, U extends T> Root<U> applySpecificationToCriteria(Specification<U> spec, Class<U> domainClass,
CriteriaQuery<S> query) {
Assert.notNull(query);
Assert.notNull(domainClass);
Root<U> root = query.from(domainClass);
if (spec == null) {
return root;
}
CriteriaBuilder builder = em.getCriteriaBuilder();
Predicate predicate = spec.toPredicate(root, query, builder);
if (predicate != null) {
query.where(predicate);
}
return root;
}
private <S> TypedQuery<S> applyRepositoryMethodMetadata(TypedQuery<S> query) {
if (getRepositoryMethodMetadata() == null) {
return query;
}
LockModeType type = getRepositoryMethodMetadata().getLockModeType();
TypedQuery<S> toReturn = type == null ? query : query.setLockMode(type);
applyQueryHints(toReturn);
return toReturn;
}
private void applyQueryHints(Query query) {
for (Map.Entry<String, Object> hint : getQueryHints().entrySet()) {
query.setHint(hint.getKey(), hint.getValue());
}
}
public Class<T> getEntityType() {
return entityInformation.getJavaType();
}
public EntityManager getEm() {
return em;
}
}
There are 4 ways to do it as far as I know.
Number(x);
parseInt(x, 10);
parseFloat(x);
+x;
By this quick test I made, it actually depends on browsers.
http://jsperf.com/best-of-string-to-number-conversion/2
Implicit
marked the fastest on 3 browsers, but it makes the code hard to read… So choose whatever you feel like it!
If you can create a numbers table, that contains numbers from 1 to the maximum fields to split, you could use a solution like this:
select
tablename.id,
SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) name
from
numbers inner join tablename
on CHAR_LENGTH(tablename.name)
-CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1
order by
id, n
Please see fiddle here.
If you cannot create a table, then a solution can be this:
select
tablename.id,
SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) name
from
(select 1 n union all
select 2 union all select 3 union all
select 4 union all select 5) numbers INNER JOIN tablename
on CHAR_LENGTH(tablename.name)
-CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1
order by
id, n
an example fiddle is here.
JSON is similar to other data formats like XML - if you need to transmit more data, you just send more data. There's no inherent size limitation to the JSON request. Any limitation would be set by the server parsing the request. (For instance, ASP.NET has the "MaxJsonLength" property of the serializer.)
I like the "querystring" syntax for argument passing, especially when there are a lot of arguments to be passed.
Example:
rake "mytask[width=10&height=20]"
The "querystring" being:
width=10&height=20
Warning: note that the syntax is rake "mytask[foo=bar]"
and NOT rake mytask["foo=bar"]
When parsed inside the rake task using Rack::Utils.parse_nested_query
, we get a Hash
:
=> {"width"=>"10", "height"=>"20"}
(The cool thing is that you can pass hashes and arrays, more below)
This is how to achieve this:
require 'rack/utils'
task :mytask, :args_expr do |t,args|
args.with_defaults(:args_expr => "width=10&height=10")
options = Rack::Utils.parse_nested_query(args[:args_expr])
end
Here's a more extended example that I'm using with Rails in my delayed_job_active_record_threaded gem:
bundle exec rake "dj:start[ebooks[workers_number]=16&ebooks[worker_timeout]=60&albums[workers_number]=32&albums[worker_timeout]=120]"
Parsed the same way as above, with an environment dependency (in order load the Rails environment)
namespace :dj do
task :start, [ :args_expr ] => :environment do |t, args|
# defaults here...
options = Rack::Utils.parse_nested_query(args[:args_expr])
end
end
Gives the following in options
=> {"ebooks"=>{"workers_number"=>"16", "worker_timeout"=>"60"}, "albums"=>{"workers_number"=>"32", "worker_timeout"=>"120"}}
I am on Windows 8.1, and I tried everything from the other answers and nothing worked. Finally, I decided to try "Pick from a list of drivers" and found "LGE Mobile Sooner Single ADB Interface" under "ADB Interface". ADB.exe was finally able to find the Nexus 5 and sideload 4.4.1.
I hope this helps.
SnowsPenultimateNormalityTest
certainly has its virtues, but you may also want to look at qqnorm
.
X <- rlnorm(100)
qqnorm(X)
qqnorm(rnorm(100))
Using toPrecision method:
var a = 1.2345
a.toPrecision(2)
// result "1.2"
You can do this either with multiple System.Net.Mail.MailAddress
objects or you can provide a single string containing all of the addresses separated by commas
Have you googled about it - insert update delete access vb.net, there are lots of reference about this.
Insert Update Delete Navigation & Searching In Access Database Using VB.NET
what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB
is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.
it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:
Example code snippet:
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class DBUtil
Private connectionString As String
Public Sub New()
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
Dim dbSource = "Data Source=d:\DB\Database11.accdb"
connectionString = dbProvider & dbSource
End Sub
Public Function GetCategories() As DataSet
Dim query As String = "SELECT * FROM Categories"
Dim cmd As New OleDbCommand(query)
Return FillDataSet(cmd, "Categories")
End Function
Public SubUpdateCategories(ByVal name As String)
Dim query As String = "update Categories set name = 'new2' where name = ?"
Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
Return FillDataSet(cmd, "Categories")
End Sub
Public Function GetItems() As DataSet
Dim query As String = "SELECT * FROM Items"
Dim cmd As New OleDbCommand(query)
Return FillDataSet(cmd, "Items")
End Function
Public Function GetItems(ByVal categoryID As Integer) As DataSet
'Create the command.
Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("category_ID", categoryID)
'Fill the dataset.
Return FillDataSet(cmd, "Items")
End Function
Public Sub AddCategory(ByVal name As String)
Dim con As New OleDbConnection(connectionString)
'Create the command.
Dim insertSQL As String = "INSERT INTO Categories "
insertSQL &= "VALUES(?)"
Dim cmd As New OleDbCommand(insertSQL, con)
cmd.Parameters.AddWithValue("Name", name)
Try
con.Open()
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
End Sub
Public Sub AddItem(ByVal title As String, ByVal description As String, _
ByVal price As Decimal, ByVal categoryID As Integer)
Dim con As New OleDbConnection(connectionString)
'Create the command.
Dim insertSQL As String = "INSERT INTO Items "
insertSQL &= "(Title, Description, Price, Category_ID)"
insertSQL &= "VALUES (?, ?, ?, ?)"
Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
cmd.Parameters.AddWithValue("Title", title)
cmd.Parameters.AddWithValue("Description", description)
cmd.Parameters.AddWithValue("Price", price)
cmd.Parameters.AddWithValue("CategoryID", categoryID)
Try
con.Open()
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
End Sub
Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
Dim dbSource = "Data Source=D:\DB\Database11.accdb"
connectionString = dbProvider & dbSource
con.ConnectionString = connectionString
cmd.Connection = con
Dim adapter As New OleDbDataAdapter(cmd)
Dim ds As New DataSet()
Try
con.Open()
adapter.Fill(ds, tableName)
Finally
con.Close()
End Try
Return ds
End Function
End Class
Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back
You only need 1 dependency:
dependencies {
implementation ("jakarta.xml.bind:jakarta.xml.bind-api:2.3.2")
The function returns before i
is incremented because you are using a post-fix operator (++). At any rate, the increment of i
is not global - only to respective function. If you had used a pre-fix operator, it would be 11
and then decremented to 10
.
So you then return i
as 10 and decrement it in the printf function, which shows 9
not 10
as you think.
In my case eclipse.ini entry for --launcher.library was :
--launcher.library C:\Users\UserName\.p2\pool\plugins\org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.551.v20171108-1834
and on my machine 'C:\Users\UserName\.p2\' folder was missing hence installed the eclipse again which created the .p2 folder structure at required location and now I am able to login successfully.
Your arguments are in the wrong order. Try git commit -m 'my notes' path/to/my/file.ext
, or if you want to be more explicit, git commit -m 'my notes' -- path/to/my/file.ext
.
Incidentally, git v1.5.2.1 is 4.5 years old. You may want to update to a newer version (1.7.8.3 is the current release).
In java 8, it's convenient to use the new date lib and getEpochSecond
method to get the timestamp (it's in second)
Instant.now().getEpochSecond();
C++ has no built-in concepts of interfaces. You can implement it using abstract classes which contains only pure virtual functions. Since it allows multiple inheritance, you can inherit this class to create another class which will then contain this interface (I mean, object interface :) ) in it.
An example would be something like this -
class Interface
{
public:
Interface(){}
virtual ~Interface(){}
virtual void method1() = 0; // "= 0" part makes this method pure virtual, and
// also makes this class abstract.
virtual void method2() = 0;
};
class Concrete : public Interface
{
private:
int myMember;
public:
Concrete(){}
~Concrete(){}
void method1();
void method2();
};
// Provide implementation for the first method
void Concrete::method1()
{
// Your implementation
}
// Provide implementation for the second method
void Concrete::method2()
{
// Your implementation
}
int main(void)
{
Interface *f = new Concrete();
f->method1();
f->method2();
delete f;
return 0;
}
Use LINQ and add the condition on the "selected" as a question mark condition.
var listSiteId = (from site in db.GetSiteId().ToList()
select new SelectListItem
{
Value = site.SITEID,
Text = site.NAME,
Selected = (dimension.DISPLAYVALUE == site.SITEID) ? true : false,
}).ToList();
ViewBag.SiteId = listSiteId;
Using an apostrophe ’
(Unicode: \u2019
) instead of a single quote '
fixed the issue without doubling the \'
.
These is a little thing to point out.
Using the function pg_get_viewdef or pg_views or information_schema.views you will always get a rewrited version of your original DDL.
The rewited version may or not be the same as your originl DDL script.
If the Rule Manager rewrite your view definition your original DLL will be lost and you will able to read the only the rewrited version of your view definition.
Not all views are rewrited but if you use sub-select or joins probably your views will be rewrited.
If you want a generic error you can setup all $.ajax()
(which $.get()
uses underneath) requests jQuery makes to display an error using $.ajaxSetup()
, for example:
$.ajaxSetup({
error: function(xhr, status, error) {
alert("An AJAX error occured: " + status + "\nError: " + error);
}
});
Just run this once before making any AJAX calls (no changes to your current code, just stick this before somewhere). This sets the error
option to default to the handler/function above, if you made a full $.ajax()
call and specified the error
handler then what you had would override the above.
What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent
in an Activity
and then pass any extra data to fragments by instantiating them with arguments.
There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity
and Fragment
from the support library.
You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:
public static class DetailsActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// (omitted some other stuff)
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(
android.R.id.content, details).commit();
}
}
}
In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance
in the examples given by Google. There actually is a newInstance
method in DetailsFragment
, so I'm unsure why it isn't used in the snippet above...
Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments()
. Since this returns a Bundle
, its usage is similar to that of the extras in an Activity
.
public static class DetailsFragment extends Fragment {
/**
* Create a new instance of DetailsFragment, initialized to
* show the text at 'index'.
*/
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
// (other stuff omitted)
}
This page is a neat summary, but is not entirely accurate:
Git has two types of branches: local
and remote
. To use git pull
and git push
as you'd like, you have to tell your local branch (my_test
) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.
Commands
Make sure you're on your master
branch with
1)git checkout master
then create the new branch with
2)git branch --track my_test origin/my_test
and check it out with
3)git checkout my_test
.
You can then push
and pull
without specifying which local and remote.
However if you've already created the branch then you can use the -u
switch to tell git's push
and pull
you'd like to use the specified local and remote branches from now on, like so:
git pull -u my_test origin/my_test
git push -u my_test origin/my_test
Config
The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config
and add the following to the bottom.
[remote "origin"]
url = [email protected]:username/repo.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
remote = origin
merge = refs/heads/my_test
This specifies a remote called origin
, in this case a GitHub style one, and then tells the branch my_test
to use it as it's remote.
You can find something very similar to this in the config after running the commands above.
Some useful resources:
Use Process Explorer from the Sysinternals Suite, the Find Handle or DLL function will let you search for the process with that file open.
Here:
window.onload = function start() {
slide();
}
function slide() {
var num = 0;
for (num=0;num==10;) {
setTimeout("document.getElementById('container').style.marginLeft='-600px'",3000);
setTimeout("document.getElementById('container').style.marginLeft='-1200px'",6000);
setTimeout("document.getElementById('container').style.marginLeft='-1800px'",9000);
setTimeout("document.getElementById('container').style.marginLeft='0px'",12000);
}
}
That makes it keep looping alright! That's why it isn't runnable here.
Download the Windows SDK and then go to View->Properties->Configuration Manager->Active Solution Platform->New->x64.