public static List<SelectListItem> States = new List<SelectListItem>()
{
new SelectListItem() {Text="Alabama", Value="AL"},
new SelectListItem() { Text="Alaska", Value="AK"},
new SelectListItem() { Text="Arizona", Value="AZ"},
new SelectListItem() { Text="Arkansas", Value="AR"},
new SelectListItem() { Text="California", Value="CA"},
new SelectListItem() { Text="Colorado", Value="CO"},
new SelectListItem() { Text="Connecticut", Value="CT"},
new SelectListItem() { Text="District of Columbia", Value="DC"},
new SelectListItem() { Text="Delaware", Value="DE"},
new SelectListItem() { Text="Florida", Value="FL"},
new SelectListItem() { Text="Georgia", Value="GA"},
new SelectListItem() { Text="Hawaii", Value="HI"},
new SelectListItem() { Text="Idaho", Value="ID"},
new SelectListItem() { Text="Illinois", Value="IL"},
new SelectListItem() { Text="Indiana", Value="IN"},
new SelectListItem() { Text="Iowa", Value="IA"},
new SelectListItem() { Text="Kansas", Value="KS"},
new SelectListItem() { Text="Kentucky", Value="KY"},
new SelectListItem() { Text="Louisiana", Value="LA"},
new SelectListItem() { Text="Maine", Value="ME"},
new SelectListItem() { Text="Maryland", Value="MD"},
new SelectListItem() { Text="Massachusetts", Value="MA"},
new SelectListItem() { Text="Michigan", Value="MI"},
new SelectListItem() { Text="Minnesota", Value="MN"},
new SelectListItem() { Text="Mississippi", Value="MS"},
new SelectListItem() { Text="Missouri", Value="MO"},
new SelectListItem() { Text="Montana", Value="MT"},
new SelectListItem() { Text="Nebraska", Value="NE"},
new SelectListItem() { Text="Nevada", Value="NV"},
new SelectListItem() { Text="New Hampshire", Value="NH"},
new SelectListItem() { Text="New Jersey", Value="NJ"},
new SelectListItem() { Text="New Mexico", Value="NM"},
new SelectListItem() { Text="New York", Value="NY"},
new SelectListItem() { Text="North Carolina", Value="NC"},
new SelectListItem() { Text="North Dakota", Value="ND"},
new SelectListItem() { Text="Ohio", Value="OH"},
new SelectListItem() { Text="Oklahoma", Value="OK"},
new SelectListItem() { Text="Oregon", Value="OR"},
new SelectListItem() { Text="Pennsylvania", Value="PA"},
new SelectListItem() { Text="Rhode Island", Value="RI"},
new SelectListItem() { Text="South Carolina", Value="SC"},
new SelectListItem() { Text="South Dakota", Value="SD"},
new SelectListItem() { Text="Tennessee", Value="TN"},
new SelectListItem() { Text="Texas", Value="TX"},
new SelectListItem() { Text="Utah", Value="UT"},
new SelectListItem() { Text="Vermont", Value="VT"},
new SelectListItem() { Text="Virginia", Value="VA"},
new SelectListItem() { Text="Washington", Value="WA"},
new SelectListItem() { Text="West Virginia", Value="WV"},
new SelectListItem() { Text="Wisconsin", Value="WI"},
new SelectListItem() { Text="Wyoming", Value="WY"}
};
How we do it is put this method into a class and then call the class from the view
@Html.DropDownListFor(x => x.State, Class.States)
Create a tar archive file on the fly and pipe that to md5sum
:
tar c dir | md5sum
This produces a single md5sum that should be unique to your file and sub-directory setup. No files are created on disk.
This should work. I converted the date to unix time via strtotime.
foreach ($originalArray as $key => $part) {
$sort[$key] = strtotime($part['datetime']);
}
array_multisort($sort, SORT_DESC, $originalArray);
One-liner version would be using multiple array methods:
array_multisort(array_map('strtotime',array_column($originalArray,'datetime')),
SORT_DESC,
$originalArray);
In Mgmt Studio, when you are editing the top 200, you can view the SQL pane - either by right clicking in the grid and choosing Pane->SQL or by the button in the upper left. This will allow you to write a custom query to drill down to the row(s) you want to edit.
But ultimately mgmt studio isn't a data entry/update tool which is why this is a little cumbersome.
You can put an apostrophe in a single quoted JavaScript string by escaping it with a backslash, like so:
theAnchorText = 'I\'m home';
The solution that work for is were add the next dependency to my pom.xml file.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
I have inherited a desktop app that makes calls to a series of Web Services on IIS. The web services (also) have to be able to run timed processes, independently (without having the client on). Hence they all have timers. The web service timers were shutting down (memory leak?) so we set the Idle time out to 0 and timers stay on.
I would use:
awk 'FNR <= 1' file_*.txt
As @Kusalananda points out there are many ways to capture the first line in command line but using the head -n 1
may not be the best option when using wildcards since it will print additional info. Changing 'FNR == i'
to 'FNR <= i'
allows to obtain the first i lines.
For example, if you have n files named file_1.txt, ... file_n.txt:
awk 'FNR <= 1' file_*.txt
hello
...
bye
But with head
wildcards print the name of the file:
head -1 file_*.txt
==> file_1.csv <==
hello
...
==> file_n.csv <==
bye
I had the same problem. I copied the example code from Google code, and could not compile.
xmlns:ads="http://schemas.android.com/apk/res/com.google.example"
Finally, I figured it out. The last part of the code "com.google.example
", is their package name, so you need to replace it with your project package.
For example, my project package is "com.jms.AdmobExample
", so my ads
naming space is:
xmlns:ads="http://schemas.android.com/apk/res/com.jms.AdmobExample"
Check my example, it works fine. You can download the APK to try. I also put my source code here: Add Google Admob in Android Application
What works for me is to kill and start the adb server again. On linux: sudo adb kill-server
and then sudo adb start-server
. Then it will detect nearly every device out of the box.
I think Amith Koujalgi is correct but also, in cases where the webservice responses are in JSON then it might be more useful to see the results in a clean JSON format instead of a very long string. Just add | grep }| python -mjson.tool to the end of curl commands here is two examples:
GET approach with JSON result
curl -i -H "Accept: application/json" http://someHostName/someEndpoint | grep }| python -mjson.tool
POST approach with JSON result
curl -X POST -H "Accept: Application/json" -H "Content-Type: application/json" http://someHostName/someEndpoint -d '{"id":"IDVALUE","name":"Mike"}' | grep }| python -mjson.tool
The problem in your code is xml.LoadXml(filePath);
LoadXml
method take parameter as xml data not the xml file path
Try this code
string xmlFile = File.ReadAllText(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xmlFile);
XmlNodeList nodeList = xmldoc.GetElementsByTagName("Short_Fall");
string Short_Fall=string.Empty;
foreach (XmlNode node in nodeList)
{
Short_Fall = node.InnerText;
}
Edit
Seeing the last edit of your question i found the solution,
Just replace the below 2 lines
XmlNode node = xml.SelectSingleNode("/Data[@*]/Short_Fall");
string id = node["Short_Fall"].InnerText; // Exception occurs here ("Object reference not set to an instance of an object.")
with
string id = xml.SelectSingleNode("Data/Short_Fall").InnerText;
It should solve your problem or you can use the solution i provided earlier.
According to this answer, you just don't include minsdkversion in the manifest.xml, and the build system will use the values from the build.gradle file and put the information into the final apk.
Because the build system needs this information anyway, this makes sense. You should not need to define this values two times.
You just have to sync the project after changing the build.gradle
file, but Android Studio 0.5.2 display a yellow status bar on top of the build.gradle editor window to help you
Also note there at least two build.gradle
files: one master and one for the app/module. The one to change is in the app/module, it already includes a property minSdkVersion
in a newly generated project.
This can be an efficient way of performing different tests on a single statement
select
case colour_txt
when 'red' then 5
when 'green' then 4
when 'orange' then 3
else 0
end as Pass_Flag
this only works on equality comparisons!
By default, Sublime Text set 'UTF8 without BOM'
, but that wasn't specified.
The only specicified things is 'UTF8 with BOM'
.
Hope this help :)
Simply add this CSS:
html, body {
overflow-x: hidden;
}
body {
position: relative
}
Use numpy.asarray
:
import numpy as np
myarray = np.asarray(mylist)
About the INT, TINYINT... These are different data types, INT is 4-byte number, TINYINT is 1-byte number. More information here - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT.
The syntax of TINYINT data type is TINYINT(M), where M indicates the maximum display width (used only if your MySQL client supports it).
To see the full code(query) written in stored procedure/ functions, Use below Command:
sp_helptext procedure/function_name
for function name and procedure name don't add prefix 'dbo.' or 'sys.'.
don't add brackets at the end of procedure or function name and also don't pass the parameters.
use sp_helptext keyword and then just pass the procedure/ function name.
use below command to see full code written for Procedure:
sp_helptext ProcedureName
use below command to see full code written for function:
sp_helptext FunctionName
Interestingly enough, it is possible to initialize arrays in any way at any time in the program, provided they are members of a struct
or union
.
Example program:
#include <stdio.h>
struct ccont
{
char array[32];
};
struct icont
{
int array[32];
};
int main()
{
int cnt;
char carray[32] = { 'A', 66, 6*11+1 }; // 'A', 'B', 'C', '\0', '\0', ...
int iarray[32] = { 67, 42, 25 };
struct ccont cc = { 0 };
struct icont ic = { 0 };
/* these don't work
carray = { [0]=1 }; // expected expression before '{' token
carray = { [0 ... 31]=1 }; // (likewise)
carray = (char[32]){ [0]=3 }; // incompatible types when assigning to type 'char[32]' from type 'char *'
iarray = (int[32]){ 1 }; // (likewise, but s/char/int/g)
*/
// but these perfectly work...
cc = (struct ccont){ .array='a' }; // 'a', '\0', '\0', '\0', ...
// the following is a gcc extension,
cc = (struct ccont){ .array={ [0 ... 2]='a' } }; // 'a', 'a', 'a', '\0', '\0', ...
ic = (struct icont){ .array={ 42,67 } }; // 42, 67, 0, 0, 0, ...
// index ranges can overlap, the latter override the former
// (no compiler warning with -Wall -Wextra)
ic = (struct icont){ .array={ [0 ... 1]=42, [1 ... 2]=67 } }; // 42, 67, 67, 0, 0, ...
for (cnt=0; cnt<5; cnt++)
printf("%2d %c %2d %c\n",iarray[cnt], carray[cnt],ic.array[cnt],cc.array[cnt]);
return 0;
}
There appears to be a bug with appendTo using a frameset ID appending to a FORM in Chrome. Swapped out the attribute type directly with div and it works.
Full days between end of month and start of today, including the last day of the month:
SELECT LAST_DAY (TRUNC(SysDate)) - TRUNC(SysDate) + 1 FROM dual
Days between using exact time:
SELECT SysDate - TO_DATE('2018-01-01','YYYY-MM-DD') FROM dual
The Timer function also applies to Access 2007, Access 2010, Access 2013, Access 2016, Access 2007 Developer, Access 2010 Developer, Access 2013 Developer. Insert this code to to pause time for certain amount of seconds
T0 = Timer
Do
Delay = Timer - T0
Loop Until Delay = 1 'Change this value to pause time in second
There are a lot of jQuery plugins available for this
Thickbox Examples
For a single image
- Create a link element ()
- Give the link a class attribute with a value of thickbox (class="thickbox")
- Provide a path in the href attribute to an image file (.jpg .jpeg .png .gif .bmp)
I also faced this issue and struggled hours to solve it, I have tried all of the above options but nothing solved my problem. This issue occurs due to version mismatch of angular/cli and angular-devkit, so I did the following :
Manually changed version of files:
@angular-devkit/build-angular": "^0.13.9",
@angular/cli": "~7.0.3",
//This is for Angular7, for Angular8 : 0.803.23
Deleted package-lock.json
It solved my problem.
Using Android Studio 3.4.1, it no longer creates layout-land
folder. It will create a folder and put two layout files together.
Replacing one string with another can be done in the below methods
Method 1: Using String replaceAll
String myInput = "HelloBrother";
String myOutput = myInput.replaceAll("HelloBrother", "Brother"); // Replace hellobrother with brother
---OR---
String myOutput = myInput.replaceAll("Hello", ""); // Replace hello with empty
System.out.println("My Output is : " +myOutput);
Method 2: Using Pattern.compile
import java.util.regex.Pattern;
String myInput = "JAVAISBEST";
String myOutputWithRegEX = Pattern.compile("JAVAISBEST").matcher(myInput).replaceAll("BEST");
---OR -----
String myOutputWithRegEX = Pattern.compile("JAVAIS").matcher(myInput).replaceAll("");
System.out.println("My Output is : " +myOutputWithRegEX);
Method 3: Using Apache Commons
as defined in the link below:
http://commons.apache.org/proper/commons-lang/javadocs/api-z.1/org/apache/commons/lang3/StringUtils.html#replace(java.lang.String, java.lang.String, java.lang.String)
Please let me know if it is not easy:
var jsonObject = {
name: 'Amit Kumar',
Age: '27'
};
for (var prop in jsonObject) {
alert("Key:" + prop);
alert("Value:" + jsonObject[prop]);
}
Try this:
Custom formula is
=countif(A:A,A1)>1
(or change A
to your chosen column)A1:A100
).Anything written in the A1:A100 cells will be checked, and if there is a duplicate (occurs more than once) then it'll be coloured.
For locales using comma (,
) as a decimal separator, the argument separator is most likely a semi-colon (;
). That is, try: =countif(A:A;A1)>1
, instead.
For multiple columns, use countifs
.
With Bootstrap 4+, you can simply add the class custom-select
for your select inputs to drop the browser-specific styling and keep the arrow icons.
Documentation Here: Bootstrap 4 Custom Forms Select Menu
Improving on the answer by musiphil, you can write a standard deviation function without the temporary vector diff
, just using a single inner_product
call with the C++11 lambda capabilities:
double stddev(std::vector<double> const & func)
{
double mean = std::accumulate(func.begin(), func.end(), 0.0) / func.size();
double sq_sum = std::inner_product(func.begin(), func.end(), func.begin(), 0.0,
[](double const & x, double const & y) { return x + y; },
[mean](double const & x, double const & y) { return (x - mean)*(y - mean); });
return std::sqrt(sq_sum / func.size());
}
I suspect doing the subtraction multiple times is cheaper than using up additional intermediate storage, and I think it is more readable, but I haven't tested the performance yet.
If your batch file is not interactive and you don't need to see it run then this should work.
@echo off
call file.bat >textfile.txt 2>&1
Otherwise use a tee
filter. There are many, some not NT compatible. SFK the Swiss Army Knife has a tee feature and is still being developed. Maybe that will work for you.
Most layout managers work best with a component's preferredSize, and most GUI's are best off allowing the components they contain to set their own preferredSizes based on their content or properties. To use these layout managers to their best advantage, do call pack()
on your top level containers such as your JFrames before making them visible as this will tell these managers to do their actions -- to layout their components.
Often when I've needed to play a more direct role in setting the size of one of my components, I'll override getPreferredSize and have it return a Dimension that is larger than the super.preferredSize (or if not then it returns the super's value).
For example, here's a small drag-a-rectangle app that I created for another question on this site:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MoveRect extends JPanel {
private static final int RECT_W = 90;
private static final int RECT_H = 70;
private static final int PREF_W = 600;
private static final int PREF_H = 300;
private static final Color DRAW_RECT_COLOR = Color.black;
private static final Color DRAG_RECT_COLOR = new Color(180, 200, 255);
private Rectangle rect = new Rectangle(25, 25, RECT_W, RECT_H);
private boolean dragging = false;
private int deltaX = 0;
private int deltaY = 0;
public MoveRect() {
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
addMouseListener(myMouseAdapter);
addMouseMotionListener(myMouseAdapter);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (rect != null) {
Color c = dragging ? DRAG_RECT_COLOR : DRAW_RECT_COLOR;
g.setColor(c);
Graphics2D g2 = (Graphics2D) g;
g2.draw(rect);
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private class MyMouseAdapter extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
Point mousePoint = e.getPoint();
if (rect.contains(mousePoint)) {
dragging = true;
deltaX = rect.x - mousePoint.x;
deltaY = rect.y - mousePoint.y;
}
}
@Override
public void mouseReleased(MouseEvent e) {
dragging = false;
repaint();
}
@Override
public void mouseDragged(MouseEvent e) {
Point p2 = e.getPoint();
if (dragging) {
int x = p2.x + deltaX;
int y = p2.y + deltaY;
rect = new Rectangle(x, y, RECT_W, RECT_H);
MoveRect.this.repaint();
}
}
}
private static void createAndShowGui() {
MoveRect mainPanel = new MoveRect();
JFrame frame = new JFrame("MoveRect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Note that my main class is a JPanel, and that I override JPanel's getPreferredSize:
public class MoveRect extends JPanel {
//.... deleted constants
private static final int PREF_W = 600;
private static final int PREF_H = 300;
//.... deleted fields and constants
//... deleted methods and constructors
@Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
Also note that when I display my GUI, I place it into a JFrame, call pack();
on the JFrame, set its position, and then call setVisible(true);
on my JFrame:
private static void createAndShowGui() {
MoveRect mainPanel = new MoveRect();
JFrame frame = new JFrame("MoveRect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Try this, Its working:
mysql -h {hostname} -u{username} -p{password} -N -e "{query to execute}"
Good news! String.prototype.repeat
is now a part of JavaScript.
"yo".repeat(2);
// returns: "yoyo"
The method is supported by all major browsers, except Internet Explorer. For an up to date list, see MDN: String.prototype.repeat > Browser compatibility.
MDN has a polyfill for browsers without support.
Try use it:
Uri uri = Uri.fromFile(entry);
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
String mime = "*/*";
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
if (mimeTypeMap.hasExtension(
mimeTypeMap.getFileExtensionFromUrl(uri.toString())))
mime = mimeTypeMap.getMimeTypeFromExtension(
mimeTypeMap.getFileExtensionFromUrl(uri.toString()));
intent.setDataAndType(uri,mime);
startActivity(intent);
Here is an overview of how the .NET framework and compiler versions are related, set and modified. Each project has a target .NET framework version(s), for example version 3.x or 2.x . The .NET framework contains the run time types and components.
The Visual Studio version installation and the .NET framework version determine the compatible c# language version and compiler options that can be used. The default c# version and options used in a Visual Studio project is the latest language version installed that is compatible with the .NET framework version being used.
To view or update the Framework or C# language within a project within Visual Studio 2011:
select 'Application' in the left navigation pane. Under Target framework: is the .NET framework version. Select the down arrow to see all available framework versions.
select 'Build' in the left navigation pane. In the 'General' section of the pane next to 'Language Version:' is the c# compiler language version being used, for example 'default' or c# 5.0
To see the exact compiler language version for 'default', enter the following in the developer command prompt for your installed Visual Studio version. For example, from the Windows Start icon select icon: "Developer Command Prompt for VS2011' and enter:
csc -langversion:Default
Microsoft (R) Visual C# Compiler version 4.7.3062.0 for c# 5
When it comes to labels, I would say it's up to you what you prefer. Some examples when it can be useful with HTML helper tags are, for instance
@Html.LabelFor
, @Html.TextBoxFor
, etc@Html.EditorFor
, as you can assign specific behavior och looks in a editor viewYou can use Eclipse DDMS perspective to see connected devices and browse through files, you can also pull and push files to the device. You can also do a bunch of stuff using DDMS, this link explains a little bit more of DDMS uses.
EDIT:
If you just want to copy a database you can locate the database on eclipse DDMS file explorer, select it and then pull the database from the device to your computer.
You can use
change config to cookie & type your password in ' ' in password like bellow
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'your password';
Then save & type on browser localhost/phpmyadmin/
Enter your given password & enjoy
If you would like to do your filtering in LINQ, you can do it like this:
var ext = new List<string> { "jpg", "gif", "png" };
var myFiles = Directory
.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories)
.Where(s => ext.Contains(Path.GetExtension(s).TrimStart(".").ToLowerInvariant()));
Now ext
contains a list of allowed extensions; you can add or remove items from it as necessary for flexible filtering.
At first open terminal/command line then go to your project directory, now install nodemon by using command npm install nodemon --save-dev this command will make sure it saved as developer dependency. If you are working with expressjs then in your package file it will look like
{
"name": "expressjs-app",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"morgan": "~1.9.1",
"pug": "^2.0.4"
},
"devDependencies": {
"nodemon": "^2.0.3"
}
}
now modify the "start" value in your package.json file, for production we will use the exsiting value but for development will use nodemon to track the changes in source file without restarting server. There for new value for start is "start": "if [[$NODE_ENV=='production']]; then node ./bin/www; else nodemon ./bin/www; fi"
final package.json file will look like
{
"name": "expressjs-app",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "if [[$NODE_ENV=='production']]; then node ./bin/www; else nodemon ./bin/www; fi"
},
"dependencies": {
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"morgan": "~1.9.1",
"pug": "^2.0.4"
},
"devDependencies": {
"nodemon": "^2.0.3"
}
}
to uninstall nodemon jusy simply run the command npm uninstall nodemon
According to the go documentation, Unix returns a local time.
Unix returns the local Time corresponding to the given Unix time
This means the output would depend on the machine your code runs on, which, most often is what you need, but sometimes, you may want to have the value in UTC.
To do so, I adapted the snippet to make it return a time in UTC:
i, err := strconv.ParseInt("1405544146", 10, 64)
if err != nil {
panic(err)
}
tm := time.Unix(i, 0)
fmt.Println(tm.UTC())
This prints on my machine (in CEST)
2014-07-16 20:55:46 +0000 UTC
I have head around lots of solutions and none of them works perfectly. I've used variation of solutions available in my project which is here as below. Please use this code inside class where you are initialising toolbar and drawer layout.
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
drawerFragment.mDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);// show back button
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
} else {
//show hamburger
drawerFragment.mDrawerToggle.setDrawerIndicatorEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
drawerFragment.mDrawerToggle.syncState();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawerFragment.mDrawerLayout.openDrawer(GravityCompat.START);
}
});
}
}
});
How about
sub foo()
dim r As Range, rows As Long, i As Long
Set r = ActiveSheet.Range("A1:Z50")
rows = r.rows.Count
For i = rows To 1 Step (-1)
If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
Next
End Sub
Try this
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Range("A" & i & ":" & "Z" & i)
Else
Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
IF you want to delete the entire row then use this code
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Rows(i)
Else
Set DelRange = Union(DelRange, Rows(i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
You can try this: By Using Authentication Object from Spring we can get User details from it in the controller method . Below is the example , by passing Authentication object in the controller method along with argument.Once user is authenticated the details are populated in the Authentication Object.
@GetMapping(value = "/mappingEndPoint") <ReturnType> methodName(Authentication auth) {
String userName = auth.getName();
return <ReturnType>;
}
The keyword extends
can be used for interfaces and classes only.
If you just want to declare a type that has additional properties, you can use intersection type:
type UserEvent = Event & {UserId: string}
UPDATE for TypeScript 2.2, it's now possible to have an interface that extends object-like type, if the type satisfies some restrictions:
type Event = {
name: string;
dateCreated: string;
type: string;
}
interface UserEvent extends Event {
UserId: string;
}
It does not work the other way round - UserEvent
must be declared as interface, not a type
if you want to use extends
syntax.
And it's still impossible to use extend
with arbitrary types - for example, it does not work if Event
is a type parameter without any constraints.
This will work for your case:
sonar.exclusions=**/src/java/dig/ ** , **/src/java/test/dig/ **
Use this one. It will fix it.
#ibox_footer {
padding-top: 3px;
position: absolute;
height: 20px;
margin-bottom: 0;
bottom: 0;
width: 100%;
}
I use this way, you should put a backslash at the end of the directory name to avoid that place exists in a file without extension with the same name as the directory you specified, never use "C:\VTS" because it can a file exists with the name "VTS" saved in "C:" partition, the correct way is to use "C:\VTS\", check out the backslash after the VTS, so is the right way.
@echo off
@break off
@title Create folder with batch but only if it doesn't already exist - D3F4ULT
@color 0a
@cls
setlocal EnableDelayedExpansion
if not exist "C:\VTS\" (
mkdir "C:\VTS\"
if "!errorlevel!" EQU "0" (
echo Folder created successfully
) else (
echo Error while creating folder
)
) else (
echo Folder already exists
)
pause
exit
Late to the conversation...
But, why not use css? That way you can keep the button as a submit type.
html:
<input type="submit" value="go" />
css:
button, input[type="submit"] {
background:url(/images/submit.png) no-repeat;"
}
Works like a charm.
EDIT: If you want to remove the default button styles, you can use the following css:
button, input[type="submit"]{
color: inherit;
border: none;
padding: 0;
font: inherit;
cursor: pointer;
outline: inherit;
}
from this SO question
Found the answer in How to lay out Views in RelativeLayout programmatically?
We should explicitly set id's using setId(). Only then, RIGHT_OF rules make sense.
Another mistake I did is, reusing the layoutparams object between the controls. We should create new object for each control
Everytime docker successfully executes a RUN
command from a Dockerfile, a new layer in the image filesystem is committed. Conveniently you can use those layers ids as images to start a new container.
Take the following Dockerfile:
FROM busybox
RUN echo 'foo' > /tmp/foo.txt
RUN echo 'bar' >> /tmp/foo.txt
and build it:
$ docker build -t so-2622957 .
Sending build context to Docker daemon 47.62 kB
Step 1/3 : FROM busybox
---> 00f017a8c2a6
Step 2/3 : RUN echo 'foo' > /tmp/foo.txt
---> Running in 4dbd01ebf27f
---> 044e1532c690
Removing intermediate container 4dbd01ebf27f
Step 3/3 : RUN echo 'bar' >> /tmp/foo.txt
---> Running in 74d81cb9d2b1
---> 5bd8172529c1
Removing intermediate container 74d81cb9d2b1
Successfully built 5bd8172529c1
You can now start a new container from 00f017a8c2a6
, 044e1532c690
and 5bd8172529c1
:
$ docker run --rm 00f017a8c2a6 cat /tmp/foo.txt
cat: /tmp/foo.txt: No such file or directory
$ docker run --rm 044e1532c690 cat /tmp/foo.txt
foo
$ docker run --rm 5bd8172529c1 cat /tmp/foo.txt
foo
bar
of course you might want to start a shell to explore the filesystem and try out commands:
$ docker run --rm -it 044e1532c690 sh
/ # ls -l /tmp
total 4
-rw-r--r-- 1 root root 4 Mar 9 19:09 foo.txt
/ # cat /tmp/foo.txt
foo
When one of the Dockerfile command fails, what you need to do is to look for the id of the preceding layer and run a shell in a container created from that id:
docker run --rm -it <id_last_working_layer> bash -il
Once in the container:
If you really need to experiment in the actual layer that failed instead of working from the last working layer, see Drew's answer.
You need to update currentTime video element and then draw the frame in canvas. Don't init play() event on the video.
You can also use for ex. this plugin https://github.com/tstabla/stVideo
If this is just a one-off exercise, as an easier alternative, you could apply filters to your source data, and then copy and paste the filtered rows into your new worksheet?
Change div to span. And space the icons using
HTML
<div class="nav3" style="height:705px;">
<span class="icons"><a href="http://www.facebook.com/"><img src="images/facebook.png"></a>
</span>
<span class="icons"><a href="https://twitter.com"><img src="images/twitter.png"></a>
</span>
</div>
CSS
.nav3 {
background-color: #E9E8C7;
height: auto;
width: 150px;
float: left;
padding-left: 20px;
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
color: #333333;
padding-top: 20px;
padding-right: 20px;
}
.icons{
display:inline-block;
width: 64px;
height: 64px;
}
a.icons:hover {
background: #C93;
}
span does not break line, div does.
<?php
namespace CMS;
class Model {
const _class = __CLASS__;
}
echo Model::_class; // will return 'CMS\Model'
for older than PHP 5.5
If you're more comfortable PCRE regex syntax, which
you have [g]vim compiled with perl feature, test using
:ver and inspect features; if +perl is there you're good to go)
try search/replace using
:perldo s///
Example. Swap src and alt attributes in img tag:
<p class="logo"><a href="/"><img src="/caminoglobal_en/includes/themes/camino/images/header_logo.png" alt=""></a></p>
:perldo s/(src=".*?")\s+(alt=".*?")/$2 $1/
<p class="logo"><a href="/"><img alt="" src="/caminoglobal_en/includes/themes/camino/images/header_logo.png"></a></p>
They say it right there in the documentation for the FPDF constructor:
FPDF([string orientation [, string unit [, mixed size]]])
This is the class constructor. It allows to set up the page size, the orientation and the unit of measure used in all methods (except for font sizes). Parameters ...
size
The size used for pages. It can be either one of the following values (case insensitive):
A3 A4 A5 Letter Legal
or an array containing the width and the height (expressed in the unit given by unit).
They even give an example with custom size:
Example with a custom 100x150 mm page size:
$pdf = new FPDF('P','mm',array(100,150));
Although Clayton's answer will get you there (eventually), in SQL2005/2008/R2/2012 you have a far easier option:
Right-click on the Database, select Tasks
and then Generate Scripts
, which will launch the Script Wizard. This allows you to generate a single script that can recreate the full database including table/indexes & constraints/stored procedures/functions/users/etc. There are a multitude of options that you can configure to customise the output, but most of it is self explanatory.
If you are happy with the default options, you can do the whole job in a matter of seconds.
If you want to recreate the data in the database (as a series of INSERTS) I'd also recommend SSMS Tools Pack (Free for SQL 2008 version, Paid for SQL 2012 version).
Use option bty = "n"
in legend
to remove the box around the legend. For example:
legend(1, 5,
"This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",
bty = "n")
If you do not like double quotes like me, this will work for you with single quotes:
$value = Input::get('q');
$books = Book::where('name', 'LIKE', '%' . $value . '%')->limit(25)->get();
return view('pages/search/index', compact('books'));
If you google. "Count down for loop python" you get these, which are pretty accurate.
how to loop down in python list (countdown)
Loop backwards using indices in Python?
I recommend doing minor searches before posting. Also "Learn Python The Hard Way" is a good place to start.
The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.
To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".
To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".
Explanation:
From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):
4.3.8 ‘Local echo’
With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)
Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.
4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.
If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.
Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)
Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.
Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.
Here is a way to center content both vertically and horizontally in any situation, which is useful when you do not know the width or height or both:
CSS
#container {
display: table;
width: 300px; /* not required, just for example */
height: 400px; /* not required, just for example */
}
#update {
display: table-cell;
vertical-align: middle;
text-align: center;
}
HTML
<div id="container">
<a id="update" href="#">
<i class="icon-refresh"></i>
</a>
</div>
Note that the width and height values are just for demonstration here, you can change them to anything you want (or remove them entirely) and it will still work because the vertical centering here is a product of the way the table-cell
display property works.
I know about Android ICS that it uses a custom service called: NetworkTimeUpdateService
. This service also implements a NTP time synchronization via the NtpTrustedTime
singleton.
In NtpTrustedTime
the default NTP server is requested from the Android system string source:
final Resources res = context.getResources();
final String defaultServer = res.getString(
com.android.internal.R.string.config_ntpServer);
If the automatic time sync option in the system settings is checked and no NITZ time service is available then the time will be synchronized with the NTP server from com.android.internal.R.string.config_ntpServer
.
To get the value of com.android.internal.R.string.config_ntpServer
you can use the following method:
final Resources res = this.getResources();
final int id = Resources.getSystem().getIdentifier(
"config_ntpServer", "string","android");
final String defaultServer = res.getString(id);
you can try typescript's For
:
selectChildren(data , $event){
let parentChecked : boolean = data.checked;
for(let o of this.hierarchicalData){
for(let child of o){
child.checked = parentChecked;
}
}
}
private OutputStream outputStream;
private InputStream inStream;
private void init() throws IOException {
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
if(bondedDevices.size() > 0) {
Object[] devices = (Object []) bondedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) devices[position];
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket.connect();
outputStream = socket.getOutputStream();
inStream = socket.getInputStream();
}
Log.e("error", "No appropriate paired devices.");
} else {
Log.e("error", "Bluetooth is disabled.");
}
}
}
public void write(String s) throws IOException {
outputStream.write(s.getBytes());
}
public void run() {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int bytes = 0;
int b = BUFFER_SIZE;
while (true) {
try {
bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
To handle the lazy loading with image existence check I followed this in jQuery-
$('[data-src]').each(function() {
var $image_place_holder_element = $(this);
var image_url = $(this).data('src');
$("<div class='hidden-classe' />").load(image_url, function(response, status, xhr) {
if (!(status == "error")) {
$image_place_holder_element.removeClass('image-placeholder');
$image_place_holder_element.attr('src', image_url);
}
}).remove();
});
Reason: if I am using $image_place_holder_element.load()
method it will be adding the response to the element, so random div and removing it appeared me a good solution. Hope it works for someone trying to implement lazy loading along with url check.
I looked at a few options to do this, and ultimately decided it was simpler to just use the current time for the versionCode instead of trying to automatically increment the versionCode and check it into my revision control system.
Add the following to your build.gradle
:
/**
* Use the number of seconds/10 since Jan 1 2016 as the versionCode.
* This lets us upload a new build at most every 10 seconds for the
* next 680 years.
*/
def vcode = (int)(((new Date().getTime()/1000) - 1451606400) / 10)
android {
defaultConfig {
...
versionCode vcode
}
}
However, if you expect to upload builds beyond year 2696, you may want to use a different solution.
No need to use string functions. You can use something that's actually designed for what you want: pathinfo()
:
$path = $_FILES['image']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
You can also use the Ellipsis when specifying expected doctest output:
class MyClass(object):
"""Example of a doctest Ellipsis
>>> thing = MyClass()
>>> # Match <class '__main__.MyClass'> and <class '%(module).MyClass'>
>>> type(thing) # doctest:+ELLIPSIS
<class '....MyClass'>
"""
pass
Thanks for everyone who answered, and thanks for those who gave me the function-format idea, i'll really study it for future using.
But for this explicit case, the 'special yyyymm field' is not to be considered as a date field, but just as a tag, o whatever would be used for matching the exactly year-month researched value; there is already another date field, with the full timestamp, but if i need all the rows of january 2008, i think that is faster a select like
SELECT [columns] FROM table WHERE yearmonth = '200801'
instead of
SELECT [columns] FROM table WHERE date BETWEEN DATE('2008-01-01') AND DATE('2008-01-31')
With twitter bootstrap :
<p class="pull-left">Left aligned text.</p>
<p class="pull-right">Right aligned text.</p>
<p class="text-center">Center aligned text.</p>
You can't (and shouldn't) block processing with a sleep function. However, you can use setTimeout
to kick off a function after a delay:
setTimeout(function(){alert("hi")}, 1000);
Depending on your needs, setInterval
might be useful, too.
I don't know the intended usage of such dynamic classes, and code generation and run time compilation can be done, but takes some effort. Maybe Anonymous Types would help you, something like:
var v = new { EmployeeID = 108, EmployeeName = "John Doe" };
create div with id name
var divCreator=function (id){
newElement=document.createElement("div");
newNode=document.body.appendChild(newElement);
newNode.setAttribute("id",id);
}
add text to div
var textAdder = function(id, text) {
target = document.getElementById(id)
target.appendChild(document.createTextNode(text));
}
test code
divCreator("div1");
textAdder("div1", "this is paragraph 1");
output
this is paragraph 1
I wonder if you could write a custom rule for Fiddler to do what you want? IE uses no proxy, Firefox points to Fiddler, Fiddler uses custom rule to direct requests to the dev server...
This adds to rm8x's answer.
Download and install the NuGet command line tool.
List all of our locals:
$ nuget locals all -list
http-cache: C:\Users\MyUser\AppData\Local\NuGet\v3-cache
packages-cache: C:\Users\MyUser\AppData\Local\NuGet\Cache
global-packages: C:\Users\MyUser\.nuget\packages\
We can now delete these manually or as rm8x suggests, use nuget locals all -clear
.
For me, an issue where json_encode would return null encoding of an entity was because my jsonSerialize implementation fetched entire objects for related entities; I solved the issue by making sure that I fetched the ID of the related/associated entity and called ->toArray() when there were more than one entity associated with the object to be json serialized. Note, I'm speaking about cases where one implements JsonSerializable
on entities.
As clean as this :)
function makedir(fullpath) {
let destination_split = fullpath.replace('/', '\\').split('\\')
let path_builder = destination_split[0]
$.each(destination_split, function (i, path_segment) {
if (i < 1) return true
path_builder += '\\' + path_segment
if (!fs.existsSync(path_builder)) {
fs.mkdirSync(path_builder)
}
})
}
https://reactjs.org/docs/hooks-reference.html#usememo
Remember that the function passed to useMemo runs during rendering. Don’t do anything there that you wouldn’t normally do while rendering. For example, side effects belong in useEffect, not useMemo.
From the CLI in win xp:
python -c "import random; print(sorted(set([random.randint(6,49) for i in range(7)]))[:6])"
In Canada we have the 6/49 Lotto. I just wrap the above code in lotto.bat and run C:\home\lotto.bat
or just C:\home\lotto
.
Because random.randint
often repeats a number, I use set
with range(7)
and then shorten it to a length of 6.
Occasionally if a number repeats more than 2 times the resulting list length will be less than 6.
EDIT: However, random.sample(range(6,49),6)
is the correct way to go.
You mention the most commonly implemented, which is Adjacency List: https://blogs.msdn.microsoft.com/mvpawardprogram/2012/06/25/hierarchies-convert-adjacency-list-to-nested-sets
There are other models as well, including materialized path and nested sets: http://communities.bmc.com/communities/docs/DOC-9902
Joe Celko has written a book on this subject, which is a good reference from a general SQL perspective (it is mentioned in the nested set article link above).
Also, Itzik Ben-Gann has a good overview of the most common options in his book "Inside Microsoft SQL Server 2005: T-SQL Querying".
The main things to consider when choosing a model are:
1) Frequency of structure change - how frequently does the actual structure of the tree change. Some models provide better structure update characteristics. It is important to separate structure changes from other data changes however. For example, you may want to model a company's organizational chart. Some people will model this as an adjacency list, using the employee ID to link an employee to their supervisor. This is usually a sub-optimal approach. An approach that often works better is to model the org structure separate from employees themselves, and maintain the employee as an attribute of the structure. This way, when an employee leaves the company, the organizational structure itself does not need to be changes, just the association with the employee that left.
2) Is the tree write-heavy or read-heavy - some structures work very well when reading the structure, but incur additional overhead when writing to the structure.
3) What types of information do you need to obtain from the structure - some structures excel at providing certain kinds of information about the structure. Examples include finding a node and all its children, finding a node and all its parents, finding the count of child nodes meeting certain conditions, etc. You need to know what information will be needed from the structure to determine the structure that will best fit your needs.
You need to add a ',' between the paramValue1 and paramValue2. You missed it.
EXEC proc_name 'paramValue1','paramValue2'
Please consider the deasync module, personally I don't like the Promise way to make all functions async, and keyword async/await anythere. And I think the official node.js should consider to expose the event loop API, this will solve the callback hell simply. Node.js is a framework not a language.
var node = require("deasync");
node.loop = node.runLoopOnce;
var done = 0;
// async call here
db.query("select * from ticket", (error, results, fields)=>{
done = 1;
});
while (!done)
node.loop();
// Now, here you go
I profiled a few methods to move an item within the same list with timeit. Here are the ones to use if j>i:
+---------------------------------+ ¦ 14.4usec ¦ x[i:i]=x.pop(j), ¦ ¦ 14.5usec ¦ x[i:i]=[x.pop(j)] ¦ ¦ 15.2usec ¦ x.insert(i,x.pop(j)) ¦ +---------------------------------+
and here the ones to use if j<=i:
+--------------------------------------+ ¦ 14.4usec ¦ x[i:i]=x[j],;del x[j] ¦ ¦ 14.4usec ¦ x[i:i]=[x[j]];del x[j] ¦ ¦ 15.4usec ¦ x.insert(i,x[j]);del x[j] ¦ +--------------------------------------+
Not a huge difference if you only use it a few times, but if you do heavy stuff like manual sorting, it's important to take the fastest one. Otherwise, I'd recommend just taking the one that you think is most readable.
This exception occurred in my application and was rather misleading.
It was thrown when I was calling an .aspx page Web Method using an ajax method call, passing a JSON array object. The Web Page method signature contained an array of a strongly-typed .NET object, OrderDetails. The Actual_Qty property was defined as an int, and the JSON object Actual_Qty property contained "4 " (extra space character). After removing the extra space, the conversion was made possible, the Web Page method was successfully reached by the ajax call.
The bracket stuff (e.g., [[ $a -gt $b ]]
or (( $a > $b ))
) isn't enough if you want to use float numbers as well; it would report a syntax error. If you want to compare float numbers or float number to integer, you can use (( $(bc <<< "...") ))
.
For example,
a=2.00
b=1
if (( $(bc <<<"$a > $b") )); then
echo "a is greater than b"
else
echo "a is not greater than b"
fi
You can include more than one comparison in the if statement. For example,
a=2.
b=1
c=1.0000
if (( $(bc <<<"$b == $c && $b < $a") )); then
echo "b is equal to c but less than a"
else
echo "b is either not equal to c and/or not less than a"
fi
That's helpful if you want to check if a numeric variable (integer or not) is within a numeric range.
This is not an answer to the original question, but rather an extension of the accepted answer by @Samuel Jack. I did the following in my own application, and was in awe of the elegance of Samuel's solution. It is very clean, and very reusable, as it can be used on any control, not just the TextBox
. I thought this should be shared with the community.
If you have a Window with a thousand TextBoxes
that all require to update the Binding Source on Enter, you can attach this behaviour to all of them by including the XAML below into your Window
Resources
rather than attaching it to each TextBox. First you must implement the attached behaviour as per Samuel's post, of course.
<Window.Resources>
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Style.Setters>
<Setter Property="b:InputBindingsManager.UpdatePropertySourceWhenEnterPressed" Value="TextBox.Text"/>
</Style.Setters>
</Style>
</Window.Resources>
You can always limit the scope, if needed, by putting the Style into the Resources of one of the Window's child elements (i.e. a Grid
) that contains the target TextBoxes.
This will show you a list of database files contained in DB.bak:
RESTORE FILELISTONLY
FROM DISK = 'D:\3.0 Databases\DB.bak'
You will need the logical names from that list for the MOVE
operation in the second step:
RESTORE DATABASE YourDB
FROM DISK = 'D:\3.0 Databases\DB.bak'
and you have to move appropriate mdf,ndf & ldf files using
With Move 'primarydatafilename' To 'D:\DB\data.mdf',
Move 'secondarydatafile' To 'D:\DB\data1.ndf',
Move 'logfilename' To 'D:\DB\log.ldf'
Font myFont = new Font("Serif", Font.BOLD, 12);
, then use a setFont method on your components like
JButton b = new JButton("Hello World");
b.setFont(myFont);
In windows after this setting you can use ctrl + shift + v ( for windows)
Yeah this is related to what allen said... look for TargetMembership in Utilities section of the source file. there is a checkbox that associates that file to a project. Checking this solved this issue for me too.
You should create custom helper for just changing string format except using controller call.
Tested and working in Angular 9.0
If you're getting the data using API
array: [];
ngOnInit() {
this.service.method()
.subscribe(
data=>
{
this.array = JSON.parse(JSON.stringify(data.object));
}
)
}
You can use that array to print your results from API data in html template.
Like
<p>{{array['something']}}</p>
The newest version of docker (18.03) offers a built in port forwarding solution. Inside your docker container simply have the db host set to host.docker.internal
. This will be forwarded to the host the docker container is running on.
Documentation for this is here: https://docs.docker.com/docker-for-mac/networking/#i-want-to-connect-from-a-container-to-a-service-on-the-host
Try this it works sudo apt install python-pip pip install boto3
I had to go to File->Invalidate Caches/Restart, reboot Ubuntu 18.04 LTS, then open Pycharm and File-> Invalidate Caches/Restart again before it cleared up.
I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=D:\test.xls " & _
";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
For i = 0 To rs.Fields.Count - 1
Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
strNaam = rs.Fields(0).Value
Next
rs.MoveNext
Loop
rs.Close
There are other ways, depending on what you want to do, such as GetString (GetString Method Description).
If you are moving folders via Repository Browser, then there is no Move option on right-click; the only way is to drag and drop.
var getMatchingGroups = function(s) {
var r=/\((.*?)\)/g, a=[], m;
while (m = r.exec(s)) {
a.push(m[1]);
}
return a;
};
getMatchingGroups("something/([0-9])/([a-z])"); // => ["[0-9]", "[a-z]"]
You can't easily do this in a generic way: you can only convert an integer to a specific type of enum. As Nicholas has shown, this is a trivial cast if you only care about one kind of enum, but if you want to write a generic method that can handle different kinds of enums, things get a bit more complicated. You want a method along the lines of:
public static string GetEnumDescription<TEnum>(int value)
{
return GetEnumDescription((Enum)((TEnum)value)); // error!
}
but this results in a compiler error that "int can't be converted to TEnum" (and if you work around this, that "TEnum can't be converted to Enum"). So you need to fool the compiler by inserting casts to object:
public static string GetEnumDescription<TEnum>(int value)
{
return GetEnumDescription((Enum)(object)((TEnum)(object)value)); // ugly, but works
}
You can now call this to get a description for whatever type of enum is at hand:
GetEnumDescription<MyEnum>(1);
GetEnumDescription<YourEnum>(2);
color
and fill
are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:
d + scale_color_manual(values=c("#CC6666", "#9999CC"))
is what you want.
Mike Goodwin answer is great but it seemed, when I tried it, that it was aimed at MVC5/WebApi 2.1. The dependencies for Microsoft.AspNet.WebApi.Cors didn't play nicely with my MVC4 project.
The simplest way to enable CORS on WebApi with MVC4 was the following.
Note that I have allowed all, I suggest you limit the Origin's to just the clients you want your API to serve. Allowing everything is a security risk.
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>
</system.webServer>
We do this to allow the OPTIONS http verb
public class BaseApiController : ApiController
{
public HttpResponseMessage Options()
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}
}
IF EXISTS()
is semantically incorrect. EXISTS
condition can be used only inside a SQL statement. So you might rewrite your pl/sql block as follows:
declare
l_exst number(1);
begin
select case
when exists(select ce.s_regno
from courseoffering co
join co_enrolment ce
on ce.co_id = co.co_id
where ce.s_regno=403
and ce.coe_completionstatus = 'C'
and ce.c_id = 803
and rownum = 1
)
then 1
else 0
end into l_exst
from dual;
if l_exst = 1
then
DBMS_OUTPUT.put_line('YES YOU CAN');
else
DBMS_OUTPUT.put_line('YOU CANNOT');
end if;
end;
Or you can simply use count
function do determine the number of rows returned by the query, and rownum=1
predicate - you only need to know if a record exists:
declare
l_exst number;
begin
select count(*)
into l_exst
from courseoffering co
join co_enrolment ce
on ce.co_id = co.co_id
where ce.s_regno=403
and ce.coe_completionstatus = 'C'
and ce.c_id = 803
and rownum = 1;
if l_exst = 0
then
DBMS_OUTPUT.put_line('YOU CANNOT');
else
DBMS_OUTPUT.put_line('YES YOU CAN');
end if;
end;
If you don't want to add a wrapper, you could just add the code manually, since you know the ID you are targeting:
var myID = "xxx";
var newCode = "<div id='"+myID+"'>"+$("#"+myID).html()+"</div>";
See Google Collections. Or, as you suggest, use a map internally, and have that map use a Pair. You'll have to write or find Pair<>; it's pretty easy but not part of the standard Collections.
Use OnClicklistener
or you can use android:onClick="myMethod"
in your button's xml code from which you going to open a new layout. So when that button is clicked your myMethod function will be called automatically. Your myMethod
function in class look like this.
public void myMethod(View v) {
Intent intent=new Intent(context,SecondActivty.class);
startActivity(intent);
}
And in that SecondActivity.class set new layout in contentview.
Step one: Go to... C:\xampp\phpMyAdmin
Step Two: Open the config.inc.php
file
Step Three: Locate the following information and change the password.
/* Authentication type and info */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'ENTER_YOUR_USER_NAME_HERE';
$cfg['Servers'][$i]['password'] = 'ENTER_YOUR_PASS_HERE';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
$cfg['Lang'] = '';
You simply misspelled $stateParam
, it should be $stateParams
(with an s). That's why you get undefined ;)
I am an iOS dev, so I made a solution similar to NotificationCenter:
object NotificationCenter {
var observers: MutableMap<String, MutableList<NotificationObserver>> = mutableMapOf()
fun addObserver(observer: NotificationObserver, notificationName: NotificationName) {
var os = observers[notificationName.value]
if (os == null) {
os = mutableListOf<NotificationObserver>()
observers[notificationName.value] = os
}
os.add(observer)
}
fun removeObserver(observer: NotificationObserver, notificationName: NotificationName) {
val os = observers[notificationName.value]
if (os != null) {
os.remove(observer)
}
}
fun removeObserver(observer:NotificationObserver) {
observers.forEach { name, mutableList ->
if (mutableList.contains(observer)) {
mutableList.remove(observer)
}
}
}
fun postNotification(notificationName: NotificationName, obj: Any?) {
val os = observers[notificationName.value]
if (os != null) {
os.forEach {observer ->
observer.onNotification(notificationName,obj)
}
}
}
}
interface NotificationObserver {
fun onNotification(name: NotificationName,obj:Any?)
}
enum class NotificationName(val value: String) {
onPlayerStatReceived("on player stat received"),
...
}
Some class that want to observe notification must conform to observer protocol:
class MainActivity : AppCompatActivity(), NotificationObserver {
override fun onCreate(savedInstanceState: Bundle?) {
...
NotificationCenter.addObserver(this,NotificationName.onPlayerStatReceived)
}
override fun onDestroy() {
...
super.onDestroy()
NotificationCenter.removeObserver(this)
}
...
override fun onNotification(name: NotificationName, obj: Any?) {
when (name) {
NotificationName.onPlayerStatReceived -> {
Log.d(tag, "onPlayerStatReceived")
}
else -> Log.e(tag, "Notification not handled")
}
}
Finally, post some notification to observers:
NotificationCenter.postNotification(NotificationName.onPlayerStatReceived,null)
input.next();
String s = input.toString();
change it to
String s = input.next();
May be that's what you were trying to do.
I am using WSL with ubuntu 16.04 LTS version with php 7.3 and laravel 5.7
sudo apt-get install php7.3-zip
Work for me
In my angular app the following style worked for me to achieve ellipsis on the overflow of text on the second line:
<div style="height:45px; overflow: hidden; position: relative;">
<span class=" block h6 font-semibold clear" style="overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
line-height: 20px; /* fallback */
max-height: 40px; /* fallback */
-webkit-line-clamp: 2; /* number of lines to show */
-webkit-box-orient: vertical;">
{{ event?.name}} </span>
</div>
Hope it helps someone.
you can use the views *_DEPENDENCIES
, for example:
SELECT owner, NAME
FROM dba_dependencies
WHERE referenced_owner = :table_owner
AND referenced_name = :table_name
AND TYPE IN ('PACKAGE', 'PACKAGE BODY')
array=("word" "two words") # let's look for "two words"
grep
and printf
:(printf '%s\n' "${array[@]}" | grep -x -q "two words") && <run_your_if_found_command_here>
for
:(for e in "${array[@]}"; do [[ "$e" == "two words" ]] && exit 0; done; exit 1) && <run_your_if_found_command_here>
For not_found results add || <run_your_if_notfound_command_here>
There are 2 solutions to this issue:
1) Download the relevant Android SDK via Tools -> Android -> SDK Manager -> SDK Tools (ensure you have 'Show Package Details') checked. Your case would be Android 6.0 (Marshmallow / API level 21)
2) Alternatively, open your build.gradle
file and update the following attributes :
compileSdkVersion
buildToolsVersion
targetSdkVersion
either to the most recent version of the Android API that you have installed / another installed version you'd like to use (although I'd always recommend going with the latest version for the usual reasons: bug fixes etc.)
If you're following step 2 it's also important that you remember to update the Android support library version if your app is using it. This can be found in the dependencies
section of your build file and looks something like this:
compile 'com.android.support:appcompat-v7:27.0.2'
(replace 27.0.2
with the most recent support library version for the API level you intend to use with your app)
To be clear on the bits vs byte, vs characters.
2**8
possible combinations: 256 combinationsWhen you look at a hex character,
[0-9] + [a-f]
: the full range of 0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
2**4
: that means one hex character can store 4 bits in a byte (half a byte).2**8
combinations.[0-9a-f][0-9a-f]
and that represents both halfs of a byte (we call a half-byte a nibble).When you look at a regular single-byte character, (we're totally going to skip multi-byte and wide-characters here)
2**8
range.md5()
could store all that, you'd see all the lowercase letters, all the uppercase letters, all the punctuation and things like ¡°ÀÐàð
, whitespace like (newlines, and tabs), and control characters (which you can't even see and many of which aren't in use).So they're clearly different and I hope that provides the best break down of the differences.
document.forms[ 'forms1' ].onsubmit = function() {
return [].some.call( this.elements, function( el ) {
return el.type === 'radio' ? el.checked : false
} )
}
Just something out of my head. Not sure the code is working.
There are instances when element.isDisplayed() && element.isEnabled()
will return true
but still element will not be clickable, because it is hidden/overlapped by some other element.
In such case, Exception
caught is:
org.openqa.selenium.WebDriverException: unknown error: Element is not clickable at point (781, 704). Other element would receive the click:
<div class="footer">...</div>
Use this code instead:
WebElement element=driver.findElement(By.xpath"");
JavascriptExecutor ex=(JavascriptExecutor)driver;
ex.executeScript("arguments[0].click()", element);
It will work.
I would like to give another example in which multiple (3) joins are used.
DataClasses1DataContext ctx = new DataClasses1DataContext();
var Owners = ctx.OwnerMasters;
var Category = ctx.CategoryMasters;
var Status = ctx.StatusMasters;
var Tasks = ctx.TaskMasters;
var xyz = from t in Tasks
join c in Category
on t.TaskCategory equals c.CategoryID
join s in Status
on t.TaskStatus equals s.StatusID
join o in Owners
on t.TaskOwner equals o.OwnerID
select new
{
t.TaskID,
t.TaskShortDescription,
c.CategoryName,
s.StatusName,
o.OwnerName
};
You can't use UIImagePickerController
, but you can use a custom image picker. I think ELCImagePickerController
is the best option, but here are some other libraries you could use:
Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection
Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker
Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.
An other approach using borders and no CSS3 properties :
div, div:after{_x000D_
border-width: 80px 0 80px 80px;_x000D_
border-color: transparent transparent transparent #000;_x000D_
border-style:solid;_x000D_
position:relative;_x000D_
}_x000D_
div:after{_x000D_
content:'';_x000D_
position:absolute;_x000D_
left:-115px; top:-80px;_x000D_
border-left-color:#fff;_x000D_
}
_x000D_
<div></div>
_x000D_
My way to do this job is:
char to int
char var;
cout<<(int)var-48;
int to char
int var;
cout<<(char)(var|48);
And I write these functions for conversions:
int char2int(char *szBroj){
int counter=0;
int results=0;
while(1){
if(szBroj[counter]=='\0'){
break;
}else{
results*=10;
results+=(int)szBroj[counter]-48;
counter++;
}
}
return results;
}
char * int2char(int iNumber){
int iNumbersCount=0;
int iTmpNum=iNumber;
while(iTmpNum){
iTmpNum/=10;
iNumbersCount++;
}
char *buffer=new char[iNumbersCount+1];
for(int i=iNumbersCount-1;i>=0;i--){
buffer[i]=(char)((iNumber%10)|48);
iNumber/=10;
}
buffer[iNumbersCount]='\0';
return buffer;
}
As an alternative to JPA/Hibernate solutions : you could use a CASCADE DELETE clause in the database definition of your foregin key on your join table, such as (Oracle syntax) :
CONSTRAINT fk_to_group
FOREIGN KEY (group_id)
REFERENCES group (id)
ON DELETE CASCADE
That way the DBMS itself automatically deletes the row that points to the group when you delete the group. And it works whether the delete is made from Hibernate/JPA, JDBC, manually in the DB or any other way.
the cascade delete feature is supported by all major DBMS (Oracle, MySQL, SQL Server, PostgreSQL).
Here is how I add parameters:
sprocCommand.Parameters.Add(New SqlParameter("@Date_Of_Birth",Data.SqlDbType.DateTime))
sprocCommand.Parameters("@Date_Of_Birth").Value = DOB
I am assuming when you write out DOB there are no quotes.
Are you using a third-party control to get the date? I have had problems with the way the text value is generated from some of them.
Lastly, does it work if you type in the .Value attribute of the parameter without referencing DOB?
You can do
new XMLSerializer().serializeToString(document)
in browsers newer than IE 9
I have worked on some servers where sort don't support '-u' option. there we have to use
sort xyz | uniq
I've had to do this before using Paramiko in a case where I wanted to run a dynamic, local PyQt4 script on a host running an ssh server that has connected my OpenVPN server and ask for their routing preference (split tunneling).
So long as the ssh server you are connecting to has all of the required dependencies of your script (PyQt4 in my case), you can easily encapsulate the data by encoding it in base64 and use the exec()
built-in function on the decoded message. If I remember correctly my one-liner for this was:
stdout = client.exec_command('python -c "exec(\\"' + open('hello.py','r').read().encode('base64').strip('\n') + '\\".decode(\\"base64\\"))"' )[1]
It is hard to read and you have to escape the escape sequences because they are interpreted twice (once by the sender and then again by the receiver). It also may need some debugging, I've packed up my server to PCS or I'd just reference my OpenVPN routing script.
The difference in doing it this way as opposed to sending a file is that it never touches the disk on the server and is run straight from memory (unless of course they log the command). You'll find that encapsulating information this way (although inefficient) can help you package data into a single file.
For instance, you can use this method to include raw data from external dependencies (i.e. an image) in your main script.
Solution I have json object which has data
[{"name":"Ata","email":"[email protected]"}]
You can use following approach to iterate through ng-repeat and use table format instead of list.
<div class="container" ng-controller="fetchdataCtrl">
<ul ng-repeat="item in numbers">
<li>
{{item.name}}: {{item.email}}
</li>
</ul>
</div>
The solution is to stringify the object before calling setItem on the sessionStorage.
var user = {'name':'John'};
sessionStorage.setItem('user', JSON.stringify(user));
var obj = JSON.parse(sessionStorage.user);
import json
cursor = conn.cursor()
qry = """ SELECT details FROM test_csvfile """
cursor.execute(qry)
rows = cursor.fetchall()
value = json.dumps(rows)
with open("/home/asha/Desktop/Income_output.json","w+") as f:
f.write(value)
print 'Saved to File Successfully'
This works for me:
$("#dateselector").datepicker("option", "defaultDate", new Date(2008,9,3));
ElcomSoft makes Advanced Office Password Breaker and Advanced Office Password Recovery products which may apply to this case, as long as the document was created in Office 2007 or prior.
If you're using spring >= 3.0, try using Springs @Configuration
annotation to define part of the application context
@Configuration
@ImportResource("com/blah/blurk/rest-of-config.xml")
public class DaoTestConfiguration {
@Bean
public ApplicationService applicationService() {
return mock(ApplicationService.class);
}
}
If you don't want to use the @ImportResource, it can be done the other way around too:
<beans>
<!-- rest of your config -->
<!-- the container recognize this as a Configuration and adds it's beans
to the container -->
<bean class="com.package.DaoTestConfiguration"/>
</beans>
For more information, have a look at spring-framework-reference : Java-based container configuration
I've been using
$.fn.rotate = function(degrees, step, current) {_x000D_
var self = $(this);_x000D_
current = current || 0;_x000D_
step = step || 5;_x000D_
current += step;_x000D_
self.css({_x000D_
'-webkit-transform' : 'rotate(' + current + 'deg)',_x000D_
'-moz-transform' : 'rotate(' + current + 'deg)',_x000D_
'-ms-transform' : 'rotate(' + current + 'deg)',_x000D_
'transform' : 'rotate(' + current + 'deg)'_x000D_
});_x000D_
if (current != degrees) {_x000D_
setTimeout(function() {_x000D_
self.rotate(degrees, step, current);_x000D_
}, 5);_x000D_
}_x000D_
};_x000D_
_x000D_
$(".r90").click(function() { $("span").rotate(90) });_x000D_
$(".r0").click(function() { $("span").rotate(0, -5, 90) });
_x000D_
span { display: inline-block }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
<span>potato</span>_x000D_
_x000D_
<button class="r90">90 degrees</button>_x000D_
<button class="r0">0 degrees</button>
_x000D_
Honestly, I feel more comfortable with Alfred blog definitions:
Object: real world objects shares 2 main characteristics, state and behavior. Human have state (name, age) and behavior (running, sleeping). Car have state (current speed, current gear) and behavior (applying brake, changing gear). Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields and exposes its behavior through methods.
Class: is a “template” / “blueprint” that is used to create objects. Basically, a class will consists of field, static field, method, static method and constructor. Field is used to hold the state of the class (eg: name of Student object). Method is used to represent the behavior of the class (eg: how a Student object going to stand-up). Constructor is used to create a new Instance of the Class.
Instance: An instance is a unique copy of a Class that representing an Object. When a new instance of a class is created, the JVM will allocate a room of memory for that class instance.
Given the next example:
public class Person {
private int id;
private String name;
private int age;
public Person (int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (id != other.id)
return false;
return true;
}
public static void main(String[] args) {
//case 1
Person p1 = new Person(1, "Carlos", 20);
Person p2 = new Person(1, "Carlos", 20);
//case 2
Person p3 = new Person(2, "John", 15);
Person p4 = new Person(3, "Mary", 17);
}
}
For case 1, there are two instances of the class Person, but both instances represent the same object.
For case 2, there are two instances of the class Person, but each instance represent a different object.
So class, object and instance are different things. Object and instance are not synonyms as is suggested in the answer selected as right answer.
Add the path to where your new library is to LD_LIBRARY_PATH
(it has slightly different name on Mac ...)
Your solution should work with using the -L/my/dir -lfoo
options, at runtime use LD_LIBRARY_PATH to point to the location of your library.
Careful with using LD_LIBRARY_PATH - in short (from link):
..implications..:
Security: Remember that the directories specified in LD_LIBRARY_PATH get searched before(!) the standard locations? In that way, a nasty person could get your application to load a version of a shared library that contains malicious code! That’s one reason why setuid/setgid executables do neglect that variable!
Performance: The link loader has to search all the directories specified, until it finds the directory where the shared library resides – for ALL shared libraries the application is linked against! This means a lot of system calls to open(), that will fail with “ENOENT (No such file or directory)”! If the path contains many directories, the number of failed calls will increase linearly, and you can tell that from the start-up time of the application. If some (or all) of the directories are in an NFS environment, the start-up time of your applications can really get long – and it can slow down the whole system!
Inconsistency: This is the most common problem. LD_LIBRARY_PATH forces an application to load a shared library it wasn’t linked against, and that is quite likely not compatible with the original version. This can either be very obvious, i.e. the application crashes, or it can lead to wrong results, if the picked up library not quite does what the original version would have done. Especially the latter is sometimes hard to debug.
OR
Use the rpath option via gcc to linker - runtime library search path, will be used instead of looking in standard dir (gcc option):
-Wl,-rpath,$(DEFAULT_LIB_INSTALL_PATH)
This is good for a temporary solution. Linker first searches the LD_LIBRARY_PATH for libraries before looking into standard directories.
If you don't want to permanently update LD_LIBRARY_PATH you can do it on the fly on command line:
LD_LIBRARY_PATH=/some/custom/dir ./fooo
You can check what libraries linker knows about using (example):
/sbin/ldconfig -p | grep libpthread
libpthread.so.0 (libc6, OS ABI: Linux 2.6.4) => /lib/libpthread.so.0
And you can check which library your application is using:
ldd foo
linux-gate.so.1 => (0xffffe000)
libpthread.so.0 => /lib/libpthread.so.0 (0xb7f9e000)
libxml2.so.2 => /usr/lib/libxml2.so.2 (0xb7e6e000)
librt.so.1 => /lib/librt.so.1 (0xb7e65000)
libm.so.6 => /lib/libm.so.6 (0xb7d5b000)
libc.so.6 => /lib/libc.so.6 (0xb7c2e000)
/lib/ld-linux.so.2 (0xb7fc7000)
libdl.so.2 => /lib/libdl.so.2 (0xb7c2a000)
libz.so.1 => /lib/libz.so.1 (0xb7c18000)
android:inputMethod
is deprecated, instead use inputType
:
android:inputType="numberPassword"
I know that there are a lot of answers to this question already already but i wanted to share my experience as none of the answers provided fixed this issue for me.
After about a day of exploring different solutions I believe the issue was that I have recently installed XAMPP and it was interfering with the MySQL workbench. I have tried changing the port numbers however this hasn't helped, and it seems that both programs are sharing configuration files. Repairing MySQL in the Control Panel didn't resolve it, so now I am uninstalling MySQL and plan to reinstall it. Another potential solution maybe to uninstall XAMPP however the config files may either be deleted, or left in the xampp folder instead of the MySQL folder by doing so.
to insert into DropDownList:
DropDownList.Items.Insert(0, new ListItem("-- Select item --", "0"));
and to remove item from DropDownList:
DropDownList.Items.Remove(new ListItem("-- Select item --", "0"));
I know that this post is old, but this still comes up in search results. I couldn't find the solution to this problem online, so I ended up figuring it out myself. If you're using Ubuntu, then there is a program called "Apparmor" that is preventing MySQL from seeing the file. Here's what you need to do if you want MySQL to be able to read files from the "tmp" directory:
sudo vim /etc/apparmor.d/usr.sbin.mysqld
Once you are in the file, you're going to see a bunch of directories that MySQL can use. Add the line /tmp/** rwk
to the file (I am not sure that it matters where, but here is a sample of where I put it):
/etc/mysql/*.pem r,
/etc/mysql/conf.d/ r,
/etc/mysql/conf.d/* r,
/etc/mysql/*.cnf r,
/usr/lib/mysql/plugin/ r,
/usr/lib/mysql/plugin/*.so* mr,
/usr/sbin/mysqld mr,
/usr/share/mysql/** r,
/var/log/mysql.log rw,
/var/log/mysql.err rw,
/var/lib/mysql/ r,
/var/lib/mysql/** rwk,
/tmp/** rwk,
/var/log/mysql/ r,
/var/log/mysql/* rw,
/var/run/mysqld/mysqld.pid w,
/var/run/mysqld/mysqld.sock w,
/run/mysqld/mysqld.pid w,
/run/mysqld/mysqld.sock w,
Now all you need to do is reload Apparmor:
sudo /etc/init.d/apparmor reload
Note I used "vim", but substitute that with whatever your favorite text editor is that you know how to use.
I ignore all classes residing in target folder from git. add following line in open .gitignore file:
/.class
OR
*/target/**
It is working perfectly for me. try it.
const generate = n => String(Math.ceil(Math.random() * 10**n)).padStart(n, '0')
// n being the length of the random number.
Use a parseInt()
or Number()
on the result if you want an integer.
If you don't want the first integer to be a 0 then you could use padEnd()
instead of padStart()
.
CREATE TABLE someTable (
id serial PRIMARY KEY,
col1 int NOT NULL,
col2 int NOT NULL,
UNIQUE (col1, col2)
)
autoincrement
is not postgresql. You want a serial
.
If col1
and col2
make a unique and can't be null then they make a good primary key:
CREATE TABLE someTable (
col1 int NOT NULL,
col2 int NOT NULL,
PRIMARY KEY (col1, col2)
)
You can annotate a class or a method with SuppressWarnings
@java.lang.SuppressWarnings("squid:S00112")
squid:S00112 in this case is a Sonar issue ID. You can find this ID in the Sonar UI. Go to Issues Drilldown. Find an issue you want to suppress warnings on. In the red issue box in your code is there a Rule link with a definition of a given issue. Once you click that you will see the ID at the top of the page.
High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.
LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.
Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.
As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.
Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.
This line looks questionable:
page_output.innerHTML = str_output;
You can use .innerHTML
within jQuery, or you can use it without, but you have to address the selector semantically one way or the other:
$('#page_output').innerHTML /* for jQuery */
document.getElementByID('page_output').innerHTML /* for standard JS */
or better yet
$('#page_output').html(str_output);
To add more information to the correct answer above, after reading an example from Android-er I found you can easily convert your preference activity into a preference fragment. If you have the following activity:
public class MyPreferenceActivity extends PreferenceActivity
{
@Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.my_preference_screen);
}
}
The only changes you have to make is to create an internal fragment class, move the addPreferencesFromResources()
into the fragment, and invoke the fragment from the activity, like this:
public class MyPreferenceActivity extends PreferenceActivity
{
@Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
}
public static class MyPreferenceFragment extends PreferenceFragment
{
@Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.my_preference_screen);
}
}
}
There may be other subtleties to making more complex preferences from fragments; if so, I hope someone notes them here.
This is quicker than iterating through the array manually:
static bool isStringInArray(string[] strArray, string key)
{
if (strArray.Contains(key))
return true;
return false;
}
I'm extending the solution by Rushi to following (which solved the puzzle for me)
var cellInfo = Grid1.SelectedCells[0];
var content = (cellInfo.Column.GetCellContent(cellInfo.Item) as TextBlock).Text;
I think another benefit of using the MVC pattern is that it opens up the doors to other approaches to the design, such as MVP/Presenter first and the many other MV* patterns.
Without this fundamental segregation of the design "components" the adoption of these techniques would be much more difficult.
I think it helps to make your code even more interface-based.. Not only within the individual project, but you can almost start to develop common "views" which mean you can template lot more of the "grunt" code used in your applications. For example, a very abstract "data view" which simply takes a bunch of data and throws it to a common grid layout.
If I remember correctly, this is a pretty good podcast on MV* patterns (listened to it a while ago!)
Use setBackgroundResource(R.drawable.xml/png)
This may have changed since the question was asked, but there is a difference between stopping an instance and terminating an instance.
If your instance is EBS-based, it can be stopped. It will remain in your account, but you will not be charged for it (you will continue to be charged for EBS storage associated with the instance and unused Elastic IP addresses). You can re-start the instance at any time.
If the instance is terminated, it will be deleted from your account. You’ll be charged for any remaining EBS volumes, but by default the associated EBS volume will be deleted. This can be configured when you create the instance using the command-line EC2 API Tools.
dir()
is the simple way. See here:
Funkodebat posted a great solution which I have referenced many times. Still, I find myself writing my own working model each time I need this. So, here is my working model... with some added clarity.
First of all, the height of the text is equal to the pixel font size. Now, this was something I read a while ago, and it has worked out in my calculations. I'm not sure if this works with all fonts, but it seems to work with Arial, sans-serif.
Also, to make sure that you fit all of the text in your canvas (and don't trim the tails off of your "p"'s) you need to set context.textBaseline*.
You will see in the code that we are rotating the text about its center. To do this, we need to set context.textAlign = "center" and the context.textBaseline to bottom, otherwise, we trim off parts of our text.
Why resize the canvas?
I usually have a canvas that isn't appended to the page. I use it to draw all of my rotated text, then I draw it onto another canvas which I display.
For example, you can use this canvas to draw all of the labels for a chart (one by one) and draw the hidden canvas onto the chart canvas where you need the label (context.drawImage(hiddenCanvas, 0, 0);
).
IMPORTANT NOTE: Set your font before measuring your text, and re-apply all of your styling to the context after resizing your canvas. A canvas's context is completely reset when the canvas is resized.
Hope this helps!
var c = document.getElementById("myCanvas");_x000D_
var ctx = c.getContext("2d");_x000D_
var font, text, x, y;_x000D_
_x000D_
text = "Mississippi";_x000D_
_x000D_
//Set font size before measuring_x000D_
font = 20;_x000D_
ctx.font = font + 'px Arial, sans-serif';_x000D_
//Get width of text_x000D_
var metrics = ctx.measureText(text);_x000D_
//Set canvas dimensions_x000D_
c.width = font;//The height of the text. The text will be sideways._x000D_
c.height = metrics.width;//The measured width of the text_x000D_
//After a canvas resize, the context is reset. Set the font size again_x000D_
ctx.font = font + 'px Arial';_x000D_
//Set the drawing coordinates_x000D_
x = font/2;_x000D_
y = metrics.width/2;_x000D_
//Style_x000D_
ctx.fillStyle = 'black';_x000D_
ctx.textAlign = 'center';_x000D_
ctx.textBaseline = "bottom";_x000D_
//Rotate the context and draw the text_x000D_
ctx.save();_x000D_
ctx.translate(x, y);_x000D_
ctx.rotate(-Math.PI / 2);_x000D_
ctx.fillText(text, 0, font / 2);_x000D_
ctx.restore();
_x000D_
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
_x000D_
Since nobody has mentioned it, I'd like to add that Facebook chat is written in Erlang.
<input type="radio" name="radio" value="creditcard" />
<input type="radio" name="radio" value="cash"/>
<input type="radio" name="radio" value="cheque"/>
<input type="radio" name="radio" value="instore"/>
$("input[name='radio']:checked").val()
PHP already knows the current system's newline character(s). Just use the EOL constant.
explode(PHP_EOL,$string)
Actually, we're now in globalized world of 21st century and people no longer communicate using ASCII only so when anwering question about "is it letters only" you need to take into account letters from non-ASCII alphabets as well. Python has a pretty cool unicodedata library which among other things allows categorization of Unicode characters:
unicodedata.category('?')
'Lo'
unicodedata.category('A')
'Lu'
unicodedata.category('1')
'Nd'
unicodedata.category('a')
'Ll'
The categories and their abbreviations are defined in the Unicode standard. From here you can quite easily you can come up with a function like this:
def only_letters(s):
for c in s:
cat = unicodedata.category(c)
if cat not in ('Ll','Lu','Lo'):
return False
return True
And then:
only_letters('Bzdrezylo')
True
only_letters('He7lo')
False
As you can see the whitelisted categories can be quite easily controlled by the tuple inside the function. See this article for a more detailed discussion.
As everyone already mentioned, this is not the best way of using lists in Scala...
scala> val list = scala.collection.mutable.MutableList[String]()
list: scala.collection.mutable.MutableList[String] = MutableList()
scala> list += "hello"
res0: list.type = MutableList(hello)
scala> list += "world"
res1: list.type = MutableList(hello, world)
scala> list mkString " "
res2: String = hello world
ActiveRecord::Base.connection.tables
To add to the previous answers, and address some of the discussions around nulls and NPE I'm using Guava Optionals to handle absent/invalid cases. This works great for URI/parameter parsing.
public enum E {
A,B,C;
public static Optional<E> fromString(String s) {
try {
return Optional.of(E.valueOf(s.toUpperCase()));
} catch (IllegalArgumentException|NullPointerException e) {
return Optional.absent();
}
}
}
For those not aware, here's some more info on avoiding null with Optional: https://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained#Optional
A single listening port can accept more than one connection simultaneously.
There is a '64K' limit that is often cited, but that is per client per server port, and needs clarifying.
Each TCP/IP packet has basically four fields for addressing. These are:
source_ip source_port destination_ip destination_port
<----- client ------> <--------- server ------------>
Inside the TCP stack, these four fields are used as a compound key to match up packets to connections (e.g. file descriptors).
If a client has many connections to the same port on the same destination, then three of those fields will be the same - only source_port
varies to differentiate the different connections. Ports are 16-bit numbers, therefore the maximum number of connections any given client can have to any given host port is 64K.
However, multiple clients can each have up to 64K connections to some server's port, and if the server has multiple ports or either is multi-homed then you can multiply that further.
So the real limit is file descriptors. Each individual socket connection is given a file descriptor, so the limit is really the number of file descriptors that the system has been configured to allow and resources to handle. The maximum limit is typically up over 300K, but is configurable e.g. with sysctl.
The realistic limits being boasted about for normal boxes are around 80K for example single threaded Jabber messaging servers.
PHP by itself has no SMS module or functions and doesn't allow you to send SMS.
SMS ( Short Messaging System) is a GSM technology an you need a GSM provider that will provide this service for you and may have an PHP API implementation for it.
Usually people in telecom business use Asterisk to handle calls and sms programming.
Wrap your Promise inside a function or it will start to do its job right away. Plus, you can pass parameters to the function:
var some_function = function(username, password)
{
return new Promise(function(resolve, reject)
{
/*stuff using username, password*/
if ( /* everything turned out fine */ )
{
resolve("Stuff worked!");
}
else
{
reject(Error("It broke"));
}
});
}
Then, use it:
some_module.some_function(username, password).then(function(uid)
{
// stuff
})
ES6:
const some_function = (username, password) =>
{
return new Promise((resolve, reject) =>
{
/*stuff using username, password*/
if ( /* everything turned out fine */ )
{
resolve("Stuff worked!");
}
else
{
reject(Error("It broke"));
}
});
};
Use:
some_module.some_function(username, password).then(uid =>
{
// stuff
});
You either want to add "." to your CLASSPATH to specify the current directory, or add it manually at run time the way unbeli suggested.
Just extending Barnards's answer with commons-io. Separate answer because I can not format code in comments.
InputStream is = null;
try {
is = url.openStream ();
byte[] imageBytes = IOUtils.toByteArray(is);
}
catch (IOException e) {
System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
e.printStackTrace ();
// Perform any other exception handling that's appropriate.
}
finally {
if (is != null) { is.close(); }
}
I highly recommend reading the docs on the Intent.FLAG_ACTIVITY_CLEAR_TOP
flag. Using it will not necessarily go back all the way to the first (main
) activity. The flag will only remove all existing activities up to the activity class given in the Intent
. This is explained well in the docs:
For example, consider a task consisting of the activities: A, B, C, D.
If D calls startActivity() with an Intent that resolves to the component of
activity B, then C and D will be finished and B receive the given Intent,
resulting in the stack now being: A, B.
Note that the activity can set to be moved to the foreground (i.e., clearing all other activities on top of it), and then also being relaunched, or only get onNewIntent()
method called.
When it is on server side, use web services - maybe RESTful with JSON.
When Java code is in applet you can use JavaScript bridge. The bridge between the Java and JavaScript programming languages, known informally as LiveConnect, is implemented in Java plugin. Formerly Mozilla-specific LiveConnect functionality, such as the ability to call static Java methods, instantiate new Java objects and reference third-party packages from JavaScript, is now available in all browsers.
Below is example from documentation. Look at methodReturningString
.
Java code:
public class MethodInvocation extends Applet {
public void noArgMethod() { ... }
public void someMethod(String arg) { ... }
public void someMethod(int arg) { ... }
public int methodReturningInt() { return 5; }
public String methodReturningString() { return "Hello"; }
public OtherClass methodReturningObject() { return new OtherClass(); }
}
public class OtherClass {
public void anotherMethod();
}
Web page and JavaScript code:
<applet id="app"
archive="examples.jar"
code="MethodInvocation" ...>
</applet>
<script language="javascript">
app.noArgMethod();
app.someMethod("Hello");
app.someMethod(5);
var five = app.methodReturningInt();
var hello = app.methodReturningString();
app.methodReturningObject().anotherMethod();
</script>
Because datetime
is the module. The class is datetime.datetime
.
import datetime
dtDate = datetime.datetime.strptime(sDate,"%m/%d/%Y")
My computer had the wrong locale set.
I first did
>>> import locale
>>> locale.getpreferredencoding(False)
'ANSI_X3.4-1968'
locale.getpreferredencoding(False)
is the function called by open()
when you don't provide an encoding. The output should be 'UTF-8'
, but in this case it's some variant of ASCII.
Then I ran the bash command locale
and got this output
$ locale
LANG=
LANGUAGE=
LC_CTYPE="POSIX"
LC_NUMERIC="POSIX"
LC_TIME="POSIX"
LC_COLLATE="POSIX"
LC_MONETARY="POSIX"
LC_MESSAGES="POSIX"
LC_PAPER="POSIX"
LC_NAME="POSIX"
LC_ADDRESS="POSIX"
LC_TELEPHONE="POSIX"
LC_MEASUREMENT="POSIX"
LC_IDENTIFICATION="POSIX"
LC_ALL=
So, I was using the default Ubuntu locale, which causes Python to open files as ASCII instead of UTF-8. I had to set my locale to en_US.UTF-8
sudo apt install locales
sudo locale-gen en_US en_US.UTF-8
sudo dpkg-reconfigure locales
If you can't change the locale system wide, you can invoke all your Python code like this:
PYTHONIOENCODING="UTF-8" python3 ./path/to/your/script.py
or do
export PYTHONIOENCODING="UTF-8"
to set it in the shell you run that in.
This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:
var arrayOfObjects = [{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}];
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
for (var property in object) {
alert('item ' + i + ': ' + property + '=' + object[property]);
}
// If property names are known beforehand, you can also just do e.g.
// alert(object.id + ',' + object.Title);
}
If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval()
here.
var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...
To learn more about JSON, check MDN web docs: Working with JSON .
You can try also like this:
- (void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event {
for (id textField in self.view.subviews) {
if ([textField isKindOfClass:[UITextField class]] && [textField isFirstResponder]) {
[textField resignFirstResponder];
}
}
}
I didn't try it but it seems a good solution
Try with this:
var fn_name = "Colours",
fn = eval("populate_"+fn_name);
fn(args1,argsN);
All answers are old, I recommend and I am a big fan of requests
From homepage:
Python’s standard urllib2 module provides most of the HTTP capabilities you need, but the API is thoroughly broken. It was built for a different time — and a different web. It requires an enormous amount of work (even method overrides) to perform the simplest of tasks.
Things shouldn't be this way. Not in Python.
Many answers here claims to use git reset ... <file>
or git checkout ... <file>
but by doing so, you will loose every modifications on <file>
committed after the commit you want to revert.
If you want to revert changes from one commit on a single file only, just as git revert
would do but only for one file (or say a subset of the commit files), I suggest to use both git diff
and git apply
like that (with <sha>
= the hash of the commit you want to revert) :
git diff <sha>^ <sha> path/to/file.ext | git apply -R
Basically, it will first generate a patch corresponding to the changes you want to revert, and then reverse-apply the patch to drop those changes.
Of course, it shall not work if reverted lines had been modified by any commit between <sha1>
and HEAD
(conflict).
The answers to these questions vary depending on whether you are using a stream socket (SOCK_STREAM
) or a datagram socket (SOCK_DGRAM
) - within TCP/IP, the former corresponds to TCP and the latter to UDP.
How do you know how big to make the buffer passed to recv()
?
SOCK_STREAM
: It doesn't really matter too much. If your protocol is a transactional / interactive one just pick a size that can hold the largest individual message / command you would reasonably expect (3000 is likely fine). If your protocol is transferring bulk data, then larger buffers can be more efficient - a good rule of thumb is around the same as the kernel receive buffer size of the socket (often something around 256kB).
SOCK_DGRAM
: Use a buffer large enough to hold the biggest packet that your application-level protocol ever sends. If you're using UDP, then in general your application-level protocol shouldn't be sending packets larger than about 1400 bytes, because they'll certainly need to be fragmented and reassembled.
What happens if recv
gets a packet larger than the buffer?
SOCK_STREAM
: The question doesn't really make sense as put, because stream sockets don't have a concept of packets - they're just a continuous stream of bytes. If there's more bytes available to read than your buffer has room for, then they'll be queued by the OS and available for your next call to recv
.
SOCK_DGRAM
: The excess bytes are discarded.
How can I know if I have received the entire message?
SOCK_STREAM
: You need to build some way of determining the end-of-message into your application-level protocol. Commonly this is either a length prefix (starting each message with the length of the message) or an end-of-message delimiter (which might just be a newline in a text-based protocol, for example). A third, lesser-used, option is to mandate a fixed size for each message. Combinations of these options are also possible - for example, a fixed-size header that includes a length value.
SOCK_DGRAM
: An single recv
call always returns a single datagram.
Is there a way I can make a buffer not have a fixed amount of space, so that I can keep adding to it without fear of running out of space?
No. However, you can try to resize the buffer using realloc()
(if it was originally allocated with malloc()
or calloc()
, that is).
You should be able to use Windows "UNC" paths with robocopy. For example:
robocopy \\myServer\myFolder\myFile.txt \\myOtherServer\myOtherFolder
Robocopy has the ability to recover from certain types of network hiccups automatically.
It might be helpful to address this question from a package deployment perspective.
There are many tutorials out there that explain how to publish a package to PyPi. Below are a couple I have used;
My experience is that most of these tutorials only have you use the .tar of the source, not a wheel. Thus, when installing packages created using these tutorials, I've received the "Failed to build wheel" error.
I later found the link on PyPi to the Python Software Foundation's docs PSF Docs. I discovered that their setup and build process is slightly different, and does indeed included building a wheel file.
After using the officially documented method, I no longer received the error when installing my packages.
So, the error might simply be a matter of how the developer packaged and deployed the project. None of us were born knowing how to use PyPi, and if they happened upon the wrong tutorial -- well, you can fill in the blanks.
I'm sure that is not the only reason for the error, but I'm willing to bet that is a major reason for it.
I've had this problem before, you can go to "advanced" tab of "choose a data source" page and click on "suggested types" button, and set the "number of rows" as much as you want. after that, the type and text qualified are set to the true values.
i applied the above solution and can convert my data to SQL.
If i understood correct try this one
$headers = "Bcc: [email protected]";
or
$headers = "Cc: [email protected]";
Open $CATALINA_BASE/conf/web.xml
and find this
<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly -->
<!-- created sessions by modifying the value below. -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.
This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different
Per the MySQL docs DECLARE works only at the start of a BEGIN...END block as in a stored program.
I know this has been answered, but here are a couple of extension methods (for .NET 3.0+) that do the conversion. :)
/// <summary>
/// Converts a <see cref="System.Drawing.Image"/> into a WPF <see cref="BitmapSource"/>.
/// </summary>
/// <param name="source">The source image.</param>
/// <returns>A BitmapSource</returns>
public static BitmapSource ToBitmapSource(this System.Drawing.Image source)
{
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(source);
var bitSrc = bitmap.ToBitmapSource();
bitmap.Dispose();
bitmap = null;
return bitSrc;
}
/// <summary>
/// Converts a <see cref="System.Drawing.Bitmap"/> into a WPF <see cref="BitmapSource"/>.
/// </summary>
/// <remarks>Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject.
/// </remarks>
/// <param name="source">The source bitmap.</param>
/// <returns>A BitmapSource</returns>
public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)
{
BitmapSource bitSrc = null;
var hBitmap = source.GetHbitmap();
try
{
bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
}
catch (Win32Exception)
{
bitSrc = null;
}
finally
{
NativeMethods.DeleteObject(hBitmap);
}
return bitSrc;
}
and the NativeMethods class (to appease FxCop)
/// <summary>
/// FxCop requires all Marshalled functions to be in a class called NativeMethods.
/// </summary>
internal static class NativeMethods
{
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeleteObject(IntPtr hObject);
}
The correct character (comma or colon) depends on the purpose.
Comma (,
) will sum only the two cells in question.
Colon (:
) will sum all the cells within the range with corners defined by those two cells.
You can use a simple regex (updated version from user viriathus as eregi
is deprecated)
if (preg_match('#^http#', $url) === 1) {
// Starts with http (case sensitive).
}
or if you want a case insensitive search
if (preg_match('#^http#i', $url) === 1) {
// Starts with http (case insensitive).
}
Regexes allow to perform more complex tasks
if (preg_match('#^https?://#i', $url) === 1) {
// Starts with http:// or https:// (case insensitive).
}
Performance wise, you don't need to create a new string (unlike with substr) nor parse the whole string if it doesn't start with what you want. You will have a performance penalty though the 1st time you use the regex (you need to create/compile it).
This extension maintains a global per-thread cache of compiled regular expressions (up to 4096). http://www.php.net/manual/en/intro.pcre.php
.border-blue.background { ... }
is for one item with multiple classes.
.border-blue, .background { ... }
is for multiple items each with their own class.
.border-blue .background { ... }
is for one item where '.background' is the child of '.border-blue'.
See Chris' answer for a more thorough explanation.
Example 2 on w3schools shows what you are trying to achieve.
<?php header("Content-type:application/pdf"); // It will be called downloaded.pdf header("Content-Disposition:attachment;filename='downloaded.pdf'"); // The PDF source is in original.pdf readfile("original.pdf"); ?>
Also remember that,
It is important to notice that header() must be called before any actual output is sent (In PHP 4 and later, you can use output buffering to solve this problem)
I had a similar problem last week. I received a number of CSV files with varying encodings. Before importing into the database I then used the chardet libary to automatically sniff out the correct encoding.
Chardet is a port from Mozillas character detection engine and if the sample size is large enough (one accentuated character will not do) works really well.
i also had this issue- very annoying and haven't found a satisfactory sql answer myself yet (aside from long-winded ones involving creating temp tables etc.) and i didn't have time to explore it to the conclusion i'd have liked.
In the end just used SQL Server Management Studio to do it by selecting the table, right-clicking on the column and hitting rename. simples!
obviously i'd rather know how to do it without a gui but sometimes you've just gotta get sh** done!
Your regular expression should look like:
/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/
Here is an explanation:
/^
(?=.*\d) // should contain at least one digit
(?=.*[a-z]) // should contain at least one lower case
(?=.*[A-Z]) // should contain at least one upper case
[a-zA-Z0-9]{8,} // should contain at least 8 from the mentioned characters
$/
The below Query works but very slow... copied from vyaskn.tripod.com
Declare @SearchStr nvarchar(100)
SET @SearchStr='Search String' BEGIN
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128),
@SearchStr2 nvarchar(110) SET @TableName = '' SET @SearchStr2 =
QUOTENAME('%' + @SearchStr + '%','''')
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName = (
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' +
QUOTENAME(TABLE_NAME)) FROM INFORMATION_SCHEMA.TABLES
WHERE
TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)),
'IsMSShipped') = 0)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName = (
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO #Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName +
', 3630) FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM #Results END
if you use Vuejs, just make it by vue-shortkey plugin, everything will be simple
https://www.npmjs.com/package/vue-shortkey
v-shortkey="['meta', 'enter']"·
@shortkey="metaEnterTrigged"
This can be helpful as well.
SELECT YEAR(0), MONTH(0), DAY(0);
or
SELECT YEAR(getdate()), MONTH(getdate()), DAY(getdate());
or
SELECT YEAR(yourDateField), MONTH(yourDateField), DAY(yourDateField);