You can use either SEQUENCE
or TRIGGER
to increment automatically the value of a given column in your database table however the use of TRIGGERS
would be more appropriate. See the following documentation of Oracle that contains major clauses used with triggers with suitable examples.
Use the CREATE TRIGGER statement to create and enable a database trigger, which is:
A stored PL/SQL block associated with a table, a schema, or the database or
An anonymous PL/SQL block or a call to a procedure implemented in PL/SQL or Java
Oracle Database automatically executes a trigger when specified conditions occur. See.
Following is a simple TRIGGER
just as an example for you that inserts the primary key value in a specified table based on the maximum value of that column. You can modify the schema name, table name etc and use it. Just give it a try.
/*Create a database trigger that generates automatically primary key values on the CITY table using the max function.*/
CREATE OR REPLACE TRIGGER PROJECT.PK_MAX_TRIGGER_CITY
BEFORE INSERT ON PROJECT.CITY
FOR EACH ROW
DECLARE
CNT NUMBER;
PKV CITY.CITY_ID%TYPE;
NO NUMBER;
BEGIN
SELECT COUNT(*)INTO CNT FROM CITY;
IF CNT=0 THEN
PKV:='CT0001';
ELSE
SELECT 'CT'||LPAD(MAX(TO_NUMBER(SUBSTR(CITY_ID,3,LENGTH(CITY_ID)))+1),4,'0') INTO PKV
FROM CITY;
END IF;
:NEW.CITY_ID:=PKV;
END;
Would automatically generates values such as CT0001
, CT0002
, CT0002
and so on and inserts into the given column of the specified table.
Try:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<SeekBar
android:id="@+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:rotation="270"
/>
</RelativeLayout>
With literal syntax you can check as follows
static const NSString* kKeyToCheck = @"yourKey"
if (xyz[kKeyToCheck])
NSLog(@"Key: %@, has Value: %@", kKeyToCheck, xyz[kKeyToCheck]);
else
NSLog(@"Key pair do not exits for key: %@", kKeyToCheck);
As mysql official documentation:
Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).
Online Documentation:
You can actually write to a named pipe using its name, btw.
Open a command shell as Administrator to get around the default "Access is denied" error:
echo Hello > \\.\pipe\PipeName
Try this. Feed your variable in the function and save the o/p in the variable which would contain removed outliers
outliers<-function(variable){
iqr<-IQR(variable)
q1<-as.numeric(quantile(variable,0.25))
q3<-as.numeric(quantile(variable,0.75))
mild_low<-q1-(1.5*iqr)
mild_high<-q3+(1.5*iqr)
new_variable<-variable[variable>mild_low & variable<mild_high]
return(new_variable)
}
Another example using PowerShell for set permissions (File / Directory) :
Get-Acl "C:\file.txt" | fl *
$acl = Get-Acl "C:\file.txt"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("everyone","FullControl","Allow")
$acl.SetAccessRule($accessRule)
$acl | Set-Acl "C:\file.txt"
Hope this helps
Actually, RESULT contains what you want — to demonstrate:
echo "$RESULT"
What you show is what you get from:
echo $RESULT
As noted in the comments, the difference is that (1) the double-quoted version of the variable (echo "$RESULT"
) preserves internal spacing of the value exactly as it is represented in the variable — newlines, tabs, multiple blanks and all — whereas (2) the unquoted version (echo $RESULT
) replaces each sequence of one or more blanks, tabs and newlines with a single space. Thus (1) preserves the shape of the input variable, whereas (2) creates a potentially very long single line of output with 'words' separated by single spaces (where a 'word' is a sequence of non-whitespace characters; there needn't be any alphanumerics in any of the words).
into Chrome, right click -> Inspect Element. Go to the tab active tracking of resources and if you have not already. Now the left hand sidebar thingy down until you see "Cookies", click below your domain name and to remove a cookie just right-click on it and "Delete"
You can read existing sheets of your interests, for example, 'x1', 'x2', into memory and 'write' them back prior to adding more new sheets (keep in mind that sheets in a file and sheets in memory are two different things, if you don't read them, they will be lost). This approach uses 'xlsxwriter' only, no openpyxl involved.
import pandas as pd
import numpy as np
path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"
# begin <== read selected sheets and write them back
df1 = pd.read_excel(path, sheet_name='x1', index_col=0) # or sheet_name=0
df2 = pd.read_excel(path, sheet_name='x2', index_col=0) # or sheet_name=1
writer = pd.ExcelWriter(path, engine='xlsxwriter')
df1.to_excel(writer, sheet_name='x1')
df2.to_excel(writer, sheet_name='x2')
# end ==>
# now create more new sheets
x3 = np.random.randn(100, 2)
df3 = pd.DataFrame(x3)
x4 = np.random.randn(100, 2)
df4 = pd.DataFrame(x4)
df3.to_excel(writer, sheet_name='x3')
df4.to_excel(writer, sheet_name='x4')
writer.save()
writer.close()
If you want to preserve all existing sheets, you can replace above code between begin and end with:
# read all existing sheets and write them back
writer = pd.ExcelWriter(path, engine='xlsxwriter')
xlsx = pd.ExcelFile(path)
for sheet in xlsx.sheet_names:
df = xlsx.parse(sheet_name=sheet, index_col=0)
df.to_excel(writer, sheet_name=sheet)
Or perhaps you could use this class:
http://developer.android.com/reference/java/net/URLEncoder.html
Which is present in Android since API level 1.
Annoyingly however, it treats spaces specially (replacing them with + instead of %20). To get round this we simply use this fragment:
URLEncoder.encode(value, "UTF-8").replace("+", "%20");
Here's another way to do it by placing the glyphicon using the :before
pseudo element in CSS.
For this HTML:
<form class="form form-horizontal col-xs-12">
<div class="form-group">
<div class="col-xs-7">
<span class="usericon">
<input class="form-control" id="name" placeholder="Username" />
</span>
</div>
</div>
</form>
Use this CSS (Bootstrap 3.x and Webkit-based browsers compatible)
.usericon input {
padding-left:25px;
}
.usericon:before {
height: 100%;
width: 25px;
display: -webkit-box;
-webkit-box-pack: center;
-webkit-box-align: center;
position: absolute;
content: "\e008";
font-family: 'Glyphicons Halflings';
pointer-events: none;
}
As @Frizi said, we have to add pointer-events: none;
so that the cursor doesn't interfere with the input focus. All the others CSS rules are for centering and adding the proper spacing.
The result:
As mentioned before, the easiest way it to use rotation
available since API 11:
android:rotation="90" // in XML layout
view.rotation = 90f // programatically
You can also change pivot of rotation, which is by default set to center of the view. This needs to be changed programatically:
// top left
view.pivotX = 0f
view.pivotY = 0f
// bottom right
view.pivotX = width.toFloat()
view.pivotY = height.toFloat()
...
In Activity's onCreate()
or Fragment's onCreateView(...)
width and height are equal to 0, because the view wasn't measured yet. You can access it simply by using doOnPreDraw
extension from Android KTX, i.e.:
view.apply {
doOnPreDraw {
pivotX = width.toFloat()
pivotY = height.toFloat()
}
}
HTTPS proxy doesn't make sense because you can't terminate your HTTP connection at the proxy for security reasons. With your trust policy, it might work if the proxy server has a HTTPS port. Your error is caused by connecting to HTTP proxy port with HTTPS.
You can connect through a proxy using SSL tunneling (many people call that proxy) using proxy CONNECT command. However, Java doesn't support newer version of proxy tunneling. In that case, you need to handle the tunneling yourself. You can find sample code here,
http://www.javaworld.com/javaworld/javatips/jw-javatip111.html
EDIT: If you want defeat all the security measures in JSSE, you still need your own TrustManager. Something like this,
public SSLTunnelSocketFactory(String proxyhost, String proxyport){
tunnelHost = proxyhost;
tunnelPort = Integer.parseInt(proxyport);
dfactory = (SSLSocketFactory)sslContext.getSocketFactory();
}
...
connection.setSSLSocketFactory( new SSLTunnelSocketFactory( proxyHost, proxyPort ) );
connection.setDefaultHostnameVerifier( new HostnameVerifier()
{
public boolean verify( String arg0, SSLSession arg1 )
{
return true;
}
} );
EDIT 2: I just tried my program I wrote a few years ago using SSLTunnelSocketFactory and it doesn't work either. Apparently, Sun introduced a new bug sometime in Java 5. See this bug report,
http://bugs.sun.com/view_bug.do?bug_id=6614957
The good news is that the SSL tunneling bug is fixed so you can just use the default factory. I just tried with a proxy and everything works as expected. See my code,
public class SSLContextTest {
public static void main(String[] args) {
System.setProperty("https.proxyHost", "proxy.xxx.com");
System.setProperty("https.proxyPort", "8888");
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
// set up a TrustManager that trusts everything
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
System.out.println("getAcceptedIssuers =============");
return null;
}
public void checkClientTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkClientTrusted =============");
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkServerTrusted =============");
}
} }, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(
sslContext.getSocketFactory());
HttpsURLConnection
.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
System.out.println("hostnameVerifier =============");
return true;
}
});
URL url = new URL("https://www.verisign.net");
URLConnection conn = url.openConnection();
BufferedReader reader =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is what I get when I run the program,
checkServerTrusted =============
hostnameVerifier =============
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
......
As you can see, both SSLContext and hostnameVerifier are getting called. HostnameVerifier is only involved when the hostname doesn't match the cert. I used "www.verisign.net" to trigger this.
you can throw
as object
throw ({message: 'This Failed'})
then for example in your try/catch
try {
//
} catch(e) {
console.log(e); //{message: 'This Failed'}
console.log(e.message); //This Failed
}
or just throw a string error
throw ('Your error')
try {
//
} catch(e) {
console.log(e); //Your error
}
throw new Error //only accept a string
The following should suffice:
[^ ]
If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):
[^\s]
or
\S # Note this is a CAPITAL 'S'!
You can also use a callable in the default field, such as:
b = models.CharField(max_length=7, default=foo)
And then define the callable:
def foo():
return 'bar'
In my app I had a mainmenu form that had buttons to navigate to an assortment of other forms (aka sub-forms). I wanted only one instance of each sub-form to be running at a time. Plus I wanted to ensure if a user attempted to launch a sub-form already in existence, that the sub-form would be forced to show "front¢er" if minimized or behind other app windows. Using the currently most upvoted answers, I refactored their answers into this:
private void btnOpenSubForm_Click(object sender, EventArgs e)
{
Form fsf = Application.OpenForms["formSubForm"];
if (fsf != null)
{
fsf.WindowState = FormWindowState.Normal;
fsf.Show();
fsf.TopMost = true;
}
else
{
Form formSubForm = new FormSubForm();
formSubForm.Show();
formSubForm.TopMost = true;
}
}
you have to bind new event with this keyword as i mention below...
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count : 1
};
this.delta = this.delta.bind(this);
}
delta() {
this.setState({
count : this.state.count++
});
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.delta}>+</button>
</div>
);
}
}
Way later but still worth mentioning is that you can also use variables to output values in the SET clause of an UPDATE or in the fields of a SELECT;
DECLARE @val1 int;
DECLARE @val2 int;
UPDATE [dbo].[PortalCounters_TEST]
SET @val1 = NextNum, @val2 = NextNum = NextNum + 1
WHERE [Condition] = 'unique value'
SELECT @val1, @val2
In the example above @val1 has the before value and @val2 has the after value although I suspect any changes from a trigger would not be in val2 so you'd have to go with the output table in that case. For anything but the simplest case, I think the output table will be more readable in your code as well.
One place this is very helpful is if you want to turn a column into a comma-separated list;
DECLARE @list varchar(max) = '';
DECLARE @comma varchar(2) = '';
SELECT @list = @list + @comma + County, @comma = ', ' FROM County
print @list
I am not quite sure if it works with ROW FORMAT serde 'com.bizo.hive.serde.csv.CSVSerde' but I guess that it should be similar to ROW FORMAT DELIMITED FIELDS TERMINATED BY ','.
In your case first row will be treated like normal row. But first field fails to be INT so all fields, for first row, will be set as NULL. You need only one intermediate step to fix it:
INSERT OVERWRITE TABLE Test
SELECT * from Test WHERE RecordId IS NOT NULL
Only one drawback is that your original csv file will be modified. I hope it helps. GL!
As there are different paths for different versions. Here is a generic solution:
Find the path...
adb shell
in command line.ls
and Enter. Now you'll see the files and directories of Android device. Now with combination of ls
and cd dirName
find the path to the Internal or External storage.
In the root directory, the directories names will be like mnt, sdcard, emulator0,
etc
Example: adb push file.txt mnt/sdcard/myDir/Projects/
It's an old question. A lot of good things happened since then. Here are my two cents on this topic:
To accurately track the visited pages you have to normalize URI first. The normalization algorithm includes multiple steps:
GET http://www.example.com/query?id=111&cat=222
GET http://www.example.com/query?cat=222&id=111
Convert the empty path.
Example: http://example.org ? http://example.org/
Capitalize percent encoding. All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive.
Example: http://example.org/a%c2%B1b ? http://example.org/a%C2%B1b
Remove unnecessary dot-segments.
Example: http://example.org/../a/b/../c/./d.html ? http://example.org/a/c/d.html
Possibly some other normalization rules
Not only <a>
tag has href
attribute, <area>
tag has it too https://html.com/tags/area/. If you don't want to miss anything, you have to scrape <area>
tag too.
Track crawling progress. If the website is small, it is not a problem. Contrarily it might be very frustrating if you crawl half of the site and it failed. Consider using a database or a filesystem to store the progress.
Be kind to the site owners. If you are ever going to use your crawler outside of your website, you have to use delays. Without delays, the script is too fast and might significantly slow down some small sites. From sysadmins perspective, it looks like a DoS attack. A static delay between the requests will do the trick.
If you don't want to deal with that, try Crawlzone and let me know your feedback. Also, check out the article I wrote a while back https://www.codementor.io/zstate/this-is-how-i-crawl-n98s6myxm
The command
xcode-select --install
proposes 3 options: Get Xcode; Not Now; Install.
When I choose to get full Xcode the command finished successfully. It took a while, but this way I was able to complete all macports migration instructions.
I faced the same issue and it's fixed now:) Just follow the below steps and the error could be for anything, but the below steps makes the process smoother. I spend lot of time to find the fix.
1.Try restart the Eclipse (if you are using Eclipse to built JAR file) --> Actually this helped my issue in exporting the JAR file properly.
2.After eclipse restart, try to see if your eclipse is able to recognize the main class/method by your Java project --> right click --> Run as --> Run configurations --> Main --> click Search button to see if your eclipse is able to lookup for your main class in the JAR file. --> This is for the validation that JAR file will have the entry point to the main class.
After this, export your Java Dynamic project as "Runnable JAR" file and not JAR file.
In Java launch configuration, choose your main class.
Once export the jar file, use the below command to execute. java -cp [Your JAR].jar [complete package].MainClass eg: java -cp AppleTCRuleAudit.jar com.apple.tcruleaudit.classes.TCRuleAudit
You might face the unsupported java version error. the fix is to change the java_home in your shell bash profile to match the java version used to compile the project in eclipse.
Hope this helps! Kindly let me know if you still have any issues.
You can use the below change event to which will trigger when the combobox value will change.
Private Sub ComboBox1_Change()
'your code here
End Sub
Also you can get the selected value using below
ComboBox1.Value
If I were you, I would set the scale of the BigDecimal so that I dont end up on lengthy numbers. The integer 2 in the BigDecimal initialization below sets the scale.
Since you have lots of mismatch of data type, I have changed it accordingly to adjust.
class Payment
{
BigDecimal itemCost=new BigDecimal(BigInteger.ZERO, 2);
BigDecimal totalCost=new BigDecimal(BigInteger.ZERO, 2);
public BigDecimal calculateCost(int itemQuantity,BigDecimal itemPrice)
{
BigDecimal itemCost = itemPrice.multiply(new BigDecimal(itemQuantity));
return totalCost.add(itemCost);
}
}
BigDecimals are Object , not primitives, so make sure you initialize itemCost
and totalCost
, otherwise it can give you nullpointer while you try to add on totalCost
or itemCost
i use this
<style>
html, body{height:100%;margin:0;padding:0 0}
.container-fluid{height:100%;display:table;width:100%;padding-right:0;padding-left: 0}
.row-fluid{height:100%;display:table-cell;vertical-align:middle;width:100%}
.centering{float:none;margin:0 auto}
</style>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div class="offset3 span6 centering">
content here
</div>
</div>
</div>
</body>
Here is how I would do it:
bool intersects(CircleType circle, RectType rect)
{
circleDistance.x = abs(circle.x - rect.x);
circleDistance.y = abs(circle.y - rect.y);
if (circleDistance.x > (rect.width/2 + circle.r)) { return false; }
if (circleDistance.y > (rect.height/2 + circle.r)) { return false; }
if (circleDistance.x <= (rect.width/2)) { return true; }
if (circleDistance.y <= (rect.height/2)) { return true; }
cornerDistance_sq = (circleDistance.x - rect.width/2)^2 +
(circleDistance.y - rect.height/2)^2;
return (cornerDistance_sq <= (circle.r^2));
}
Here's how it works:
The first pair of lines calculate the absolute values of the x and y difference between the center of the circle and the center of the rectangle. This collapses the four quadrants down into one, so that the calculations do not have to be done four times. The image shows the area in which the center of the circle must now lie. Note that only the single quadrant is shown. The rectangle is the grey area, and the red border outlines the critical area which is exactly one radius away from the edges of the rectangle. The center of the circle has to be within this red border for the intersection to occur.
The second pair of lines eliminate the easy cases where the circle is far enough away from the rectangle (in either direction) that no intersection is possible. This corresponds to the green area in the image.
The third pair of lines handle the easy cases where the circle is close enough to the rectangle (in either direction) that an intersection is guaranteed. This corresponds to the orange and grey sections in the image. Note that this step must be done after step 2 for the logic to make sense.
The remaining lines calculate the difficult case where the circle may intersect the corner of the rectangle. To solve, compute the distance from the center of the circle and the corner, and then verify that the distance is not more than the radius of the circle. This calculation returns false for all circles whose center is within the red shaded area and returns true for all circles whose center is within the white shaded area.
Following explanation actually explains how wait() and signal() of monitor differ from P and V of semaphore.
The wait() and signal() operations on condition variables in a monitor are similar to P and V operations on counting semaphores.
A wait statement can block a process's execution, while a signal statement can cause another process to be unblocked. However, there are some differences between them. When a process executes a P operation, it does not necessarily block that process because the counting semaphore may be greater than zero. In contrast, when a wait statement is executed, it always blocks the process. When a task executes a V operation on a semaphore, it either unblocks a task waiting on that semaphore or increments the semaphore counter if there is no task to unlock. On the other hand, if a process executes a signal statement when there is no other process to unblock, there is no effect on the condition variable. Another difference between semaphores and monitors is that users awaken by a V operation can resume execution without delay. Contrarily, users awaken by a signal operation are restarted only when the monitor is unlocked. In addition, a monitor solution is more structured than the one with semaphores because the data and procedures are encapsulated in a single module and that the mutual exclusion is provided automatically by the implementation.
Link: here for further reading. Hope it helps.
It should be,
*/15 * * * * your_command_or_whatever
For completeness sake, the BeautifulSoup 4 version, making use of the encoding supplied by the server as well:
from bs4 import BeautifulSoup
import urllib.request
parser = 'html.parser' # or 'lxml' (preferred) or 'html5lib', if installed
resp = urllib.request.urlopen("http://www.gpsbasecamp.com/national-parks")
soup = BeautifulSoup(resp, parser, from_encoding=resp.info().get_param('charset'))
for link in soup.find_all('a', href=True):
print(link['href'])
or the Python 2 version:
from bs4 import BeautifulSoup
import urllib2
parser = 'html.parser' # or 'lxml' (preferred) or 'html5lib', if installed
resp = urllib2.urlopen("http://www.gpsbasecamp.com/national-parks")
soup = BeautifulSoup(resp, parser, from_encoding=resp.info().getparam('charset'))
for link in soup.find_all('a', href=True):
print link['href']
and a version using the requests
library, which as written will work in both Python 2 and 3:
from bs4 import BeautifulSoup
from bs4.dammit import EncodingDetector
import requests
parser = 'html.parser' # or 'lxml' (preferred) or 'html5lib', if installed
resp = requests.get("http://www.gpsbasecamp.com/national-parks")
http_encoding = resp.encoding if 'charset' in resp.headers.get('content-type', '').lower() else None
html_encoding = EncodingDetector.find_declared_encoding(resp.content, is_html=True)
encoding = html_encoding or http_encoding
soup = BeautifulSoup(resp.content, parser, from_encoding=encoding)
for link in soup.find_all('a', href=True):
print(link['href'])
The soup.find_all('a', href=True)
call finds all <a>
elements that have an href
attribute; elements without the attribute are skipped.
BeautifulSoup 3 stopped development in March 2012; new projects really should use BeautifulSoup 4, always.
Note that you should leave decoding the HTML from bytes to BeautifulSoup. You can inform BeautifulSoup of the characterset found in the HTTP response headers to assist in decoding, but this can be wrong and conflicting with a <meta>
header info found in the HTML itself, which is why the above uses the BeautifulSoup internal class method EncodingDetector.find_declared_encoding()
to make sure that such embedded encoding hints win over a misconfigured server.
With requests
, the response.encoding
attribute defaults to Latin-1 if the response has a text/*
mimetype, even if no characterset was returned. This is consistent with the HTTP RFCs but painful when used with HTML parsing, so you should ignore that attribute when no charset
is set in the Content-Type header.
While debugging, when you hit a break-point.
CTRL+ALT+C
I had this problem as well. I found out that having a $(document).ready function that included a $.cookie in a script tag inside body while having cookie js load in the head BELOW jquery as intended resulted in $(document).ready beeing processed before the cookie plugin could finish loading.
I moved the cookie plugin load script in the body before the $(document).ready script and the error disappeared :D
This error is occurs at runs loop overlimit times.Let's consider simple example like this,
class demo{
public static void main(String a[]){
int[] numberArray={4,8,2,3,89,5};
int i;
for(i=0;i<numberArray.length;i++){
System.out.print(numberArray[i+1]+" ");
}
}
At first, I have initialized an array as 'numberArray'. then , some array elements are printed using for loop. When loop is running 'i' time , print the (numberArray[i+1] element..(when i value is 1, numberArray[i+1] element is printed.)..Suppose that, when i=(numberArray.length-2), last element of array is printed..When 'i' value goes to (numberArray.length-1) , no value for printing..In that point , 'ArrayIndexOutOfBoundsException' is occur.I hope to you could get idea.thank you !
in my case, i was sure that the action is correct, but i was passing wrong URL, i passed the website link without the http:// in it's beginning, so it caused the same issue, here is my manifest (part of it)
<activity
android:name=".MyBrowser"
android:label="MyBrowser Activity" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="com.dsociety.activities.MyBrowser" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>
</activity>
when i code the following, the same Exception is thrown at run time :
Intent intent = new Intent();
intent.setAction("com.dsociety.activities.MyBrowser");
intent.setData(Uri.parse("www.google.com")); // should be http://www.google.com
startActivity(intent);
Sahil has a great answer and I wanted to take that and expand it into an @IBDesignable so developers can add images to their UITextFields on the Storyboard.
import UIKit
@IBDesignable
class DesignableUITextField: UITextField {
// Provides left padding for images
override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
var textRect = super.leftViewRect(forBounds: bounds)
textRect.origin.x += leftPadding
return textRect
}
@IBInspectable var leftImage: UIImage? {
didSet {
updateView()
}
}
@IBInspectable var leftPadding: CGFloat = 0
@IBInspectable var color: UIColor = UIColor.lightGray {
didSet {
updateView()
}
}
func updateView() {
if let image = leftImage {
leftViewMode = UITextField.ViewMode.always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
imageView.contentMode = .scaleAspectFit
imageView.image = image
// Note: In order for your image to use the tint color, you have to select the image in the Assets.xcassets and change the "Render As" property to "Template Image".
imageView.tintColor = color
leftView = imageView
} else {
leftViewMode = UITextField.ViewMode.never
leftView = nil
}
// Placeholder text color
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor: color])
}
}
What is happening here?
This designable allows you to:
Notes
Set
input:focus{
outline: 0 none;
}
"!important" is just in case. That's not necessary. [And now it's gone. –Ed.]
This isn't an answer to the tagline question, but it is an answer to the problems mentioned in the body of the question. Instead of using @Before or @After, look into using @org.junit.Rule because it gives you more flexibility. ExternalResource (as of 4.7) is the rule you will be most interested in if you are managing connections. Also, If you want guaranteed execution order of your rules use a RuleChain (as of 4.10). I believe all of these were available when this question was asked. Code example below is copied from ExternalResource's javadocs.
public static class UsesExternalResource {
Server myServer= new Server();
@Rule
public ExternalResource resource= new ExternalResource() {
@Override
protected void before() throws Throwable {
myServer.connect();
};
@Override
protected void after() {
myServer.disconnect();
};
};
@Test
public void testFoo() {
new Client().run(myServer);
}
}
Notice how most of these can only be used WITHOUT a DOCTYPE. I'm looking for the same answer, but I have a DOCTYPE. There is one way to do it with a DOCTYPE however, although it doesn't apply to the style of my site, but it will work on the type of page you want to create:
div#full-size{
position: absolute;
top:0;
bottom:0;
right:0;
left:0;
overflow:hidden;
Now, this was mentioned earlier but I just wanted to clarify that this is normally used with a DOCTYPE, height:100%; only works without a DOCTYPE
It's short hand for the ternary operator.
FormsAuth = (formsAuth != null) ? formsAuth : new FormsAuthenticationWrapper();
Or for those who don't do ternary:
if (formsAuth != null)
{
FormsAuth = formsAuth;
}
else
{
FormsAuth = new FormsAuthenticationWrapper();
}
Or, as inspired by @MatheusAraujo:
df[nrow(df) + 1,] = list("v1","v2")
This would allow for mixed data types.
Your regex says the following:
/^ - if the line starts with
( - start a capture group
Clinton| - "Clinton"
| - or
[^Bush] - Any single character except "B", "u", "s" or "h"
| - or
Reagan) - "Reagan". End capture group.
/i - Make matches case-insensitive
So, in other words, your middle part of the regex is screwing you up. As it is a "catch-all" kind of group, it will allow any line that does not begin with any of the upper or lower case letters in "Bush". For example, these lines would match your regex:
Our president, George Bush
In the news today, pigs can fly
012-3123 33
You either make a negative look-ahead, as suggested earlier, or you simply make two regexes:
if( ($string =~ m/^(Clinton|Reagan)/i) and
($string !~ m/^Bush/i) ) {
print "$string\n";
}
As mirod has pointed out in the comments, the second check is quite unnecessary when using the caret (^
) to match only beginning of lines, as lines that begin with "Clinton" or "Reagan" could never begin with "Bush".
However, it would be valid without the carets.
In PL/SQL, there is a trick to use the undocumented OWA_UTIL.ITE
function.
SET SERVEROUTPUT ON
DECLARE
x VARCHAR2(10);
BEGIN
x := owa_util.ite('a' = 'b','T','F');
dbms_output.put_line(x);
END;
/
F
PL/SQL procedure successfully completed.
EDIT: (As per the comments in question:)
I've been looking into this since then. I was lucky enough that I had repo laying around. Still it's not clear to me whether you need to enclose your commands between single quotes by force. I looked into the repo syntax and I don't think you need to. You could used double quotes around your command, and then use whatever single and double quotes you need inside provided you escape double ones.
I had this problem, or one that looked superficially similar, yesterday. It turned out that I wasn't being careful when mixing jQuery and prototype. I found several solutions at http://docs.jquery.com/Using_jQuery_with_Other_Libraries. I opted for
var $j = jQuery.noConflict();
but there are other reasonable options described there.
You can also try the randomcoloR
package:
library(randomcoloR)
n <- 20
palette <- distinctColorPalette(n)
You can see that a set of highly distinct colors are chosen when visualizing in a pie chart (as suggested by other answers here):
pie(rep(1, n), col=palette)
Shown in a pie chart with 50 colors:
n <- 50
palette <- distinctColorPalette(n)
pie(rep(1, n), col=palette)
i even tryed to avoid this, just in case doing the Abort on the thread manually, but i rather leave it with the "CompleteRequest" and move on - my code has return commands after redirects anyway. So this can be done
public static void Redirect(string VPathRedirect, global::System.Web.UI.Page Sender)
{
Sender.Response.Redirect(VPathRedirect, false);
global::System.Web.UI.HttpContext.Current.ApplicationInstance.CompleteRequest();
}
Have you tried using Form.ShowDialog() instead of Form.Show()?
ShowDialog shows your window as modal, which means you cannot interact with the parent form until it closes.
The error pretty much explains what the problem is: you are trying to include a file that is not there.
Try to use the full path to the file, using realpath()
, and use dirname(__FILE__)
to get your current directory:
require_once(realpath(dirname(__FILE__) . '/../includes/dbconn.inc'));
with a little help of math
#include <math.h>
int main(){
int a = -1;
unsigned int b;
b = abs(a);
}
By default, inheritance is private. You have to explicitly use public
:
class Bar : public Foo
The task
Find the least number of coins required, that can make any change from 1 to 99 cent.
differs from the task
For each single change from 1 to 99 cent, find the least number of coins required.
because the solution might be a complete different multiset of coins.
Suppose you have not (1), (5), (10), and (25) cent coins, but (1), (3), (5), and (17) cent coins: To make the change for 5, you only need one (5) coin; but for all changes from 1 to 5 you need two (1) coins and one (3) coin, not any (5) coin.
The greedy algorithm iterates from the smallest value to the largest, concerning the change values and coin values:
With 1x(1) you get all change values below 2.
To make a change of 2, you need an additional coin,
which could have any value up to 2;
choose greedy -> choose the largest -> (1).
With 2x(1) you get all change values below 3.
To make a change of 3, you need an additional coin,
which could have any value up to 3;
choose greedy -> choose the largest -> (3).
With 2x(1)+1x(3) you get all change values below 6.
To make a change of 6, you need an additional coin,
which could have any value up to 6;
choose greedy -> choose the largest -> (5).
and so on...
That is in Haskell:
coinsforchange [1,3,5,17] 99
where
coinsforchange coins change =
let f (coinssofar::[Int],sumsofar::Int) (largestcoin::Int,wanttogoto::Int) =
let coincount=(max 0 (wanttogoto-sumsofar+largestcoin-1))`div`largestcoin
in (replicate coincount largestcoin++coinssofar,sumsofar+coincount*largestcoin)
in foldl f ([],0) $ zip coins $ tail [c-1|c<-coins] ++ [change]
And in C++:
void f(std::map<unsigned,int> &coinssofar,int &sumsofar, unsigned largestcoin, int wanttogoto)
{
int x = wanttogoto - sumsofar + largestcoin - 1;
coinssofar[largestcoin] = (x>0) ? (x / largestcoin) : 0;
//returns coinssofar and sumsofar;
}
std::map<unsigned,int> coinsforchange(const std::list<unsigned> &coins, int change)
{
std::map<unsigned,int> coinssofar;
int sumsofar=0;
std::list<unsigned>::const_iterator coin = coins.begin();
unsigned largestcoin = *coin;
for( ++coin ; coin!=coins.end() ; largestcoin=*(coin++))
f(coinssofar,sumsofar,largestcoin,(*coin) - 1);
f(coinssofar,sumsofar,largestcoin,change);
return coinssofar;
}
Looks like the image is too big and the window simply doesn't fit the screen.
Create window with the cv2.WINDOW_NORMAL
flag, it will make it scalable. Then you can resize it to fit your screen like this:
from __future__ import division
import cv2
img = cv2.imread('1.jpg')
screen_res = 1280, 720
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)
cv2.namedWindow('dst_rt', cv2.WINDOW_NORMAL)
cv2.resizeWindow('dst_rt', window_width, window_height)
cv2.imshow('dst_rt', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
According to the OpenCV documentation CV_WINDOW_KEEPRATIO
flag should do the same, yet it doesn't and it's value not even presented in the python module.
If you turn db.js
into a module you can require it from db_init.js
and just: node db_init.js
.
db.js:
module.exports = {
method1: function () { ... },
method2: function () { ... }
}
db_init.js:
var db = require('./db');
db.method1();
db.method2();
// array of $ids that you need to select
$ids = array('1', '2', '3', '4', '5', '6', '7', '8');
// create sql part for IN condition by imploding comma after each id
$in = '(' . implode(',', $ids) .')';
// create sql
$sql = 'SELECT * FROM products WHERE catid IN ' . $in;
// see what you get
var_dump($sql);
Update: (a short version and update missing comma)
$ids = array('1','2','3','4');
$sql = 'SELECT * FROM products WHERE catid IN (' . implode(',', $ids) . ')';
In an ideal case, you would like to test for all three values, null, "" or empty(field doesn't exist in the record)
You can do the following.
db.users.find({$and: [{"name" : {$nin: ["", null]}}, {"name" : {$exists: true}}]})
Just came here to share what was happening to me.
You don't need to specify the parent, states work in an document oriented way so, instead of specifying parent: app, you could just change the state to app.index
.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise("/index.html");
$stateProvider.state('app', {
abstract: true,
templateUrl: "tpl.menu.html"
});
$stateProvider.state('app.index', {
url: '/',
templateUrl: "tpl.index.html"
});
$stateProvider.state('app.register', {
url: "/register",
templateUrl: "tpl.register.html"
});
EDIT Warning, if you want to go deep in the nesting, the full path must me specified. For example, you can't have a state like
app.cruds.posts.create
without having a
app
app.cruds
app.cruds.posts
or angular will throw an exception saying it can't figure out the rout. To solve that you can define abstract states
.state('app', {
url: "/app",
abstract: true
})
.state('app.cruds', {
url: "/app/cruds",
abstract: true
})
.state('app/cruds/posts', {
url: "/app/cruds/posts",
abstract: true
})
Extention for prior Java 8 solution
String result = String.join(",", name);
If you need prefix or/ and suffix for array values
StringJoiner joiner = new StringJoiner(",");
for (CharSequence cs: name) {
joiner.add("'" + cs + "'");
}
return joiner.toString();
Or simple method concept
public static String genInValues(String delimiter, String prefix, String suffix, String[] name) {
StringJoiner joiner = new StringJoiner(delimiter);
for (CharSequence cs: name) {
joiner.add(prefix + cs + suffix);
}
return joiner.toString();
}
For example
For Oracle i need "id in (1,2,3,4,5)"
then use genInValues(",", "", "", name);
But for Postgres i need "id in (values (1),(2),(3),(4),(5))"
then use genInValues(",", "(", ")", name);
If the variable is interchangable, you must have logic somewhere that's determining which variable gets used. All you need to do is put the variable name in $variable
within that logic while you're doing everything else.
I think we're all having a hard time understanding what you're needing this for. Sample code or an explanation of what you're actually trying to do might help, but I suspect you're way, way overthinking this.
On RHEL Linux, I had trouble getting my message in the body of the email instead of as an attachment . Using od -cx, I found that the body of my email contained several /r. I used a perl script to strip the /r, and the message was correctly inserted into the body of the email.
mailx -s "subject text" [email protected] < 'body.txt'
The text file body.txt contained the char \r, so I used perl to strip \r.
cat body.txt | perl success.pl > body2.txt
mailx -s "subject text" [email protected] < 'body2.txt'
This is success.pl
while (<STDIN>) {
my $currLine = $_;
s?\r??g;
print
}
;
There is a CSS unit called viewport height / viewport width.
Example
.mainbody{height: 100vh;}
similarly html,body{width: 100vw;}
or 90vh = 90% of the viewport height.
**IE9+ and most modern browsers.
The best way to do this is probably to use a third party library.
There's an implementation of what you're looking for in jQuery UI jQuery UI and in dojo dojo. jQuery is more popular, but dojo allows you to declaratively define widgets in HTML, which sounds more like what you're looking for.
Which one you use will depend on your style, but both are developed for cross browser work, and both will be updated more often than copy and paste code.
You can use FormData to submit your data by a POST request. Here is a simple example:
var myFormData = new FormData();
myFormData.append('pictureFile', pictureInput.files[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: myFormData
});
You don't have to use a form to make an ajax request, as long as you know your request setting (like url, method and parameters data).
2017 one-liner:
openssl req \
-newkey rsa:2048 \
-x509 \
-nodes \
-keyout server.pem \
-new \
-out server.pem \
-subj /CN=localhost \
-reqexts SAN \
-extensions SAN \
-config <(cat /System/Library/OpenSSL/openssl.cnf \
<(printf '[SAN]\nsubjectAltName=DNS:localhost')) \
-sha256 \
-days 3650
This also works in Chrome 57, as it provides the SAN, without having another configuration file. It was taken from an answer here.
This creates a single .pem file that contains both the private key and cert. You can move them to separate .pem files if needed.
char members[255] = {0};
GET will send the data as a querystring, but POST will not. Rather it will send it in the body of the request.
char largeSrt[] = "123456789-123"; // original string
char * substr;
substr = strchr(largeSrt, '-'); // we save the new string "-123"
int substringLength = strlen(largeSrt) - strlen(substr); // 13-4=9 (bigger string size) - (new string size)
char *newStr = malloc(sizeof(char) * substringLength + 1);// keep memory free to new string
strcpy(newStr, largeSrt, substringLength); // copy only 9 characters
newStr[substringLength] = '\0'; // close the new string with final character
printf("newStr=%s\n", newStr);
free(newStr); // you free the memory
I tried the steps mentioned in the earlier posts but without any success. However, what worked for me was uninstalling R completely and then deleting the R folder which files in the documents folder, so basically everything do with R except the scripts and work spaces I had saved. I then reinstalled R and ran
remove.packages(c("ggplot2", "data.table"))
install.packages('Rcpp', dependencies = TRUE)
install.packages('ggplot2', dependencies = TRUE)
install.packages('data.table', dependencies = TRUE)
This rather crude method somehow worked for me.
Albeit from the useless _T
and incorrectly spelled histories. If you are using SQL*Plus
, it does not accept create table statements with empty new lines between create table <name> (
and column definitions.
To totally steal from Bill answer you can make an extension method and use some syntactic sugar to help you out.
Create a class file, StringExtensions.cs
Content:
public static class StringExt
{
public static bool IsNumeric(this string text)
{
double test;
return double.TryParse(text, out test);
}
}
EDIT: This is for updated C# 7 syntax. Declaring out parameter in-line.
public static class StringExt
{
public static bool IsNumeric(this string text) => double.TryParse(text, out _);
}
Call method like such:
var text = "I am not a number";
text.IsNumeric() //<--- returns false
You can also use query(), i.e.:
df_filtered = df.query('a == 4 & b != 2')
The good part is we can make basic maths directly:
let nuts = 7_x000D_
_x000D_
more.innerHTML = `_x000D_
_x000D_
<h2>You collected ${nuts} nuts so far!_x000D_
_x000D_
<hr>_x000D_
_x000D_
Double it, get ${nuts + nuts} nuts!!_x000D_
_x000D_
`
_x000D_
<div id="more"></div>
_x000D_
It became really useful in a factory function:
function nuts(it){_x000D_
return `_x000D_
You have ${it} nuts! <br>_x000D_
Cosinus of your nuts: ${Math.cos(it)} <br>_x000D_
Triple nuts: ${3 * it} <br>_x000D_
Your nuts encoded in BASE64:<br> ${btoa(it)}_x000D_
`_x000D_
}_x000D_
_x000D_
nut.oninput = (function(){_x000D_
out.innerHTML = nuts(nut.value)_x000D_
})
_x000D_
<h3>NUTS CALCULATOR_x000D_
<input type="number" id="nut">_x000D_
_x000D_
<div id="out"></div>
_x000D_
Andy's answer helps but if you have concern on exposing your database password in your django setting, I suggest to follow django official configuration on mysql connection: https://docs.djangoproject.com/en/1.7/ref/databases/
Quoted here as:
# settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': '/path/to/my.cnf',
},
}
}
# my.cnf
[client]
database = NAME
user = USER
password = PASSWORD
default-character-set = utf8
To replace 'HOST': '127.0.0.1' in setting, simply add it in my.cnf:
# my.cnf
[client]
database = NAME
host = HOST NAME or IP
user = USER
password = PASSWORD
default-character-set = utf8
Another OPTION that is useful, is to set your storage engine for django, you might want it in your setting.py:
'OPTIONS': {
'init_command': 'SET storage_engine=INNODB',
}
I think the best library is : https://github.com/chrisbanes/Android-PullToRefresh.
Works with:
ListView
ExpandableListView
GridView
WebView
ScrollView
HorizontalScrollView
ViewPager
The Major difference is Given Below -
1: Constructor must have same name as the class name while this is not the case of methods
class Calendar{
int year = 0;
int month= 0;
//constructor
public Calendar(int year, int month){
this.year = year;
this.month = month;
System.out.println("Demo Constructor");
}
//Method
public void Display(){
System.out.println("Demo method");
}
}
2: Constructor initializes objects of a class whereas method does not. Methods performs operations on objects that already exist. In other words, to call a method we need an object of the class.
public class Program {
public static void main(String[] args) {
//constructor will be called on object creation
Calendar ins = new Calendar(25, 5);
//Methods will be called on object created
ins.Display();
}
}
3: Constructor does not have return type but a method must have a return type
class Calendar{
//constructor – no return type
public Calendar(int year, int month){
}
//Method have void return type
public void Display(){
System.out.println("Demo method");
}
}
try
states.split()
it returns the list
['Alaska',
'Alabama',
'Arkansas',
'American',
'Samoa',
'Arizona',
'California',
'Colorado']
and this returns the random element of the list
import random
random.choice(states.split())
split statement parses the string and returns the list, by default it's divided into the list by spaces, if you specify the string it's divided by this string, so for example
states.split('Ari')
returns
['Alaska Alabama Arkansas American Samoa ', 'zona California Colorado']
Btw, list is in python interpretated with [] brackets instead of {} brackets, {} brackets are used for dictionaries, you can read more on this here
I see you are probably new to python, so I'd give you some advice how to use python's great documentation
Almost everything you need can be found here You can use also python included documentation, open python console and write help() If you don't know what to do with some object, I'd install ipython, write statement and press Tab, great tool which helps you with interacting with the language
I just wrote this here to show that python is great tool also because it's great documentation and it's really powerful to know this
A pointer can receive a NULL parameter, a reference parameter can not. If there's ever a chance that you could want to pass "no object", then use a pointer instead of a reference.
Also, passing by pointer allows you to explicitly see at the call site whether the object is passed by value or by reference:
// Is mySprite passed by value or by reference? You can't tell
// without looking at the definition of func()
func(mySprite);
// func2 passes "by pointer" - no need to look up function definition
func2(&mySprite);
In Bootstrap 3 (3.0.3) adding the "text-center"
class to a td
element works out of the box.
I.e., the following centers some text
in a table cell:
<td class="text-center">some text</td>
As Marineio said, you could use the onclick
attribute of the <li>
to change location.href
, through javascript:
<li onclick="location.href='http://example';"> ... </li>
Alternatively, you could remove any margins or padding in the <li>
, and add a large padding to the left side of the <a>
to avoid text going over the bullet.
define a custom pojo class say sureveyQueryAnalytics and store the query returned value in your custom pojo class
@Query(value = "select new com.xxx.xxx.class.SureveyQueryAnalytics(s.answer, count(sv)) from Survey s group by s.answer")
List<SureveyQueryAnalytics> calculateSurveyCount();
Bash4 supports this natively. Do not use grep
or eval
, they are the ugliest of hacks.
For a verbose, detailed answer with example code see: https://stackoverflow.com/questions/3467959
You could use getNetworkCountryIso()
from TelephonyManager
to get the country the phone is currently in (although apparently this is unreliable on CDMA networks).
package com.mycompany;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Car {
@NotNull
private String manufacturer;
@NotNull
@Size(min = 2, max = 14)
private String licensePlate;
@Min(2)
private int seatCount;
public Car(String manufacturer, String licencePlate, int seatCount) {
this.manufacturer = manufacturer;
this.licensePlate = licencePlate;
this.seatCount = seatCount;
}
//getters and setters ...
}
@NotNull
, @Size
and @Min
are so-called constraint annotations, that we use to declare constraints, which shall be applied to the fields of a Car instance:
manufacturer
shall never be null
licensePlate
shall never be null and must be between 2 and 14 characters long
seatCount
shall be at least 2.
you can use the below code to bring focus to a div, in this example the page scrolls to the <div id="navigation">
$('html, body').animate({ scrollTop: $('#navigation').offset().top }, 'slow');
I work on Mercurial, but fundamentally I believe both systems are equivalent. They both work with the same abstractions: a series of snapshots (changesets) which make up the history. Each changeset knows where it came from (the parent changeset) and can have many child changesets. The recent hg-git extension provides a two-way bridge between Mercurial and Git and sort of shows this point.
Git has a strong focus on mutating this history graph (with all the consequences that entails) whereas Mercurial does not encourage history rewriting, but it's easy to do anyway and the consequences of doing so are exactly what you should expect them to be (that is, if I modify a changeset you already have, your client will see it as new if you pull from me). So Mercurial has a bias towards non-destructive commands.
As for light-weight branches, then Mercurial has supported repositories with multiple branches since..., always I think. Git repositories with multiple branches are exactly that: multiple diverged strands of development in a single repository. Git then adds names to these strands and allow you to query these names remotely. The Bookmarks extension for Mercurial adds local names, and with Mercurial 1.6, you can move these bookmarks around when you push/pull..
I use Linux, but apparently TortoiseHg is faster and better than the Git equivalent on Windows (due to better usage of the poor Windows filesystem). Both http://github.com and http://bitbucket.org provide online hosting, the service at Bitbucket is great and responsive (I haven't tried github).
I chose Mercurial since it feels clean and elegant -- I was put off by the shell/Perl/Ruby scripts I got with Git. Try taking a peek at the git-instaweb.sh
file if you want to know what I mean: it is a shell script which generates a Ruby script, which I think runs a webserver. The shell script generates another shell script to launch the first Ruby script. There is also a bit of Perl, for good measure.
I like the blog post that compares Mercurial and Git with James Bond and MacGyver -- Mercurial is somehow more low-key than Git. It seems to me, that people using Mercurial are not so easily impressed. This is reflected in how each system do what Linus described as "the coolest merge EVER!". In Git you can merge with an unrelated repository by doing:
git fetch <project-to-union-merge>
GIT_INDEX_FILE=.git/tmp-index git-read-tree FETCH_HEAD
GIT_INDEX_FILE=.git/tmp-index git-checkout-cache -a -u
git-update-cache --add -- (GIT_INDEX_FILE=.git/tmp-index git-ls-files)
cp .git/FETCH_HEAD .git/MERGE_HEAD
git commit
Those commands look quite arcane to my eye. In Mercurial we do:
hg pull --force <project-to-union-merge>
hg merge
hg commit
Notice how the Mercurial commands are plain and not special at all -- the only unusual thing is the --force
flag to hg pull
, which is needed since Mercurial will abort otherwise when you pull from an unrelated repository. It is differences like this that makes Mercurial seem more elegant to me.
I use objects JSON style for dumb structs (no member functions).
Already there are lots of answers to your question, You can do it like this also. You can give your table an alias name and use that in the select query like this:
SELECT a.id, b.id, name, section
FROM tbl_names as a
LEFT JOIN tbl_section as b ON a.id = b.id;
For those late-comers that are looking for a solution that "just works":
#include <utility>
#include <iostream>
template< typename T >
class Y {
template< bool cond, typename U >
using resolvedType = typename std::enable_if< cond, U >::type;
public:
template< typename U = T >
resolvedType< true, U > foo() {
return 11;
}
template< typename U = T >
resolvedType< false, U > foo() {
return 12;
}
};
int main() {
Y< double > y;
std::cout << y.foo() << std::endl;
}
Compile with:
g++ -std=gnu++14 test.cpp
Running gives:
./a.out
11
The document.location
is an object that contains properties for the current location.
The href
property is one of these properties, containing the complete URL, i.e. all the other properties put together.
Some browsers allow you to assign an URL to the location
object and acts as if you assigned it to the href
property. Some other browsers are more picky, and requires you to use the href
property. Thus, to make the code work in all browsers, you have to use the href
property.
Both the window
and document
objects has a location
object. You can set the URL using either window.location.href
or document.location.href
. However, logically the document.location
object should be read-only (as you can't change the URL of a document; changing the URL loads a new document), so to be on the safe side you should rather use window.location.href
when you want to set the URL.
use below command while installing packages
sudo npm install --unsafe-perm=true --allow-root
Using following sample code we can filter array in angular controller by name. this is based on following description. http://docs.angularjs.org/guide/filter
this.filteredArray = filterFilter(this.array, {name:'Igor'});
JS:
angular.module('FilterInControllerModule', []).
controller('FilterController', ['filterFilter', function(filterFilter) {
this.array = [
{name: 'Tobias'},
{name: 'Jeff'},
{name: 'Brian'},
{name: 'Igor'},
{name: 'James'},
{name: 'Brad'}
];
this.filteredArray = filterFilter(this.array, {name:'Igor'});
}]);
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example96-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.3/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="FilterInControllerModule">
<div ng-controller="FilterController as ctrl">
<div>
All entries:
<span ng-repeat="entry in ctrl.array">{{entry.name}} </span>
</div>
<div>
Filter By Name in angular controller
<span ng-repeat="entry in ctrl.filteredArray">{{entry.name}} </span>
</div>
</div>
</body>
</html>
PHP has JSON_PRETTY_PRINT option since 5.4.0 (release date 01-Mar-2012).
This should do the job:
$json = json_decode($string);
echo json_encode($json, JSON_PRETTY_PRINT);
See http://www.php.net/manual/en/function.json-encode.php
Note: Don't forget to echo "<pre>" before and "</pre>" after, if you're printing it in HTML to preserve formatting ;)
Some important and successfully executed software projects like Google Chrome and Mozilla Firefox are fine examples of both iterative and incremental software development.
I will quote fine ars technica article which describes this approach: http://arstechnica.com/information-technology/2010/07/chrome-team-sets-six-week-cadence-for-new-major-versions/
According to Chrome program manager Anthony Laforge, the increased pace is designed to address three main goals. One is to get new features out to users faster. The second is make the release schedule predictable and therefore easier to plan which features will be included and which features will be targeted for later releases. Third, and most counterintuitive, is to cut the level of stress for Chrome developers. Laforge explains that the shorter, predictable time periods between releases are more like "trains leaving Grand Central Station." New features that are ready don't have to wait for others that are taking longer to complete—they can just hop on the current release "train." This can in turn take the pressure off developers to rush to get other features done, since another release train will be coming in six weeks. And they can rest easy knowing their work isn't holding the train from leaving the station.<<
You can select dropdown options by value:
$('#locregion').$('[value="1"]').click();
I was looking for a way to parse object arrays in a more generic way; here is my contribution:
CollectionDeserializer.java
:
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
public class CollectionDeserializer implements JsonDeserializer<Collection<?>> {
@Override
public Collection<?> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
Type realType = ((ParameterizedType)typeOfT).getActualTypeArguments()[0];
return parseAsArrayList(json, realType);
}
/**
* @param serializedData
* @param type
* @return
*/
@SuppressWarnings("unchecked")
public <T> ArrayList<T> parseAsArrayList(JsonElement json, T type) {
ArrayList<T> newArray = new ArrayList<T>();
Gson gson = new Gson();
JsonArray array= json.getAsJsonArray();
Iterator<JsonElement> iterator = array.iterator();
while(iterator.hasNext()){
JsonElement json2 = (JsonElement)iterator.next();
T object = (T) gson.fromJson(json2, (Class<?>)type);
newArray.add(object);
}
return newArray;
}
}
JSONParsingTest.java
:
public class JSONParsingTest {
List<World> worlds;
@Test
public void grantThatDeserializerWorksAndParseObjectArrays(){
String worldAsString = "{\"worlds\": [" +
"{\"name\":\"name1\",\"id\":1}," +
"{\"name\":\"name2\",\"id\":2}," +
"{\"name\":\"name3\",\"id\":3}" +
"]}";
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Collection.class, new CollectionDeserializer());
Gson gson = builder.create();
Object decoded = gson.fromJson((String)worldAsString, JSONParsingTest.class);
assertNotNull(decoded);
assertTrue(JSONParsingTest.class.isInstance(decoded));
JSONParsingTest decodedObject = (JSONParsingTest)decoded;
assertEquals(3, decodedObject.worlds.size());
assertEquals((Long)2L, decodedObject.worlds.get(1).getId());
}
}
World.java
:
public class World {
private String name;
private Long id;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
I've been pulling my hair out over this one for a couple of hours also. fakeartist appears correct though - I changed the file extension from .htm to .php and I can now see my page in Facebook! It also works if you change the extension to .aspx - perhaps it just needs to be a server side extension (I've not tried with .jsp).
I'll assume you need it for one-off things. I'll assume you're a PC developer.
Use the Stack, Luke. Use it everywhere. Don't use malloc / free for small allocations, ever.
#include <string.h>
#include <stdio.h>
#define STR_SIZE 10000
int main()
{
char s1[] = "oppa";
char s2[] = "gangnam";
char s3[] = "style";
{
char result[STR_SIZE] = {0};
snprintf(result, sizeof(result), "%s %s %s", s1, s2, s3);
printf("%s\n", result);
}
}
If 10 KB per string won't be enough, add a zero to the size and don't bother, - they'll release their stack memory at the end of the scopes anyway.
I would most definitely recommend using the built in standard password libraries that come with PHP - Here is a good example on how to use them.
For those coming here to figure out how to go from Binary Strings to Decimals and back, there are some good examples below.
For converting binary "strings" to decimals/chars you can do something like this...
echo bindec("00000001") . "\n";
echo bindec("00000010") . "\n";
echo bindec("00000100") . "\n";
echo bindec("00001000") . "\n";
echo bindec("00010000") . "\n";
echo bindec("00100000") . "\n";
echo bindec("01000000") . "\n";
echo bindec("10000000") . "\n";
echo bindec("01000001") . "\n";
# big binary string
echo bindec("111010110111011110000110001")."\n";
The above outputs:
1
2
4
8
16
32
64
128
65
123452465
For converting decimals to char/strings you can do this:
# convert to binary strings "00000001"
echo decbin(1) . "\n";
echo decbin(2) . "\n";
echo decbin(4) . "\n";
echo decbin(8) . "\n";
echo decbin(16) . "\n";
echo decbin(32) . "\n";
echo decbin(64) . "\n";
echo decbin(128) . "\n";
# convert a ascii character
echo str_pad(decbin(65), 8, 0, STR_PAD_LEFT) ."\n";
# convert a 'char'
echo str_pad(decbin(ord('A')), 8, 0, STR_PAD_LEFT) ."\n";
# big number...
echo str_pad(decbin(65535), 8, 0, STR_PAD_LEFT) ."\n";
echo str_pad(decbin(123452465), 8, 0, STR_PAD_LEFT) ."\n";
The above outputs:
1
10
100
1000
10000
100000
1000000
10000000
01000001
01000001
1111111111111111
111010110111011110000110001
By default Bundler will check your system first and if it can't find a gem it will use the sources specified in your Gemfile.
I had the same issue because my file was called email.py. I renamed the file and the issue disappeared.
you can use nvidia-smi pmon -i 0
to monitor every process in GPU 0.
including compute mode, sm usage, memory usage, encoder usage, decoder usage.
You can use $setDirty();
method. See documentation https://docs.angularjs.org/api/ng/type/form.FormController
Example:
$scope.myForm.$setDirty();
You can index dataframe columns by the position using ix
.
df1.ix[:,1]
This returns the first column for example. (0 would be the index)
df1.ix[0,]
This returns the first row.
df1.ix[:,1]
This would be the value at the intersection of row 0 and column 1:
df1.ix[0,1]
and so on. So you can enumerate()
returns.keys():
and use the number to index the dataframe.
In C++11, there are actually std::to_string and std::to_wstring functions in <string>.
string to_string(int val);
string to_string(long val);
string to_string(long long val);
string to_string(unsigned val);
string to_string(unsigned long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string (long double val);
Make sure you are sending the proper parameters too. This happened to me after switching to UI-Router.
To fix it, I changed $routeParams to use $stateParams in my controller. The main issue was that $stateParams was no longer sending a proper parameter to the resource.
There were (at time of posting) one or two little typos in the accepted answer above, so here's the cleaned up version. In this example I'm stopping the CPU profiler when receiving Ctrl+C.
// capture ctrl+c and stop CPU profiler
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for sig := range c {
log.Printf("captured %v, stopping profiler and exiting..", sig)
pprof.StopCPUProfile()
os.Exit(1)
}
}()
Option 1. First you map the array to get those numbers (and not the full details):
$numbers = array_column($array, 'weight')
Then you get the min and max:
$min = min($numbers);
$max = max($numbers);
Option 2. (Only if you don't have PHP 5.5 or better) The same as option 1, but to pluck the values, use array_map
:
$numbers = array_map(function($details) {
return $details['Weight'];
}, $array);
Option 3.
Option 4. If you only need a min OR max, array_reduce()
might be faster:
$min = array_reduce($array, function($min, $details) {
return min($min, $details['weight']);
}, PHP_INT_MAX);
This does more min()
s, but they're very fast. The PHP_INT_MAX
is to start with a high, and get lower and lower. You could do the same for $max
, but you'd start at 0
, or -PHP_INT_MAX
.
I feel that none of the preexisting answers fully identify the answer here, so I'm going to articulate my own perspective. Functionally, the two methods are the same. If the programer is familiar with other languages following C syntax, then they will likely feel more comfortable with the braces, or else if php is the first language that they're learning, they will feel more comfortable with the if
endif
syntax, since it seems closer to regular language.
If you're a really serious programmer and need to get things done fast, then I do believe that the curly brace syntax is superior because it saves time typing
if(/*condition*/){
/*body*/
}
compared to
if(/*condition*/):
/*body*/
endif;
This is especially true with other loops, say, a foreach
where you would end up typing an extra 10 chars. With braces, you just need to type two characters, but for the keyword based syntax you have to type a whole extra keyword for every loop and conditional statement.
We faced the same issue and fixed it. Below is the reason and solution.
Problem
When the connection pool mechanism is used, the application server (in our case, it is JBOSS) creates connections according to the min-connection
parameter. If you have 10 applications running, and each has a min-connection
of 10, then a total of 100 sessions will be created in the database. Also, in every database, there is a max-session
parameter, if your total number of connections crosses that border, then you will get Got minus one from a read call
.
FYI: Use the query below to see your total number of sessions:
SELECT username, count(username) FROM v$session
WHERE username IS NOT NULL group by username
Solution: With the help of our DBA, we increased that max-session
parameter, so that all our application min-connection
can accommodate.
You can get the DOM element, and set the disabled property directly.
$(".shownextrow").click(function() {
$(this).closest("tr").next().show()
.find('.longboxsmall').hide()[0].disabled = 'disabled';
});
or if there's more than one, you can use each()
to set all of them:
$(".shownextrow").click(function() {
$(this).closest("tr").next().show()
.find('.longboxsmall').each(function() {
this.style.display = 'none';
this.disabled = 'disabled';
});
});
Solution One: You can use new react HOOKS API. Currently in React v16.8.0
Hooks let you use more of React’s features without classes. Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle. Hooks solves all the problems addressed with Recompose.
A Note from the Author of recompose
(acdlite, Oct 25 2018):
Hi! I created Recompose about three years ago. About a year after that, I joined the React team. Today, we announced a proposal for Hooks. Hooks solves all the problems I attempted to address with Recompose three years ago, and more on top of that. I will be discontinuing active maintenance of this package (excluding perhaps bugfixes or patches for compatibility with future React releases), and recommending that people use Hooks instead. Your existing code with Recompose will still work, just don't expect any new features.
Solution Two:
If you are using react version that does not support hooks, no worries, use recompose
(A React utility belt for function components and higher-order components.) instead. You can use recompose
for attaching lifecycle hooks, state, handlers etc
to a function component.
Here’s a render-less component that attaches lifecycle methods via the lifecycle HOC (from recompose).
// taken from https://gist.github.com/tsnieman/056af4bb9e87748c514d#file-auth-js-L33
function RenderlessComponent() {
return null;
}
export default lifecycle({
componentDidMount() {
const { checkIfAuthed } = this.props;
// Do they have an active session? ("Remember me")
checkIfAuthed();
},
componentWillReceiveProps(nextProps) {
const {
loadUser,
} = this.props;
// Various 'indicators'..
const becameAuthed = (!(this.props.auth) && nextProps.auth);
const isCurrentUser = (this.props.currentUser !== null);
if (becameAuthed) {
loadUser(nextProps.auth.uid);
}
const shouldSetCurrentUser = (!isCurrentUser && nextProps.auth);
if (shouldSetCurrentUser) {
const currentUser = nextProps.users[nextProps.auth.uid];
if (currentUser) {
this.props.setCurrentUser({
'id': nextProps.auth.uid,
...currentUser,
});
}
}
}
})(RenderlessComponent);
Try this:
String urle = HOST + url + value;
Then return the values from:
urle.replace(" ", "%20").trim();
From the Jinja2 template designer documentation:
{% if variable is defined %}
value of variable: {{ variable }}
{% else %}
variable is not defined
{% endif %}
try
myString.match(/\d/g).join``
var myString = 'abc123.8<blah>'_x000D_
console.log( myString.match(/\d/g).join`` );
_x000D_
If you are using Java 7+, you may want to use NIO.2, e.g.:
❍ Code:
public static void main(String[] args) throws Exception {
File file = new File("test.csv");
List<String> lines = Files.readAllLines(file.toPath(),
StandardCharsets.UTF_8);
for (String line : lines) {
String[] array = line.split(",", -1);
System.out.println(array[0]);
}
}
❍ Output:
a
1RW
1RW
1RW
1RW
1RW
1RW
1R1W
1R1W
1R1W
You could use an anchor element (<a></a>
), and use a:active and a:link to change the background image to toggle on or off. Just a thought.
Edit: The above method doesn't work too well for toggle. But you don't need to use jquery. Write a simple onClick javascript function for the element, which changes the background image appropriately to make it look like the button is pressed, and set some flag. Then on next click, image and flag is is reverted. Like so
var flag = 0;
function toggle(){
if(flag==0){
document.getElementById("toggleDiv").style.backgroundImage="path/to/img/img1.gif";
flag=1;
}
else if(flag==1){
document.getElementById("toggleDiv").style.backgroundImage="path/to/img/img2.gif";
flag=0;
}
}
And the html like so
<div id="toggleDiv" onclick="toggle()">Some thing</div>
Try to Use Flex as that is the new standard of html5.
http://jsfiddle.net/maxspan/1b431hxm/
<div id="row1">
<div id="column1">I am column one</div>
<div id="column2">I am column two</div>
</div>
#row1{
display:flex;
flex-direction:row;
justify-content: space-around;
}
#column1{
display:flex;
flex-direction:column;
}
#column2{
display:flex;
flex-direction:column;
}
sorry for late answer but may be my code may help u.
I placed 3 buttons on the winform surface. button1 & 2 will set different value and button3 will retrieve current value. so when run my code first add the reference System.configuration
and click on first button and then click on 3rd button to see what value has been set. next time again click on second & 3rd button to see again what value has been set after change.
so here is the code.
using System.Configuration;
private void button1_Click(object sender, EventArgs e)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings.Remove("DBServerName");
config.AppSettings.Settings.Add("DBServerName", "FirstAddedValue1");
config.Save(ConfigurationSaveMode.Modified);
}
private void button2_Click(object sender, EventArgs e)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings.Remove("DBServerName");
config.AppSettings.Settings.Add("DBServerName", "SecondAddedValue1");
config.Save(ConfigurationSaveMode.Modified);
}
private void button3_Click(object sender, EventArgs e)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
MessageBox.Show(config.AppSettings.Settings["DBServerName"].Value);
}
There are two issues are at play here:
The CSS 2.1 specification states that "The :before
and :after
pseudo-elements elements interact with other boxes, such as run-in boxes, as if they were real elements inserted just inside their associated element." Given the way z-indexes are implemented in most browsers, it's pretty difficult (read, I don't know of a way) to move content lower than the z-index of their parent element in the DOM that works in all browsers.
Number 1 above does not necessarily mean it's impossible, but the second impediment to it is actually worse: Ultimately it's a matter of browser support. Firefox didn't support positioning of generated content at all until FF3.6. Who knows about browsers like IE. So even if you can find a hack to make it work in one browser, it's very likely it will only work in that browser.
The only thing I can think of that's going to work across browsers is to use javascript to insert the element rather than CSS. I know that's not a great solution, but the :before
and :after
pseudo-selectors just really don't look like they're gonna cut it here.
Before looking at the difference between java.lang.RuntimeException
and java.lang.Exception
classes, you must know the Exception
hierarchy. Both Exception
and Error
classes are derived from class Throwable
(which derives from the class Object
). And the class RuntimeException
is derived from class Exception
.
All the exceptions are derived either from Exception
or RuntimeException
.
All the exceptions which derive from RuntimeException
are referred to as unchecked exceptions. And all the other exceptions are checked exceptions. A checked exception must be caught somewhere in your code, otherwise, it will not compile. That is why they are called checked exceptions. On the other hand, with unchecked exceptions, the calling method is under no obligation to handle or declare it.
Therefore all the exceptions which compiler forces you to handle are directly derived from java.lang.Exception
and all the other which compiler does not force you to handle are derived from java.lang.RuntimeException
.
Following are some of the direct known subclasses of RuntimeException.
AnnotationTypeMismatchException,
ArithmeticException,
ArrayStoreException,
BufferOverflowException,
BufferUnderflowException,
CannotRedoException,
CannotUndoException,
ClassCastException,
CMMException,
ConcurrentModificationException,
DataBindingException,
DOMException,
EmptyStackException,
EnumConstantNotPresentException,
EventException,
IllegalArgumentException,
IllegalMonitorStateException,
IllegalPathStateException,
IllegalStateException,
ImagingOpException,
IncompleteAnnotationException,
IndexOutOfBoundsException,
JMRuntimeException,
LSException,
MalformedParameterizedTypeException,
MirroredTypeException,
MirroredTypesException,
MissingResourceException,
NegativeArraySizeException,
NoSuchElementException,
NoSuchMechanismException,
NullPointerException,
ProfileDataException,
ProviderException,
RasterFormatException,
RejectedExecutionException,
SecurityException,
SystemException,
TypeConstraintException,
TypeNotPresentException,
UndeclaredThrowableException,
UnknownAnnotationValueException,
UnknownElementException,
UnknownTypeException,
UnmodifiableSetException,
UnsupportedOperationException,
WebServiceException
Map:
Map transformation.
The map works on a single Row at a time.
Map returns after each input Row.
The map doesn’t hold the output result in Memory.
Map no way to figure out then to end the service.
// map example
val dfList = (1 to 100) toList
val df = dfList.toDF()
val dfInt = df.map(x => x.getInt(0)+2)
display(dfInt)
MapPartition:
MapPartition transformation.
MapPartition works on a partition at a time.
MapPartition returns after processing all the rows in the partition.
MapPartition output is retained in memory, as it can return after processing all the rows in a particular partition.
MapPartition service can be shut down before returning.
// MapPartition example
Val dfList = (1 to 100) toList
Val df = dfList.toDF()
Val df1 = df.repartition(4).rdd.mapPartition((int) => Iterator(itr.length))
Df1.collec()
//display(df1.collect())
For more details, please refer to the Spark map vs mapPartitions transformation article.
Hope this is helpful!
How to use PUT method using WebRequest.
//JsonResultModel class
public class JsonResultModel
{
public string ErrorMessage { get; set; }
public bool IsSuccess { get; set; }
public string Results { get; set; }
}
// HTTP_PUT Function
public static JsonResultModel HTTP_PUT(string Url, string Data)
{
JsonResultModel model = new JsonResultModel();
string Out = String.Empty;
string Error = String.Empty;
System.Net.WebRequest req = System.Net.WebRequest.Create(Url);
try
{
req.Method = "PUT";
req.Timeout = 100000;
req.ContentType = "application/json";
byte[] sentData = Encoding.UTF8.GetBytes(Data);
req.ContentLength = sentData.Length;
using (System.IO.Stream sendStream = req.GetRequestStream())
{
sendStream.Write(sentData, 0, sentData.Length);
sendStream.Close();
}
System.Net.WebResponse res = req.GetResponse();
System.IO.Stream ReceiveStream = res.GetResponseStream();
using (System.IO.StreamReader sr = new
System.IO.StreamReader(ReceiveStream, Encoding.UTF8))
{
Char[] read = new Char[256];
int count = sr.Read(read, 0, 256);
while (count > 0)
{
String str = new String(read, 0, count);
Out += str;
count = sr.Read(read, 0, 256);
}
}
}
catch (ArgumentException ex)
{
Error = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message);
}
catch (WebException ex)
{
Error = string.Format("HTTP_ERROR :: WebException raised! :: {0}", ex.Message);
}
catch (Exception ex)
{
Error = string.Format("HTTP_ERROR :: Exception raised! :: {0}", ex.Message);
}
model.Results = Out;
model.ErrorMessage = Error;
if (!string.IsNullOrWhiteSpace(Out))
{
model.IsSuccess = true;
}
return model;
}
Split the CSV into two files in Notepad. It's a pain, but you can just edit each of them individually in Excel after that.
You need to use the change directory command 'cd' to change directory
cd C:\Users\MyName\Desktop
you can use cd \d
to change the drive as well.
link for additional resources http://ss64.com/nt/cd.html
Just as a complement of Reinout's answer.
The permanent way to solve this kind of problem is to edit .matplotlibrc file. Find it via
>>> import matplotlib
>>> matplotlib.matplotlib_fname()
# This is the file location in Ubuntu
'/etc/matplotlibrc'
Then modify the backend in that file to backend : Agg
. That is it.
Just to generate the java classes from wsdl to me the best tool is "cxf wsdl2java". Its pretty simple and easy to use. I have found some complexities with some data type in axis2. But unfortunately you can't use those client stub code in your android application because android environment doesn't allow the "java/javax" package name in compiling time unless you rename the package name.
And in the android.jar all the javax.* sources for web service consuming are not available. To resolve these I have developed this WS Client Generation Tool for android.
In background it uses "cxf wsdl2java" to generate the java client stub for android platform for you, And I have written some sources to consume the web service in a smarter way.
Just give the wsdl file location it will give you the sources and some library. you have to just put the sources and the libraries in your project. and you can just call it in some "method call fashion" just we do in our enterprise project, you don't need to know the namespace/soap action etc. For example, you have a service to login, what you need to do is :
LoginService service = new LoginService ( );
Login login = service.getLoginPort ( );
LoginServiceResponse resp = login.login ( "someUser", "somePass" );
And its fully open and free.
There are a lot of possible MIME types for CSV files, depending on the user's OS and browser version.
This is how I currently validate the MIME types of my CSV files:
$csv_mimetypes = array(
'text/csv',
'text/plain',
'application/csv',
'text/comma-separated-values',
'application/excel',
'application/vnd.ms-excel',
'application/vnd.msexcel',
'text/anytext',
'application/octet-stream',
'application/txt',
);
if (in_array($_FILES['upload']['type'], $csv_mimetypes)) {
// possible CSV file
// could also check for file content at this point
}
This is a press down button example I've made:
<div>
<form id="forminput" action="action" method="POST">
...
</form>
<div style="right: 0px;bottom: 0px;position: fixed;" class="thumbnail">
<div class="image">
<a onclick="document.getElementById('forminput').submit();">
<img src="images/button.png" alt="Some awesome text">
</a>
</div>
</div>
</div>
the CSS file:
.thumbnail {
width: 128px;
height: 128px;
}
.image {
width: 100%;
height: 100%;
}
.image img {
-webkit-transition: all .25s ease; /* Safari and Chrome */
-moz-transition: all .25s ease; /* Firefox */
-ms-transition: all .25s ease; /* IE 9 */
-o-transition: all .25s ease; /* Opera */
transition: all .25s ease;
max-width: 100%;
max-height: 100%;
}
.image:hover img {
-webkit-transform:scale(1.05); /* Safari and Chrome */
-moz-transform:scale(1.05); /* Firefox */
-ms-transform:scale(1.05); /* IE 9 */
-o-transform:scale(1.05); /* Opera */
transform:scale(1.05);
}
.image:active img {
-webkit-transform:scale(.95); /* Safari and Chrome */
-moz-transform:scale(.95); /* Firefox */
-ms-transform:scale(.95); /* IE 9 */
-o-transform:scale(.95); /* Opera */
transform:scale(.95);
}
Enjoy it!
Changing the address's port number (localhost:) worked for me :)
Yes:
bigInt.sign = !(number < 0);
The !
operator always evaluates to true
or false
. When converted to int
, these become 1
and 0
respectively.
Of course this is equivalent to:
bigInt.sign = (number >= 0);
Here the parentheses are redundant but I add them for clarity. All of the comparison and relational operator evaluate to true
or false
.
Even if you have resolved your issue, here is another one try to export csv using mvc.
return new FileStreamResult(fileStream, "text/csv") { FileDownloadName = fileDownloadName };
I added TO_DATE
and it resolved issue.
Before modification - due to below condition i got this error
record_update_dt>='05-May-2017'
After modification - after adding to_date
, issue got resolved.
record_update_dt>=to_date('05-May-2017','DD-Mon-YYYY')
Use File.mkdirs()
:
File dir = new File("C:\\user\\Desktop\\dir1\\dir2");
dir.mkdirs();
File file = new File(dir, "filename.txt");
FileWriter newJsp = new FileWriter(file);
There's a free php script made by Celeron Dude that can do this called Celeron Dude Indexer 2. It doesn't require .htaccess
The source code is easy to understand and provides a good starting point.
Here's a download link: https://gitlab.com/desbest/celeron-dude-indexer/
Alternatively, you can delay the closing using the following code:
System.Threading.Thread.Sleep(1000);
Note the Sleep
is using milliseconds.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<button style="display:block;width:120px; height:30px;" onclick="document.getElementById('getFile').click()">Your text here</button>
<input type='file' id="getFile" style="display:none">
</body>
</html>
_x000D_
Another option is to download and install a new version using an installer.
The ultimate curl php function:
function getURL($url,$fields=null,$method=null,$file=null){
// author = Ighor Toth <[email protected]>
// required:
// url = include http or https
// optionals:
// fields = must be array (e.g.: 'field1' => $field1, ...)
// method = "GET", "POST"
// file = if want to download a file, declare store location and file name (e.g.: /var/www/img.jpg, ...)
// please crete 'cookies' dir to store local cookies if neeeded
// do not modify below
$useragent = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
$timeout= 240;
$dir = dirname(__FILE__);
$_SERVER["REMOTE_ADDR"] = $_SERVER["REMOTE_ADDR"] ?? '127.0.0.1';
$cookie_file = $dir . '/cookies/' . md5($_SERVER['REMOTE_ADDR']) . '.txt';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_ENCODING, "" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_AUTOREFERER, true );
curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com/');
if($file!=null){
if (!curl_setopt($ch, CURLOPT_FILE, $file)){ // Handle error
die("curl setopt bit the dust: " . curl_error($ch));
}
//curl_setopt($ch, CURLOPT_FILE, $file);
$timeout= 3600;
}
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout );
if($fields!=null){
$postvars = http_build_query($fields); // build the urlencoded data
if($method=="POST"){
// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
}
if($method=="GET"){
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$url = $url.'?'.$postvars;
}
}
curl_setopt($ch, CURLOPT_URL, $url);
$content = curl_exec($ch);
if (!$content){
$error = curl_error($ch);
$info = curl_getinfo($ch);
die("cURL request failed, error = {$error}; info = " . print_r($info, true));
}
if(curl_errno($ch)){
echo 'error:' . curl_error($ch);
} else {
return $content;
}
curl_close($ch);
}
%load_ext snakeviz
%%snakeviz
It just takes those 2 lines of code in a Jupyter notebook, and it generates a nice interactive diagram. For example:
Here is the code. Again, the 2 lines starting with %
are the only extra lines of code needed to use snakeviz:
# !pip install snakeviz
%load_ext snakeviz
import glob
import hashlib
%%snakeviz
files = glob.glob('*.txt')
def print_files_hashed(files):
for file in files:
with open(file) as f:
print(hashlib.md5(f.read().encode('utf-8')).hexdigest())
print_files_hashed(files)
It also seems possible to run snakeviz outside notebooks. More info on the snakeviz website.
This option works only if you can open the DB in a DB Browser like DB Browser for SQLite.
In DB Browser for SQLite:
This is the code to update the file but not to install This program is made through dos for copying files to the latest date and run your program automatically. may help you
open notepad and save file below with ext .bat
xcopy \\IP address\folder_share_name\*.* /s /y /d /q
start "label" /b "youraplicationname.exe"
Here's a simple, yet powerful example, using the apache class HierarchicalINIConfiguration:
HierarchicalINIConfiguration iniConfObj = new HierarchicalINIConfiguration(iniFile);
// Get Section names in ini file
Set setOfSections = iniConfObj.getSections();
Iterator sectionNames = setOfSections.iterator();
while(sectionNames.hasNext()){
String sectionName = sectionNames.next().toString();
SubnodeConfiguration sObj = iniObj.getSection(sectionName);
Iterator it1 = sObj.getKeys();
while (it1.hasNext()) {
// Get element
Object key = it1.next();
System.out.print("Key " + key.toString() + " Value " +
sObj.getString(key.toString()) + "\n");
}
Commons Configuration has a number of runtime dependencies. At a minimum, commons-lang and commons-logging are required. Depending on what you're doing with it, you may require additional libraries (see previous link for details).
This is badly formed HTML. You need to either have a single id or space separated classes. Either way if you're new I'd look into jQuery.
<div id="sub1">some text</div>
or
<div class="sub1 sub2 sub3">some text</div>
If you had the following HTML:
<div id="sub1">some text</div>
<div id="welcome" style="display:none;">Some welcome message</div>
$(document).ready(function() {
$('#sub1').hover(
function() { $('#welcome').show(); },
function() { $('#welcome').hide(); }
);
});
you'd probably want to include the events on your html:
<div id="sub1" onmouseover="showWelcome();" onmouseout="hideWelcome();">some text</div>
then your javascript would have these two functions
function showWelcome()
{
var welcome = document.getElementById('welcome');
welcome.style.display = 'block';
}
function hideWelcome()
{
var welcome = document.getElementById('welcome');
welcome.style.display = 'none';
}
Please note: this javascript doesn't take cross browser issues into consideration. for this you'd need to elaborate on your code, just another reason to use jquery.
I would suggest checking the drivers and updating them if required.
There are various methods available in Rust to concatenate strings
concat!()
):fn main() {
println!("{}", concat!("a", "b"))
}
The output of the above code is :
ab
push_str()
and +
operator):fn main() {
let mut _a = "a".to_string();
let _b = "b".to_string();
let _c = "c".to_string();
_a.push_str(&_b);
println!("{}", _a);
println!("{}", _a + &_c);
}
The output of the above code is:
ab
abc
Using format!()
):fn main() {
let mut _a = "a".to_string();
let _b = "b".to_string();
let _c = format!("{}{}", _a, _b);
println!("{}", _c);
}
The output of the above code is :
ab
Check it out and experiment with Rust playground.
It really depends on the situation, for me its in fpm as I'm using PHP5-FPM. A solution to your problem could be a universal php.ini and then using a symbolic link created like:
ln -s /etc/php5/php.ini php.ini
Then any modifications you make will be in one general .ini file. This is probably not really the best solution though, you might want to look into modifying some configuration so that you literally use one file, on one location. Not multiple locations hacked together.
POSIX 2008 added the +
marker to find
which means it now automatically groups as many files as are reasonable into a single command execution, very much like xargs
does, but with a number of advantages:
The file name issue is a problem with xargs
without the -0
option, and the 'run even with zero file names' issue is a problem with or without the -0
option — but GNU xargs
has the -r
or --no-run-if-empty
option to prevent that happening. Also, this notation cuts down on the number of processes, not that you're likely to measure the difference in performance. Hence, you could sensibly write:
find . -exec grep something {} +
find . -print | xargs grep something
If you're on Linux or have the GNU find
and xargs
commands, then use -print0
with find
and -0
with xargs
to handle file names containing spaces and other odd-ball characters.
find . -print0 | xargs -0 grep something
grep
If you don't want the file names (just the text) then add an appropriate option to grep
(usually -h
to suppressing 'headings'). To absolutely guarantee the file name is printed by grep
(even if only one file is found, or the last invocation of grep
is only given 1 file name), then add /dev/null
to the xargs
command line, so that there will always be at least two file names.
I'm using Java 8 and this worked for me.
Add the dependency on pom.xml
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.4.0</version>
</dependency>
and add JodaModule on your ObjectMapper
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
I am providing the modern answer.
To get the current date:
LocalDate today = LocalDate.now(ZoneId.of("America/Hermosillo"));
This gives you a LocalDate
object, which is what you should use for keeping a date in your program. A LocalDate
is a date without time of day.
Only when you need to display the date to a user, format it into a string suitable for the user’s locale:
DateTimeFormatter userFormatter
= DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
System.out.println(today.format(userFormatter));
When I ran this snippet today in US English locale, output was:
July 13, 2019
If you want it shorter, specify FormatStyle.MEDIUM
or even FormatStyle.SHORT
. DateTimeFormatter.ofLocalizedDate
uses the default formatting locale, so the point is that it will give output suitable for that locale, different for different locales.
If your user has very special requirements for the output format, use a format pattern string:
DateTimeFormatter userFormatter = DateTimeFormatter.ofPattern(
"d-MMM-u", Locale.forLanguageTag("ar-AE"));
13-???-2019
I am using and recommending java.time, the modern Java date and time API. DateFormat
, SimpleDateFormat
, Date
and Calendar
used in the question and/or many of the other answers, are poorly designed and long outdated. And java.time is so much nicer to work with.
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).I think it boils down to a personal preference.
Do you want to hide your silly mistakes before pushing your changes? If so, git pull --rebase
is perfect. It allows you to later squash your commits to a few (or one) commits. If you have merges in your (unpushed) history, it is not so easy to do a git rebase
later one.
I personally don't mind publishing all my silly mistakes, so I tend to merge instead of rebase.
All those implementation about finding the keyboard view and adding the done button at the 3rd row (that is why button.y = 163 b/c keyboard's height is 216) are fragile because iOS keeps change the view hierarchy. For example none of above codes work for iOS9.
I think it is more safe to just find the topmost view, by [[[UIApplication sharedApplication] windows] lastObject], and just add the button at bottom left corner of it, doneButton.frame = CGRectMake(0, SCREEN_HEIGHT-53, 106, 53);// portrait mode
This console warning is not an error or an actual problem — Chrome is just spreading the word about this new standard to increase developer adoption.
It has nothing to do with your code. It is something their web servers will have to support.
Release date for a fix is February 4, 2020 per: https://www.chromium.org/updates/same-site
February, 2020: Enforcement rollout for Chrome 80 Stable: The SameSite-by-default and SameSite=None-requires-Secure behaviors will begin rolling out to Chrome 80 Stable for an initial limited population starting the week of February 17, 2020, excluding the US President’s Day holiday on Monday. We will be closely monitoring and evaluating ecosystem impact from this initial limited phase through gradually increasing rollouts.
For the full Chrome release schedule, see here.
I solved same problem by adding in response header
response.setHeader("Set-Cookie", "HttpOnly;Secure;SameSite=Strict");
SameSite
prevents the browser from sending the cookie along with cross-site requests. The main goal is mitigating the risk of cross-origin information leakage. It also provides some protection against cross-site request forgery attacks. Possible values for the flag are Lax or Strict.
SameSite cookies explained here
Please refer this before applying any option.
Hope this helps you.
The format option %ai
was what I wanted:
%ai
: author date, ISO 8601-like format
--format="%ai"
you can try this code to solve your problem
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/login_selected" /> <!-- pressed -->
<item android:state_focused="true"
android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
<item android:drawable="@drawable/login" /> <!-- default -->
</selector>
write this code in your drawable make a new resource and name it what you want and then write the name of this drwable in the button same as we refer to image src in android
Simply, when you go from the login screen, not when finishing the login screen.
And then in all forward activities, use this for logout:
final Intent intent = new Intent(getBaseContext(), LoginScreen.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
It works perfectly.
I finally found a solution. I wasted hours just trying to figure what this issue was. I tried deleting all those files suggested above and it didn't work for me, I tried adding new inbound rules to firewall for myslqd.exe and it didn't work. The thing that is causing this error is MySQL port is misconfigured and the fix was really simple. if you are using Wamp or Xampp go to Main Folder/Bin/mysql/mysql/ and find a file named my.ini
Open my.ini file press CTRL + F and inside it search for PORT and change whatever value of port to - 3306 and save file;
After that go to Wamp icon at the bottom of the taskbar (system tray) and left click choose mysql option and click "test port 3306 used" and see if it gives you any error. you can also click use other port other than whatever is shown there and port 3306.
Goodluck. if it works comment.
Here is a JavaScript Implementation that fakes Breadth First Traversal with Depth First recursion. I'm storing the node values at each depth inside an array, inside of a hash. If a level already exists(we have a collision), so we just push to the array at that level. You could use an array instead of a JavaScript object as well since our levels are numeric and can serve as array indices. You can return nodes, values, convert to a Linked List, or whatever you want. I'm just returning values for the sake of simplicity.
BinarySearchTree.prototype.breadthFirstRec = function() {
var levels = {};
var traverse = function(current, depth) {
if (!current) return null;
if (!levels[depth]) levels[depth] = [current.value];
else levels[depth].push(current.value);
traverse(current.left, depth + 1);
traverse(current.right, depth + 1);
};
traverse(this.root, 0);
return levels;
};
var bst = new BinarySearchTree();
bst.add(20, 22, 8, 4, 12, 10, 14, 24);
console.log('Recursive Breadth First: ', bst.breadthFirstRec());
/*Recursive Breadth First:
{ '0': [ 20 ],
'1': [ 8, 22 ],
'2': [ 4, 12, 24 ],
'3': [ 10, 14 ] } */
Here is an example of actual Breadth First Traversal using an iterative approach.
BinarySearchTree.prototype.breadthFirst = function() {
var result = '',
queue = [],
current = this.root;
if (!current) return null;
queue.push(current);
while (current = queue.shift()) {
result += current.value + ' ';
current.left && queue.push(current.left);
current.right && queue.push(current.right);
}
return result;
};
console.log('Breadth First: ', bst.breadthFirst());
//Breadth First: 20 8 22 4 12 24 10 14
"Best" is a partially subjective decision. Use tuples for small return sets in the general case where an immutable is acceptable. A tuple is always preferable to a list when mutability is not a requirement.
For more complex return values, or for the case where formality is valuable (i.e. high value code) a named tuple is better. For the most complex case an object is usually best. However, it's really the situation that matters. If it makes sense to return an object because that is what you naturally have at the end of the function (e.g. Factory pattern) then return the object.
As the wise man said:
Premature optimization is the root of all evil (or at least most of it) in programming.
There is a pip source that makes this very easy.
If you have another version of opencv-python installed use this command to remove it to avoid conflicts:
pip uninstall opencv-python
Then install the contrib version with this:
pip install opencv-contrib-python
SIFT usage:
import cv2
sift = cv2.xfeatures2d.SIFT_create()
There are five ways to use SetOnClickListener:
First:
button.setOnClickListener {
// Do some work here
}
Second:
button.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View?) {
// Do some work here
}
})
Third:
button.setOnClickListener(View.OnClickListener { view ->
// Do some work here
})
Forth:
class MainActivity : AppCompatActivity(), View.OnClickListener{
lateinit var button : Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button = findViewById(R.id.button1)
button.setOnClickListener(this)
}
override fun onClick(view: View?) {
when(view?.id){
R.id.button1->{
// do some work here
}
}
}
}
Fifth:
class MainActivity : AppCompatActivity(){
lateinit var button : Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button = findViewById(R.id.button1)
button.setOnClickListener(listener)
}
val listener= View.OnClickListener { view ->
when (view.getId()) {
R.id.button1 -> {
// Do some work here
}
}
}
}
Cheers!
If you're using it in a switch case then you need to get the type of the enum even before you plug that value in the switch. For instance :
SomeEnum someEnum = SomeEnum.values()[1];
switch (someEnum) {
case GRAPES:
case BANANA: ...
And the enum is like:
public enum SomeEnum {
GRAPES("Grapes", 0),
BANANA("Banana", 1),
private String typeName;
private int typeId;
SomeEnum(String typeName, int typeId){
this.typeName = typeName;
this.typeId = typeId;
}
}
If anyone is looking for a way to create an instance of a class despite the class following the Singleton Pattern, here is a way to do it.
// Get Class instance
Class<?> clazz = Class.forName("myPackage.MyClass");
// Get the private constructor.
Constructor<?> cons = clazz.getDeclaredConstructor();
// Since it is private, make it accessible.
cons.setAccessible(true);
// Create new object.
Object obj = cons.newInstance();
This only works for classes that implement singleton pattern using a private constructor.
document.getElementById("someFormId").elements;
This collection will also contain <select>
, <textarea>
and <button>
elements (among others), but you probably want that.
You can only do it at compile time using templates, unless you use RTTI.
It lets you use the typeid function which will yield a pointer to a type_info structure which contains information about the type.
Read up on it at Wikipedia
You can create a Task with cancellation token, when you app goto background you can cancel this token.
You can do this in PCL https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/app-lifecycle
var cancelToken = new CancellationTokenSource();
Task.Factory.StartNew(async () => {
await Task.Delay(10000);
// call web API
}, cancelToken.Token);
//this stops the Task:
cancelToken.Cancel(false);
Anther solution is user Timer in Xamarin.Forms, stop timer when app goto background https://xamarinhelp.com/xamarin-forms-timer/
If you are on Linux then make sure your File name must match with the string passed in the load model methods the first argument.
$this->load->model('Order_Model','order_model');
You can use the second argument using that you can call methods from your model and it will work on Linux and windows as well
$result = $this->order_model->get_order_details($orderID);
this is how I do it
JAVASCRIPT:
var module = angular.module('yourModuleName', ['ui.router']);
module.run( ['$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
]);
HTML:
<pre id="uiRouterInfo">
$state = {{$state.current.name}}
$stateParams = {{$stateParams}}
$state full url = {{ $state.$current.url.source }}
</pre>
EXAMPLE
I'm starting to learn about this myself, being very new to android development and I found this video very helpful.
https://www.youtube.com/watch?v=qcotbMLjlA4
It specifically covers to to get JSONArray to JSONObject at 19:30 in the video.
Code from the video for JSONArray to JSONObject:
JSONArray queryArray = quoteJSONObject.names();
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < queryArray.length(); i++){
list.add(queryArray.getString(i));
}
for(String item : list){
Log.v("JSON ARRAY ITEMS ", item);
}
If removing empty lines means lines including any spaces, use:
grep '\S' FILE
For example:
$ printf "line1\n\nline2\n \nline3\n\t\nline4\n" > FILE
$ cat -v FILE
line1
line2
line3
line4
$ grep '\S' FILE
line1
line2
line3
line4
$ grep . FILE
line1
line2
line3
line4
See also:
If you're using Maven, it could be that it is not looking at the right place for the META-INF folder. Others have mentioned copying the folder, but another way that worked for me was to tell Maven where to look for it, using the <resources>
tag. See: http://maven.apache.org/plugins/maven-resources-plugin/examples/resource-directory.html
If you are using Windows.Data.Xml.Dom.XmlDocument
version of XmlDocument
(used in UWP apps for example), you can use yourXmlDocument.GetXml()
to get the XML as a string.
Unfortunately, combining multiple entity contexts into a single named connection isn't possible. If you want to use named connection strings from a .config file to define your Entity Framework connections, they will each have to have a different name. By convention, that name is typically the name of the context:
<add name="ModEntity" connectionString="metadata=res://*/ModEntity.csdl|res://*/ModEntity.ssdl|res://*/ModEntity.msl;provider=System.Data.SqlClient;provider connection string="Data Source=SomeServer;Initial Catalog=SomeCatalog;Persist Security Info=True;User ID=Entity;Password=SomePassword;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
<add name="Entity" connectionString="metadata=res://*/Entity.csdl|res://*/Entity.ssdl|res://*/Entity.msl;provider=System.Data.SqlClient;provider connection string="Data Source=SOMESERVER;Initial Catalog=SOMECATALOG;Persist Security Info=True;User ID=Entity;Password=Entity;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
However, if you end up with namespace conflicts, you can use any name you want and simply pass the correct name to the context when it is generated:
var context = new Entity("EntityV2");
Obviously, this strategy works best if you are using either a factory or dependency injection to produce your contexts.
Another option would be to produce each context's entire connection string programmatically, and then pass the whole string in to the constructor (not just the name).
// Get "Data Source=SomeServer..."
var innerConnectionString = GetInnerConnectionStringFromMachinConfig();
// Build the Entity Framework connection string.
var connectionString = CreateEntityConnectionString("Entity", innerConnectionString);
var context = new EntityContext(connectionString);
How about something like this:
Type contextType = typeof(test_Entities);
string innerConnectionString = ConfigurationManager.ConnectionStrings["Inner"].ConnectionString;
string entConnection =
string.Format(
"metadata=res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl;provider=System.Data.SqlClient;provider connection string=\"{1}\"",
contextType.Name,
innerConnectionString);
object objContext = Activator.CreateInstance(contextType, entConnection);
return objContext as test_Entities;
... with the following in your machine.config:
<add name="Inner" connectionString="Data Source=SomeServer;Initial Catalog=SomeCatalog;Persist Security Info=True;User ID=Entity;Password=SomePassword;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
This way, you can use a single connection string for every context in every project on the machine.
For anyone wishing to do this in a single line (e.g in the Display/Immediate window, a watch expression or similar in a debug session), the following will do so and "pretty print" the SQL:
new org.hibernate.jdbc.util.BasicFormatterImpl().format((new org.hibernate.loader.criteria.CriteriaJoinWalker((org.hibernate.persister.entity.OuterJoinLoadable)((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getEntityPersister(((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getImplementors(((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName())[0]),new org.hibernate.loader.criteria.CriteriaQueryTranslator(((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),((org.hibernate.impl.CriteriaImpl)crit),((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),org.hibernate.loader.criteria.CriteriaQueryTranslator.ROOT_SQL_ALIAS),((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),(org.hibernate.impl.CriteriaImpl)crit,((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),((org.hibernate.impl.CriteriaImpl)crit).getSession().getEnabledFilters())).getSQLString());
...or here's an easier to read version:
new org.hibernate.jdbc.util.BasicFormatterImpl().format(
(new org.hibernate.loader.criteria.CriteriaJoinWalker(
(org.hibernate.persister.entity.OuterJoinLoadable)
((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getEntityPersister(
((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getImplementors(
((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName())[0]),
new org.hibernate.loader.criteria.CriteriaQueryTranslator(
((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),
((org.hibernate.impl.CriteriaImpl)crit),
((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),
org.hibernate.loader.criteria.CriteriaQueryTranslator.ROOT_SQL_ALIAS),
((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),
(org.hibernate.impl.CriteriaImpl)crit,
((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),
((org.hibernate.impl.CriteriaImpl)crit).getSession().getEnabledFilters()
)
).getSQLString()
);
Notes:
crit
. If named differently, do a search and replace.getEnabledFilters
rather than getLoadQueryInfluencers()
for backwards compatibility since the latter was introduced in a later version of Hibernate (3.5???)to disable
document.getElementById("btnPlaceOrder").disabled = true;
to enable
document.getElementById("btnPlaceOrder").disabled = false;
I was looking for a similar solution and this is what I would suggest. In the OnTouch method, record the time for MotionEvent.ACTION_DOWN event and then for MotionEvent.ACTION_UP, record the time again. This way you can set your own threshold also. After experimenting few times you will know the max time in millis it would need to record a simple touch and you can use this in move or other method as you like.
Hope this helped. Please comment if you used a different method and solved your problem.
Try moving the --exclude
to before the include.
tar -pczf MyBackup.tar.gz --exclude "/home/user/public_html/tmp/" /home/user/public_html/
Do this :
<script type="text/javascript"> function showDetails(username) { window.location = '/player_detail?username='+username; } </script> <input type="button" name="theButton" value="Detail" onclick="showDetails('username');">
Here's an example that let's you set the color of the background. If you don't want to use float, then you might need to set the width and height manually. But even that really depends on the surrounding CSS/HTML.
<style>
#color {
background-color: red;
float: left;
}#opacity {
opacity : 0.4;
filter: alpha(opacity=40);
}
</style>
<div id="color">
<div id="opacity">
<img src="image.jpg" />
</div>
</div>
string is a shortcut for System.String
. The only difference is that you don´t need to reference to System.String
namespace. So would be better using string than String.
Abstract:
The reason why you are getting this error
message is because you are trying to call a method on an int
type of a variable. This would work if would have called len()
function on a list
type of a variable. Let's examin the two cases:
Fail:
num = 10
print(len(num))
The above will produce an error similar to yours due to calling len()
function on an int
type of a variable;
Success:
data = [0, 4, 8, 9, 12]
print(len(data))
The above will work since you are calling a function on a list
type of a variable;
This is a old question, and the OP seems to mix C++ and C in his intends/examples. In C, when you pass a array to a function, it's decayed to pointer. So, there is no way to pass the array size except by using a second argument in your function that stores the array size:
void func(int A[])
// should be instead: void func(int * A, const size_t elemCountInA)
They are very few cases, where you don't need this, like when you're using multidimensional arrays:
void func(int A[3][whatever here]) // That's almost as if read "int* A[3]"
Using the array notation in a function signature is still useful, for the developer, as it might be an help to tell how many elements your functions expects. For example:
void vec_add(float out[3], float in0[3], float in1[3])
is easier to understand than this one (although, nothing prevent accessing the 4th element in the function in both functions):
void vec_add(float * out, float * in0, float * in1)
If you were to use C++, then you can actually capture the array size and get what you expect:
template <size_t N>
void vec_add(float (&out)[N], float (&in0)[N], float (&in1)[N])
{
for (size_t i = 0; i < N; i++)
out[i] = in0[i] + in1[i];
}
In that case, the compiler will ensure that you're not adding a 4D vector with a 2D vector (which is not possible in C without passing the dimension of each dimension as arguments of the function). There will be as many instance of the vec_add function as the number of dimensions used for your vectors.
This old question has a new answer. There are a few "async" solutions for PHP this days (which are equivalent to Python's multiprocess in the sense that they spawn new independent PHP processes rather than manage it at the framework level)
The two solutions I have seen are
Give them a try!
If you do not care about tick shifting (depending on how long did it took previously on each execution) and you do not want to use channels, it's possible to use native range function.
i.e.
package main
import "fmt"
import "time"
func main() {
go heartBeat()
time.Sleep(time.Second * 5)
}
func heartBeat() {
for range time.Tick(time.Second * 1) {
fmt.Println("Foo")
}
}
Using split(), you just have to change what you wish to split on.
public static String reverseString(String str)
{
String[] rstr;
String result = "";
int count = 0;
rstr = str.split(" ");
String words[] = new String[rstr.length];
for(int i = rstr.length-1; i >= 0; i--)
{
words[count] = rstr[i];
count++;
}
for(int j = 0; j <= words.length-1; j++)
{
result += words[j] + " ";
}
return result;
}
There's nothing wrong with saving the whole history in the database, they are prepared for that kind of tasks.
Actually you can find here in Stack Overflow a link to an example schema for a chat: example
If you are still worried for the size, you could apply some optimizations to group messages, like adding a buffer to your application that you only push after some time (like 1 minute or so); that way you would avoid having only 1 line messages
Here's some Python 2 / Python 3 code that generates timing information for both list-based and set-based methods of finding the intersection of two lists.
The pure list comprehension algorithms are O(n^2), since in
on a list is a linear search. The set-based algorithms are O(n), since set search is O(1), and set creation is O(n) (and converting a set to a list is also O(n)). So for sufficiently large n the set-based algorithms are faster, but for small n the overheads of creating the set(s) make them slower than the pure list comp algorithms.
#!/usr/bin/env python
''' Time list- vs set-based list intersection
See http://stackoverflow.com/q/3697432/4014959
Written by PM 2Ring 2015.10.16
'''
from __future__ import print_function, division
from timeit import Timer
setup = 'from __main__ import a, b'
cmd_lista = '[u for u in a if u in b]'
cmd_listb = '[u for u in b if u in a]'
cmd_lcsa = 'sa=set(a);[u for u in b if u in sa]'
cmd_seta = 'list(set(a).intersection(b))'
cmd_setb = 'list(set(b).intersection(a))'
reps = 3
loops = 50000
def do_timing(heading, cmd, setup):
t = Timer(cmd, setup)
r = t.repeat(reps, loops)
r.sort()
print(heading, r)
return r[0]
m = 10
nums = list(range(6 * m))
for n in range(1, m + 1):
a = nums[:6*n:2]
b = nums[:6*n:3]
print('\nn =', n, len(a), len(b))
#print('\nn = %d\n%s %d\n%s %d' % (n, a, len(a), b, len(b)))
la = do_timing('lista', cmd_lista, setup)
lb = do_timing('listb', cmd_listb, setup)
lc = do_timing('lcsa ', cmd_lcsa, setup)
sa = do_timing('seta ', cmd_seta, setup)
sb = do_timing('setb ', cmd_setb, setup)
print(la/sa, lb/sa, lc/sa, la/sb, lb/sb, lc/sb)
output
n = 1 3 2
lista [0.082171916961669922, 0.082588911056518555, 0.0898590087890625]
listb [0.069530963897705078, 0.070394992828369141, 0.075379848480224609]
lcsa [0.11858987808227539, 0.1188349723815918, 0.12825107574462891]
seta [0.26900982856750488, 0.26902294158935547, 0.27298116683959961]
setb [0.27218389511108398, 0.27459001541137695, 0.34307217597961426]
0.305460649521 0.258469975867 0.440838458259 0.301898526833 0.255455833892 0.435697630214
n = 2 6 4
lista [0.15915989875793457, 0.16000485420227051, 0.16551494598388672]
listb [0.13000702857971191, 0.13060092926025391, 0.13543915748596191]
lcsa [0.18650484085083008, 0.18742108345031738, 0.19513416290283203]
seta [0.33592700958251953, 0.34001994132995605, 0.34146714210510254]
setb [0.29436492919921875, 0.2953648567199707, 0.30039691925048828]
0.473793098554 0.387009751735 0.555194537893 0.540689066428 0.441652573672 0.633583767462
n = 3 9 6
lista [0.27657914161682129, 0.28098297119140625, 0.28311991691589355]
listb [0.21585917472839355, 0.21679902076721191, 0.22272896766662598]
lcsa [0.22559309005737305, 0.2271728515625, 0.2323150634765625]
seta [0.36382699012756348, 0.36453008651733398, 0.36750602722167969]
setb [0.34979605674743652, 0.35533690452575684, 0.36164689064025879]
0.760194128313 0.59330170819 0.62005595016 0.790686848184 0.61710008036 0.644927481902
n = 4 12 8
lista [0.39616990089416504, 0.39746403694152832, 0.41129183769226074]
listb [0.33485794067382812, 0.33914685249328613, 0.37850618362426758]
lcsa [0.27405810356140137, 0.2745978832244873, 0.28249192237854004]
seta [0.39211201667785645, 0.39234519004821777, 0.39317893981933594]
setb [0.36988520622253418, 0.37011313438415527, 0.37571001052856445]
1.01034878821 0.85398540833 0.698928091731 1.07106176249 0.905302334456 0.740927452493
n = 5 15 10
lista [0.56792402267456055, 0.57422614097595215, 0.57740211486816406]
listb [0.47309303283691406, 0.47619009017944336, 0.47628307342529297]
lcsa [0.32805585861206055, 0.32813096046447754, 0.3349759578704834]
seta [0.40036201477050781, 0.40322518348693848, 0.40548801422119141]
setb [0.39103078842163086, 0.39722800254821777, 0.43811702728271484]
1.41852623806 1.18166313332 0.819398061028 1.45237674242 1.20986133789 0.838951479847
n = 6 18 12
lista [0.77897095680236816, 0.78187918663024902, 0.78467702865600586]
listb [0.629547119140625, 0.63210701942443848, 0.63321495056152344]
lcsa [0.36563992500305176, 0.36638498306274414, 0.38175487518310547]
seta [0.46695613861083984, 0.46992206573486328, 0.47583580017089844]
setb [0.47616910934448242, 0.47661614418029785, 0.4850609302520752]
1.66818870637 1.34819326075 0.783028414812 1.63591241329 1.32210827369 0.767878297495
n = 7 21 14
lista [0.9703209400177002, 0.9734041690826416, 1.0182771682739258]
listb [0.82394003868103027, 0.82625699043273926, 0.82796716690063477]
lcsa [0.40975093841552734, 0.41210508346557617, 0.42286920547485352]
seta [0.5086359977722168, 0.50968098640441895, 0.51014018058776855]
setb [0.48688101768493652, 0.4879908561706543, 0.49204087257385254]
1.90769222837 1.61990115188 0.805587768483 1.99293236904 1.69228211566 0.841583309951
n = 8 24 16
lista [1.204819917678833, 1.2206029891967773, 1.258256196975708]
listb [1.014998197555542, 1.0206191539764404, 1.0343101024627686]
lcsa [0.50966787338256836, 0.51018595695495605, 0.51319599151611328]
seta [0.50310111045837402, 0.50556015968322754, 0.51335406303405762]
setb [0.51472997665405273, 0.51948785781860352, 0.52113485336303711]
2.39478683834 2.01748351664 1.01305257092 2.34068341135 1.97190418975 0.990165516871
n = 9 27 18
lista [1.511646032333374, 1.5133969783782959, 1.5639569759368896]
listb [1.2461750507354736, 1.254518985748291, 1.2613379955291748]
lcsa [0.5565330982208252, 0.56119203567504883, 0.56451296806335449]
seta [0.5966339111328125, 0.60275578498840332, 0.64791703224182129]
setb [0.54694414138793945, 0.5508568286895752, 0.55375313758850098]
2.53362406013 2.08867620074 0.932788243907 2.76380331728 2.27843203069 1.01753187594
n = 10 30 20
lista [1.7777848243713379, 2.1453688144683838, 2.4085969924926758]
listb [1.5070111751556396, 1.5202279090881348, 1.5779800415039062]
lcsa [0.5954139232635498, 0.59703707695007324, 0.60746097564697266]
seta [0.61563014984130859, 0.62125110626220703, 0.62354087829589844]
setb [0.56723213195800781, 0.57257509231567383, 0.57460403442382812]
2.88774814689 2.44791645689 0.967161734066 3.13413984189 2.6567803378 1.04968299523
Generated using a 2GHz single core machine with 2GB of RAM running Python 2.6.6 on a Debian flavour of Linux (with Firefox running in the background).
These figures are only a rough guide, since the actual speeds of the various algorithms are affected differently by the proportion of elements that are in both source lists.
You may use these...
Parameters:
%date:~4,2% -- month
%date:~7,2% -- days
%date:~10,4% -- years
%time:~1,1% -- hours
%time:~3,2% -- minutes
%time:~6,2% -- seconds
%time:~9,2% -- mili-seconds
%date:~4,2%%date:~7,2%%date:~10,4% : MMDDYYYY
%date:~7,2%%date:~4,2%%date:~10,4% : DDMMYYYY
%date:~10,4%%date:~4,2%%date:~7,2% : YYYYMMDD
In summary, valid characters in the text are:
&
and <
.>
is not valid if following ]]
.Sections 2.2 and 2.4 of the XML specification provide the answer in detail:
Characters
Legal characters are tab, carriage return, line feed, and the legal characters of Unicode and ISO/IEC 10646
Character data
The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. If they are needed elsewhere, they must be escaped using either numeric character references or the strings " & " and " < " respectively. The right angle bracket (>) may be represented using the string " > ", and must, for compatibility, be escaped using either " > " or a character reference when it appears in the string " ]]> " in content, when that string is not marking the end of a CDATA section.
You were just missing the second half of the column statement telling it to remove the entire column, since most normal Ranges start with a Column Letter, it was looking for a number and didn't get one. The ":" gets the whole column, or row.
I think what you were looking for in your Range was this:
Range("C:C,F:F,I:I,L:L,O:O,R:R").Delete
Just change the column letters to match your needs.
Here's yet another way to skin this cat, using a dictionary to map new values onto the keys in the list:
def map_values(row, values_dict):
return values_dict[row]
values_dict = {'A': 1, 'B': 2, 'C': 3, 'D': 4}
df = pd.DataFrame({'INDICATOR': ['A', 'B', 'C', 'D'], 'VALUE': [10, 9, 8, 7]})
df['NEW_VALUE'] = df['INDICATOR'].apply(map_values, args = (values_dict,))
What's it look like:
df
Out[2]:
INDICATOR VALUE NEW_VALUE
0 A 10 1
1 B 9 2
2 C 8 3
3 D 7 4
This approach can be very powerful when you have many ifelse
-type statements to make (i.e. many unique values to replace).
And of course you could always do this:
df['NEW_VALUE'] = df['INDICATOR'].map(values_dict)
But that approach is more than three times as slow as the apply
approach from above, on my machine.
And you could also do this, using dict.get
:
df['NEW_VALUE'] = [values_dict.get(v, None) for v in df['INDICATOR']]
Very similar to peixe.
You don't have to mention the number if the variables you add as parameters are in order of appearance
f = open('{}.csv'.format(name), 'wb')
Another option - the f-string formatting (ref):
f = open(f"{name}.csv", 'wb')
I used the System.Xml.Linq.XElement for the purpose. Just check code below for reading the value of first child node of the xml(not the root node).
string textXml = "<xmlroot><firstchild>value of first child</firstchild>........</xmlroot>";
XElement xmlroot = XElement.Parse(textXml);
string firstNodeContent = ((System.Xml.Linq.XElement)(xmlroot.FirstNode)).Value;
This is a tweak from previous answer for python 3.x from @GShocked, I would post it to the comment, but dont have enough reputation
import sys
import argparse
import cv2
print(cv2.__version__)
def extractImages(pathIn, pathOut):
vidcap = cv2.VideoCapture(pathIn)
success,image = vidcap.read()
count = 0
success = True
while success:
success,image = vidcap.read()
print ('Read a new frame: ', success)
cv2.imwrite( pathOut + "\\frame%d.jpg" % count, image) # save frame as JPEG file
count += 1
if __name__=="__main__":
print("aba")
a = argparse.ArgumentParser()
a.add_argument("--pathIn", help="path to video")
a.add_argument("--pathOut", help="path to images")
args = a.parse_args()
print(args)
extractImages(args.pathIn, args.pathOut)
In my case,
but still I was getting the error as lombok is incompatible and getter and setters was not recognized. with further checking I found that recently my intelliJ version got upgraded and the old Lombok plugin is not compatible.
Go to Preference -> Plugins -> Search lombok and update
OR
Go to Preference -> Plugins -> Search lombok-> Uninstall restart IDE and install again from MarketPlace
My preferred method:
if (*ptr == 0) // empty string
Probably more common:
if (strlen(ptr) == 0) // empty string
I had the same problem when using a 32 bit version of java in a 64 bit environment. When using 64 java in a 64 OS it was ok.
I think that one important point that was not mentioned in the previous answers is that, if not explicitly indicated, the matlab interpreter will remain open.
Therefore, to the answer of @hkBattousai I will add the exit
command:
"C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "run('C:\<a long path here>\mfile.m');exit;"