Simple solution which worked for me.
Seems like only real solutions today revolve around scaling out or sharding. All modern databases (NoSQLs as well as NewSQLs) support horizontal scaling right out of the box, at the database layer, without the need for the application to have sharding code or something.
Unfortunately enough, for the trusted good-old MySQL, sharding is not provided "out of the box". ScaleBase (disclaimer: I work there) is a maker of a complete scale-out solution an "automatic sharding machine" if you like. ScaleBae analyzes your data and SQL stream, splits the data across DB nodes, and aggregates in runtime – so you won’t have to! And it's free download.
Don't get me wrong, NoSQLs are great, they're new, new is more choice and choice is always good!! But choosing NoSQL comes with a price, make sure you can pay it...
You can see here some more data about MySQL, NoSQL...: http://www.scalebase.com/extreme-scalability-with-mongodb-and-mysql-part-1-auto-sharding
Hope that helped.
$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
ADD COLUMN `ping_status` INT(1) NOT NULL
AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";
I believe you need to have ADD COLUMN
and use AFTER
, not BEFORE
.
In case you want to place column at the beginning of a table, use the FIRST
statement:
$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
ADD COLUMN `ping_status` INT(1) NOT NULL
FIRST";
Try it.. It will first look for anchor tag that contain span with class "ui-icon-circle-triangle-w", then it set the text of span to "<<".
$('a span.ui-icon-circle-triangle-w').text('<<');
I don't think it is possible to share a database link between more than one user but not all. They are either private (for one user only) or public (for all users).
A good way around this is to create a view in SCHEMA_B that exposes the table you want to access through the database link. This will also give you good control over who is allowed to select from the database link, as you can control the access to the view.
Do like this:
create database link db_link... as before;
create view mytable_view as select * from mytable@db_link;
grant select on mytable_view to myuser;
In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])
In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]:
A B C D
1 0.319124 0.296653 0.138206 0.246017
2 0.376994 0.326481 0.230464 0.066062
3 0.036134 0.192954 0.430341 0.340571
In fact, most compilers emit the same code for both functions calls, because references are generally implemented using pointers.
Following this logic, when an argument of (non-const) reference type is used in the function body, the generated code will just silently operate on the address of the argument and it will dereference it. In addition, when a call to such a function is encountered, the compiler will generate code that passes the address of the arguments instead of copying their value.
Basically, references and pointers are not very different from an implementation point of view, the main (and very important) difference is in the philosophy: a reference is the object itself, just with a different name.
References have a couple more advantages compared to pointers (e. g. they can't be NULL
, so they are safer to use). Consequently, if you can use C++, then passing by reference is generally considered more elegant and it should be preferred. However, in C, there's no passing by reference, so if you want to write C code (or, horribile dictu, code that compiles with both a C and a C++ compiler, albeit that's not a good idea), you'll have to restrict yourself to using pointers.
Try that:
/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
/sbin/swapon /var/swap.1
from sklearn.metrics import confusion_matrix
import seaborn as sns
import matplotlib.pyplot as plt
model.fit(train_x, train_y,validation_split = 0.1, epochs=50, batch_size=4)
y_pred=model.predict(test_x,batch_size=15)
cm =confusion_matrix(test_y.argmax(axis=1), y_pred.argmax(axis=1))
index = ['neutral','happy','sad']
columns = ['neutral','happy','sad']
cm_df = pd.DataFrame(cm,columns,index)
plt.figure(figsize=(10,6))
sns.heatmap(cm_df, annot=True)
This will depend on the logging configuration. The default value will depend on the framework being used. The idea is that later on by changing a configuration setting from INFO to DEBUG you will see a ton of more (or less if the other way around) lines printed without recompiling the whole application.
If you think which one to use then it boils down to thinking what you want to see on which level. For other levels for example in Log4J look at the API, http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Level.html
Open the output stream and store properties after you have closed the input stream.
FileInputStream in = new FileInputStream("First.properties");
Properties props = new Properties();
props.load(in);
in.close();
FileOutputStream out = new FileOutputStream("First.properties");
props.setProperty("country", "america");
props.store(out, null);
out.close();
I hope this helps:
begin try drop table #tempTable end try
begin catch end catch
Try this, example, the required property in below input tag will ensure that the name field should be submitted empty.
<input type="text" placeholder="Your Name" required />
You can always do a git checkout <SHA code>
of the previous version and then commit again with the new code.
You can also use OPENROWSET to import excel file in sql server.
SELECT * INTO Your_Table FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;Database=C:\temp\MySpreadsheet.xlsx',
'SELECT * FROM [Data$]')
pymemcompat.h:10: fatal error: Python.h: ?????????
Boy you should post your error log with LANG=C
or people can't get the real cause from your log. The log above says: No such file or directory.
That means you should install the develop package of Python. That's usually "python-dev" on Debian flavored distro, and "python-devel" on RHEL flavored distro.
Note: This answer addresses part of the problem. For a complete solution (in the form of a library), look at Paul Burke's answer.
You could use the URI to obtain document id
, and then query either MediaStore.Images.Media.EXTERNAL_CONTENT_URI
or MediaStore.Images.Media.INTERNAL_CONTENT_URI
(depending on the SD card situation).
To get document id:
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(uriThatYouCurrentlyHave);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ id }, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
Reference: I'm not able to find the post that this solution is taken from. I wanted to ask the original poster to contribute here. Will look some more tonight.
if none of this answers solves you the problem, I solved it by removing the tables and creating them again automatically in this way:
when creating the backup, first backup structure and be sure of add:
DROP TABLE / VIEW / PROCEDURE / FUNCTION / EVENT
CREATE PROCEDURE / FUNCTION / EVENT
IF NOT EXISTS
AUTO_INCREMENT
then just use this backup with your db and it will remove and recreate the tables you need.
Then you backup just data, and do the same, and it will work.
Split() Variation
I just want to add this variation for reference. Urls are often strings and so it's simpler to use the Split()
method than Uri.GetLeftPart()
. And Split()
can also be made to work with relative, empty, and null values whereas Uri throws an exception. Additionally, Urls may also contain a hash such as /report.pdf#page=10
(which opens the pdf at a specific page).
The following method deals with all of these types of Urls:
var path = (url ?? "").Split('?', '#')[0];
Example Output:
page.html ---> page.html
Dictionary<string, Dictionary<string, string>> like = new Dictionary<string, Dictionary<string, string>>();
Dictionary<string, string> first = like.Values.First();
The symlink solution for this stopped working for me in zsh today. I ended up creating an alias in my .zshrc
file instead:
alias atom='sh /Applications/Atom.app/Contents/Resources/app/atom.sh'
Note that, in addition to number of predictive variables, the Adjusted R-squared formula above also adjusts for sample size. A small sample will give a deceptively large R-squared.
Ping Yin & Xitao Fan, J. of Experimental Education 69(2): 203-224, "Estimating R-squared shrinkage in multiple regression", compares different methods for adjusting r-squared and concludes that the commonly-used ones quoted above are not good. They recommend the Olkin & Pratt formula.
However, I've seen some indication that population size has a much larger effect than any of these formulas indicate. I am not convinced that any of these formulas are good enough to allow you to compare regressions done with very different sample sizes (e.g., 2,000 vs. 200,000 samples; the standard formulas would make almost no sample-size-based adjustment). I would do some cross-validation to check the r-squared on each sample.
I wanted a long dash like line, so I used this.
.dash{_x000D_
border: 1px solid red;_x000D_
width: 120px;_x000D_
height: 0px;_x000D_
_x000D_
}
_x000D_
<div class="dash"></div>
_x000D_
Firstly, we just CAN'T make the variable final as its state may be changing during the run of the program and our decisions within the inner class override may depend on its current state.
Secondly, good object-oriented programming practice suggests using only variables/constants that are vital to the class definition as class members. This means that if the variable we are referencing within the anonymous inner class override is just a utility variable, then it should not be listed amongst the class members.
But – as of Java 8 – we have a third option, described here :
https://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html
Starting in Java SE 8, if you declare the local class in a method, it can access the method's parameters.
So now we can simply put the code containing the new inner class & its method override into a private method whose parameters include the variable we call from inside the override. This static method is then called after the btnInsert declaration statement :-
. . . .
. . . .
Statement statement = null;
. . . .
. . . .
Button btnInsert = new Button(shell, SWT.NONE);
addMouseListener(Button btnInsert, Statement statement); // Call new private method
. . .
. . .
. . .
private static void addMouseListener(Button btn, Statement st) // New private method giving access to statement
{
btn.addMouseListener(new MouseAdapter()
{
@Override
public void mouseDown(MouseEvent e)
{
String name = text.getText();
String from = text_1.getText();
String to = text_2.getText();
String price = text_3.getText();
String query = "INSERT INTO booking (name, fromst, tost,price) VALUES ('"+name+"', '"+from+"', '"+to+"', '"+price+"')";
try
{
st.executeUpdate(query);
}
catch (SQLException e1)
{
e1.printStackTrace(); // TODO Auto-generated catch block
}
}
});
return;
}
. . . .
. . . .
. . . .
First of all, public static
non-final
fields are evil. Spring does not allow injecting to such fields for a reason.
Your workaround is valid, you don't even need getter/setter, private
field is enough. On the other hand try this:
@Value("${my.name}")
public void setPrivateName(String privateName) {
Sample.name = privateName;
}
(works with @Autowired
/@Resource
). But to give you some constructive advice: Create a second class with private
field and getter instead of public static
field.
The simplest solution to this, that also works between different Linux machines through ssh
is:
Check whether vim supports X-11 clipboard: vim --version | grep clipboard
. If it reports back -clipboard
and -xterm_clipboard
you should install either vim-gtk
or vim-gnome
(gvim on arch linux)
Add the following lines to your .vimrc
:
set clipboard=unnamedplus set paste
ssh -Y machine
Now copying and pasting should work exactly as expected on a single, and across different machines by only using y
for yank and p
for paste. NB modify .vimrc
on all machines where you want to use this feature.
An alternative way you can do this, is using dictionary comprehension. This should be compatible with 2.7+
result = {
key: value for key, value in
{"foo": "bar", "lorem": None}.items()
if value
}
just use UPDATE query without condition like this
UPDATE tablename SET online_status=0;
SELECT
SUBSTRING( '[email protected]', charindex('@','[email protected]',1) + 1, charindex('.','[email protected]',1) - charindex('@','[email protected]',1) - 1 )
If you have Div as follows in one Iframe
<iframe id="ifrmReportViewer" name="ifrmReportViewer" frameborder="0" width="980"
<div id="EndLetterSequenceNoToShow" runat="server"> 11441551 </div> Or
<form id="form1" runat="server">
<div style="clear: both; width: 998px; margin: 0 auto;" id="divInnerForm">
Some Text
</div>
</form>
</iframe>
Then you can find the text of those Div using the following code
var iContentBody = $("#ifrmReportViewer").contents().find("body");
var endLetterSequenceNo = iContentBody.find("#EndLetterSequenceNoToShow").text();
var divInnerFormText = iContentBody.find("#divInnerForm").text();
I hope this will help someone.
In my case 'await' never finished because of exception while executing the request, e.g. server not responding, etc. Surround it with try..catch to identify what happened, it'll also complete your 'await' gracefully.
public async Task<Stuff> GetStuff(string id)
{
string path = $"/api/v2/stuff/{id}";
try
{
HttpResponseMessage response = await client.GetAsync(path);
if (response.StatusCode == HttpStatusCode.OK)
{
string json = await response.Content.ReadAsStringAsync();
return JsonUtility.FromJson<Stuff>(json);
}
else
{
Debug.LogError($"Could not retrieve stuff {id}");
}
}
catch (Exception exception)
{
Debug.LogError($"Exception when retrieving stuff {exception}");
}
return null;
}
You can do it by setting the aspect of the image manually (or by letting it auto-scale to fill up the extent of the figure).
By default, imshow
sets the aspect of the plot to 1, as this is often what people want for image data.
In your case, you can do something like:
import matplotlib.pyplot as plt
import numpy as np
grid = np.random.random((10,10))
fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, figsize=(6,10))
ax1.imshow(grid, extent=[0,100,0,1])
ax1.set_title('Default')
ax2.imshow(grid, extent=[0,100,0,1], aspect='auto')
ax2.set_title('Auto-scaled Aspect')
ax3.imshow(grid, extent=[0,100,0,1], aspect=100)
ax3.set_title('Manually Set Aspect')
plt.tight_layout()
plt.show()
If you need to inject a whole file then you can use this:
With Browser.Document
Dim Head As HtmlElement = .GetElementsByTagName("head")(0)
Dim Script As HtmlElement = .CreateElement("script")
Dim Streamer As New StreamReader(<Here goes path to file as String>)
Using Streamer
Script.SetAttribute("text", Streamer.ReadToEnd())
End Using
Head.AppendChild(Script)
.InvokeScript(<Here goes a method name as String and without parentheses>)
End With
Remember to import System.IO
in order to use the StreamReader
. I hope this helps.
To ignore missing @param
and @return
tags, it's enough to disable the missing
doclint group. This way, the javadoc will still be checked for higher level and syntax issues:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<doclint>all,-missing</doclint>
</configuration>
</plugin>
Note that this is for plugin version 3.0 or newer.
Create a new method for Array class in core level file and use it all over your project.
// say in app.js
Array.prototype.occurrence = function(val) {
return this.filter(e => e === val).length;
}
Use this anywhere in your project -
[1, 2, 4, 5, 2, 7, 2, 9].occurrence(2);
// above line returns 3
I would recommend OAuth 2/3. You can find more information at http://oauth.net/2/
Try this:
var setCanvasSize = function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
There's 3 satellites at least that you must be able to receive from of the 24-32 out there, and they each broadcast a time from a synchronized atomic clock. The differences in those times that you receive at any one time tell you how long the broadcast took to reach you, and thus where you are in relation to the satellites. So, it sort of reads from something, but it doesn't connect to that thing. Note that this doesn't tell you your orientation, many GPSes fake that (and speed) by interpolating data points.
If you don't count the cost of the receiver, it's a free service. Apparently there's higher resolution services out there that are restricted to military use. Those are likely a fixed cost for a license to decrypt the signals along with a confidentiality agreement.
Now your device may support GPS tracking, in which case it might communicate, say via GPRS, to a database which will store the location the device has found itself to be at, so that multiple devices may be tracked. That would require some kind of connection.
Maps are either stored on the device or received over a connection. Navigation is computed based on those maps' databases. These likely are a licensed item with a cost associated, though if you use a service like Google Maps they have the license with NAVTEQ and others.
The MVC 5 stock install puts javascript references in the _Layout.cshtml file that is shared in all pages. So the javascript files were below the main content and document.ready function where all my $'s were.
BOTTOM PART OF _Layout.cshtml:
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
I moved them above the @RenderBody() and all was fine.
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
</body>
</html>
I think you may be looking for org.springframework.beans.factory.config.ListFactoryBean
.
You declare a ListFactoryBean instance, providing the list to be instantiated as a property withe a <list>
element as its value, and give the bean an id
attribute. Then, each time you use the declared id
as a ref
or similar in some other bean declaration, a new copy of the list is instantiated. You can also specify the List
class to be used.
Use Math.round()
function.
Math.round(65.98) // will return 66
Math.round(65.28) // will return 65
"Subscript out of range" indicates that you've tried to access an element from a collection that doesn't exist. Is there a "Sheet1" in your workbook? If not, you'll need to change that to the name of the worksheet you want to protect.
unicode
is meant to handle text. Text is a sequence of code points which may be bigger than a single byte. Text can be encoded in a specific encoding to represent the text as raw bytes(e.g. utf-8
, latin-1
...).
Note that unicode
is not encoded! The internal representation used by python is an implementation detail, and you shouldn't care about it as long as it is able to represent the code points you want.
On the contrary str
in Python 2 is a plain sequence of bytes. It does not represent text!
You can think of unicode
as a general representation of some text, which can be encoded in many different ways into a sequence of binary data represented via str
.
Note: In Python 3, unicode
was renamed to str
and there is a new bytes
type for a plain sequence of bytes.
Some differences that you can see:
>>> len(u'à') # a single code point
1
>>> len('à') # by default utf-8 -> takes two bytes
2
>>> len(u'à'.encode('utf-8'))
2
>>> len(u'à'.encode('latin1')) # in latin1 it takes one byte
1
>>> print u'à'.encode('utf-8') # terminal encoding is utf-8
à
>>> print u'à'.encode('latin1') # it cannot understand the latin1 byte
?
Note that using str
you have a lower-level control on the single bytes of a specific encoding representation, while using unicode
you can only control at the code-point level. For example you can do:
>>> 'àèìòù'
'\xc3\xa0\xc3\xa8\xc3\xac\xc3\xb2\xc3\xb9'
>>> print 'àèìòù'.replace('\xa8', '')
à?ìòù
What before was valid UTF-8, isn't anymore. Using a unicode string you cannot operate in such a way that the resulting string isn't valid unicode text. You can remove a code point, replace a code point with a different code point etc. but you cannot mess with the internal representation.
I got an error because DatePipe is not a provider, so it cannot be injected. One solution is to put it as a provider in your app module but my preferred solution was to instantiate it.
I looked at DatePipe's source code to see how it got the locale: https://github.com/angular/angular/blob/5.2.5/packages/common/src/pipes/date_pipe.ts#L15-L174
I wanted to use it within a pipe, so my example is within another pipe:
import { Pipe, PipeTransform, Inject, LOCALE_ID } from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({
name: 'when',
})
export class WhenPipe implements PipeTransform {
static today = new Date((new Date).toDateString().split(' ').slice(1).join(' '));
datePipe: DatePipe;
constructor(@Inject(LOCALE_ID) private locale: string) {
this.datePipe = new DatePipe(locale);
}
transform(value: string | Date): string {
if (typeof(value) === 'string')
value = new Date(value);
return this.datePipe.transform(value, value < WhenPipe.today ? 'MMM d': 'shortTime')
}
}
The key here is importing Inject, and LOCALE_ID from angular's core, and then injecting that so you can give it to the DatePipe to instantiate it properly.
In your app module you could also add DatePipe to your providers array like this:
import { DatePipe } from '@angular/common';
@NgModule({
providers: [
DatePipe
]
})
Now you can just have it injected in your constructor where needed (like in cexbrayat's answer).
Either solution worked, I don't know which one angular would consider most "correct" but I chose to instantiate it manually since angular didn't provide datepipe as a provider itself.
Set the position to absolute; to move the caption area in the correct position
CSS
.post-content {
background: none repeat scroll 0 0 #FFFFFF;
opacity: 0.5;
margin: -54px 20px 12px;
position: absolute;
}
Thanks a lot Codo.
I've just updated and completed what you have done to :
add, remove and update node (who knows)
Option Explicit
Private ScriptEngine As ScriptControl
Public Sub InitScriptEngine()
Set ScriptEngine = New ScriptControl
ScriptEngine.Language = "JScript"
ScriptEngine.AddCode "function getProperty(jsonObj, propertyName) { return jsonObj[propertyName]; } "
ScriptEngine.AddCode "function getType(jsonObj, propertyName) {return typeof(jsonObj[propertyName]);}"
ScriptEngine.AddCode "function getKeys(jsonObj) { var keys = new Array(); for (var i in jsonObj) { keys.push(i); } return keys; } "
ScriptEngine.AddCode "function addKey(jsonObj, propertyName, value) { jsonObj[propertyName] = value; return jsonObj;}"
ScriptEngine.AddCode "function removeKey(jsonObj, propertyName) { var json = jsonObj; delete json[propertyName]; return json }"
End Sub
Public Function removeJSONProperty(ByVal JsonObject As Object, propertyName As String)
Set removeJSONProperty = ScriptEngine.Run("removeKey", JsonObject, propertyName)
End Function
Public Function updateJSONPropertyValue(ByVal JsonObject As Object, propertyName As String, value As String) As Object
Set updateJSONPropertyValue = ScriptEngine.Run("removeKey", JsonObject, propertyName)
Set updateJSONPropertyValue = ScriptEngine.Run("addKey", JsonObject, propertyName, value)
End Function
Public Function addJSONPropertyValue(ByVal JsonObject As Object, propertyName As String, value As String) As Object
Set addJSONPropertyValue = ScriptEngine.Run("addKey", JsonObject, propertyName, value)
End Function
Public Function DecodeJsonString(ByVal JsonString As String)
InitScriptEngine
Set DecodeJsonString = ScriptEngine.Eval("(" + JsonString + ")")
End Function
Public Function GetProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Variant
GetProperty = ScriptEngine.Run("getProperty", JsonObject, propertyName)
End Function
Public Function GetObjectProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Object
Set GetObjectProperty = ScriptEngine.Run("getProperty", JsonObject, propertyName)
End Function
Public Function SerializeJSONObject(ByVal JsonObject As Object) As String()
Dim Length As Integer
Dim KeysArray() As String
Dim KeysObject As Object
Dim Index As Integer
Dim Key As Variant
Dim tmpString As String
Dim tmpJSON As Object
Dim tmpJSONArray() As Variant
Dim tmpJSONObject() As Variant
Dim strJsonObject As String
Dim tmpNbElement As Long, i As Long
InitScriptEngine
Set KeysObject = ScriptEngine.Run("getKeys", JsonObject)
Length = GetProperty(KeysObject, "length")
ReDim KeysArray(Length - 1)
Index = 0
For Each Key In KeysObject
tmpString = ""
If ScriptEngine.Run("getType", JsonObject, Key) = "object" Then
'MsgBox "object " & SerializeJSONObject(GetObjectProperty(JsonObject, Key))(0)
Set tmpJSON = GetObjectProperty(JsonObject, Key)
strJsonObject = VBA.Replace(ScriptEngine.Run("getKeys", tmpJSON), " ", "")
tmpNbElement = Len(strJsonObject) - Len(VBA.Replace(strJsonObject, ",", ""))
If VBA.IsNumeric(Left(ScriptEngine.Run("getKeys", tmpJSON), 1)) = True Then
ReDim tmpJSONArray(tmpNbElement)
For i = 0 To tmpNbElement
tmpJSONArray(i) = GetProperty(tmpJSON, i)
Next
tmpString = "[" & Join(tmpJSONArray, ",") & "]"
Else
tmpString = "{" & Join(SerializeJSONObject(tmpJSON), ", ") & "}"
End If
Else
tmpString = GetProperty(JsonObject, Key)
End If
KeysArray(Index) = Key & ": " & tmpString
Index = Index + 1
Next
SerializeJSONObject = KeysArray
End Function
Public Function GetKeys(ByVal JsonObject As Object) As String()
Dim Length As Integer
Dim KeysArray() As String
Dim KeysObject As Object
Dim Index As Integer
Dim Key As Variant
InitScriptEngine
Set KeysObject = ScriptEngine.Run("getKeys", JsonObject)
Length = GetProperty(KeysObject, "length")
ReDim KeysArray(Length - 1)
Index = 0
For Each Key In KeysObject
KeysArray(Index) = Key
Index = Index + 1
Next
GetKeys = KeysArray
End Function
I just run this command as a root from terminal and problem is solved,
sudo apt-get install -y postgis postgresql-9.3-postgis-2.1
pip install psycopg2
or
sudo apt-get install libpq-dev python-dev
pip install psycopg2
Inspired by many other FFmpeg on Android implementations out there (mainly the guadianproject), I found a solution (with Lame support also).
(lame and FFmpeg: https://github.com/intervigilium/liblame and http://bambuser.com/opensource)
to call FFmpeg:
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
FfmpegController ffmpeg = null;
try {
ffmpeg = new FfmpegController(context);
} catch (IOException ioe) {
Log.e(DEBUG_TAG, "Error loading ffmpeg. " + ioe.getMessage());
}
ShellDummy shell = new ShellDummy();
String mp3BitRate = "192";
try {
ffmpeg.extractAudio(in, out, audio, mp3BitRate, shell);
} catch (IOException e) {
Log.e(DEBUG_TAG, "IOException running ffmpeg" + e.getMessage());
} catch (InterruptedException e) {
Log.e(DEBUG_TAG, "InterruptedException running ffmpeg" + e.getMessage());
}
Looper.loop();
}
}).start();
and to handle the console output:
private class ShellDummy implements ShellCallback {
@Override
public void shellOut(String shellLine) {
if (someCondition) {
doSomething(shellLine);
}
Utils.logger("d", shellLine, DEBUG_TAG);
}
@Override
public void processComplete(int exitValue) {
if (exitValue == 0) {
// Audio job OK, do your stuff:
// i.e.
// write id3 tags,
// calls the media scanner,
// etc.
}
}
@Override
public void processNotStartedCheck(boolean started) {
if (!started) {
// Audio job error, as above.
}
}
}
Learn from another guy:
<a onclick="window.open(this.href,'_blank');return false;" href="http://www.foracure.org.au">Some Other Site</a>
It makes sense to me.
You can convert them to Set
collections, and perform a set difference operation on them.
Like this:
Set<Date> ad = new HashSet<Date>(a);
Set<Date> bd = new HashSet<Date>(b);
ad.removeAll(bd);
Just call the "type" built in using three parameters, like this:
ClassName = type("ClassName", (Base1, Base2,...), classdictionary)
update as stated in the comment bellow this is not the answer to this question at all. I will keep it undeleted, since there are hints some people get here trying to dynamically create classes - which is what the line above does.
To create an object of a class one has a reference too, as put in the accepted answer, one just have to call the class:
instance = ClassObject()
The mechanism for instantiation is thus:
Python does not use the new
keyword some languages use - instead it's data model explains the mechanism used to create an instantance of a class when it is called with the same syntax as any other callable:
Its class' __call__
method is invoked (in the case of a class, its class is the "metaclass" - which is usually the built-in type
). The normal behavior of this call is to invoke the (pseudo) static __new__
method on the class being instantiated, followed by its __init__
. The __new__
method is responsible for allocating memory and such, and normally is done by the __new__
of object
which is the class hierarchy root.
So calling ClassObject()
invokes ClassObject.__class__.call()
(which normally will be type.__call__
) this __call__
method will receive ClassObject itself as the first parameter - a Pure Python implementation would be like this: (the cPython version is of course, done in C, and with lots of extra code for cornercases and optimizations)
class type:
...
def __call__(cls, *args, **kw):
constructor = getattr(cls, "__new__")
instance = constructor(cls) if constructor is object.__new__ else constructor(cls, *args, **kw)
instance.__init__(cls, *args, **kw)
return instance
(I don't recall seeing on the docs the exact justification (or mechanism) for suppressing extra parameters to the root __new__
and passing it to other classes - but it is what happen "in real life" - if object.__new__
is called with any extra parameters it raises a type error - however, any custom implementation of a __new__
will get the extra parameters normally)
You can use following code to get the date and time separately.
DateTime now = DateTime.Now;
string date = now.GetDateTimeFormats('d')[0];
string time = now.GetDateTimeFormats('t')[0];
You can also, check the MSDN for more information.
I got this exception while coping a object(variable) Matrix Array into Excel sheet. The solution to this is, Matrix array Index(i,j) must start from (0,0) whereas Excel sheet should start with Matrix Array index (i,j) from (1,1) .
I hope you this concept.
Use scipy:
import scipy;
a=[1,2,4];
print(scipy.mean(a));
All the answers provide sufficient details to the question. However, let me add something more.
Why are we using these Interfaces:
Which interface does what:
When to use which interface:
According to http://jtuts.com/2014/08/26/difference-between-crudrepository-and-jparepository-in-spring-data-jpa/
Generally the best idea is to use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.
The JpaRepository should be avoided if possible, because it ties you repositories to the JPA persistence technology, and in most cases you probably wouldn’t even use the extra methods provided by it.
Very simple:
var dt=new Date("2011/11/30");
Date should be in ISO format yyyy/MM/dd.
So for everyone starting out with XAMPP cgi
change the extension from pl to cgi
change the permissions to 755
mv test.pl test.cgi
chmod 755 test.cgi
It fixed mine as well.
You can try put in a shortcut to the site and tell the .bat file to open that.
start Google.HTML
exit
You can add it from the notepad++ toolbar Plugins > Plugin Manager > Show Plugin Manager. Then select the Explorer plugin and click the Install button.
In case all your source and replacement strings are just one character long, you can simply use the TRANSLATE
function:
SELECT translate('THIS IS UPPERCASE', 'THISUP', 'thisup')
FROM DUAL
See the Oracle documentation for details.
You forgot to add a position property to the .dummy-wrap
class, and the top/left/bottom/right values don't apply to statically positioned elements (the default)
e.g.
ColorTranslator.ToHtml(Color.FromArgb(Color.Tomato.ToArgb()))
This can avoid the KnownColor trick.
Maybe this will be helpful for answering the question: Count of days in given year,
new DateTime(anyDate.Year, 12, 31).DayOfYear //will include leap years too
Regarding DateTime.DayOfYear Property.
The above answers get at the most fundamental aspects of the C++ memory model. In practice, most uses of std::atomic<>
"just work", at least until the programmer over-optimizes (e.g., by trying to relax too many things).
There is one place where mistakes are still common: sequence locks. There is an excellent and easy-to-read discussion of the challenges at https://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf. Sequence locks are appealing because the reader avoids writing to the lock word. The following code is based on Figure 1 of the above technical report, and it highlights the challenges when implementing sequence locks in C++:
atomic<uint64_t> seq; // seqlock representation
int data1, data2; // this data will be protected by seq
T reader() {
int r1, r2;
unsigned seq0, seq1;
while (true) {
seq0 = seq;
r1 = data1; // INCORRECT! Data Race!
r2 = data2; // INCORRECT!
seq1 = seq;
// if the lock didn't change while I was reading, and
// the lock wasn't held while I was reading, then my
// reads should be valid
if (seq0 == seq1 && !(seq0 & 1))
break;
}
use(r1, r2);
}
void writer(int new_data1, int new_data2) {
unsigned seq0 = seq;
while (true) {
if ((!(seq0 & 1)) && seq.compare_exchange_weak(seq0, seq0 + 1))
break; // atomically moving the lock from even to odd is an acquire
}
data1 = new_data1;
data2 = new_data2;
seq = seq0 + 2; // release the lock by increasing its value to even
}
As unintuitive as it seams at first, data1
and data2
need to be atomic<>
. If they are not atomic, then they could be read (in reader()
) at the exact same time as they are written (in writer()
). According to the C++ memory model, this is a race even if reader()
never actually uses the data. In addition, if they are not atomic, then the compiler can cache the first read of each value in a register. Obviously you wouldn't want that... you want to re-read in each iteration of the while
loop in reader()
.
It is also not sufficient to make them atomic<>
and access them with memory_order_relaxed
. The reason for this is that the reads of seq (in reader()
) only have acquire semantics. In simple terms, if X and Y are memory accesses, X precedes Y, X is not an acquire or release, and Y is an acquire, then the compiler can reorder Y before X. If Y was the second read of seq, and X was a read of data, such a reordering would break the lock implementation.
The paper gives a few solutions. The one with the best performance today is probably the one that uses an atomic_thread_fence
with memory_order_relaxed
before the second read of the seqlock. In the paper, it's Figure 6. I'm not reproducing the code here, because anyone who has read this far really ought to read the paper. It is more precise and complete than this post.
The last issue is that it might be unnatural to make the data
variables atomic. If you can't in your code, then you need to be very careful, because casting from non-atomic to atomic is only legal for primitive types. C++20 is supposed to add atomic_ref<>
, which will make this problem easier to resolve.
To summarize: even if you think you understand the C++ memory model, you should be very careful before rolling your own sequence locks.
em is the typography unit of font width. one em in a 16-point typeface is 16 points
I know this is an old thread but PARTITION is the equiv of GROUP BY not ORDER BY. ORDER BY in this function is . . . ORDER BY. It's just a way to create uniqueness out of redundancy by adding a sequence number. Or you may eliminate the other redundant records by the WHERE clause when referencing the aliased column for the function. However, DISTINCT in the SELECT statement would probably accomplish the same thing in that regard.
Not sure if it's just me, but using .remove() doesn't seem to work if you are selecting by an id.
Ex: $("#my-element").remove();
I had to use the element's class instead, or nothing happened.
Ex: $(".my-element").remove();
I know this is quite an old post but I just spent some time trying to make this work in IE8.
It appears that there are some differences in IE8 versions because solutions posted here and in other threads didn't work for me.
Let's say that we have this code:
$('a').on('click', function(event) {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
});
In my IE8 preventDefault()
method exists because of jQuery, but is not working (probably because of the point below), so this will fail.
Even if I set returnValue
property directly to false:
$('a').on('click', function(event) {
event.returnValue = false;
event.preventDefault();
});
This also won't work, because I just set some property of jQuery custom event object.
Only solution that works for me is to set property returnValue
of global variable event
like this:
$('a').on('click', function(event) {
if (window.event) {
window.event.returnValue = false;
}
event.preventDefault();
});
Just to make it easier for someone who will try to convince IE8 to work. I hope that IE8 will die horribly in painful death soon.
UPDATE:
As sv_in points out, you could use event.originalEvent
to get original event object and set returnValue
property in the original one. But I haven't tested it in my IE8 yet.
I tried @Aaron's solution and it didn't quite work for me, because it would re-add my keys every time I opened a new tab in my terminal. So I modified it a bit(note that most of my keys are also password-protected so I can't just send the output to /dev/null):
added_keys=`ssh-add -l`
if [ ! $(echo $added_keys | grep -o -e my_key) ]; then
ssh-add "$HOME/.ssh/my_key"
fi
What this does is that it checks the output of ssh-add -l
(which lists all keys that have been added) for a specific key and if it doesn't find it, then it adds it with ssh-add
.
Now the first time I open my terminal I'm asked for the passwords for my private keys and I'm not asked again until I reboot(or logout - I haven't checked) my computer.
Since I have a bunch of keys I store the output of ssh-add -l
in a variable to improve performance(at least I guess it improves performance :) )
PS: I'm on linux and this code went to my ~/.bashrc
file - if you are on Mac OS X, then I assume you should add it to .zshrc
or .profile
EDIT:
As pointed out by @Aaron in the comments, the .zshrc
file is used from the zsh
shell - so if you're not using that(if you're not sure, then most likely, you're using bash
instead), this code should go to your .bashrc
file.
import MySQLdb
class Database:
host = 'localhost'
user = 'root'
password = '123'
db = 'test'
def __init__(self):
self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
self.cursor = self.connection.cursor()
def insert(self, query):
try:
self.cursor.execute(query)
self.connection.commit()
except:
self.connection.rollback()
def query(self, query):
cursor = self.connection.cursor( MySQLdb.cursors.DictCursor )
cursor.execute(query)
return cursor.fetchall()
def __del__(self):
self.connection.close()
if __name__ == "__main__":
db = Database()
#CleanUp Operation
del_query = "DELETE FROM basic_python_database"
db.insert(del_query)
# Data Insert into the table
query = """
INSERT INTO basic_python_database
(`name`, `age`)
VALUES
('Mike', 21),
('Michael', 21),
('Imran', 21)
"""
# db.query(query)
db.insert(query)
# Data retrieved from the table
select_query = """
SELECT * FROM basic_python_database
WHERE age = 21
"""
people = db.query(select_query)
for person in people:
print "Found %s " % person['name']
There are at least three places where you may find shared_ptr
:
If your C++ implementation supports C++11 (or at least the C++11 shared_ptr
), then std::shared_ptr
will be defined in <memory>
.
If your C++ implementation supports the C++ TR1 library extensions, then std::tr1::shared_ptr
will likely be in <memory>
(Microsoft Visual C++) or <tr1/memory>
(g++'s libstdc++). Boost also provides a TR1 implementation that you can use.
Otherwise, you can obtain the Boost libraries and use boost::shared_ptr
, which can be found in <boost/shared_ptr.hpp>
.
It's always problematic and often misleading to try and translate constructs and concepts between languages. Casting is no exception. Particularly because Java is a dynamic language and C++ is somewhat different.
All casting in Java, no matter how you do it, is done at runtime. Type information is held at runtime. C++ is a bit more of a mix. You can cast a struct in C++ to another and it's merely a reinterpretation of the bytes that represent those structs. Java doesn't work that way.
Also generics in Java and C++ are vastly different. Don't concern yourself overly with how you do C++ things in Java. You need to learn how to do things the Java way.
The standard solution didn't work for me, when changing the type from TEXT to LONGTEXT.
I had to it like this:
public function up()
{
DB::statement('ALTER TABLE mytable MODIFY mycolumn LONGTEXT;');
}
public function down()
{
DB::statement('ALTER TABLE mytable MODIFY mycolumn TEXT;');
}
This could be a Doctrine issue. More information here.
Another way to do it is to use the string() method, and set the value to the text type max length:
Schema::table('mytable', function ($table) {
// Will set the type to LONGTEXT.
$table->string('mycolumn', 4294967295)->change();
});
It is a pretty old post, but I just had to do it today. I just right-clicked database from SQL2014 and selected Export Data option and that helped me to move data to SQL2012.
The best way is to use an And
clause in your While
statement
Dim count as Integer
count =0
While True And count <= 10
count=count+1
Debug.Print(count)
Wend
Also $( "#container" ).find( "div.robotarm" );
is equal to: $( "div.robotarm", "#container" )
IE9 no longer supports triggering the Print() VBScript by calling window.print() like IE7 and IE8 do, and thus window.print() will now always trigger the print dialog in IE9.
The fix is pretty simple. You just need to call Print() itself, instead of window.print() in the onclick event.
I've described the fix in more detail in an answer to another question, with a working code example sporting slightly updated HTML syntax (as much as possible while still tested as working code).
You can find that sample code here:
This works:
word = str(input("Enter string:"))
notChar = 0
isChar = 0
for char in word:
if not char.isalpha():
notChar += 1
else:
isChar += 1
print(isChar, " were letters; ", notChar, " were not letters.")
As it's not specified if you mean the system's current date or the date held in a variable, I'll answer for latter with an example.
<?php
$dateAsString = "Wed, 11 Apr 2018 19:00:00 -0500";
// This converts it to a unix timestamp so that the date() function can work with it.
$dateAsUnixTimestamp = strtotime($dateAsString);
// Output it month is various formats according to http://php.net/date
echo date('M',$dateAsUnixTimestamp);
// Will output Apr
echo date('n',$dateAsUnixTimestamp);
// Will output 4
echo date('m',$dateAsUnixTimestamp);
// Will output 04
?>
I don't know if this is Ruby intention or if this is a bug but try this code below. This code was run on Ruby version 2.5.1 and was on a Linux system.
puts 1 > -1 and 257 < 256
# => false
puts 1 > -1 && 257 < 256
# => true
What you are trying should work according to the MSDN doc's for .Net 2.0. You could also try a try/catch right in main around your entry point for the console app.
static void Main(string[] args)
{
try
{
// Start Working
}
catch (Exception ex)
{
// Output/Log Exception
}
finally
{
// Clean Up If Needed
}
}
And now your catch will handle anything not caught (in the main thread). It can be graceful and even restart where it was if you want, or you can just let the app die and log the exception. You woul add a finally if you wanted to do any clean up. Each thread will require its own high level exception handling similar to the main.
Edited to clarify the point about threads as pointed out by BlueMonkMN and shown in detail in his answer.
Query syntax
var query = from p in context.People
group p by p.name into g
select new
{
name = g.Key,
count = g.Count()
};
Method syntax
var query = context.People
.GroupBy(p => p.name)
.Select(g => new { name = g.Key, count = g.Count() });
There is an incredible compatibility issue with using keystrokes to detect the character pressed... see quirksmode to know more about that.
I would suggest using keyup to create your filter because then you have the $(element).val() method you can use to evaluate actual universal characters.
Then you can filter out any NON digits using a regex like:
replace(/[^0-9]/g,'');
This takes care of all issues like shift and paste problems because there is always a keyup and so the value will always be evaluated (unless javascript is turned off).
So... to turn this into JQuery... Here is a little unfinished plugin I'm writing, it is called inputmask and will support more masks when finished. For now it has the digits mask working.
Here it goes...
/**
* @author Tom Van Schoor
* @company Tutuka Software
*/
(function($) {
/**
* @param {Object}
* $$options options to override settings
*/
jQuery.fn.inputmask = function($$options) {
var $settings = $.extend( {}, $.fn.inputmask.defaults, $$options);
return this.each(function() {
// $this is an instance of the element you call the plug-in on
var $this = $(this);
/*
* This plug-in does not depend on the metadata plug-in, but if this
* plug-in detects the existence of the metadata plug-in it will
* override options with the metadata provided by that plug-in. Look at
* the metadata plug-in for more information.
*/
// o will contain your defaults, overruled by $$options,
// overruled by the meta-data
var o = $.metadata ? $.extend( {}, $settings, $this.metadata()) : $settings;
/*
* if digits is in the array 'validators' provided by the options,
* stack this event handler
*/
if($.inArray('digits', o.validators) != -1) {
$this.keyup(function(e) {
$this.val(stripAlphaChars($this.val()));
});
}
/*
* There is no such things as public methods in jQuery plug-ins since
* there is no console to perform commands from a client side point of
* view. Typically only private methods will be fired by registered
* events as on-click, on-drag, etc... Those registered events could be
* seen as public methods.
*/
// private method
var stripAlphaChars = function(string) {
var str = new String(string);
str = str.replace(/[^0-9]/g, '');
return str;
}
});
};
// static public functions
//jQuery.fn.inputmask.doSomething = function(attr) {
//};
// static public members
//jQuery.fn.inputmask.someStaticPublicMember;
// some default settings that can be overridden by either $$options or
// metadata
// If you need callback functions for the plug-in, this is where they get
// set
jQuery.fn.inputmask.defaults = {
validators : []
};
})(jQuery);
To use it just do:
$('#someElementId').inputmask({
validators: ['digits','someOtherNotYetImplementedValidator']
});
The 'someOtherNotYetImplementedValidator' is just there to show how this can be expanded for extra future masks/validators. You can add it or leave it out, it doesn't break anything ;-)
Appologies for the extra clutter of comments, I'm using a template I created for the guys here at work.
Hope this helps, Cheers
To differentiate between scroll up/down in jQuery, you could use:
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0) {
//scroll up
}
else{
//scroll down
}
});
This method also works in divs that have overflow:hidden
.
I successfully tested it in FireFox, IE and Chrome.
iconv('UTF-8', 'ASCII//TRANSLIT', 'é@ùµ$`à');
// "e@uu$`a"
iconv('UTF-8', 'ASCII//IGNORE', 'é@ùµ$`à');
// "@$`"
iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', 'é@ùµ$`à');
// "e@uu$`a"
iconv('UTF-8', 'ASCII//TRANSLIT', 'é@ùµ$`à');
// PHP Notice: iconv(): Detected an illegal character
iconv('UTF-8', 'ASCII//IGNORE', 'é@ùµ$`à');
// "@$`"
iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', 'é@ùµ$`à');
// "e@u$`a"
iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', Transliterator::create('Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC')->transliterate('é@ùµ$`à'))
// "e@uu$`a" -> same as PHP 7.2
We know React is SPA. Everything is rendered from the root component by expanding to appropriate HTML from JSX.
So it does not matter where you want to use the images. Best practice is to use an absolute path (with reference to public). Do not worry about relative paths.
In your case, this should work everywhere:
"./images/logofooter.png"
In fact, the original S3 auth does allow for the content to be signed, albeit with a weak MD5 signature. You can simply enforce their optional practice of including a Content-MD5 header in the HMAC (string to be signed).
http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html
Their new v4 authentication scheme is more secure.
http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
See the git-pull man page:
git pull [options] [<repository> [<refspec>...]]
and in the examples section:
Merge into the current branch the remote branch next:
$ git pull origin next
So I imagine you want to do something like:
git pull origin dev
To set it up so that it does this by default while you're on the dev branch:
git branch --set-upstream-to dev origin/dev
Yes, docker has restart policies such as docker run --restart=always
that will handle this. This is also available in the compose.yml config file as restart: always
.
create or replace procedure point_triangle
AS
BEGIN
FOR thisteam in (select FIRSTNAME,LASTNAME,SUM(PTS) from PLAYERREGULARSEASON where TEAM = 'IND' group by FIRSTNAME, LASTNAME order by SUM(PTS) DESC)
LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);
END LOOP;
END;
/
Perhaps their problem is the moment when the search is made in the database. In his Fragment Override cycles of its Fragment.java to figure out just: try testing with the methods:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_x, container, false); //Your query and ListView code probably will be here
Log.i("FragmentX", "Step OnCreateView");// Try with it
return rootView;
}
Try it similarly put Log.i
... "onStart" and "onResume".
Finally cut the code in "onCreate" e put it in "onStart" for example:
@Override
public void onStart(){
super.onStart();
Log.i("FragmentX","Step OnStart");
dbManager = new DBManager(getContext());
Cursor cursor = dbManager.getAllNames();
listView = (ListView)getView().findViewById(R.id.lvNames);
adapter = new CustomCursorAdapter(getContext(),cursor,0);// your adapter
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
}
object.setForeground(Color.green);
*any colour you wish *object being declared earlier
You could do this if it's short:
int[] array = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
but that gets bad for more than just a few.
Easier would be a for
loop:
int[] myArray = new int[10];
for (int i = 0; i < array.length; i++)
myArray[i] = -1;
Edit: I also like the Arrays.fill()
option other people have mentioned.
Another way to add a default namespace to an XML Document before feeding it to JAXB is to use JDom:
Like this:
public class XMLObjectFactory {
private static Namespace DEFAULT_NS = Namespace.getNamespace("http://tempuri.org/");
public static Object createObject(InputStream in) {
try {
SAXBuilder sb = new SAXBuilder(false);
Document doc = sb.build(in);
setNamespace(doc.getRootElement(), DEFAULT_NS, true);
Source src = new JDOMSource(doc);
JAXBContext context = JAXBContext.newInstance("org.tempuri");
Unmarshaller unmarshaller = context.createUnmarshaller();
JAXBElement root = unmarshaller.unmarshal(src);
return root.getValue();
} catch (Exception e) {
throw new RuntimeException("Failed to create Object", e);
}
}
private static void setNamespace(Element elem, Namespace ns, boolean recurse) {
elem.setNamespace(ns);
if (recurse) {
for (Object o : elem.getChildren()) {
setNamespace((Element) o, ns, recurse);
}
}
}
7-Zip should do the trick.
With it, you can extract all the files inside the EXE (thus, also an MSI file).
Although you can do it with 7-Zip, the better way is the administrative installation as pointed out by Stein Åsmul.
This is by far the best post for exporting to excel from SQL:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926
To quote from user madhivanan
,
Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel
Create an Excel file named testing having the headers same as that of table columns and use these queries
1 Export data to existing EXCEL file from SQL Server table
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;',
'SELECT * FROM [SheetName$]') select * from SQLServerTable
2 Export data from Excel to new SQL Server table
select *
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [Sheet1$]')
3 Export data from Excel to existing SQL Server table (edited)
Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [SheetName$]')
4 If you dont want to create an EXCEL file in advance and want to export data to it, use
EXEC sp_makewebtask
@outputfile = 'd:\testing.xls',
@query = 'Select * from Database_name..SQLServerTable',
@colheaders =1,
@FixedFont=0,@lastupdated=0,@resultstitle='Testing details'
(Now you can find the file with data in tabular format)
5 To export data to new EXCEL file with heading(column names), create the following procedure
create procedure proc_generate_excel_with_columns
(
@db_name varchar(100),
@table_name varchar(100),
@file_name varchar(100)
)
as
--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select
@columns=coalesce(@columns+',','')+column_name+' as '+column_name
from
information_schema.columns
where
table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')
--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'
--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)
--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)
--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)
--Delete dummy file
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)
After creating the procedure, execute it by supplying database name, table name and file path:
EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'
Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.
Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.
To update single cells
A member also there Peter Larson posts the following: I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?
This is the principle of how you do manage that
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99
You can also add formulas to Excel using this:
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'
Exporting with column names using T-SQL
Member Mladen Prajdic also has a blog entry on how to do this here
References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). For error referencing I used this
If you get the following error:
OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries
Then run this:
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO
Have you tried height: auto;
on your .container
div?
Here is a fiddle, if you change img height, container height will adjust to it.
EDIT
So if you "can't" change the inline min-height
, you can overwrite the inline style with an !important
parameter. It's not the cleanest way, but it solves your problem.
add to your .container
class this line
min-height:0px !important;
I've updated my fiddle to give you an example.
This is because width
when provided a %
doesn't account for padding
/margin
s. You will need to reduce the amount to possibly 24%
or 24.5%
. Once this is done you should be good, but you will need to provide different options based on the screen size if you want this to always work correct since you have a hardcoded margin, but a relative size.
The solution lies in understanding these two keyword arguments:
usecols
) using column names rather than integer indices.So because you have a header row, passing header=0
is sufficient and additionally passing names
appears to be confusing pd.read_csv
.
Removing names
from the second call gives the desired output:
import pandas as pd
from StringIO import StringIO
csv = r"""dummy,date,loc,x
bar,20090101,a,1
bar,20090102,a,3
bar,20090103,a,5
bar,20090101,b,1
bar,20090102,b,3
bar,20090103,b,5"""
df = pd.read_csv(StringIO(csv),
header=0,
index_col=["date", "loc"],
usecols=["date", "loc", "x"],
parse_dates=["date"])
Which gives us:
x
date loc
2009-01-01 a 1
2009-01-02 a 3
2009-01-03 a 5
2009-01-01 b 1
2009-01-02 b 3
2009-01-03 b 5
Old question but it kind of pointed me in the right direction. The method I went for was to add the disabled class to the li and then added the following code to my Javascript file.
$('.nav-tabs li.disabled > a[data-toggle=tab]').on('click', function(e) {
e.stopImmediatePropagation();
});
This will disable any link where the li has a class of disabled. Kind of similar to totas's answer but it won't run the if every time a user clicks any tab link and it doesn't use return false.
Hopefully it'll be useful to someone!
Why don't you just save/serve the CSS file as UTF-8?
nav a:hover:after {
content: "?";
}
If that's not good enough, and you want to keep it all-ASCII:
nav a:hover:after {
content: "\2193";
}
The general format for a Unicode character inside a string is \000000
to \FFFFFF
– a backslash followed by six hexadecimal digits. You can leave out leading 0
digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.
Relevant part of the CSS2 spec:
Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:
- with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
- by providing exactly 6 hexadecimal digits: "\000026B" ("&B")
In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.
If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).
- Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
The identifier "te\st" is exactly the same identifier as "test".
Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).
I recommend using the middle index, as it can be calculated easily.
You can calculate it by rounding (array.length / 2).
In Scala, there are no operators, just methods. So a + b - c
is actually the same as a.+(b).-(c)
. In this, it is equal to Smalltalk. However, unlike Smalltalk, precedence is taken into account. The rules are based on the first character, so an hypothetical method called *+
would have precedence over one called +*
. An exception is made so that any method ending in =
will have the same precedence as ==
-- meaning !!
and !=
(non-hypothetical methods) have different precedence.
All ASCII letters have the lowest precedence, but all non-ASCII (unicode) characters have the highest precedence. So if you wrote a method is
comparing two ints, then 2 + 2 is 1 + 3
would compile and be true. Were you to write it in portuguese, é
, then 2 + 2 é 1 + 3
would result in error, as it would see that as 2 + (2 é 1) + 3
.
And, just to top off the WTF of operators in Scala, all methods ending in :
are right-associative instead of left-associative. That means that 1 :: 2 :: Nil
is equivalent to Nil.::(2).::(1)
instead of 1.::(2).::(Nil)
.
I'd like to make some changes: In C, you can use the built in qsort command:
int compare( const void* a, const void* b)
{
int int_a = * ( (int*) a );
int int_b = * ( (int*) b );
// an easy expression for comparing
return (int_a > int_b) - (int_a < int_b);
}
qsort( a, 6, sizeof(int), compare )
Install an share your printer: \localhost\zebra Send ZPL as text, try with copy first:
copy file.zpl \localhost\zebra
very simple, almost no coding.
There are no vertical lines in html that you can use but you can fake one by absolutely positioning a div outside of your container with a top:0;
and bottom:0;
style.
Try this:
CSS
.vr {
width:10px;
background-color:#000;
position:absolute;
top:0;
bottom:0;
left:150px;
}
HTML
<div class="vr"> </div>
First, this is the directory layout that I am using:
.
+-- include
¦ +-- class1.hpp
¦ +-- ...
¦ +-- class2.hpp
+-- src
+-- class1.cpp
+-- ...
+-- class2.cpp
After a couple of days taking a look into this, this is my favourite way of doing this thanks to modern CMake:
cmake_minimum_required(VERSION 3.5)
project(mylib VERSION 1.0.0 LANGUAGES CXX)
set(DEFAULT_BUILD_TYPE "Release")
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
message(STATUS "Setting build type to '${DEFAULT_BUILD_TYPE}' as none was specified.")
set(CMAKE_BUILD_TYPE "${DEFAULT_BUILD_TYPE}" CACHE STRING "Choose the type of build." FORCE)
# Set the possible values of build type for cmake-gui
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo")
endif()
include(GNUInstallDirs)
set(SOURCE_FILES src/class1.cpp src/class2.cpp)
add_library(${PROJECT_NAME} ...)
target_include_directories(${PROJECT_NAME} PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
PRIVATE src)
set_target_properties(${PROJECT_NAME} PROPERTIES
VERSION ${PROJECT_VERSION}
SOVERSION 1)
install(TARGETS ${PROJECT_NAME} EXPORT MyLibConfig
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME})
install(EXPORT MyLibConfig DESTINATION share/MyLib/cmake)
export(TARGETS ${PROJECT_NAME} FILE MyLibConfig.cmake)
After running CMake and installing the library, there is no need to use Find***.cmake files, it can be used like this:
find_package(MyLib REQUIRED)
#No need to perform include_directories(...)
target_link_libraries(${TARGET} mylib)
That's it, if it has been installed in a standard directory it will be found and there is no need to do anything else. If it has been installed in a non-standard path, it is also easy, just tell CMake where to find MyLibConfig.cmake using:
cmake -DMyLib_DIR=/non/standard/install/path ..
I hope this helps everybody as much as it has helped me. Old ways of doing this were quite cumbersome.
These are all great suggestions, but if you know location of text in another file use sed with ease. :r! sed -n '1,10 p' < input_file.txt
This will insert 10 lines in an already open file at the current position of the cursor.
You need to put % name
straight after the string:
f = open('%s.csv' % name, 'wb')
The reason your code doesn't work is because you are trying to %
a file, which isn't string formatting, and is also invalid.
See git gist with instructions here
Run this:
sudo -u postgres psql
OR
psql -U postgres
in your terminal to get into postgres
NB: If you're on a Mac and both of the commands above failed jump to the section about Mac below
postgres=#
Run
CREATE USER new_username;
Note: Replace new_username with the user you want to create, in your case that will be tom.
postgres=# CREATE USER new_username;
CREATE ROLE
Since you want that user to be able to create a DB, you need to alter the role to superuser
postgres=# ALTER USER new_username SUPERUSER CREATEDB;
ALTER ROLE
To confirm, everything was successful,
postgres=# \du
List of roles
Role name | Attributes | Member of
-----------+------------------------------------------------+-----------
new_username | Superuser, Create DB | {}
postgres | Superuser, Create role, Create DB, Replication | {}
root | Superuser, Create role, Create DB | {}
postgres=#
Update/Modification (For Mac):
I recently encountered a similar error on my Mac:
psql: FATAL: role "postgres" does not exist
This was because my installation was setup with a database superuser whose role name is the same as your login (short) name.
But some linux scripts assume the superuser has the traditional role name of postgres
How did I resolve this?
If you installed with homebrew
run:
/usr/local/opt/postgres/bin/createuser -s postgres
If you're using a specific version of postgres, say
10.5
then run:
/usr/local/Cellar/postgresql/10.5/bin/createuser -s postgres
OR:
/usr/local/Cellar/postgresql/10.5/bin/createuser -s new_username
OR:
/usr/local/opt/postgresql@11/bin/createuser -s postgres
If you installed with
postgres.app
for Mac run:
/Applications/Postgres.app/Contents/Versions/10.5/bin/createuser -s postgres
P.S: replace 10.5 with your PostgreSQL version
To get the number of days the easiest way would be:
SELECT EXTRACT(DAY FROM NOW() - '2014-08-02 08:10:56');
As far as I know it would return the same as:
SELECT (EXTRACT(epoch FROM (SELECT (NOW() - '2014-08-02 08:10:56')))/86400)::int;
I had this issue using live-server
(using the Fullstack React book):
I kept getting:
Error: Cannot find module './disable-browser-cache.js' ...
I had to tweak my package.json
From:
"scripts": { ... "server": "live-server public --host=localhost --port=3000 --middleware=./disable-browser-cache.js" ... } "scripts": {
To:
... "server": "live-server public --host=localhost --port=3000 --middleware=../../disable-browser-cache.js" ... }
Notice relative paths seem broken/awkward... ./
becomes ../../
I found the issue here
Also if anyone follows along with that book:
"live-server": "https://github.com/tapio/live-server/tarball/master"
Currently that upgrades from v1.2.0 to v1.2.1
nvm install v13.14.0
nvm alias default v13.14.0
npm i -g [email protected]
npm update
npm list
to see the hierarchy of dependencies too. (For some reason node 15 + latest npm defaults to only showing first level of depth - a la package.json. That renders default command pointless! You can append --depth=n
) to make command more useful again).npm audit
too. There issues requiring (update of chokidar
and some others packages) to newer versions. live-server
hasn't been updated to support the newer corresponding node v 14 library versions.See similar post here
Footnote: Another thing when you get to the JSX section, check out my answer here: https://stackoverflow.com/a/65430910/495157
When you get to:
If you use Java 1.5 or beyond you could use:
List<String> S = new ArrayList<String>();
s.add("My text");
for (String item : S) {
System.out.println(item);
}
Most answers I've found are long and require being familiar with other modules or advanced python features, and will be rather confusing to someone unless they're already familiar with everything the answer talks about.
Working code for a simplified approach:
import threading, time, random
class ThreadWithResult(threading.Thread):
def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None):
def function():
self.result = target(*args, **kwargs)
super().__init__(group=group, target=function, name=name, daemon=daemon)
def function_to_thread(n):
count = 0
while count < 3:
print(f'still running thread {n}')
count +=1
time.sleep(3)
result = random.random()
print(f'Return value of thread {n} should be: {result}')
return result
def main():
thread1 = ThreadWithResult(target=function_to_thread, args=(1,))
thread2 = ThreadWithResult(target=function_to_thread, args=(2,))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print(thread1.result)
print(thread2.result)
main()
Explanation:
I wanted to simplify things significantly, so I created a ThreadWithResult
class and had it inherit from threading.Thread
. The nested function function
in __init__
calls the threaded function we want to save the value of, and saves the result of that as the instance attribute self.result
after the thread finishes executing.
Creating an instance of this is identical to creating an instance of threading.Thread
. Pass in the function you want to run on a new thread to the target
argument and any arguments that your function might need to the args
argument and any keyword arguments to the kwargs
argument.
e.g.
my_thread = ThreadWithResult(target=my_function, args=(arg1, arg2, arg3))
I think this is significantly easier to understand than the vast majority of answers, and this approach requires no extra imports! I included the time
and random
module to simulate the behavior of a thread, but they're not required to achieve the functionality asked in the original question.
I know I'm answering this looong after the question was asked, but I hope this can help more people in the future!
EDIT: I created the save-thread-result
PyPI package to allow you to access the same code above and reuse it across projects (GitHub code is here). The PyPI package fully extends the threading.Thread
class, so you can set any attributes you would set on threading.thread
on the ThreadWithResult
class as well!
The original answer above goes over the main idea behind this subclass, but for more information, see the more detailed explanation (from the module docstring) here.
Quick usage example:
pip3 install -U save-thread-result # MacOS/Linux
pip install -U save-thread-result # Windows
python3 # MacOS/Linux
python # Windows
from save_thread_result import ThreadWithResult
# As of Release 0.0.3, you can also specify values for
#`group`, `name`, and `daemon` if you want to set those
# values manually.
thread = ThreadWithResult(
target = my_function,
args = (my_function_arg1, my_function_arg2, ...)
kwargs = (my_function_kwarg1=kwarg1_value, my_function_kwarg2=kwarg2_value, ...)
)
thread.start()
thread.join()
if getattr(thread, 'result', None):
print(thread.result)
else:
# thread.result attribute not set - something caused
# the thread to terminate BEFORE the thread finished
# executing the function passed in through the
# `target` argument
print('ERROR! Something went wrong while executing this thread, and the function you passed in did NOT complete!!')
# seeing help about the class and information about the threading.Thread super class methods and attributes available:
help(ThreadWithResult)
Did not read all the answers. Anyway Accepted one didn't work for me. What did was upgrading the android studio to last stable version and then created a new virtual device. I guess my nexus 5p virtual device got out of sync with the android studio environment.
I am running VS 2012, and SQL Server 2008 R2 SP2, Developer Edition. I ended up having to install items from the Microsoft® SQL Server® 2012 Feature Pack. I think that the install instructions noted that these items work for SQL Server 2005 through 2012. I don't know what the exact requirements are to fix this error, but I installed the three items, and the error stopped appearing.
Microsoft® SQL Server® 2012 Feature Pack Items
Based on threads elsewhere, you may not end up needing the last item or two. Good luck!
Though the first approach is advocated as 'the angular like' approach, I feel this adds overheads.
Consider if I want to use this myservice.foo function in 10 different controllers. I will have to specify this 'myService' dependency and then $scope.callFoo scope property in all ten of them. This is simply a repetition and somehow violates the DRY principle.
Whereas, if I use the $rootScope approach, I specify this global function gobalFoo only once and it will be available in all my future controllers, no matter how many.
If you check the system.log
file for cassandra in /var/log/cassandra
, you will see that this problem occurs because the rpc server has not started.
By default, the start_rpc
is set to false in the cassandra.yaml
file. Set it to start_rpc: true
and then try again.
From Cassandra 3.0 onwards, start_rpc
is set to true by default. https://docs.datastax.com/en/cassandra/3.0/cassandra/configuration/configCassandra_yaml.html
Leaving the catch block empty should do the trick. This is almost always a bad idea, though. On one hand, there's a performance penalty, and on the other (and this is more important), you always want to know when there's an error.
I would guess that the "callee" function failing, in your case, is actually not necessarily an "error," so to speak. That is, it is expected for it to fail sometimes. If this is the case, there is almost always a better way to handle it than using exceptions.
There are, if you'll pardon the pun, exceptions to the "rule", though. For example, if function2 were to call a web service whose results aren't really necessary for your page, this kind of pattern might be ok. Although, in almost 100% of cases, you should at least be logging it somewhere. In this scenario I'd log it in a finally
block and report whether or not the service returned. Remember that data like that which may not be valuable to you now can become valuable later!
Last edit (probably):
In a comment I suggested you put the try/catch inside function2. Just thought I would elaborate. Function2 would look like this:
public Something? function2()
{
try
{
//all of your function goes here
return anActualObjectOfTypeSomething;
}
catch(Exception ex)
{
//logging goes here
return null;
}
}
That way, since you use a nullable return type, returning null doesn't hurt you.
You need to configure a raw HttpClient with SSL support, something like this:
@Test
public void givenAcceptingAllCertificatesUsing4_4_whenUsingRestTemplate_thenCorrect()
throws ClientProtocolException, IOException {
CloseableHttpClient httpClient
= HttpClients.custom()
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
HttpComponentsClientHttpRequestFactory requestFactory
= new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
ResponseEntity<String> response
= new RestTemplate(requestFactory).exchange(
urlOverHttps, HttpMethod.GET, null, String.class);
assertThat(response.getStatusCode().value(), equalTo(200));
}
First, we need GOPATH
The $GOPATH
is a folder (or set of folders) specified by its environment variable. We must notice that this is not the $GOROOT
directory where Go is installed.
export GOPATH=$HOME/gocode
export PATH=$PATH:$GOPATH/bin
We used ~/gocode
path in our computer to store the source of our application and its dependencies. The GOPATH
directory will also store the binaries of their packages.
Then check Go env
You system must have $GOPATH
and $GOROOT
, below is my Env:
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/elpsstu/gocode"
GORACE=""
GOROOT="/home/pravin/go"
GOTOOLDIR="/home/pravin/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"
Now, you run download go package:
go get [-d] [-f] [-fix] [-t] [-u] [build flags] [packages]
Get downloads and installs the packages named by the import paths, along with their dependencies. For more details you can look here.
You just need a binary (with debugging symbols included) that is identical to the one that generated the core dump file. Then you can run gdb path/to/the/binary path/to/the/core/dump/file
to debug it.
When it starts up, you can use bt
(for backtrace) to get a stack trace from the time of the crash. In the backtrace, each function invocation is given a number. You can use frame number
(replacing number with the corresponding number in the stack trace) to select a particular stack frame.
You can then use list
to see code around that function, and info locals
to see the local variables. You can also use print name_of_variable
(replacing "name_of_variable" with a variable name) to see its value.
Typing help
within GDB will give you a prompt that will let you see additional commands.
PHPMailer handles errors nicely, also a good script to use for sending mail via SMTP...
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
Firstly run this query
SHOW VARIABLES LIKE '%char%';
You have character_set_server='latin1'
If so,go into your config file,my.cnf and add or uncomment these lines:
character-set-server = utf8
collation-server = utf8_unicode_ci
Restart the server. Yes late to the party,just encountered the same issue.
Your question is a bit vague, but I suppose UPSERT
could be considered a design pattern. For languages that don't implement MERGE
, a number of alternatives to solve the problem (if a suitable rows exists, UPDATE
; else INSERT
) exist.
Try from tensorflow.python import keras
with this, you can easily change keras dependent code to tensorflow in one line change.
You can also try from tensorflow.contrib import keras
. This works on tensorflow 1.3
Edited: for tensorflow 1.10 and above you can use import tensorflow.keras as keras
to get keras in tensorflow.
Worksheets("Sheet1").Range("A1:A5").Copy
Worksheets("Sheet2").Range("A1").PasteSpecial Transpose:=True
The &
makes the command run in the background.
From man bash
:
If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0.
VAR=value
sets VAR to value.
After that export VAR
will give it to child processes too.
export VAR=value
is a shorthand doing both.
I think the problem is that when you're trying to compile testpoint.c, it includes point.h but it doesn't know about point.c. Since point.c has the definition for create
, not having point.c will cause the compilation to fail.
I'm not familiar with MinGW, but you need to tell the compiler to look for point.c. For example with gcc you might do this:
gcc point.c testpoint.c
As others have pointed out, you also need to remove one of your main
functions, since you can only have one.
<tbody *ngFor="let defect of items">
<tr>
<td>{{defect.param1}}</td>
<td>{{defect.param2}}</td>
<td>{{defect.param3}}</td>
<td>{{defect.param4}}</td>
<td>{{defect.param5}} </td>
<td>{{defect.param6}}</td>
<td>{{defect.param7}}</td>
</tr>
<tr>
<td> <strong> Notes:</strong></td>
<td colspan="6"> {{defect.param8}}
</td>`enter code here`
</tr>
</tbody>
If you have multiple Menus with Submenus, then you can go with the below solution.
HTML
<ul class="sidebar-menu" id="nav-accordion">
<li class="sub-menu">
<a href="" ng-click="hasSubMenu('dashboard')">
<i class="fa fa-book"></i>
<span>Dashboard</span>
<i class="fa fa-angle-right pull-right"></i>
</a>
<ul class="sub" ng-show="showDash">
<li><a ng-class="{ active: isActive('/dashboard/loan')}" href="#/dashboard/loan">Loan</a></li>
<li><a ng-class="{ active: isActive('/dashboard/recovery')}" href="#/dashboard/recovery">Recovery</a></li>
</ul>
</li>
<li class="sub-menu">
<a href="" ng-click="hasSubMenu('customerCare')">
<i class="fa fa-book"></i>
<span>Customer Care</span>
<i class="fa fa-angle-right pull-right"></i>
</a>
<ul class="sub" ng-show="showCC">
<li><a ng-class="{ active: isActive('/customerCare/eligibility')}" href="#/CC/eligibility">Eligibility</a></li>
<li><a ng-class="{ active: isActive('/customerCare/transaction')}" href="#/CC/transaction">Transaction</a></li>
</ul>
</li>
</ul>
There are two functions i have called first is ng-click = hasSubMenu('dashboard'). This function will be used to toggle the menu and it is explained in the code below. The ng-class="{ active: isActive('/customerCare/transaction')} it will add a class active to the current menu item.
Now i have defined some functions in my app:
First, add a dependency $rootScope which is used to declare variables and functions. To learn more about $roootScope refer to the link : https://docs.angularjs.org/api/ng/service/$rootScope
Here is my app file:
$rootScope.isActive = function (viewLocation) {
return viewLocation === $location.path();
};
The above function is used to add active class to the current menu item.
$rootScope.showDash = false;
$rootScope.showCC = false;
var location = $location.url().split('/');
if(location[1] == 'customerCare'){
$rootScope.showCC = true;
}
else if(location[1]=='dashboard'){
$rootScope.showDash = true;
}
$rootScope.hasSubMenu = function(menuType){
if(menuType=='dashboard'){
$rootScope.showCC = false;
$rootScope.showDash = $rootScope.showDash === false ? true: false;
}
else if(menuType=='customerCare'){
$rootScope.showDash = false;
$rootScope.showCC = $rootScope.showCC === false ? true: false;
}
}
By default $rootScope.showDash and $rootScope.showCC are set to false. It will set the menus to closed when page is initially loaded. If you have more than two submenus add accordingly.
hasSubMenu() function will work for toggling between the menus. I have added a small condition
if(location[1] == 'customerCare'){
$rootScope.showCC = true;
}
else if(location[1]=='dashboard'){
$rootScope.showDash = true;
}
it will remain the submenu open after reloading the page according to selected menu item.
I have defined my pages like:
$routeProvider
.when('/dasboard/loan', {
controller: 'LoanController',
templateUrl: './views/loan/view.html',
controllerAs: 'vm'
})
You can use isActive() function only if you have a single menu without submenu. You can modify the code according to your requirement. Hope this will help. Have a great day :)
Try this:
<meta http-equiv="refresh" content="5;URL= your url">
or
<meta http-equiv="refresh" content="5">
Actually, there is a command to move a collection from one database to another. It's just not called "move" or "copy".
To copy a collection, you can clone it on the same database, then move the cloned collection.
To clone:
> use db1
switched to db db1
> db.source_collection.find().forEach(
function(x){
db.collection_copy.insert(x)
}
);
To move:
> use admin
switched to db admin
> db.runCommand(
{
renameCollection: 'db1.source_collection',
to : 'db2.target_collection'
}
);
The other answers are better for copying the collection, but this is especially useful if you're looking to move it.
I've been willing to use something like this in a sheet where all lines are identical and usually refer to other cells in the same line - but as the formulas get complex, the references to other columns get hard to read.
I tried the trick given in other answers, with for example column A named as "Sales" I can refers to it as INDEX(Sales;row())
but I found it a bit too long for my tastes.
However, in this particular case, I found that using Sales
alone works just as well - Excel (2010 here) just gets the corresponding row automatically.
It appears to work with other ranges too; for example let's say I have values in A2:A11
which I name Sales
, I can just use =Sales*0.21
in B2:11
and it will use the same row value, giving out ten different results.
I also found a nice trick on this page: named ranges can also be relative. Going back to your original question, if your value "Age" is in column A and assuming you're using that value in formulas in the same line, you can define Age as being $A2 instead of $A$2, so that when used in B5 or C5 for example, it will actually refer to $A5. (The Name Manager always show the reference relative to the cell currently selected)
Are you missing a using directive for System.Linq
?
The proper way that actually works:
URL resource = YourClass.class.getResource("abc");
Paths.get(resource.toURI()).toFile();
It doesn't matter now where the file in the classpath physically is, it will be found as long as the resource is actually a file and not a JAR entry.
(The seemingly obvious new File(resource.getPath())
doesn't work for all paths! The path is still URL-encoded!)
As the user running the Oracle Database one can also try $ORACLE_HOME/OPatch/opatch lsinventory
which shows the exact version and patches installed.
For example this is a quick oneliner which should only return the version number:
$ORACLE_HOME/OPatch/opatch lsinventory | awk '/^Oracle Database/ {print $NF}'
Using imagemagick, you can try:
convert page.png page.pdf
Or for multiple images:
convert page*.png mydoc.pdf
What if you want your parts to contain commas? Well, quote them. And then what about the quotes? Well, double them up. In other words:
part1,"part2,with a comma and a quote "" in it",part3
PHP provides the https://php.net/str_getcsv function to parse a string as if it were a line in a CSV file which can be used with the above line instead of explode
:
print_r(str_getcsv('part1,"part2,with a comma and a quote "" in it",part3'));
Array
(
[0] => part1
[1] => part2,with a comma and a quote " in it
[2] => part3
)
Use below command on UNIX terminal :
java -XshowSettings
This will display all java properties and system settings.
In this look for java.io.tmpdir
value.
extern
declaration in the other file.static
. Such variables are said to have internal linkage.Consider following example:
void f(int i);
extern const int max = 10;
int n = 0;
int main()
{
int a;
//...
f(a);
//...
f(a);
//...
}
f
declares f
as a function with external linkage (default). Its definition must be provided later in this file or in other translation unit (given below).max
is defined as an integer constant. The default linkage for constants is internal. Its linkage is changed to external with the keyword extern
. So now max
can be accessed in other files. n
is defined as an integer variable. The default linkage for variables defined outside function bodies is external.#include <iostream>
using namespace std;
extern const int max;
extern int n;
static float z = 0.0;
void f(int i)
{
static int nCall = 0;
int a;
//...
nCall++;
n++;
//...
a = max * z;
//...
cout << "f() called " << nCall << " times." << endl;
}
max
is declared to have external linkage. A matching definition for max
(with external linkage) must appear in some file. (As in 1.cpp)n
is declared to have external linkage.z
is defined as a global variable with internal linkage.nCall
specifies nCall
to be a variable that retains its value across calls to function f()
. Unlike local variables with the default auto storage class, nCall
will be initialized only once at the start of the program and not once for each invocation of f()
. The storage class specifier static
affects the lifetime of the local variable and not its scope.NB: The keyword static
plays a double role. When used in the definitions of global variables, it specifies internal linkage. When used in the definitions of the local variables, it specifies that the lifetime of the variable is going to be the duration of the program instead of being the duration of the function.
Hope that helps!
Private Sub Command0_Click()
Application.FollowHyperlink "D:\1Zsnsn\SusuBarokah\20151008 Inventory.mdb"
End Sub
Have you tried ALTER SYSTEM KILL SESSION? Get the SID and SERIAL# from V$SESSION for each session in the given schema, then do
ALTER SCHEMA KILL SESSION sid,serial#;
Derived from @Goner Doug answer, with a few things updated:
- using REPLACE where possible
- conversion of predefined entities like é
(I chose the ones I needed :-)
- some conversion of list tags <ul> and <li>
ALTER FUNCTION [dbo].[udf_StripHTML]
--by Patrick Honorez --- www.idevlop.com
--inspired by http://stackoverflow.com/questions/457701/best-way-to-strip-html-tags-from-a-string-in-sql-server/39253602#39253602
(
@HTMLText varchar(MAX)
)
RETURNS varchar(MAX)
AS
BEGIN
DECLARE @Start int
DECLARE @End int
DECLARE @Length int
set @HTMLText = replace(@htmlText, '<br>',CHAR(13) + CHAR(10))
set @HTMLText = replace(@htmlText, '<br/>',CHAR(13) + CHAR(10))
set @HTMLText = replace(@htmlText, '<br />',CHAR(13) + CHAR(10))
set @HTMLText = replace(@htmlText, '<li>','- ')
set @HTMLText = replace(@htmlText, '</li>',CHAR(13) + CHAR(10))
set @HTMLText = replace(@htmlText, '’' collate Latin1_General_CS_AS, '''' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '"' collate Latin1_General_CS_AS, '"' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '&' collate Latin1_General_CS_AS, '&' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '€' collate Latin1_General_CS_AS, '€' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '<' collate Latin1_General_CS_AS, '<' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '>' collate Latin1_General_CS_AS, '>' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'œ' collate Latin1_General_CS_AS, 'oe' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, ' ' collate Latin1_General_CS_AS, ' ' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '©' collate Latin1_General_CS_AS, '©' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '«' collate Latin1_General_CS_AS, '«' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '®' collate Latin1_General_CS_AS, '®' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '±' collate Latin1_General_CS_AS, '±' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '²' collate Latin1_General_CS_AS, '²' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '³' collate Latin1_General_CS_AS, '³' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'µ' collate Latin1_General_CS_AS, 'µ' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '·' collate Latin1_General_CS_AS, '·' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'º' collate Latin1_General_CS_AS, 'º' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '»' collate Latin1_General_CS_AS, '»' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '¼' collate Latin1_General_CS_AS, '¼' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '½' collate Latin1_General_CS_AS, '½' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '¾' collate Latin1_General_CS_AS, '¾' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '&Aelig' collate Latin1_General_CS_AS, 'Æ' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'Ç' collate Latin1_General_CS_AS, 'Ç' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'È' collate Latin1_General_CS_AS, 'È' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'É' collate Latin1_General_CS_AS, 'É' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'Ê' collate Latin1_General_CS_AS, 'Ê' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'Ö' collate Latin1_General_CS_AS, 'Ö' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'à' collate Latin1_General_CS_AS, 'à' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'â' collate Latin1_General_CS_AS, 'â' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'ä' collate Latin1_General_CS_AS, 'ä' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'æ' collate Latin1_General_CS_AS, 'æ' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'ç' collate Latin1_General_CS_AS, 'ç' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'è' collate Latin1_General_CS_AS, 'è' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'é' collate Latin1_General_CS_AS, 'é' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'ê' collate Latin1_General_CS_AS, 'ê' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'ë' collate Latin1_General_CS_AS, 'ë' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'î' collate Latin1_General_CS_AS, 'î' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'ô' collate Latin1_General_CS_AS, 'ô' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'ö' collate Latin1_General_CS_AS, 'ö' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '÷' collate Latin1_General_CS_AS, '÷' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'ø' collate Latin1_General_CS_AS, 'ø' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'ù' collate Latin1_General_CS_AS, 'ù' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'ú' collate Latin1_General_CS_AS, 'ú' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'û' collate Latin1_General_CS_AS, 'û' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, 'ü' collate Latin1_General_CS_AS, 'ü' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '"' collate Latin1_General_CS_AS, '"' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '&' collate Latin1_General_CS_AS, '&' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '‹' collate Latin1_General_CS_AS, '<' collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '›' collate Latin1_General_CS_AS, '>' collate Latin1_General_CS_AS)
-- Remove anything between <STYLE> tags
SET @Start = CHARINDEX('<STYLE', @HTMLText)
SET @End = CHARINDEX('</STYLE>', @HTMLText, CHARINDEX('<', @HTMLText)) + 7
SET @Length = (@End - @Start) + 1
WHILE (@Start > 0 AND @End > 0 AND @Length > 0) BEGIN
SET @HTMLText = STUFF(@HTMLText, @Start, @Length, '')
SET @Start = CHARINDEX('<STYLE', @HTMLText)
SET @End = CHARINDEX('</STYLE>', @HTMLText, CHARINDEX('</STYLE>', @HTMLText)) + 7
SET @Length = (@End - @Start) + 1
END
-- Remove anything between <whatever> tags
SET @Start = CHARINDEX('<', @HTMLText)
SET @End = CHARINDEX('>', @HTMLText, CHARINDEX('<', @HTMLText))
SET @Length = (@End - @Start) + 1
WHILE (@Start > 0 AND @End > 0 AND @Length > 0) BEGIN
SET @HTMLText = STUFF(@HTMLText, @Start, @Length, '')
SET @Start = CHARINDEX('<', @HTMLText)
SET @End = CHARINDEX('>', @HTMLText, CHARINDEX('<', @HTMLText))
SET @Length = (@End - @Start) + 1
END
RETURN LTRIM(RTRIM(@HTMLText))
END
You can see all the version of a module with npm view
.
eg: To list all versions of bootstrap including beta.
npm view bootstrap versions
But if the version list is very big it will truncate. An --json
option will print all version including beta versions as well.
npm view bootstrap versions --json
If you want to list only the stable versions not the beta then use singular version
npm view bootstrap@* versions
Or
npm view bootstrap@* versions --json
And, if you want to see only latest version then here you go.
npm view bootstrap version
Had a similar problem with the GitHub because I was using HTTPS protocol. To check what protocol you're using just run
git config -l
and look at the line starting with remote.origin.url
. To switch your protocol
git config remote.origin.url [email protected]:your_username/your_project.git
This is the easier way I had ever found. Fast and only two lines of code :-D
$keys = array_keys($array);
echo $array[$keys[0]];
If a case-insensitive comparison is acceptable, just use =
:
=IF(A1="ENG",1,0)
Use the pandas.DataFrame.rename funtion. Check this link for description.
data.rename(columns = {'gdp': 'log(gdp)'}, inplace = True)
If you intend to rename multiple columns then
data.rename(columns = {'gdp': 'log(gdp)', 'cap': 'log(cap)', ..}, inplace = True)
I think buffers are e.g. useful when interfacing python to native libraries. (Guido van Rossum explains buffer
in this mailinglist post).
For example, numpy seems to use buffer for efficient data storage:
import numpy
a = numpy.ndarray(1000000)
the a.data
is a:
<read-write buffer for 0x1d7b410, size 8000000, offset 0 at 0x1e353b0>
Try insmod
instead of modprobe. Modprobe
looks in the module directory /lib/modules/uname -r
for all the modules and other
files
The Angular microsyntax lets you configure a directive in a compact, friendly string. The microsyntax parser translates that string into attributes on the <ng-template>
. The let keyword declares a template input variable that you reference within the template.
Do this:
$(document).ready(function(){
$(".header").click(function(){
$(this).children(".children").toggle();
});
$(".header a").click(function(e) {
e.stopPropagation();
});
});
If you want to read more on .stopPropagation(), look here.
This is a standard interview question:
Is memory allocated at runtime using calloc()
, malloc()
and friends. It is sometimes also referred to as 'heap' memory, although it has nothing to do with the heap data-structure ref.
int * a = malloc(sizeof(int));
Heap memory is persistent until free()
is called. In other words, you control the lifetime of the variable.
This is what is commonly known as 'stack' memory, and is allocated when you enter a new scope (usually when a new function is pushed on the call stack). Once you move out of the scope, the values of automatic memory addresses are undefined, and it is an error to access them.
int a = 43;
Note that scope does not necessarily mean function. Scopes can nest within a function, and the variable will be in-scope only within the block in which it was declared. Note also that where this memory is allocated is not specified. (On a sane system it will be on the stack, or registers for optimisation)
Is allocated at compile time*, and the lifetime of a variable in static memory is the lifetime of the program.
In C, static memory can be allocated using the static
keyword. The scope is the compilation unit only.
Things get more interesting when the extern
keyword is considered. When an extern
variable is defined the compiler allocates memory for it. When an extern
variable is declared, the compiler requires that the variable be defined elsewhere. Failure to declare/define extern
variables will cause linking problems, while failure to declare/define static
variables will cause compilation problems.
in file scope, the static keyword is optional (outside of a function):
int a = 32;
But not in function scope (inside of a function):
static int a = 32;
Technically, extern
and static
are two separate classes of variables in C.
extern int a; /* Declaration */
int a; /* Definition */
It's somewhat confusing to say that static memory is allocated at compile time, especially if we start considering that the compilation machine and the host machine might not be the same or might not even be on the same architecture.
It may be better to think that the allocation of static memory is handled by the compiler rather than allocated at compile time.
For example the compiler may create a large data
section in the compiled binary and when the program is loaded in memory, the address within the data
segment of the program will be used as the location of the allocated memory. This has the marked disadvantage of making the compiled binary very large if uses a lot of static memory. It's possible to write a multi-gigabytes binary generated from less than half a dozen lines of code. Another option is for the compiler to inject initialisation code that will allocate memory in some other way before the program is executed. This code will vary according to the target platform and OS. In practice, modern compilers use heuristics to decide which of these options to use. You can try this out yourself by writing a small C program that allocates a large static array of either 10k, 1m, 10m, 100m, 1G or 10G items. For many compilers, the binary size will keep growing linearly with the size of the array, and past a certain point, it will shrink again as the compiler uses another allocation strategy.
The last memory class are 'register' variables. As expected, register variables should be allocated on a CPU's register, but the decision is actually left to the compiler. You may not turn a register variable into a reference by using address-of.
register int meaning = 42;
printf("%p\n",&meaning); /* this is wrong and will fail at compile time. */
Most modern compilers are smarter than you at picking which variables should be put in registers :)
As others have said, the style you're after is actually just the Mac OS checkbox style, so it will look radically different on other devices.
In fact both screenshots you linked show what checkboxes look like on Mac OS in Chrome, the grey one is shown at non-100% zoom levels.
you can use "Line1<br>Line2"
To get around the problem, find out where pymysql is installed.
If for example it is installed in /usr/lib/python3.7/site-packages
, add the following code above the import pymysql
command:
import sys
sys.path.insert(0,"/usr/lib/python3.7/site-packages")
import pymysql
This ensures that your Python program can find where pymysql is installed.
Be careful when accessing DateTime.Now twice, as it's possible for the calls to straddle midnight and you'll get wacky results on rare occasions and be left scratching your head.
To be safe, you should assign DateTime.Now to a local variable first if you're going to use it more than once:
var now = DateTime.Now;
var time = now.ToString("hh:mm:ss tt");
var date = now.ToString("MM/dd/yy");
Note the use of lower case "hh" do display hours from 00-11 even in the afternoon, and "tt" to show AM/PM, as the question requested. If you want 24 hour clock 00-23, use "HH".
My solution is to add this code to the app.php
define('WEB_DIRECTORY', __DIR__);
The problem is that in command line code that uses the constant will break. You can also add the constant to app/console file and the other environment front controllers
Another solution may be add an static method at AppKernel that returns DIR.'/../web/' So you can access everywhere
<?php $data = array('a'=>'apple','b'=>'banana','c'=>'orange');?>
<pre><?php print_r($data); ?></pre>
Result:
Array
(
[a] => apple
[b] => banana
[c] => orange
)
From another point of view: Consider that you want to make some changes on a single String. for example you want to make the letters Uppercase and so on. you make another class named "Tools" for these actions. there is no meaning of making instance of "Tools" class because there is not any kind of entity available inside that class (compare to "Person" or "Teacher" class). So we use static keyword in order to use "Tools" class without making any instance of that, and when you press dot after class name ("Tools") you can have access to the methods you want.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Tools.ToUpperCase("Behnoud Sherafati"));
Console.ReadKey();
}
}
public static class Tools
{
public static string ToUpperCase(string str)
{
return str.ToUpper();
}
}
}
I had this problem because I updated packages, which included Microsoft.AspNet.WebApi that has a reference to Newtonsoft.Json 4.5.6 and I already had version 6 installed. It wasn't clever enough to use the version 6.
To resolve it, after the WebApi update I opened the Tools > NuGet Package Manager > Pacakge Manager Console and ran:
Update-Package Newtonsoft.Json
The log showed that the 6.0.x and 4.5.6 versions were all updated to the latest one and everything was fine.
I have a feeling this will come up again.
If you want the old directive back, you can add this to your app:
Directive:
directives.directive('ngBindHtmlUnsafe', ['$sce', function($sce){
return {
scope: {
ngBindHtmlUnsafe: '=',
},
template: "<div ng-bind-html='trustedHtml'></div>",
link: function($scope, iElm, iAttrs, controller) {
$scope.updateView = function() {
$scope.trustedHtml = $sce.trustAsHtml($scope.ngBindHtmlUnsafe);
}
$scope.$watch('ngBindHtmlUnsafe', function(newVal, oldVal) {
$scope.updateView(newVal);
});
}
};
}]);
Usage
<div ng-bind-html-unsafe="group.description"></div>
Like so
DECLARE @t INT=1
SELECT CASE
WHEN @t>0 THEN
CASE
WHEN @t=1 THEN 'one'
ELSE 'not one'
END
ELSE 'less than one'
END
EDIT: After looking more at the question, I think the best option is to create a function that calculates the value. That way, if you end up having multiple places where the calculation needs done, you only have one point to maintain the logic.
0 0 * * * [ $(($((
date +%-j- 1)) % 3)) == 0 ] && script
Get the day of the year from date
, offset by 1 to start at 0, check if it is modulo three.
For anyone else reading this (in 2019 onwards) unfortunately most JS RSS reading implementations don't now work. Firstly Google API has shut down so this is no longer an option and because of the CORS security policy you generally cannot now request RSS feeds cross-domains.
Using the example on https://www.raymondcamden.com/2015/12/08/parsing-rss-feeds-in-javascript-options (2015) I get the following:
Access to XMLHttpRequest at 'https://feeds.feedburner.com/raymondcamdensblog?format=xml' from origin 'MYSITE' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is correct and is a security precaution by the end website but does now mean that the answers above are unlikely to work.
My workaround will probably be to parse the RSS feed through PHP and allow the javascript to access my PHP rather than trying to access the end-destination feed itself.
I had the exactly same issue, with a very very long stack trace. At the end of the trace I saw this:
InvalidQueryException: Keyspace 'mykeyspace' does not exist
I created the keyspace in cassandra, and solved the problem.
CREATE KEYSPACE mykeyspace
WITH REPLICATION = {
'class' : 'SimpleStrategy',
'replication_factor' : 1
};
spring.data.mongodb.host
and spring.data.mongodb.port
are not supported if you’re using the Mongo 3.0 Java driver. In such cases, spring.data.mongodb.uri
should be used to provide all of the configuration, like this:
spring.data.mongodb.uri=mongodb://user:[email protected]:12345
Public Declare Function GetUserName Lib "advapi32.dll"
Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
....
Dim strLen As Long
Dim strtmp As String * 256
Dim strUserName As String
strLen = 255
GetUserName strtmp, strLen
strUserName = Trim$(TrimNull(strtmp))
Turns out question has been asked before: How can I get the currently logged-in windows user in Access VBA?
<a href="#"><button>Link Text</button></a>
You asked for a link that looks like a button, so use a link and a button :-) This will preserve default browser button styling. The button by itself does nothing, but clicking it activates its parent link.
Demo:
<a href="http://stackoverflow.com"><button>Link Text</button></a>
_x000D_
Pandas DataFrame object should be thought of as a Series of Series. In other words, you should think of it in terms of columns. The reason why this is important is because when you use pd.DataFrame.iterrows
you are iterating through rows as Series. But these are not the Series that the data frame is storing and so they are new Series that are created for you while you iterate. That implies that when you attempt to assign tho them, those edits won't end up reflected in the original data frame.
Ok, now that that is out of the way: What do we do?
Suggestions prior to this post include:
pd.DataFrame.set_value
is deprecated as of Pandas version 0.21pd.DataFrame.ix
is deprecatedpd.DataFrame.loc
is fine but can work on array indexers and you can do betterMy recommendation
Use pd.DataFrame.at
for i in df.index:
if <something>:
df.at[i, 'ifor'] = x
else:
df.at[i, 'ifor'] = y
You can even change this to:
for i in df.index:
df.at[i, 'ifor'] = x if <something> else y
and what if I need to use the value of the previous row for the if condition?
for i in range(1, len(df) + 1):
j = df.columns.get_loc('ifor')
if <something>:
df.iat[i - 1, j] = x
else:
df.iat[i - 1, j] = y
Go to your Postgresql Config and Edit pg_hba.conf
sudo vim /etc/postgresql/9.3/main/pg_hba.conf
Then Change this Line :
Database administrative login by Unix domain socket
local all postgres md5
to :
Database administrative login by Unix domain socket
local all postgres peer
then Restart the PostgreSQL service via SUDO command then
psql -U postgres
You will be now entered and will See the Postgresql terminal
then enter
\password
and enter the NEW Password for Postgres default user, After Successfully changing the Password again go to the pg_hba.conf and revert the change to "md5"
now you will be logged in as
psql -U postgres
with your new Password.
Let me know if you all find any issue in it.
For me, the problem was that I used:
List<Some> someCollection ...;
_dbContext.Remove(someCollection);
instead of:
_dbContext.RemoveRange(someCollection);
To directly save the file in HDFS, use the below command:
hive> insert overwrite directory '/user/cloudera/Sample' row format delimited fields terminated by '\t' stored as textfile select * from table where id >100;
This will put the contents in the folder /user/cloudera/Sample in HDFS.
Java 8 has introduced a new class, Optional<T>
, that can be used in such cases. To use it, you'd modify your code slightly as follows:
interface B<E>{ Optional<E> method(); }
class A implements B<Void>{
public Optional<Void> method(){
// do something
return Optional.empty();
}
}
This allows you to ensure that you always get a non-null return value from your method, even when there isn't anything to return. That's especially powerful when used in conjunction with tools that detect when null
can or can't be returned, e.g. the Eclipse @NonNull
and @Nullable
annotations.
This isn't so difficult.
Just check your gtk+ toolkit utilities version from terminal:
gtk-launch --version
Put the text file in the assets directory. If there isnt an assets dir create one in the root of the project. Then you can use Context.getAssets().open("BlockForTest.txt");
to open a stream to this file.
Thanks @Harry the following code works for me:
.your-div{
vertical-align: bottom;
display: table-cell;
}
A typographical error in the string describing the database driver can also produce the error.
A string specified as:
"jdbc:mysql//localhost:3307/dbname,"usrname","password"
can result in a "no suitable driver found" error. The colon following "mysql" is missing in this example.
The correct driver string would be:
jdbc:mysql://localhost:3307/dbname,"usrname","password"
This question asked long before. But I thought following information will useful for newbies. Actually you can easily get the values from class name like this.
Sub ExtractLastValue()
Set objIE = CreateObject("InternetExplorer.Application")
objIE.Top = 0
objIE.Left = 0
objIE.Width = 800
objIE.Height = 600
objIE.Visible = True
objIE.Navigate ("https://uk.investing.com/rates-bonds/financial-futures/")
Do
DoEvents
Loop Until objIE.readystate = 4
MsgBox objIE.document.getElementsByClassName("pid-8907-last")(0).innerText
End Sub
And if you are new to web scraping please read this blog post.
And also there are various techniques to extract data from web pages. This article explain few of them with examples.
I put
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
first thing after
<head>
(I read it somewhere, I can't recall)
I could not believe it did work!!
Adding my two cents here since I have not seen an answer that uses the option "Build with parameters" in Jenkins.
Here I am using Jenkins CI browser console for project starwars_api and I was able to build directly with "Build with parameters" with value refs/tags/tag-name
You can iterate through JavaScript objects this way:
for(var attributename in myobject){
console.log(attributename+": "+myobject[attributename]);
}
myobject could be your json.data
First, it usually does not matter that much in practice. Most hash functions are "good enough".
But if you really care, you should know that it is a research subject by itself. There are thousand of papers about that. You can still get a PhD today by studying & designing hashing algorithms.
Your second hash function might be slightly better, because it probably should separate the string "ab"
from the string "ba"
. On the other hand, it is probably less quick than the first hash function. It may, or may not, be relevant for your application.
I'll guess that hash functions used for genome strings are quite different than those used to hash family names in telephone databases. Perhaps even some string hash functions are better suited for German, than for English or French words.
Many software libraries give you good enough hash functions, e.g. Qt has qhash, and C++11 has std::hash in <functional>
, Glib has several hash functions in C, and POCO has some hash function.
I quite often have hashing functions involving primes (see Bézout's identity) and xor, like e.g.
#define A 54059 /* a prime */
#define B 76963 /* another prime */
#define C 86969 /* yet another prime */
#define FIRSTH 37 /* also prime */
unsigned hash_str(const char* s)
{
unsigned h = FIRSTH;
while (*s) {
h = (h * A) ^ (s[0] * B);
s++;
}
return h; // or return h % C;
}
But I don't claim to be an hash expert. Of course, the values of A
, B
, C
, FIRSTH
should preferably be primes, but you could have chosen other prime numbers.
Look at some MD5 implementation to get a feeling of what hash functions can be.
Most good books on algorithmics have at least a whole chapter dedicated to hashing. Start with wikipages on hash function & hash table.
All of the existing answers use the deprecated MD5Init()
, MD5Update()
, and MD5Final()
.
Instead, use EVP_DigestInit_ex()
, EVP_DigestUpdate()
, and EVP_DigestFinal_ex()
, e.g.
// example.c
//
// gcc example.c -lssl -lcrypto -o example
#include <openssl/evp.h>
#include <stdio.h>
#include <string.h>
void bytes2md5(const char *data, int len, char *md5buf) {
// Based on https://www.openssl.org/docs/manmaster/man3/EVP_DigestUpdate.html
EVP_MD_CTX *mdctx = EVP_MD_CTX_new();
const EVP_MD *md = EVP_md5();
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len, i;
EVP_DigestInit_ex(mdctx, md, NULL);
EVP_DigestUpdate(mdctx, data, len);
EVP_DigestFinal_ex(mdctx, md_value, &md_len);
EVP_MD_CTX_free(mdctx);
for (i = 0; i < md_len; i++) {
snprintf(&(md5buf[i * 2]), 16 * 2, "%02x", md_value[i]);
}
}
int main(void) {
const char *hello = "hello";
char md5[33]; // 32 characters + null terminator
bytes2md5(hello, strlen(hello), md5);
printf("%s\n", md5);
}
A solution that works for S3 modified from Minkymorgan.
Simply pass the temporary partitioned directory path (with different name than final path) as the srcPath
and single final csv/txt as destPath
Specify also deleteSource
if you want to remove the original directory.
/**
* Merges multiple partitions of spark text file output into single file.
* @param srcPath source directory of partitioned files
* @param dstPath output path of individual path
* @param deleteSource whether or not to delete source directory after merging
* @param spark sparkSession
*/
def mergeTextFiles(srcPath: String, dstPath: String, deleteSource: Boolean): Unit = {
import org.apache.hadoop.fs.FileUtil
import java.net.URI
val config = spark.sparkContext.hadoopConfiguration
val fs: FileSystem = FileSystem.get(new URI(srcPath), config)
FileUtil.copyMerge(
fs, new Path(srcPath), fs, new Path(dstPath), deleteSource, config, null
)
}
They need to be percent-encoded:
> encodeURIComponent('&')
"%26"
So in your case, the URL would look like:
http://www.mysite.com?candy_name=M%26M
The '::' is for static members.
Use the selectedIndex
property:
document.getElementById("Mobility").selectedIndex = 12; //Option 10
Alternate method:
Loop through each value:
//Get select object
var objSelect = document.getElementById("Mobility");
//Set selected
setSelectedValue(objSelect, "10");
function setSelectedValue(selectObj, valueToSet) {
for (var i = 0; i < selectObj.options.length; i++) {
if (selectObj.options[i].text== valueToSet) {
selectObj.options[i].selected = true;
return;
}
}
}
.NET 4.0 allows primary interop assemblies (or rather, the bits of it that you need) to be embedded into your assembly so that you don't need to deploy them alongside your application.
For whatever reason, this assembly can't be embedded - but it sounds like that's not a problem for you. Just open the Properties tab for the assembly in Visual Studio 2010 and set "Embed Interop Types" to "False".
EDIT: See also Michael Gustus's answer, removing the Class
suffix from the types you're using.
I don't know why all the answers over here are so confusing. I found a quite simpler one. Use a css class for the asp:menu, say, mainMenu and all the menu items under this will be "a tags" when rendered into HTML. So you just have to provide :hover property to those "a tags" in your CSS. See below for the example:
<asp:Menu ID="mnuMain" Orientation="Horizontal" runat="server" Font-Bold="True" Width="100%" CssClass="mainMenu">
<Items>
<asp:MenuItem Text="Home"></asp:MenuItem>
<asp:MenuItem Text="About Us"></asp:MenuItem>
</Items>
</asp:Menu>
And in the CSS, write:
.mainMenu { background:#900; }
.mainMenu a { color:#fff; }
.mainMenu a:hover { background:#c00; color:#ff9; }
I hope this helps. :)
I had the same problem after a MacOS system upgrade. Solved it by upgrading the postgres with brew. Details: it looks like the system was trying to access Postgres 11 using older Postgres 10 settings. I'm sure it was my mistake somewhere in the past, but luckily it all got sorted out with the upgrade above.
Use the glob function in a foreach loop to do whatever is an option. I also used the file_exists function in the example below to check if the directory exists before going any further.
$directory = 'my_directory/';
$extension = '.txt';
if ( file_exists($directory) ) {
foreach ( glob($directory . '*' . $extension) as $file ) {
echo $file;
}
}
else {
echo 'directory ' . $directory . ' doesn\'t exist!';
}
I finally found out how to do this! Basically you need to run adb shell
first and then while you're in the shell run su
, which will switch the shell to run as root!
$: adb shell
$: su
The one problem I still have is that sqlite3 is not installed so the command is not recognized.
I personally use interfaces for my models, There hoewver are 3 schools regarding this question, and choosing one is most often based on your requirements:
interface
is a virtual structure that only exists within the context of TypeScript. The TypeScript compiler uses interfaces solely for type-checking purposes. Once your code is transpiled to its target language, it will be stripped from its interfaces - JavaScript isn’t typed.
interface User {
id: number;
username: string;
}
// inheritance
interface UserDetails extends User {
birthdate: Date;
biography?: string; // use the '?' annotation to mark this property as optionnal
}
Mapping server response to an interface
is straight forward if you are using HttpClient
from HttpClientModule
if you are using Angular 4.3.x and above.
getUsers() :Observable<User[]> {
return this.http.get<User[]>(url); // no need for '.map((res: Response) => res.json())'
}
when to use interfaces:
let instance: FooInterface = { ... };
, you risk having semi-instances all over the place.A class
defines the blueprints of an object. They express the logic, methods, and properties these objects will inherit.
class User {
id: number;
username: string;
constructor(id :number, username: string) {
this.id = id;
this.username = username.replace(/^\s+|\s+$/g, ''); // trim whitespaces and new lines
}
}
// inheritance
class UserDetails extends User {
birthdate: Date;
biography?: string;
constructor(id :number, username: string, birthdate:Date, biography? :string ) {
super(id,username);
this.birthdate = ...;
}
}
when to use classes:
With the latest versions of typescript, interfaces and types becoming more similar.
types
do not express logic or state inside your application. It is best to use types when you want to describe some form of information. They can describe varying shapes of data, ranging from simple constructs like strings, arrays, and objects.
Like interfaces, types are only virtual structures that don't transpile to any javascript, they just help the compiler making our life easier.
type User = {
id: number;
username: string;
}
// inheritance
type UserDetails = User & {
birthDate :Date;
biography?:string;
}
when to use types: