You should use some background image to your radio buttons and flip it with another image on change
.radio {
background: url(customButton.png) no-repeat;
}
var i;
if (i === null || typeof i === 'undefined') {
console.log(i, 'i is undefined or null')
}
else {
console.log(i, 'i has some value')
}
XAMPP is an integrated package and you can not downgrade or change one of its component such as php. (There are some solutions that you can use but there is little chances that everything work fine.)
You can download the package from these links:
You had better to download the old package form sourceforge.net.
Selenium 4 is already included this feature now, you can directly
open new Tab or new Window with any URL.
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver(options);
driver.get("www.Url1.com");
// below code will open Tab for you as well as switch the control to new Tab
driver.switchTo().newWindow(WindowType.TAB);
// below code will navigate you to your desirable Url
driver.get("www.Url2.com");
download Maven dependencies, this is what I downloaded -
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>3.7.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
you can refer: https://codoid.com/selenium-4-0-command-to-open-new-window-tab/
watch video : https://www.youtube.com/watch?v=7SpCMkUKq-Y&t=8s
google out for - WebDriverManager selenium 4
1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.
1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.
C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.
You can specify a format string if you don't want to use the e-notation.
I solved this issue by removing all the NuGet packages from solution and reinstalling them. One of the NuGet Packages was dependent upon NewtonSoft and it was not showing in references
You can use:
JSONObject jsonObject = new JSONObject();
jsonObject.toString();
And if you want to get a specific value, you can use:
jsonObject.getString("msg");
or Integer value
jsonObject.getInt("codeNum");
Actualy you don't need an internet connection to use ip address. Each computer in LAN has an internal IP address you can discover by runing
ipconfig /all
in cmd.
You can use the ip address of the server (probabily something like 192.168.0.x or 10.0.0.x) to access the website remotely.
If you found the ip and still cannot access the website, it means WAMP is not configured to respond to that name ( what did you call me? 192.168.0.3? That's not my name. I'm Localhost ) and you have to modify ....../apache/config/httpd.conf
Listen *:80
You can also use strcspn(string, "e")
but this may be much slower since it's able to handle searching for multiple possible characters. Using strchr
and subtracting the pointer is the best way.
Here is a quick DOM example that shows how to read and write a simple xml file with its dtd:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE roles SYSTEM "roles.dtd">
<roles>
<role1>User</role1>
<role2>Author</role2>
<role3>Admin</role3>
<role4/>
</roles>
and the dtd:
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT roles (role1,role2,role3,role4)>
<!ELEMENT role1 (#PCDATA)>
<!ELEMENT role2 (#PCDATA)>
<!ELEMENT role3 (#PCDATA)>
<!ELEMENT role4 (#PCDATA)>
First import these:
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.xml.sax.*;
import org.w3c.dom.*;
Here are a few variables you will need:
private String role1 = null;
private String role2 = null;
private String role3 = null;
private String role4 = null;
private ArrayList<String> rolev;
Here is a reader (String xml is the name of your xml file):
public boolean readXML(String xml) {
rolev = new ArrayList<String>();
Document dom;
// Make an instance of the DocumentBuilderFactory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// use the factory to take an instance of the document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// parse using the builder to get the DOM mapping of the
// XML file
dom = db.parse(xml);
Element doc = dom.getDocumentElement();
role1 = getTextValue(role1, doc, "role1");
if (role1 != null) {
if (!role1.isEmpty())
rolev.add(role1);
}
role2 = getTextValue(role2, doc, "role2");
if (role2 != null) {
if (!role2.isEmpty())
rolev.add(role2);
}
role3 = getTextValue(role3, doc, "role3");
if (role3 != null) {
if (!role3.isEmpty())
rolev.add(role3);
}
role4 = getTextValue(role4, doc, "role4");
if ( role4 != null) {
if (!role4.isEmpty())
rolev.add(role4);
}
return true;
} catch (ParserConfigurationException pce) {
System.out.println(pce.getMessage());
} catch (SAXException se) {
System.out.println(se.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
return false;
}
And here a writer:
public void saveToXML(String xml) {
Document dom;
Element e = null;
// instance of a DocumentBuilderFactory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// use factory to get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// create instance of DOM
dom = db.newDocument();
// create the root element
Element rootEle = dom.createElement("roles");
// create data elements and place them under root
e = dom.createElement("role1");
e.appendChild(dom.createTextNode(role1));
rootEle.appendChild(e);
e = dom.createElement("role2");
e.appendChild(dom.createTextNode(role2));
rootEle.appendChild(e);
e = dom.createElement("role3");
e.appendChild(dom.createTextNode(role3));
rootEle.appendChild(e);
e = dom.createElement("role4");
e.appendChild(dom.createTextNode(role4));
rootEle.appendChild(e);
dom.appendChild(rootEle);
try {
Transformer tr = TransformerFactory.newInstance().newTransformer();
tr.setOutputProperty(OutputKeys.INDENT, "yes");
tr.setOutputProperty(OutputKeys.METHOD, "xml");
tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tr.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd");
tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
// send DOM to file
tr.transform(new DOMSource(dom),
new StreamResult(new FileOutputStream(xml)));
} catch (TransformerException te) {
System.out.println(te.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
} catch (ParserConfigurationException pce) {
System.out.println("UsersXML: Error trying to instantiate DocumentBuilder " + pce);
}
}
getTextValue is here:
private String getTextValue(String def, Element doc, String tag) {
String value = def;
NodeList nl;
nl = doc.getElementsByTagName(tag);
if (nl.getLength() > 0 && nl.item(0).hasChildNodes()) {
value = nl.item(0).getFirstChild().getNodeValue();
}
return value;
}
Add a few accessors and mutators and you are done!
Run this command line on your preferred shell session:
db2 "select tabname from syscat.tables where owner = 'DB2INST1'"
Maybe you'd like to modify the owner name, and need to check the list of current owners?
db2 "select distinct owner from syscat.tables"
I always use this code, which print the year to second in a tuple
import datetime
now = datetime.datetime.now()
time_now = (now.year, now.month, now.day, now.hour, now.minute, now.second)
print(time_now)
To generate an inner builder in Intellij IDEA, check out this plugin: https://github.com/analytically/innerbuilder
You can use string.indexof ()
function. This will be case insensitive
First of all, you have got the concept of hashing a little wrong and it had been rectified by Mr. Sanjay.
And yes, Java indeed implement a collision resolution technique. When two keys get hashed to a same value (as the internal array used is finite in size and at some point the hashcode() method will return same hash value for two different keys) at this time, a linked list is formed at the bucket location where all the informations are entered as an Map.Entry object that contains a key-value pair. Accessing an object via a key will at worst require O(n) if the entry in present in such a lists. Comparison between the key you passed with each key in such list will be done by the equals() method.
Although, from Java 8 , the linked lists are replaced with trees (O(log n))
If you are loading images, you are likely going to be working with one or both of matplotlib
and opencv
to manipulate and view the images.
For this reason, I tend to use their image readers and append those to lists, from which I make a NumPy array.
import os
import matplotlib.pyplot as plt
import cv2
import numpy as np
# Get the file paths
im_files = os.listdir('path/to/files/')
# imagine we only want to load PNG files (or JPEG or whatever...)
EXTENSION = '.png'
# Load using matplotlib
images_plt = [plt.imread(f) for f in im_files if f.endswith(EXTENSION)]
# convert your lists into a numpy array of size (N, H, W, C)
images = np.array(images_plt)
# Load using opencv
images_cv = [cv2.imread(f) for f in im_files if f.endswith(EXTENSION)]
# convert your lists into a numpy array of size (N, C, H, W)
images = np.array(images_cv)
The only difference to be aware of is the following:
So a single image that is 256*256 in size would produce matrices of size (3, 256, 256) with opencv and (256, 256, 3) using matplotlib.
This is an improvement over @Mottie's answer because as of jQuery 1.5.2 :text
selects input
elements that have no specified type
attribute (in which case type="text"
is implied):
$('form').find(':text,textarea,select').filter(':visible:first')
SELECT
category,
COUNT(*) AS `num`
FROM
posts
GROUP BY
category
getcwd();
or
dirname(__FILE__);
or (PHP5)
basename(__DIR__)
http://php.net/manual/en/function.getcwd.php
http://php.net/manual/en/function.dirname.php
You can use basename()
to get the trailing part of the path :)
In your case, I'd say you are most likely looking to use getcwd()
, dirname(__FILE__)
is more useful when you have a file that needs to include another library and is included in another library.
Eg:
main.php
libs/common.php
libs/images/editor.php
In your common.php
you need to use functions in editor.php
, so you use
common.php
:
require_once dirname(__FILE__) . '/images/editor.php';
main.php
:
require_once libs/common.php
That way when common.php is require'd
in main.php
, the call of require_once
in common.php
will correctly includes editor.php
in images/editor.php
instead of trying to look in current directory where main.php
is run.
This is actually a JDK bug. It has been reported several times over the years, but only in 8139507 was it finally taken seriously by Oracle.
The problem was in the JDK source code for WindowsPreferences.java
. In this class, both nodes userRoot
and systemRoot
were declared static as in:
/**
* User root node.
*/
static final Preferences userRoot =
new WindowsPreferences(USER_ROOT_NATIVE_HANDLE, WINDOWS_ROOT_PATH);
/**
* System root node.
*/
static final Preferences systemRoot =
new WindowsPreferences(SYSTEM_ROOT_NATIVE_HANDLE, WINDOWS_ROOT_PATH);
This means that the first time the class is referenced both static variables would be initiated and by this the Registry Key for HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs
(= system tree) will be attempted to be created if it doesn't already exist.
So even if the user took every precaution in his own code and never touched or referenced the system tree, then the JVM would actually still try to instantiate systemRoot
, thus causing the warning. It is an interesting subtle bug.
There's a fix committed to the JDK source in June 2016 and it is part of Java9 onwards. There's also a backport for Java8 which is in u202.
What you see is really a warning from the JDK's internal logger. It is not an exception. I believe that the warning can be safely ignored .... unless the user code is indeed wanting the system preferences, but that is very rarely the case.
The bug did not reveal itself in versions prior to Java 1.7.21, because up until then the JRE installer would create Registry key HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs
for you and this would effectively hide the bug. On the other hand you've never really been required to run an installer in order to have a JRE on your machine, or at least this hasn't been Sun/Oracle's intent. As you may be aware Oracle has been distributing the JRE for Windows in .tar.gz
format for many years.
Getting a list of tables:
SELECT
Table_Name = Name,
FROM
MSysObjects
WHERE
(Left([Name],1)<>"~")
AND (Left([Name],4) <> "MSys")
AND ([Type] In (1, 4, 6))
ORDER BY
Name
Use the following extensions and just pass the action like:
_frmx.PerformSafely(() => _frmx.Show());
_frmx.PerformSafely(() => _frmx.Location = new Point(x,y));
Extension class:
public static class CrossThreadExtensions
{
public static void PerformSafely(this Control target, Action action)
{
if (target.InvokeRequired)
{
target.Invoke(action);
}
else
{
action();
}
}
public static void PerformSafely<T1>(this Control target, Action<T1> action,T1 parameter)
{
if (target.InvokeRequired)
{
target.Invoke(action, parameter);
}
else
{
action(parameter);
}
}
public static void PerformSafely<T1,T2>(this Control target, Action<T1,T2> action, T1 p1,T2 p2)
{
if (target.InvokeRequired)
{
target.Invoke(action, p1,p2);
}
else
{
action(p1,p2);
}
}
}
Most of these linker errors occur because of missing libraries.
I added the libstdc++.6.dylib in my Project->Targets->Build Phases-> Link Binary With Libraries.
That solved it for me on Xcode 6.3.2 for iOS 8.3
Cheers!
The solution from this thread is to use the jquery plugin dotdotdot. Not a CSS solution, but it gives you a lot of options for "read more" links, dynamic resizing etc.
AJAX is simply Asyncronous JSON or XML (in most newer situations JSON). Because we are doing an ASYNC task we will likely be providing our users with a more enjoyable UI experience. In this specific case we are doing a FORM submission using AJAX.
Really quickly there are 4 general web actions GET
, POST
, PUT
, and DELETE
; these directly correspond with SELECT/Retreiving DATA
, INSERTING DATA
, UPDATING/UPSERTING DATA
, and DELETING DATA
. A default HTML/ASP.Net webform/PHP/Python or any other form
action is to "submit" which is a POST action. Because of this the below will all describe doing a POST. Sometimes however with http you might want a different action and would likely want to utilitize .ajax
.
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get the action attribute from the <form action=""> element */
var $form = $(this),
url = $form.attr('action');
/* Send the data using post with element id name and name2*/
var posting = $.post(url, {
name: $('#name').val(),
name2: $('#name2').val()
});
/* Alerts the results */
posting.done(function(data) {
$('#result').text('success');
});
posting.fail(function() {
$('#result').text('failed');
});
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formoid" action="studentFormInsert.php" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name">
</div>
<div>
<label class="title">Last Name</label>
<input type="text" id="name2" name="name2">
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<div id="result"></div>
_x000D_
From jQuery website $.post
documentation.
Example: Send form data using ajax requests
$.post("test.php", $("#testform").serialize());
Example: Post a form using ajax and put results in a div
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form action="/" id="searchForm">
<input type="text" name="s" placeholder="Search..." />
<input type="submit" value="Search" />
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
/* attach a submit handler to the form */
$("#searchForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this),
term = $form.find('input[name="s"]').val(),
url = $form.attr('action');
/* Send the data using post */
var posting = $.post(url, {
s: term
});
/* Put the results in a div */
posting.done(function(data) {
var content = $(data).find('#content');
$("#result").empty().append(content);
});
});
</script>
</body>
</html>
Without using OAuth or at minimum HTTPS (TLS/SSL) please don't use this method for secure data (credit card numbers, SSN, anything that is PCI, HIPAA, or login related)
The short answer is no (technically you can give whatever name of the class you want, but this will have no effect, unless you define your own CSS class - and remember - no dots in the class selector). The long answer is again no, because Bootstrap includes a responsive, mobile first fluid grid system that appropriately scales up to 12 columns as the device or view port size increases.
Rows must be placed within a .container
(fixed-width) or .container-fluid
(full-width) for proper alignment and padding.
.row
and .col-xs-4
are available for quickly making grid layouts. Less mixins can also be used for more semantic layouts..rows
..col-xs-4
..col-md-*
class to an element will not only affect its styling on medium devices but also on large devices if a .col-lg-*
class is not present.A possible solution to your problem is to define your own CSS class with desired width, let's say .col-half{width:XXXem !important}
then add this class to elements you want along with original Bootstrap CSS classes.
You can set the default value of your Id in your db to newsequentialid() or newid(). Then the identity configuration of EF should work.
If you have your dates in DateTime variables, they don't have a format.
You can use the Date
property to return a DateTime value with the time portion set to midnight. So, if you have:
DateTime dt1 = DateTime.Parse("07/12/2011");
DateTime dt2 = DateTime.Now;
if(dt1.Date > dt2.Date)
{
//It's a later date
}
else
{
//It's an earlier or equal date
}
Here is the full solution for Android Client + Socket IO Server (Lot of code but works). There seems to be lack of support for Android and IOS when it comes to socket io which is a tragedy of sorts.
Basically creating a room name by joining user unique id from mysql or mongo then sorting it (done in Android Client and sent to server). So each pair has a unique but common amongst the pair room name. Then just go about chatting in that room.
For quick refernce how room is created in Android
// Build The Chat Room
if (Integer.parseInt(mySqlUserId) < Integer.parseInt(toMySqlUserId)) {
room = "ic" + mySqlUserId + toMySqlUserId;
} else {
room = "ic" + toMySqlUserId + mySqlUserId;
}
The Full Works
Package Json
"dependencies": {
"express": "^4.17.1",
"socket.io": "^2.3.0"
},
"devDependencies": {
"nodemon": "^2.0.6"
}
Socket IO Server
app = require('express')()
http = require('http').createServer(app)
io = require('socket.io')(http)
app.get('/', (req, res) => {
res.send('Chat server is running on port 5000')
})
io.on('connection', (socket) => {
// console.log('one user connected ' + socket.id);
// Join Chat Room
socket.on('join', function(data) {
console.log('======Joined Room========== ');
console.log(data);
// Json Parse String To Access Child Elements
var messageJson = JSON.parse(data);
const room = messageJson.room;
console.log(room);
socket.join(room);
});
// On Receiving Individual Chat Message (ic_message)
socket.on('ic_message', function(data) {
console.log('======IC Message========== ');
console.log(data);
// Json Parse String To Access Child Elements
var messageJson = JSON.parse(data);
const room = messageJson.room;
const message = messageJson.message;
console.log(room);
console.log(message);
// Sending to all clients in room except sender
socket.broadcast.to(room).emit('new_msg', {
msg: message
});
});
socket.on('disconnect', function() {
console.log('one user disconnected ' + socket.id);
});
});
http.listen(5000, () => {
console.log('Node app is running on port 5000')
})
Android Socket IO Class
public class SocketIOClient {
public Socket mSocket;
{
try {
mSocket = IO.socket("http://192.168.1.5:5000");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public Socket getSocket() {
return mSocket;
}
}
Android Activity
public class IndividualChatSocketIOActivity extends AppCompatActivity {
// Activity Number For Bottom Navigation Menu
private final Context mContext = IndividualChatSocketIOActivity.this;
// Strings
private String mySqlUserId;
private String toMySqlUserId;
// Widgets
private EditText etTextMessage;
private ImageView ivSendMessage;
// Socket IO
SocketIOClient socketIOClient = new SocketIOClient();
private String room;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
// Widgets
etTextMessage = findViewById(R.id.a_chat_et_text_message);
ivSendMessage = findViewById(R.id.a_chat_iv_send_message);
// Get The MySql UserId from Shared Preference
mySqlUserId = StartupMethods.getFromSharedPreferences("shared",
"id",
mContext);
// Variables From Individual List Adapter
Intent intent = getIntent();
if (intent.hasExtra("to_id")) {
toMySqlUserId = Objects.requireNonNull(Objects.requireNonNull(getIntent().getExtras())
.get("to_id"))
.toString();
}
// Build The Chat Room
if (Integer.parseInt(mySqlUserId) < Integer.parseInt(toMySqlUserId)) {
room = "ic" + mySqlUserId + toMySqlUserId;
} else {
room = "ic" + toMySqlUserId + mySqlUserId;
}
connectToSocketIO();
joinChat();
leaveChat();
getChatMessages();
sendChatMessages();
}
@Override
protected void onPause() {
super.onPause();
}
private void connectToSocketIO() {
socketIOClient.mSocket = socketIOClient.getSocket();
socketIOClient.mSocket.on(Socket.EVENT_CONNECT_ERROR,
onConnectError);
socketIOClient.mSocket.on(Socket.EVENT_CONNECT_TIMEOUT,
onConnectError);
socketIOClient.mSocket.on(Socket.EVENT_CONNECT,
onConnect);
socketIOClient.mSocket.on(Socket.EVENT_DISCONNECT,
onDisconnect);
socketIOClient.mSocket.connect();
}
private void joinChat() {
// Prepare To Send Data Through WebSockets
JSONObject jsonObject = new JSONObject();
// Header Fields
try {
jsonObject.put("room",
room);
socketIOClient.mSocket.emit("join",
String.valueOf(jsonObject));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void leaveChat() {
}
private void getChatMessages() {
socketIOClient.mSocket.on("new_msg",
new Emitter.Listener() {
@Override
public void call(Object... args) {
try {
JSONObject messageJson = new JSONObject(args[0].toString());
String message = String.valueOf(messageJson);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(IndividualChatSocketIOActivity.this,
message,
Toast.LENGTH_SHORT)
.show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
private void sendChatMessages() {
ivSendMessage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String message = etTextMessage.getText()
.toString()
.trim();
// Prepare To Send Data Thru WebSockets
JSONObject jsonObject = new JSONObject();
// Header Fields
try {
jsonObject.put("room",
room);
jsonObject.put("message",
message);
socketIOClient.mSocket.emit("ic_message",
String.valueOf(jsonObject));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
public Emitter.Listener onConnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(IndividualChatSocketIOActivity.this,
"Connected To Socket Server",
Toast.LENGTH_SHORT)
.show();
}
});
Log.d("TAG",
"Socket Connected!");
}
};
private Emitter.Listener onConnectError = new Emitter.Listener() {
@Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
}
};
private Emitter.Listener onDisconnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
}
};
}
Android Gradle
// SocketIO
implementation ('io.socket:socket.io-client:1.0.0') {
// excluding org.json which is provided by Android
exclude group: 'org.json', module: 'json'
}
if you are removing all disabled attributes from input, then why not just do:
$("input").removeAttr('disabled');
Then after ajax success:
$("input[type='text']").attr('disabled', true);
Make sure you use remove the disabled attribute before submit, or it won't submit that data. If you need to submit it before changing, you need to use readonly instead.
Exporting without default
means it's a "named export". You can have multiple named exports in a single file. So if you do this,
class Template {}
class AnotherTemplate {}
export { Template, AnotherTemplate }
then you have to import these exports using their exact names. So to use these components in another file you'd have to do,
import {Template, AnotherTemplate} from './components/templates'
Alternatively if you export as the default
export like this,
export default class Template {}
Then in another file you import the default export without using the {}
, like this,
import Template from './components/templates'
There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.
You're free to rename the default export as you import it,
import TheTemplate from './components/templates'
And you can import default and named exports at the same time,
import Template,{AnotherTemplate} from './components/templates'
And for those of you using an anonymous expression:
await Task.Run(async () =>
{
SQLLiteUtils slu = new SQLiteUtils();
await slu.DeleteGroupAsync(groupname);
});
- Check for your script has to be write or loaded after jQuery link.
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>_x000D_
_x000D_
//after link >> write codes..._x000D_
_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
//your code_x000D_
})(jQuery);_x000D_
</script>
_x000D_
Take a look at the formats in ?strptime
R> foo <- factor("1/15/2006 0:00:00")
R> foo <- as.Date(foo, format = "%m/%d/%Y %H:%M:%S")
R> foo
[1] "2006-01-15"
R> class(foo)
[1] "Date"
Note that this will work even if foo
starts out as a character. It will also work if using other date formats (as.POSIXlt
, as.POSIXct
).
In my small experience:
"=" for Exact Matches.
"LIKE" for Partial Matches.
Also if you run pytest
within your virtual environment make sure pytest
module is installed within your virtual environment. Activate your virtual env and run pip install pytest
.
One way I can imagine is to use a linked list to implement such a scenario, if you need all the numbers entered before the user enters something which indicates the loop termination. (posting as the first option, because have never done this for user input, it just seemed to be interesting. Wasteful but artistic)
Another way is to do buffered input. Allocate a buffer, fill it, re-allocate, if the loop continues (not elegant, but the most rational for the given use-case).
I don't consider the described to be elegant though. Probably, I would change the use-case (the most rational).
For java 1.5 or greater:
java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 <YourAppName>
For java 1.4:
java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 <YourAppName>
For java 1.3:
java -Xnoagent -Djava.compiler=NONE -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 <YourAppName>
Here is output from a simple program:
java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1044 HelloWhirled
Listening for transport dt_socket at address: 1044
Hello whirled
You should use require_once and include_once. Inside parent.php use
include_once 'database.php';
And inside child1.php and child2.php use
include_once 'parent.php';
You can try using AppDomain.UnhandledException and see if that lets you catch it.
**EDIT*
Here is some more information that might be useful (it's a long read).
You (normally) cannot modify the collection you are iterating over when using foreach.
Although for and foreach seem to be similar from a developer perspective they are quite different from an implementation perspective.
Foreach
uses an Iterator
to access the individual objects while for
doesn't know (or care) about the underlying object sequence.
std::string text = "--foo=98";
std::string start = "--foo=";
if (text.find(start) == 0)
{
int n = stoi(text.substr(start.length()));
std::cout << n << std::endl;
}
Keep in mind when using the group by and order by that MySQL is the ONLY database that allows for columns to be used in the group by and/or order by piece that are not part of the select statement.
So for example: select column1 from table group by column2 order by column3
That will not fly in other databases like Postgres, Oracle, MSSQL, etc. You would have to do the following in those databases
select column1, column2, column3 from table group by column2 order by column3
Just some info in case you ever migrate your current code to another database or start working in another database and try to reuse code.
Ok, so this might not fix your issue but it definitely worked for me.
So you've created your Mysql user I take it? Go to user privileges on PhpMyAdmin and click edit next to the user your using for Symfony. Scroll down to near the bottom and where it says which host you want to use make sure you've selected LocalHost not % Any.
Then in your config file swap 127.0.0.1 for localhost. Hopefully that will work for you. Just worked for me as I was having the same issue.
Created a Kotlin Extension function for those of you who might find it handy.
Make sure to pass in pixels not dp. Happy coding :)
fun View.addLayoutMargins(left: Int? = null, top: Int? = null,
right: Int? = null, bottom: Int? = null) {
this.layoutParams = ViewGroup.MarginLayoutParams(this.layoutParams)
.apply {
left?.let { leftMargin = it }
top?.let { topMargin = it }
right?.let { rightMargin = it }
bottom?.let { bottomMargin = it }
}
}
In addition to the ioctl() method Filip demonstrated you can use getifaddrs(). There is an example program at the bottom of the man page.
Get-ADUser -Filter { memberOf -RecursiveMatch "CN=Administrators,CN=Builtin,DC=Fabrikam,DC=com" } -SearchBase "CN=Administrator,CN=Users,DC=Fabrikam,DC=com" -SearchScope Base
## NOTE: The above command will return the user object (Administrator in this case) if it finds a match recursively in memberOf attribute.
From the macOS Terminal, use open
with the -a
flag and give the name of the app you want to open. In this case "Google Chrome". You may pass it a file or URL you want it to open with.
open -a "Google Chrome" index.html
as of rc.6 / final
...
export enum AdnetNetworkPropSelector {
CONTENT,
PACKAGE,
RESOURCE
}
<div style="height: 100%">
<div [ngSwitch]="propSelector">
<div *ngSwitchCase="adnetNetworkPropSelector.CONTENT">
<AdnetNetworkPackageContentProps [setAdnetContentModels]="adnetNetworkPackageContent.selectedAdnetContentModel">
</AdnetNetworkPackageContentProps>
</div>
<div *ngSwitchCase="adnetNetworkPropSelector.PACKAGE">
</div>
</div>
</div>
export class AdnetNetwork {
private adnetNetworkPropSelector = AdnetNetworkPropSelector;
private propSelector = AdnetNetworkPropSelector.CONTENT;
}
I think that while not elegant, the oplog could be partially used for this purpose: it logs all the writes - but not the reads...
You have to enable replicatoon, if I'm right. The information is from this answer from this question: How to listen for changes to a MongoDB collection?
Try this one..
var listCheck = [];
console.log($("input[name='YourCheckBokName[]']"));
$("input[name='YourCheckBokName[]']:checked").each(function() {
console.log($(this).val());
listCheck .push($(this).val());
});
console.log(listCheck);
Consider the following code:
error_reporting(E_STRICT);
class test {
function test_arr(&$a) {
var_dump($a);
}
function get_arr() {
return array(1, 2);
}
}
$t = new test;
$t->test_arr($t->get_arr());
This will generate the following output:
Strict Standards: Only variables should be passed by reference in `test.php` on line 14
array(2) {
[0]=>
int(1)
[1]=>
int(2)
}
The reason? The test::get_arr()
method is not a variable and under strict mode this will generate a warning. This behavior is extremely non-intuitive as the get_arr()
method returns an array value.
To get around this error in strict mode, either change the signature of the method so it doesn't use a reference:
function test_arr($a) {
var_dump($a);
}
Since you can't change the signature of array_shift
you can also use an intermediate variable:
$inter = get_arr();
$el = array_shift($inter);
In your example there is no big difference between str -> str
and Function.identity()
since internally it is simply t->t
.
But sometimes we can't use Function.identity
because we can't use a Function
. Take a look here:
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
this will compile fine
int[] arrayOK = list.stream().mapToInt(i -> i).toArray();
but if you try to compile
int[] arrayProblem = list.stream().mapToInt(Function.identity()).toArray();
you will get compilation error since mapToInt
expects ToIntFunction
, which is not related to Function
. Also ToIntFunction
doesn't have identity()
method.
in windows 7 this returns the desktop path:
FOR /F "usebackq tokens=3 " %%i in (`REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop`) DO SET DESKTOPDIR=%%i FOR /F "usebackq delims=" %%i in (`ECHO %DESKTOPDIR%`) DO SET DESKTOPDIR=%%i ECHO %DESKTOPDIR%
Well, my answer to interviewer's question is - Private members are not inherited in sub-classes but they are accessible to subclass or subclass's object only via public getter or setter methods or any such appropriate methods of original class. The normal practice is to keep the members private and access them using getter and setter methods which are public. So whats the point in only inheriting getter and setter methods when the private member they deal with are not available to the object? Here 'inherited' simply means it is available directly in the sub-class to play around by newly introduced methods in sub-class.
Save the below file as ParentClass.java and try it yourself ->
public class ParentClass {
private int x;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
}
class SubClass extends ParentClass {
private int y;
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void setXofParent(int x) {
setX(x);
}
}
class Main {
public static void main(String[] args) {
SubClass s = new SubClass();
s.setX(10);
s.setY(12);
System.out.println("X is :"+s.getX());
System.out.println("Y is :"+s.getY());
s.setXofParent(13);
System.out.println("Now X is :"+s.getX());
}
}
Output:
X is :10
Y is :12
Now X is :13
If we try to use private variable x of ParentClass in SubClass's method then it is not directly accessible for any modifications (means not inherited). But x can be modified in SubClass via setX() method of original class as done in setXofParent() method OR it can be modified using ChildClass object using setX() method or setXofParent() method which ultimately calls setX(). So here setX() and getX() are kind of gates to the private member x of a ParentClass.
Another simple example is Clock superclass has hours and mins as private members and appropriate getter and setter methods as public. Then comes DigitalClock as a sub-class of Clock. Here if the DigitalClock's object doesn't contain hours and mins members then things are screwed up.
Try this. If I got any error on any file then I got error mail on my email id. Create two files index.php
and checkErrorEmail.php
and uploaded them to your server. Then load index.php
with your browser.
Index.php
<?php
include('checkErrorEmail.php');
include('dereporting.php');
$temp;
echo 'hi '.$temp;
?>
checkErrorEmail.php
<?php
// Destinations
define("ADMIN_EMAIL", "[email protected]");
//define("LOG_FILE", "/my/home/errors.log");
// Destination types
define("DEST_EMAIL", "1");
//define("DEST_LOGFILE", "3");
/* Examples */
// Send an e-mail to the administrator
//error_log("Fix me!", DEST_EMAIL, ADMIN_EMAIL);
// Write the error to our log file
//error_log("Error", DEST_LOGFILE, LOG_FILE);
/**
* my_error_handler($errno, $errstr, $errfile, $errline)
*
* Author(s): thanosb, ddonahue
* Date: May 11, 2008
*
* custom error handler
*
* Parameters:
* $errno: Error level
* $errstr: Error message
* $errfile: File in which the error was raised
* $errline: Line at which the error occurred
*/
function my_error_handler($errno, $errstr, $errfile, $errline)
{
echo "<br><br><br><br>errno ".$errno.",<br>errstr ".$errstr.",<br>errfile ".$errfile.",<br>errline ".$errline;
if($errno)
{
error_log("Error: $errstr \n error on line $errline in file $errfile \n", DEST_EMAIL, ADMIN_EMAIL);
}
/*switch ($errno) {
case E_USER_ERROR:
// Send an e-mail to the administrator
error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_EMAIL, ADMIN_EMAIL);
// Write the error to our log file
//error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_LOGFILE, LOG_FILE);
break;
case E_USER_WARNING:
// Write the error to our log file
//error_log("Warning: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
break;
case E_USER_NOTICE:
// Write the error to our log file
// error_log("Notice: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
break;
default:
// Write the error to our log file
//error_log("Unknown error [#$errno]: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
break;
}*/
// Don't execute PHP's internal error handler
return TRUE;
}
// Use set_error_handler() to tell PHP to use our method
$old_error_handler = set_error_handler("my_error_handler");
?>
A simple method of creating the service, adding headers and reading the JSON response,
private static void WebRequest()
{
const string WEBSERVICE_URL = "<<Web service URL>>";
try
{
var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
if (webRequest != null)
{
webRequest.Method = "GET";
webRequest.Timeout = 12000;
webRequest.ContentType = "application/json";
webRequest.Headers.Add("Authorization", "Basic dchZ2VudDM6cGFdGVzC5zc3dvmQ=");
using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
Console.WriteLine(String.Format("Response: {0}", jsonResponse));
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Here ready static class
import java.io.*;
import java.util.Properties;
public class Settings {
public static String Get(String name,String defVal){
File configFile = new File(Variables.SETTINGS_FILE);
try {
FileReader reader = new FileReader(configFile);
Properties props = new Properties();
props.load(reader);
reader.close();
return props.getProperty(name);
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
return defVal;
} catch (IOException ex) {
// I/O error
logger.error(ex);
return defVal;
} catch (Exception ex){
logger.error(ex);
return defVal;
}
}
public static Integer Get(String name,Integer defVal){
File configFile = new File(Variables.SETTINGS_FILE);
try {
FileReader reader = new FileReader(configFile);
Properties props = new Properties();
props.load(reader);
reader.close();
return Integer.valueOf(props.getProperty(name));
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
return defVal;
} catch (IOException ex) {
// I/O error
logger.error(ex);
return defVal;
} catch (Exception ex){
logger.error(ex);
return defVal;
}
}
public static Boolean Get(String name,Boolean defVal){
File configFile = new File(Variables.SETTINGS_FILE);
try {
FileReader reader = new FileReader(configFile);
Properties props = new Properties();
props.load(reader);
reader.close();
return Boolean.valueOf(props.getProperty(name));
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
return defVal;
} catch (IOException ex) {
// I/O error
logger.error(ex);
return defVal;
} catch (Exception ex){
logger.error(ex);
return defVal;
}
}
public static void Set(String name, String value){
File configFile = new File(Variables.SETTINGS_FILE);
try {
Properties props = new Properties();
FileReader reader = new FileReader(configFile);
props.load(reader);
props.setProperty(name, value.toString());
FileWriter writer = new FileWriter(configFile);
props.store(writer, Variables.SETTINGS_COMMENT);
writer.close();
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
} catch (IOException ex) {
// I/O error
logger.error(ex);
} catch (Exception ex){
logger.error(ex);
}
}
public static void Set(String name, Integer value){
File configFile = new File(Variables.SETTINGS_FILE);
try {
Properties props = new Properties();
FileReader reader = new FileReader(configFile);
props.load(reader);
props.setProperty(name, value.toString());
FileWriter writer = new FileWriter(configFile);
props.store(writer,Variables.SETTINGS_COMMENT);
writer.close();
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
} catch (IOException ex) {
// I/O error
logger.error(ex);
} catch (Exception ex){
logger.error(ex);
}
}
public static void Set(String name, Boolean value){
File configFile = new File(Variables.SETTINGS_FILE);
try {
Properties props = new Properties();
FileReader reader = new FileReader(configFile);
props.load(reader);
props.setProperty(name, value.toString());
FileWriter writer = new FileWriter(configFile);
props.store(writer,Variables.SETTINGS_COMMENT);
writer.close();
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
} catch (IOException ex) {
// I/O error
logger.error(ex);
} catch (Exception ex){
logger.error(ex);
}
}
}
Here sample:
Settings.Set("valueName1","value");
String val1=Settings.Get("valueName1","value");
Settings.Set("valueName2",true);
Boolean val2=Settings.Get("valueName2",true);
Settings.Set("valueName3",100);
Integer val3=Settings.Get("valueName3",100);
Use the Oracle 10g dialect. Also Hibernate 3.3.2+ is required for recent JDBC drivers (the internal class structure changed - symptoms will be whining about an abstract class).
Dialect of Oracle 11g is same as Oracle 10g (org.hibernate.dialect.Oracle10gDialect). Source: http://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/session-configuration.html#configuration-optional-dialects
Here's a far simpler solution for commits to the wrong branch. Starting on branch master
that has three mistaken commits:
git reset HEAD~3
git stash
git checkout newbranch
git stash pop
master
master
, yet leaves all working files intactmaster
working tree exactly equal to the HEAD~3 statenewbranch
You can now use git add
and git commit
as you normally would. All new commits will be added to newbranch
.
The OP stated the goal was to "take master back to before those commits were made" without losing changes and this solution does that.
I do this at least once a week when I accidentally make new commits to master
instead of develop
. Usually I have only one commit to rollback in which case using git reset HEAD^
on line 1 is a simpler way to rollback just one commit.
Don't do this if you pushed master's changes upstream
Someone else may have pulled those changes. If you are only rewriting your local master there's no impact when it's pushed upstream, but pushing a rewritten history to collaborators can cause headaches.
You could use the Python bindings to libmagic, python-magic and then check the mime types. This won't tell you if the files are corrupted or intact but it should be able to determine what type of image it is.
I did something similar to the jquery above, but I needed to reset my form data and graphic attachment canvases. So here is what I came up with:
<script>
$(document).ready(function(){
$("#text_only_radio_button_id").click(function(){
$("#single_pic_div").hide();
$("#multi_pic_div").hide();
});
$("#pic_radio_button_id").click(function(){
$("#single_pic_div").show();
$("#multi_pic_div").hide();
});
$("#gallery_radio_button_id").click(function(){
$("#single_pic_div").hide();
$("#multi_pic_div").show();
});
$("#my_Submit_button_ID").click(function() {
$("#single_pic_div").hide();
$("#multi_pic_div").hide();
var url = "script_the_form_gets_posted_to.php";
$.ajax({
type: "POST",
url: url,
data: $("#html_form_id").serialize(),
success: function(){
document.getElementById("html_form_id").reset();
var canvas=document.getElementById("canvas");
var canvasA=document.getElementById("canvasA");
var canvasB=document.getElementById("canvasB");
var canvasC=document.getElementById("canvasC");
var canvasD=document.getElementById("canvasD");
var ctx=canvas.getContext("2d");
var ctxA=canvasA.getContext("2d");
var ctxB=canvasB.getContext("2d");
var ctxC=canvasC.getContext("2d");
var ctxD=canvasD.getContext("2d");
ctx.clearRect(0, 0,480,480);
ctxA.clearRect(0, 0,480,480);
ctxB.clearRect(0, 0,480,480);
ctxC.clearRect(0, 0,480,480);
ctxD.clearRect(0, 0,480,480);
} });
return false;
}); });
</script>
That works well for me, for your application of just an html form, we can simplify this jquery code like this:
<script>
$(document).ready(function(){
$("#my_Submit_button_ID").click(function() {
var url = "script_the_form_gets_posted_to.php";
$.ajax({
type: "POST",
url: url,
data: $("#html_form_id").serialize(),
success: function(){
document.getElementById("html_form_id").reset();
} });
return false;
}); });
</script>
It also means you can use reserved words as variable names
say you want a class named class, since class is a reserved word, you can instead call your class class:
IList<Student> @class = new List<Student>();
jQuery.fn
is defined shorthand for jQuery.prototype
. From the source code:
jQuery.fn = jQuery.prototype = {
// ...
}
That means jQuery.fn.jquery
is an alias for jQuery.prototype.jquery
, which returns the current jQuery version. Again from the source code:
// The current version of jQuery being used
jquery: "@VERSION",
import pymysql
# Open database connection
db = pymysql.connect("localhost","root","","gkdemo1")
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT * from user")
# Get the fields name (only once!)
field_name = [field[0] for field in cursor.description]
# Fetch a single row using fetchone() method.
values = cursor.fetchone()
# create the row dictionary to be able to call row['login']
**row = dict(zip(field_name, values))**
# print the dictionary
print(row)
# print specific field
print(**row['login']**)
# print all field
for key in row:
print(**key," = ",row[key]**)
# close database connection
db.close()
Schema says what tables are in database, what columns they have and how they are related. Each database has its own schema.
If you have multiple projects in your solution, then right-click on the solution icon in Visual Studio and select 'Manage NuGet Packages for Solution', then click on the fourth tab 'Consolidate' to consolidate all your projects to the same version of the DLLs. This will give you a list of referenced assemblies to consolidate. Click on each item in the list, then click install in the tab that appears to the right.
If you want to assert that the two lists are identical, don't complicate things with Hamcrest:
assertEquals(expectedList, actual.getList());
If you really intend to perform an order-insensitive comparison, you can call the containsInAnyOrder
varargs method and provide values directly:
assertThat(actual.getList(), containsInAnyOrder("item1", "item2"));
(Assuming that your list is of String
, rather than Agent
, for this example.)
If you really want to call that same method with the contents of a List
:
assertThat(actual.getList(), containsInAnyOrder(expectedList.toArray(new String[expectedList.size()]));
Without this, you're calling the method with a single argument and creating a Matcher
that expects to match an Iterable
where each element is a List
. This can't be used to match a List
.
That is, you can't match a List<Agent>
with a Matcher<Iterable<List<Agent>>
, which is what your code is attempting.
The best way is to do a mongodump
then mongorestore
. You can select the collection via:
mongodump -d some_database -c some_collection
[Optionally, zip the dump (zip some_database.zip some_database/* -r
) and scp
it elsewhere]
Then restore it:
mongorestore -d some_other_db -c some_or_other_collection dump/some_collection.bson
Existing data in some_or_other_collection
will be preserved. That way you can "append" a collection from one database to another.
Prior to version 2.4.3, you will also need to add back your indexes after you copy over your data. Starting with 2.4.3, this process is automatic, and you can disable it with --noIndexRestore
.
You never want to call thread.sleep()
on the UI
thread as it sounds like you have figured out. This freezes the UI
and is always a bad thing to do. You can use a separate Thread
and postDelayed
This SO answer shows how to do that as well as several other options
You can look at these and see which will work best for your particular situation
I was getting this error today. And above answers didn't help me. I was getting this error when I try to start the SQL Server(SQLEXPRESS) service in Services(services.msc).
When I checked the error log at the location C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\Log, there was an entry related TCP/IP port.
2018-06-19 20:41:52.20 spid12s TDSSNIClient initialization failed with error 0x271d, status code 0xa. Reason: Unable to initialize the TCP/IP listener. An attempt was made to access a socket in a way forbidden by its access permissions.
Recently I was running a MSSQLEXPRESS image in my docker container, which was using the same TCP/IP port, that caused this issue.
So, what I did is, I just reset my TCP/IP by doing the below command.
netsh int ip reset resetlog.txt
Once the resetting is done, I had to restart the machine and when I try to start the SQLEXPRESS service again, it started successfully. Hope it helps.
Use variables i.e. the .BAT
variables and called %0
to %9
You can use the Like
operator with a wildcard to determine whether a given substring exists in a string, for example:
If cell.Value Like "*Word1*" Then
'...
ElseIf cell.Value Like "*Word2*" Then
'...
End If
In this example the *
character in "*Word1*"
is a wildcard character which matches zero or more characters.
NOTE: The Like
operator is case-sensitive, so "Word1" Like "word1"
is false, more information can be found on this MSDN page.
$$
is defined to return the process ID of the parent in a subshell; from the man page under "Special Parameters":
$ Expands to the process ID of the shell. In a () subshell, it expands to the process ID of the current shell, not the subshell.
In bash
4, you can get the process ID of the child with BASHPID
.
~ $ echo $$
17601
~ $ ( echo $$; echo $BASHPID )
17601
17634
The answer by Kleist certainly works, but there is an important caveat:
When you write a Makefile
manually, you might generate a SRCS
variable using a function to select all .cpp
and .h
files. If a source file is later added, re-running make
will include it.
However, CMake (with a command like file(GLOB ...)
) will explicitly generate a file list and place it in the auto-generated Makefile
. If you have a new source file, you will need to re-generate the Makefile
by re-running cmake
.
edit: No need to remove the Makefile.
names = {'John', 'Joe', 'Steve'}
for names = 1, 3 do
print (names)
end
Try:
names = {'John','Joe','Steve'}
for i = 1,3 do
print(names[i])
end
Try converting your procedure in to an Inline Function which returns a table as follows:
CREATE FUNCTION MyProc()
RETURNS TABLE AS
RETURN (SELECT * FROM MyTable)
And then you can call it as
SELECT * FROM MyProc()
You also have the option of passing parameters to the function as follows:
CREATE FUNCTION FuncName (@para1 para1_type, @para2 para2_type , ... )
And call it
SELECT * FROM FuncName ( @para1 , @para2 )
Following @Caspar comment on accepted answer, the preferred way to fix this according to Sun is :
"change the locale of the underlying platform before starting your Java program."
http://bugs.java.com/view_bug.do?bug_id=4163515
For docker see:
From the MS SQL Server online documentation (http://technet.microsoft.com/en-us/library/ms186734.aspx ), here is their example that I have tested and works, for retrieving a specific set of rows. ROW_NUMBER requires an OVER, but you can order by whatever you like:
WITH OrderedOrders AS
(
SELECT SalesOrderID, OrderDate,
ROW_NUMBER() OVER (ORDER BY OrderDate) AS RowNumber
FROM Sales.SalesOrderHeader
)
SELECT SalesOrderID, OrderDate, RowNumber
FROM OrderedOrders
WHERE RowNumber BETWEEN 50 AND 60;
if you're doing a lot of this kind of thing you should consider using numpy
.
In [56]: import random, numpy
In [57]: lst = numpy.array([random.uniform(0, 5) for _ in range(1000)]) # example list
In [58]: a, b = 1, 3
In [59]: numpy.flatnonzero((lst > a) & (lst < b))[:10]
Out[59]: array([ 0, 12, 13, 15, 18, 19, 23, 24, 26, 29])
In response to Seanny123's question, I used this timing code:
import numpy, timeit, random
a, b = 1, 3
lst = numpy.array([random.uniform(0, 5) for _ in range(1000)])
def numpy_way():
numpy.flatnonzero((lst > 1) & (lst < 3))[:10]
def list_comprehension():
[e for e in lst if 1 < e < 3][:10]
print timeit.timeit(numpy_way)
print timeit.timeit(list_comprehension)
The numpy version is over 60 times faster.
$key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion'
(Get-ItemProperty -Path $key -Name ProgramFilesDir).ProgramFilesDir
I've never liked how this was provider was implemented like this : /
Basically, it makes every registry value a PSCustomObject
object with PsPath
, PsParentPath
, PsChildname
, PSDrive
and PSProvider
properties and then a property for its actual value. So even though you asked for the item by name, to get its value you have to use the name once more.
Perhaps the pandas interface has changed since @Rutger answered, but in the version I'm using (0.15.2), the date_parser
function receives a list of dates instead of a single value. In this case, his code should be updated like so:
dateparse = lambda dates: [pd.datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in dates]
df = pd.read_csv(infile, parse_dates=['datetime'], date_parser=dateparse)
If you are creating a new app instead of converting an existing one, the easiest way to create WAR based spring boot application is through Spring Initializr.
It auto-generates the application for you. By default it creates Jar, but in the advanced options, you can select to create WAR. This war can be also executed directly.
Even easier is to create the project from IntelliJ IDEA directly:
File ? New Project ? Spring Initializr
Here is a one liner. A little improvised answer using format with print() to iterate a list.
How about this (python 3.x):
sample_list = ['cat', 'dog', 'bunny', 'pig']
print("Your list of animals are: {}, {}, {} and {}".format(*sample_list))
Read the docs here on using format().
Another workaround is just to set the li
item to flex
or inline-flex
. Depending on the circumstances that may suit you better. In case you have a real icon / image placed in the HTML the default flex position is on the central horizontal line.
We can keep our ssh connection alive by having following Global configurations
Add the following line to the /etc/ssh/ssh_config
file:
ServerAliveInterval 60
You can also do linking almost normally:
<a href="#" onclick="window.location='URL_TO_GO';">TEXT OF THE LINK</a>
And you can remove the hash tag and href, everything it does it affects appearance..
Libraries cannot be directly used in any program if not properly added to the project gradle files.
This can easily be done in smart IDEs like inteli J.
1) First as a convention add a folder names 'libs' under your project src file. (this can easily be done using the IDE itself)
2) then copy or add your library file (eg: .jar file) to the folder named 'libs'
3) now you can see the library file inside the libs folder. Now right click on the file and select 'add as library'. And this will fix all the relevant files in your program and library will be directly available for your use.
Please note:
Whenever you are adding libraries to a project, make sure that the project supports the library
Actually maybe you should choose the function update
is better.
Here's the document of function update
http://api.highcharts.com/highcharts#Series.update
You can just type code like below:
chart.series[0].update({data: [1,2,3,4,5]})
These code will merge the origin option, and update the changed data.
jquery.js = Pretty and easy to read :) Read this one.
jquery.min.js = Looks like jibberish! But has a smaller file size. Put this one on your site.
Both are the same in functionality. The difference is only in whether it's formatted nicely for readability or compactly for smaller file size.
Specifically, the second one is minified, a process which involves removing unnecessary whitespace and shortening variable names. Both contribute to making the code much harder to read: the removal of whitespace removes line breaks and spaces messing up the formatting, and the shortening of variable names (including some function names) replaces the original variable names with meaningless letters.
All this is done in such a way that it doesn't affect the way the code behaves when run, in any way. Notably, the replacement/shortening of variable and function names is only done to names that appear in a local scope where it won't interfere with any other code in other scripts.
Late to the game but here a handy little category I use that accounts for decimal places and the local symbol used for it. link to its gist here
@interface NSString (Extension)
- (BOOL) isAnEmail;
- (BOOL) isNumeric;
@end
@implementation NSString (Extension)
/**
* Determines if the current string is a valid email address.
*
* @return BOOL - True if the string is a valid email address.
*/
- (BOOL) isAnEmail
{
NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:self];
}
/**
* Determines if the current NSString is numeric or not. It also accounts for the localised (Germany for example use "," instead of ".") decimal point and includes these as a valid number.
*
* @return BOOL - True if the string is numeric.
*/
- (BOOL) isNumeric
{
NSString *localDecimalSymbol = [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator];
NSMutableCharacterSet *decimalCharacterSet = [NSMutableCharacterSet characterSetWithCharactersInString:localDecimalSymbol];
[decimalCharacterSet formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
NSCharacterSet* nonNumbers = [decimalCharacterSet invertedSet];
NSRange r = [self rangeOfCharacterFromSet: nonNumbers];
if (r.location == NSNotFound)
{
// check to see how many times the decimal symbol appears in the string. It should only appear once for the number to be numeric.
int numberOfOccurances = [[self componentsSeparatedByString:localDecimalSymbol] count]-1;
return (numberOfOccurances > 1) ? NO : YES;
}
else return NO;
}
@end
Another way, for variety. Although this is somewhat less flexible than the others. Unfortunately, the graphs appear one above the other, rather than side-by-side, which you did request in your original question. But it is very concise.
df.plot(subplots=True)
If the dataframe has more than the two series, and you only want to plot those two, you'll need to replace df
with df[['korisnika','osiguranika']]
.
On windows those guys using xampp should use this path xampp/mysql/bin/my.ini and change max_allowed_packet(under section[mysqld])to your choice size. e.g
max_allowed_packet=8M
Again on php.ini(xampp/php/php.ini) change upload_max_filesize the choice size. e.g
upload_max_filesize=8M
Gave me a headache for sometime till i discovered this. Hope it helps.
You should really use the standard List class. Unless, of course, this is a homework question, or you want to know how lists are implemented by STL.
You'll find plenty of simple tutorials via google, like this one. If you want to know how linked lists work "under the hood", try searching for C list examples/tutorials rather than C++.
SOLUTION 1
First working solution (tested) useful especially when using @EnableWebMvc:
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Autowired
private ObjectMapper objectMapper;// created elsewhere
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
// this won't add a 2nd MappingJackson2HttpMessageConverter
// as the SOLUTION 2 is doing but also might seem complicated
converters.stream().filter(c -> c instanceof MappingJackson2HttpMessageConverter).forEach(c -> {
// check default included objectMapper._registeredModuleTypes,
// e.g. Jdk8Module, JavaTimeModule when creating the ObjectMapper
// without Jackson2ObjectMapperBuilder
((MappingJackson2HttpMessageConverter) c).setObjectMapper(this.objectMapper);
});
}
SOLUTION 2
Of course the common approach below works too (also working with @EnableWebMvc):
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Autowired
private ObjectMapper objectMapper;// created elsewhere
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
// this will add a 2nd MappingJackson2HttpMessageConverter
// (additional to the default one) but will work and you
// won't lose the default converters as you'll do when overwriting
// configureMessageConverters(List<HttpMessageConverter<?>> converters)
//
// you still have to check default included
// objectMapper._registeredModuleTypes, e.g.
// Jdk8Module, JavaTimeModule when creating the ObjectMapper
// without Jackson2ObjectMapperBuilder
converters.add(new MappingJackson2HttpMessageConverter(this.objectMapper));
}
Why @EnableWebMvc usage is a problem?
@EnableWebMvc is using DelegatingWebMvcConfiguration
which extends WebMvcConfigurationSupport
which does this:
if (jackson2Present) {
Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json();
if (this.applicationContext != null) {
builder.applicationContext(this.applicationContext);
}
messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}
which means that there's no way of injecting your own ObjectMapper
with the purpose of preparing it to be used for creating the default MappingJackson2HttpMessageConverter
when using @EnableWebMvc.
You are missing spring-security-web-3.1.X.RELEASE.jar
from your classpath
The answer is really easy: It's pretty safe to say that it won't be possible in the next two decades. Before that we will probably get good translation tools. The last time I checked, the AI guys were struggling to identify the same car on two photographs shot from a slightly altered angle. Take a look on how long it took them to get good enough OCR or speech recognition together. Those are recognition problems which can benefit greatly from dictionaries and are still far from having completely reliable solutions despite of the multi-million man months thrown at them.
That being said you could simply add an "offensive?" link next to user generated contend and have a mod cross check the incoming complaints.
edit:
I forgot something: IF you are going to implement some kind of filter, you will need a reliable one. If your solution would be 50% right, 2000 out of 4000 users with decent images will get blocked. Expect an outrage.
You can use just:
Declare @pass2 binary(32)
Set @pass2 =0x4D006A00450034004E0071006B00350000000000000000000000000000000000
SELECT CONVERT(NVARCHAR(16), @pass2)
then after encoding you'll receive text 'MjE4Nqk5'
Static inner class is used in the builder pattern. Static inner class can instantiate it's outer class which has only private constructor. You can not do the same with the inner class as you need to have object of the outer class created prior to accessing the inner class.
class OuterClass {
private OuterClass(int x) {
System.out.println("x: " + x);
}
static class InnerClass {
public static void test() {
OuterClass outer = new OuterClass(1);
}
}
}
public class Test {
public static void main(String[] args) {
OuterClass.InnerClass.test();
// OuterClass outer = new OuterClass(1); // It is not possible to create outer instance from outside.
}
}
This will output x: 1
In ES6, it is also possible to iterate over the values of an object using the for..of
loop. This doesn't work right out of the box for JavaScript objects, however, as you must define an @@iterator property on the object. This works as follows:
for..of
loop asks the "object to be iterated over" (let's call it obj1 for an iterator object. The loop iterates over obj1 by successively calling the next() method on the provided iterator object and using the returned value as the value for each iteration of the loop.Here is an example:
const obj1 = {
a: 5,
b: "hello",
[Symbol.iterator]: function() {
const thisObj = this;
let index = 0;
return {
next() {
let keys = Object.keys(thisObj);
return {
value: thisObj[keys[index++]],
done: (index > keys.length)
};
}
};
}
};
Now we can use the for..of
loop:
for (val of obj1) {
console.log(val);
} // 5 hello
video/mp4
should be used when you have video content in your file. If there is none, but there is audio, you should use audio/mp4
. If no audio and no video is used, for instance if the file contains only a subtitle track or a metadata track, the MIME should be application/mp4
.
Also, as a server, you should try to include the codecs
or profiles
parameters as defined in RFC6381, as this will help clients determine if they can play the file, prior to downloading it.
this is answer for your question.
GridViewRow gvr = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
int RowIndex = gvr.RowIndex;
And to iterate on the files of a directory:
@echo off
setlocal enableDelayedExpansion
set MYDIR=C:\something
for /F %%x in ('dir /B/D %MYDIR%') do (
set FILENAME=%MYDIR%\%%x\log\IL_ERROR.log
echo =========================== Search in !FILENAME! ===========================
c:\utils\grep motiv !FILENAME!
)
You must use "enableDelayedExpansion" and !FILENAME! instead of $FILENAME$. In the second case, DOS will interpret the variable only once (before it enters the loop) and not each time the program loops.
I will show you 2 ways to accomplish what you want:
First way: Decorate your field with JsonProperty attribute in order to skip the serialization of that field if it is null.
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public List<Something> Somethings { get; set; }
}
Second way: If you are negotiation with some complex scenarios then you could use the Web Api convention ("ShouldSerialize") in order to skip serialization of that field depending of some specific logic.
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
public List<Something> Somethings { get; set; }
public bool ShouldSerializeSomethings() {
var resultOfSomeLogic = false;
return resultOfSomeLogic;
}
}
WebApi uses JSON.Net and it use reflection to serialization so when it has detected (for instance) the ShouldSerializeFieldX() method the field with name FieldX will not be serialized.
This is something of a religious debate. Both approaches have their problems.
Bloch has another relevant piece of advice in Effective Java Second Edition:
Keep it simple...
$intArray = array ();
$strArray = explode(',', $string);
foreach ($strArray as $value)
$intArray [] = intval ($value);
Why are you looking for other ways? Looping does the job without pain. If performance is your concern, you can go with json_decode ()
. People have posted how to use that, so I am not including it here.
Note: When using == operator instead of === , your string values are automatically converted into numbers (e.g. integer or double) if they form a valid number without quotes. For example:
$str = '1';
($str == 1) // true but
($str === 1) //false
Thus, == may solve your problem, is efficient, but will break if you use === in comparisons.
I don't think there is any way other then storing the previous state. Here is the solution with jQuery
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
var lastSelected;
$(function () {
//if you have any radio selected by default
lastSelected = $('[name="myRadios"]:checked').val();
});
$(document).on('click', '[name="myRadios"]', function () {
if (lastSelected != $(this).val() && typeof lastSelected != "undefined") {
alert("radio box with value " + $('[name="myRadios"][value="' + lastSelected + '"]').val() + " was deselected");
}
lastSelected = $(this).val();
});
</script>
<input type="radio" name="myRadios" value="1" />
<input type="radio" name="myRadios" value="2" />
<input type="radio" name="myRadios" value="3" />
<input type="radio" name="myRadios" value="4" />
<input type="radio" name="myRadios" value="5" />
After thinking about it a bit more, I decided to get rid of the variable and add/remove class. Here is what I got: http://jsfiddle.net/BeQh3/2/
Updated Answer:
The documentation for SmtpClient
, the class used in this answer, now reads, 'Obsolete("SmtpClient and its network of types are poorly designed, we strongly recommend you use https://github.com/jstedfast/MailKit and https://github.com/jstedfast/MimeKit instead")'.
Source: https://www.infoq.com/news/2017/04/MailKit-MimeKit-Official
Original Answer:
Using the MailDefinition class is the wrong approach. Yes, it's handy, but it's also primitive and depends on web UI controls--that doesn't make sense for something that is typically a server-side task.
The approach presented below is based on MSDN documentation and Qureshi's post on CodeProject.com.
NOTE: This example extracts the HTML file, images, and attachments from embedded resources, but using other alternatives to get streams for these elements are fine, e.g. hard-coded strings, local files, and so on.
Stream htmlStream = null;
Stream imageStream = null;
Stream fileStream = null;
try
{
// Create the message.
var from = new MailAddress(FROM_EMAIL, FROM_NAME);
var to = new MailAddress(TO_EMAIL, TO_NAME);
var msg = new MailMessage(from, to);
msg.Subject = SUBJECT;
msg.SubjectEncoding = Encoding.UTF8;
// Get the HTML from an embedded resource.
var assembly = Assembly.GetExecutingAssembly();
htmlStream = assembly.GetManifestResourceStream(HTML_RESOURCE_PATH);
// Perform replacements on the HTML file (if you're using it as a template).
var reader = new StreamReader(htmlStream);
var body = reader
.ReadToEnd()
.Replace("%TEMPLATE_TOKEN1%", TOKEN1_VALUE)
.Replace("%TEMPLATE_TOKEN2%", TOKEN2_VALUE); // and so on...
// Create an alternate view and add it to the email.
var altView = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
msg.AlternateViews.Add(altView);
// Get the image from an embedded resource. The <img> tag in the HTML is:
// <img src="pid:IMAGE.PNG">
imageStream = assembly.GetManifestResourceStream(IMAGE_RESOURCE_PATH);
var linkedImage = new LinkedResource(imageStream, "image/png");
linkedImage.ContentId = "IMAGE.PNG";
altView.LinkedResources.Add(linkedImage);
// Get the attachment from an embedded resource.
fileStream = assembly.GetManifestResourceStream(FILE_RESOURCE_PATH);
var file = new Attachment(fileStream, MediaTypeNames.Application.Pdf);
file.Name = "FILE.PDF";
msg.Attachments.Add(file);
// Send the email
var client = new SmtpClient(...);
client.Credentials = new NetworkCredential(...);
client.Send(msg);
}
finally
{
if (fileStream != null) fileStream.Dispose();
if (imageStream != null) imageStream.Dispose();
if (htmlStream != null) htmlStream.Dispose();
}
Let consider that your data are in the file values.txt
and that you want to import them in the database table myTable
then the following query does the job
COPY myTable FROM 'value.txt' (DELIMITER('|'));
https://www.postgresql.org/docs/current/static/sql-copy.html
what about this
$string = htmlspecialchars(strip_tags($_POST['example']));
or this
$string = htmlentities($_POST['example'], ENT_QUOTES, 'UTF-8');
LivingRoom.objects.create()
calls LivingRoom.__init__()
- as you might have noticed if you had read the traceback - passing it the same arguments. To make a long story short, a Django models.Model
subclass's initializer is best left alone, or should accept *args and **kwargs matching the model's meta fields. The correct way to provide default values for fields is in the field constructor using the default
keyword as explained in the FineManual.
Month start from 0. 0 = January, 1 = February, 2 = March, ..., 11 = December.
str_replace('"', "", $string);
str_replace("'", "", $string);
I assume you mean quotation marks?
Otherwise, go for some regex, this will work for html quotes for example:
preg_replace("/<!--.*?-->/", "", $string);
C-style quotes:
preg_replace("/\/\/.*?\n/", "\n", $string);
CSS-style quotes:
preg_replace("/\/*.*?\*\//", "", $string);
bash-style quotes:
preg-replace("/#.*?\n/", "\n", $string);
Etc etc...
You can use the method from Bouncy Castle Provider library:
org.bouncycastle.util.encoders.Hex.toHexString(byteArray);
The Bouncy Castle Crypto package is a Java implementation of cryptographic algorithms. This jar contains JCE provider and lightweight API for the Bouncy Castle Cryptography APIs for JDK 1.5 to JDK 1.8.
Maven dependency:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.60</version>
</dependency>
or from Apache Commons Codec:
org.apache.commons.codec.binary.Hex.encodeHexString(byteArray);
The Apache Commons Codec package contains simple encoder and decoders for various formats such as Base64 and Hexadecimal. In addition to these widely used encoders and decoders, the codec package also maintains a collection of phonetic encoding utilities.
Maven dependency:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>
'UserId' is wholly the wrong approach. The Verb (HTTP Methods) and Noun approach is what Roy Fielding meant for The REST architecture. The Nouns are either:
One good naming convention is:
[POST or Create](To the *collection*)
sub.domain.tld/class_name.{media_type}
[GET or Read](of *one* thing)
sub.domain.tld/class_name/id_value.{media_type}
[PUT or Update](of *one* thing)
sub.domain.tld/class_name/id_value.{media_type}
[DELETE](of *one* thing)
sub.domain.tld/class_name/id_value.{media_type}
[GET or Search](of a *collection*, FRIENDLY URL)
sub.domain.tld/class_name.{media_type}/{var}/{value}/{more-var-value-pairs}
[GET or Search](of a *collection*, Normal URL)
sub.domain.tld/class_name.{media_type}?var=value&more-var-value-pairs
Where {media_type} is one of: json, xml, rss, pdf, png, even html.
It is possible to distinguish the collection by adding an 's' at the end, like:
'users.json' *collection of things*
'user/id_value.json' *single thing*
But this means you have to keep track of where you have put the 's' and where you haven't. Plus half the planet (Asians for starters) speaks languages without explicit plurals so the URL is less friendly to them.
This is what I do on mine
$(document).ready(function() {
if ($('#userForm').valid()) {
var formData = $("#userForm").serializeArray();
$.ajax({
url: 'http://www.example.com/user/' + $('#Id').val() + '?callback=?',
type: "GET",
data: formData,
dataType: "jsonp",
jsonpCallback: "localJsonpCallback"
});
});
function localJsonpCallback(json) {
if (!json.Error) {
$('#resultForm').submit();
} else {
$('#loading').hide();
$('#userForm').show();
alert(json.Message);
}
}
I was facing similar problem and to my surprise the problem was in the version of Java. java.sql.DriverManager comes from rt.jar was unable to load my driver "COM.ibm.db2.jdbc.app.DB2Driver".
I upgraded from jdk 5 and jdk 6 and it worked.
Right now there is no view:clear command. For laravel 4 this can probably help you: https://gist.github.com/cjonstrup/8228165
Disabling caching can be done by skipping blade. View caching is done because blade compiling each time is a waste of time.
for example, if you want to close a windows form when an action is performed there are two methods to do it
1.To close it directly
Form1 f=new Form1();
f.close(); //u can use below comment also
//this.close();
2.We can also hide form without closing it
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
Form2 f2 = new Form2();
int flag = 0;
string u, p;
u = textBox1.Text;
p = textBox2.Text;
if(u=="username" && p=="pasword")
{
flag = 1;
}
else
{
MessageBox.Show("enter correct details");
}
if(flag==1)
{
f2.Show();
this.Hide();
}
}
It's because you're missing position:relative;
on #contentframe
<div id="contentframe" style="position:relative; top: 160px; left: 0px;">
position:absolute;
positions itself against the closest ancestor that has a position
that is not static
. Since the default is static
that is what was causing your issue.
Perhaps replace
is what you are looking for:
> x = c(3, 2, 1, 0, 4, 0)
> replace(x, x==0, 1)
[1] 3 2 1 1 4 1
Or, if you don't have x
(any specific reason why not?):
replace(c(3, 2, 1, 0, 4, 0), c(3, 2, 1, 0, 4, 0)==0, 1)
Many people are familiar with gsub
, so you can also try either of the following:
as.numeric(gsub(0, 1, x))
as.numeric(gsub(0, 1, c(3, 2, 1, 0, 4, 0)))
After reading the comments, perhaps with
is an option:
with(data.frame(x = c(3, 2, 1, 0, 4, 0)), replace(x, x == 0, 1))
I had the same problem because I changed the user from myself to someone else:
su
For some reason, after did the normal compiling I was not able to execute it (the same error message). Directly ssh to the other user account works.
~50% faster
Go to the Android SDK root folder and navigate to extras\intel\Hardware_Accelerated_Execution_Manager. Execute file IntelHaxm.exe to install. (in Android Studio you can navigate to: Settings -> Android SDK -> SDK Tools -> Intel x86 Emulator Accelerator (HAXM installer))
Create AVD with "Intel atom x86" CPU/ABI
Also don't forget install this one
P.S. during AVD creation add emulation memory: Hardware/New/Device ram size/set up value 512 or more
P.S. For Fedora, for Ubuntu
P.S: Check this tool, very convenient even trial
#Single line
'''
multi-line
comment
'''
"""
also,
multi-line comment
"""
Yes, you'll need arrays.
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
var day = days[ now.getDay() ];
var month = months[ now.getMonth() ];
Or you can use the date.js library.
EDIT:
If you're going to use these frequently, you may want to extend Date.prototype
for accessibility.
(function() {
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
Date.prototype.getMonthName = function() {
return months[ this.getMonth() ];
};
Date.prototype.getDayName = function() {
return days[ this.getDay() ];
};
})();
var now = new Date();
var day = now.getDayName();
var month = now.getMonthName();
Jacco, your solution ising a custom IComparer isn't safe. The Sort routines require the comparer to conform to several requirements in order to function properly. First among them is consistency. If the comparer is called on the same pair of objects, it must always return the same result. (the comparison must also be transitive).
Failure to meet these requirements can cause any number of problems in the sorting routine including the possibility of an infinite loop.
Regarding the solutions that associate a random numeric value with each entry and then sort by that value, these are lead to an inherent bias in the output because any time two entries are assigned the same numeric value, the randomness of the output will be compromised. (In a "stable" sort routine, whichever is first in the input will be first in the output. Array.Sort doesn't happen to be stable, but there is still a bias based on the partitioning done by the Quicksort algorithm).
You need to do some thinking about what level of randomness you require. If you are running a poker site where you need cryptographic levels of randomness to protect against a determined attacker you have very different requirements from someone who just wants to randomize a song playlist.
For song-list shuffling, there's no problem using a seeded PRNG (like System.Random). For a poker site, it's not even an option and you need to think about the problem a lot harder than anyone is going to do for you on stackoverflow. (using a cryptographic RNG is only the beginning, you need to ensure that your algorithm doesn't introduce a bias, that you have sufficient sources of entropy, and that you don't expose any internal state that would compromise subsequent randomness).
elec_and_weather['DEMAND_t-%i'% k] = np.zeros(len(elec_and_weather['DEMAND']))'
The error comes at the end of the line where you have the (') sign; this error always means that you have a syntax error.
Your code can be fixed as follows:
import numpy as np, cv
vis = np.zeros((384, 836), np.float32)
h,w = vis.shape
vis2 = cv.CreateMat(h, w, cv.CV_32FC3)
vis0 = cv.fromarray(vis)
cv.CvtColor(vis0, vis2, cv.CV_GRAY2BGR)
Short explanation:
np.uint32
data type is not supported by OpenCV (it supports uint8
, int8
, uint16
, int16
, int32
, float32
, float64
)cv.CvtColor
can't handle numpy arrays so both arguments has to be converted to OpenCV type. cv.fromarray
do this conversion.cv.CvtColor
must have the same depth. So I've changed source type to 32bit float to match the ddestination.Also I recommend you use newer version of OpenCV python API because it uses numpy arrays as primary data type:
import numpy as np, cv2
vis = np.zeros((384, 836), np.float32)
vis2 = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR)
Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.
In the code. I have used VBScript and embedded it in HTML. Try it out!
<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--
Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset
Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString
dim form1
Set form1 = document.Register
Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value
connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")
End Sub
//-->
</script>
</head>
<body>
<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name: <input type="text" name="Name">
Age: <input type="text" name="Age">
Address: <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form>
</p>
</pre>
</body>
</html>
This can happen if you call
.SingleOrDefault()
on an IEnumerable with 2 or more elements.
The content of the Manifest file in a JAR file created with version 1.0 of the Java Development Kit is the following.
Manifest-Version: 1.0
All the entries are as name-value pairs. The name of a header is separated from its value by a colon. The default manifest shows that it conforms to version 1.0 of the manifest specification. The manifest can also contain information about the other files that are packaged in the archive. Exactly what file information is recorded in the manifest will depend on the intended use for the JAR file. The default manifest file makes no assumptions about what information it should record about other files, so its single line contains data only about itself. Special-Purpose Manifest Headers
Depending on the intended role of the JAR file, the default manifest may have to be modified. If the JAR file is created only for the purpose of archival, then the MANIFEST.MF file is of no purpose. Most uses of JAR files go beyond simple archiving and compression and require special information to be in the manifest file. Summarized below are brief descriptions of the headers that are required for some special-purpose JAR-file functions
Applications Bundled as JAR Files: If an application is bundled in a JAR file, the Java Virtual Machine needs to be told what the entry point to the application is. An entry point is any class with a public static void main(String[] args) method. This information is provided in the Main-Class header, which has the general form:
Main-Class: classname
The value classname is to be replaced with the application's entry point.
Download Extensions: Download extensions are JAR files that are referenced by the manifest files of other JAR files. In a typical situation, an applet will be bundled in a JAR file whose manifest references a JAR file (or several JAR files) that will serve as an extension for the purposes of that applet. Extensions may reference each other in the same way. Download extensions are specified in the Class-Path header field in the manifest file of an applet, application, or another extension. A Class-Path header might look like this, for example:
Class-Path: servlet.jar infobus.jar acme/beans.jar
With this header, the classes in the files servlet.jar, infobus.jar, and acme/beans.jar will serve as extensions for purposes of the applet or application. The URLs in the Class-Path header are given relative to the URL of the JAR file of the applet or application.
Package Sealing: A package within a JAR file can be optionally sealed, which means that all classes defined in that package must be archived in the same JAR file. A package might be sealed to ensure version consistency among the classes in your software or as a security measure. To seal a package, a Name header needs to be added for the package, followed by a Sealed header, similar to this:
Name: myCompany/myPackage/
Sealed: true
The Name header's value is the package's relative pathname. Note that it ends with a '/' to distinguish it from a filename. Any headers following a Name header, without any intervening blank lines, apply to the file or package specified in the Name header. In the above example, because the Sealed header occurs after the Name: myCompany/myPackage header, with no blank lines between, the Sealed header will be interpreted as applying (only) to the package myCompany/myPackage.
Package Versioning: The Package Versioning specification defines several manifest headers to hold versioning information. One set of such headers can be assigned to each package. The versioning headers should appear directly beneath the Name header for the package. This example shows all the versioning headers:
Name: java/util/
Specification-Title: "Java Utility Classes"
Specification-Version: "1.2"
Specification-Vendor: "Sun Microsystems, Inc.".
Implementation-Title: "java.util"
Implementation-Version: "build57"
Implementation-Vendor: "Sun Microsystems, Inc."
you can use ref
to call the function of the child component from the parent
in functional component, you have to use useImperativeHandle
for getting ref into a child like below
import React, { forwardRef, useRef, useImperativeHandle } from 'react';
export default function ParentFunction() {
const childRef = useRef();
return (
<div className="container">
<div>
Parent Component
</div>
<button
onClick={() => { childRef.current.showAlert() }}
>
Call Function
</button>
<Child ref={childRef}/>
</div>
)
}
const Child = forwardRef((props, ref) => {
useImperativeHandle(
ref,
() => ({
showAlert() {
alert("Child Function Called")
}
}),
)
return (
<div>Child Component</div>
)
})
Child.js
import s from './Child.css';
class Child extends Component {
getAlert() {
alert('clicked');
}
render() {
return (
<h1>Hello</h1>
);
}
}
export default Child;
Parent.js
class Parent extends Component {
render() {
onClick() {
this.refs.child.getAlert();
}
return (
<div>
<Child ref="child" />
<button onClick={this.onClick}>Click</button>
</div>
);
}
}
I had the same requirement and I have done this in following way.You also can try out this..
Use loadData method
web.loadData("<p style='text-align:center'><img class='aligncenter size-full wp-image-1607' title='' src="+movImage+" alt='' width='240px' height='180px' /></p><p><center><U><H2>"+movName+"("+movYear+")</H2></U></center></p><p><strong>Director : </strong>"+movDirector+"</p><p><strong>Producer : </strong>"+movProducer+"</p><p><strong>Character : </strong>"+movActedAs+"</p><p><strong>Summary : </strong>"+movAnecdotes+"</p><p><strong>Synopsis : </strong>"+movSynopsis+"</p>\n","text/html", "UTF-8");
movDirector movProducer like all are my string variable.
In short i retain custom styling for my url.
here is more simple way without StartCoroutine:
float t = 0f;
float waittime = 1f;
and inside Update/FixedUpdate:
if (t < 0){
t += Time.deltaTIme / waittime;
yield return t;
}
Try this
div_x000D_
{_x000D_
width:100px;_x000D_
height:100px;_x000D_
background:red;_x000D_
transition: all 1s ease-in-out;_x000D_
-webkit-transition: all 1s ease-in-out;_x000D_
-moz-transition: all 1s ease-in-out;_x000D_
-o-transition: all 1s ease-in-out;_x000D_
-ms-transition: all 1s ease-in-out;_x000D_
position:absolute;_x000D_
}_x000D_
div:hover_x000D_
{_x000D_
transform: translate(3em,0);_x000D_
-webkit-transform: translate(3em,0);_x000D_
-moz-transform: translate(3em,0);_x000D_
-o-transform: translate(3em,0);_x000D_
-ms-transform: translate(3em,0);_x000D_
}
_x000D_
<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>_x000D_
<div></div>_x000D_
<p>Hover over the div element above, to see the transition effect.</p>
_x000D_
Typescript from v1.4 has the type
keyword which declares a type alias (analogous to a typedef
in C/C++). You can declare your callback type thus:
type CallbackFunction = () => void;
which declares a function that takes no arguments and returns nothing. A function that takes zero or more arguments of any type and returns nothing would be:
type CallbackFunctionVariadic = (...args: any[]) => void;
Then you can say, for example,
let callback: CallbackFunctionVariadic = function(...args: any[]) {
// do some stuff
};
If you want a function that takes an arbitrary number of arguments and returns anything (including void):
type CallbackFunctionVariadicAnyReturn = (...args: any[]) => any;
You can specify some mandatory arguments and then a set of additional arguments (say a string, a number and then a set of extra args) thus:
type CallbackFunctionSomeVariadic =
(arg1: string, arg2: number, ...args: any[]) => void;
This can be useful for things like EventEmitter handlers.
Functions can be typed as strongly as you like in this fashion, although you can get carried away and run into combinatoric problems if you try to nail everything down with a type alias.
Web application context, specified by the WebApplicationContext
interface, is a Spring application context for a web applications. It has all the properties of a regular Spring application context, given that the WebApplicationContext
interface extends the ApplicationContext
interface, and add a method for retrieving the standard Servlet API ServletContext
for the web application.
In addition to the standard Spring bean scopes singleton
and prototype
, there are three additional scopes available in a web application context:
request
- scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definitionsession
- scopes a single bean definition to the lifecycle of an HTTP Sessionapplication
- scopes a single bean definition to the lifecycle of a ServletContext
You can also, do this.
$(window).on("scroll", function () {
if ($(this).scrollTop() > 800) {
#code here
} else {
#code here
}
});
You should wrap your elements inside a container, then use new CSS3 features like css grid, free course, and then use grid-gap:value
that was created for your specific problem
span{_x000D_
border:1px solid red;_x000D_
}_x000D_
.inRow{_x000D_
display:grid;_x000D_
grid-template-columns:repeat(auto-fill,auto);_x000D_
grid-gap:10px /*This add space between elements, only works on grid items*/_x000D_
}_x000D_
.inColumn{_x000D_
display:grid;_x000D_
grid-template-rows:repeat(auto-fill,auto);_x000D_
grid-gap:15px;_x000D_
}
_x000D_
<div class="inrow">_x000D_
<span>1</span>_x000D_
<span>2</span>_x000D_
<span>3</span>_x000D_
</div>_x000D_
<div class="inColumn">_x000D_
<span>4</span>_x000D_
<span>5</span>_x000D_
<span>6</span>_x000D_
</div>
_x000D_
i'm not sure what you're expecting this
to refer to in your example.. here's an alternative method:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$.get("banner.html", function (data) {
$("#appendToThis").append(data);
});
});
</script>
</head>
<body>
<div id="appendToThis"></div>
</body>
</html>
I would add some points that helped me to solve this problem :
Having the local repository OK, on the other hand, turned out to be quite costly, as many archetypes would not get loaded, due apparently to timeouts of m2eclipse and very unstable communication speeds in my case.
In many cases only the error file could be found in the folder ex : xxx.jar.lastUpdated
, instead of the jar or pom file. I had always to suppress this file to permit a new download.
Also really worthy were :
as already said, using the mvn clean install from the command line, apparently much more patient than m2eclipse, and also efficient and verbose, at least for the time being.
(and also the Update Project of the Maven menu)
downloading using the dependency:get goal
mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get -DrepoUrl=url -Dartifact=groupId:artifactId:version1
(from within the project folder) (hint given in another thread, thanks also).
also downloading and installing manually (.jar+.sha1), from in particular, "m2proxy atlassian" .
adding other repositories in the pom.xml itself (the settings.xml mirror configuration did'nt do the job, I don't know yet why). Ex : nexus/content/repositories/releases/ et nexus/content/repositories/releases/, sous repository.jboss.org, ou download.java.net/maven/2 .
To finish, in any case, a lot of time (!..) could have been et could certainly still be spared with a light tool repairing thoroughly the local repository straightaway. I could not yet find it. Actually it should even be normally a mvn command ("--repair-local-repository").
Method 01:
$.browser was deprecated in jQuery version 1.3 and removed in 1.9
if ( $.browser.msie) {
alert( "Hello! This is IE." );
}
Method 02:
Using Conditional Comments
<!--[if gte IE 8]>
<p>You're using a recent version of Internet Explorer.</p>
<![endif]-->
<!--[if lt IE 7]>
<p>Hm. You should upgrade your copy of Internet Explorer.</p>
<![endif]-->
<![if !IE]>
<p>You're not using Internet Explorer.</p>
<![endif]>
Method 03:
/**
* Returns the version of Internet Explorer or a -1
* (indicating the use of another browser).
*/
function getInternetExplorerVersion()
{
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
function checkVersion()
{
var msg = "You're not using Internet Explorer.";
var ver = getInternetExplorerVersion();
if ( ver > -1 )
{
if ( ver >= 8.0 )
msg = "You're using a recent copy of Internet Explorer."
else
msg = "You should upgrade your copy of Internet Explorer.";
}
alert( msg );
}
Method 04:
Use JavaScript/Manual Detection
/*
Internet Explorer sniffer code to add class to body tag for IE version.
Can be removed if your using something like Modernizr.
*/
var ie = (function ()
{
var undef,
v = 3,
div = document.createElement('div'),
all = div.getElementsByTagName('i');
while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i>< ![endif]-->',
all[0]);
//append class to body for use with browser support
if (v > 4)
{
$('body').addClass('ie' + v);
}
}());
I have been working on this problem for two days and have a solution that may work for you and anyone else trying to make a responsive Fixed width left and have the right side fill in the remainder of the screen without wrapping around the left side. The intention I assume is to make the page responsive in browsers as well as mobile devices.
Here is the Code
// Fix the width of the right side to cover the screen when resized_x000D_
$thePageRefreshed = true;_x000D_
// The delay time below is needed to insure that the resize happens after the window resize event fires_x000D_
// In addition the show() helps. Without this delay the right div may go off screen when browser is refreshed _x000D_
setTimeout(function(){_x000D_
fixRightSideWidth();_x000D_
$('.right_content_container').show(600);_x000D_
}, 50);_x000D_
_x000D_
// Capture the window resize event (only fires when you resize the browser)._x000D_
$( window ).resize(function() {_x000D_
fixRightSideWidth();_x000D_
});_x000D_
_x000D_
function fixRightSideWidth(){_x000D_
$blockWrap = 300; // Point at which you allow the right div to drop below the top div_x000D_
$normalRightResize = $( window ).width() - $('.left_navigator_items').width() - 20; // The -20 forces the right block to fall below the left_x000D_
if( ($normalRightResize >= $blockWrap) || $thePageRefreshed == true ){_x000D_
$('.right_content_container').width( $normalRightResize );_x000D_
$('.right_content_container').css("padding-left","0px");_x000D_
_x000D_
/* Begin test lines these can be deleted */_x000D_
$rightrightPosition = $('.right_content_container').css("right");_x000D_
$rightleftPosition = $('.right_content_container').css("left");_x000D_
$rightwidthPosition = $('.right_content_container').css("width");_x000D_
$(".top_title").html('window width: '+$( window ).width()+" "+'width: '+$rightwidthPosition+" "+'right: '+$rightrightPosition);_x000D_
/* End test lines these can be deleted */_x000D_
_x000D_
_x000D_
}_x000D_
else{_x000D_
if( $('.right_content_container').width() > 300 ){_x000D_
$('.right_content_container').width(300);_x000D_
}_x000D_
_x000D_
/* Begin test lines these can be deleted */_x000D_
$rightrightPosition = $('.right_content_container').css("right");_x000D_
$rightleftPosition = $('.right_content_container').css("left");_x000D_
$rightwidthPosition = $('.right_content_container').css("width");_x000D_
$(".top_title").html('window width: '+$( window ).width()+" "+'width: '+$rightwidthPosition+" "+'right: '+$rightrightPosition);_x000D_
/* End test lines these can be deleted */_x000D_
_x000D_
}_x000D_
if( $thePageRefreshed == true ){_x000D_
$thePageRefreshed = false;_x000D_
}_x000D_
}
_x000D_
/* NOTE: The html and body settings are needed for full functionality_x000D_
and they are ignored by jsfiddle so create this exapmle on your web site_x000D_
*/_x000D_
html {_x000D_
min-width: 310px;_x000D_
background: #333;_x000D_
min-height:100vh;_x000D_
}_x000D_
_x000D_
body{_x000D_
background: #333;_x000D_
background-color: #333;_x000D_
color: white;_x000D_
min-height:100vh;_x000D_
}_x000D_
_x000D_
.top_title{_x000D_
background-color: blue;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.bottom_content{_x000D_
border: 0px;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.left_right_container * {_x000D_
position: relative;_x000D_
margin: 0px;_x000D_
padding: 0px;_x000D_
background: #333 !important;_x000D_
background-color: #333 !important;_x000D_
display:inline-block;_x000D_
text-shadow: none;_x000D_
text-transform: none;_x000D_
letter-spacing: normal;_x000D_
font-size: 14px;_x000D_
font-weight: 400;_x000D_
font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",sans-serif;_x000D_
border-radius: 0;_x000D_
box-sizing: content-box;_x000D_
transition: none;_x000D_
}_x000D_
_x000D_
.left_navigator_item{_x000D_
display:inline-block;_x000D_
margin-right: 5px;_x000D_
margin-bottom: 0px !important;_x000D_
width: 100%;_x000D_
min-height: 20px !important;_x000D_
text-align:center !important;_x000D_
margin: 0px;_x000D_
padding-top: 3px;_x000D_
padding-bottom: 3px;_x000D_
vertical-align: top;_x000D_
}_x000D_
_x000D_
.left_navigator_items {_x000D_
float: left;_x000D_
width: 150px;_x000D_
}_x000D_
_x000D_
.right_content_container{_x000D_
float: right;_x000D_
overflow: visible!important;_x000D_
width:95%; /* width don't matter jqoery overwrites on refresh */_x000D_
display:none;_x000D_
right:0px;_x000D_
}_x000D_
_x000D_
.span_text{_x000D_
background: #eee !important;_x000D_
background-color: #eee !important;_x000D_
color: black !important;_x000D_
padding: 5px;_x000D_
margin: 0px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
<div class="top_title">Test Title</div>_x000D_
<div class="bottom_content">_x000D_
<div class="left_right_container">_x000D_
<div class="left_navigator_items">_x000D_
<div class="left_navigator_item">Dashboard</div>_x000D_
<div class="left_navigator_item">Calendar</div>_x000D_
<div class="left_navigator_item">Calendar Validator</div>_x000D_
<div class="left_navigator_item">Bulletin Board Slide Editor</div>_x000D_
<div class="left_navigator_item">Bulletin Board Slide Show (Live)</div>_x000D_
<div class="left_navigator_item">TV Guide</div>_x000D_
</div>_x000D_
<div class="right_content_container">_x000D_
<div class="span_text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ullamcorper maximus tellus a commodo. Fusce posuere at nisi in venenatis. Sed posuere dui sapien, sit amet facilisis purus maximus sit amet. Proin luctus lectus nec rutrum accumsan. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Ut fermentum lectus consectetur sapien tempus molestie. Donec bibendum pulvinar purus, ac aliquet est commodo sit amet. Duis vel euismod mauris, eu congue ex. In vel arcu vel sem lobortis posuere. Cras in nisi nec urna blandit porta at et nunc. Morbi laoreet consectetur odio ultricies ullamcorper. Suspendisse potenti. Nulla facilisi._x000D_
_x000D_
Quisque cursus lobortis molestie. Aliquam ut scelerisque leo. Integer sed sodales lectus, eget varius odio. Nullam nec dapibus lorem. Aenean a mattis velit, ut porta nunc. Phasellus aliquam volutpat molestie. Aliquam tristique purus neque, vitae interdum ante aliquam ut._x000D_
_x000D_
Pellentesque quis finibus velit. Fusce ac pulvinar est, in placerat sem. Suspendisse nec nunc id nunc vestibulum hendrerit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Mauris id lectus dapibus, tempor nunc non, bibendum nisl. Proin euismod, erat nec aliquet mollis, erat metus convallis nulla, eu tincidunt eros erat a lectus. Vivamus sed mattis neque. In vitae pellentesque mauris. Ut aliquet auctor vulputate. Duis eleifend tincidunt gravida. Sed tincidunt blandit tempor._x000D_
_x000D_
Duis pharetra, elit id aliquam placerat, nunc arcu interdum neque, ac luctus odio felis vitae magna. Curabitur commodo finibus suscipit. Maecenas ut risus eget nisl vehicula feugiat. Sed sed bibendum justo. Curabitur in laoreet dolor. Suspendisse eget ligula ac neque ullamcorper blandit. Phasellus sit amet ultricies tellus._x000D_
_x000D_
In fringilla, augue sed fringilla accumsan, orci eros laoreet urna, vel aliquam ex nulla in eros. Quisque aliquet nisl et scelerisque vehicula. Curabitur facilisis, nisi non maximus facilisis, augue erat gravida nunc, in tempus massa diam id dolor. Suspendisse dapibus leo vel pretium ultrices. Sed finibus dolor est, sit amet pharetra quam dapibus fermentum. Ut nec risus pharetra, convallis nisl nec, tempor nisl. Vivamus sit amet quam quis dolor dapibus maximus. Suspendisse accumsan sagittis ligula, ut ultricies nisi feugiat pretium. Cras aliquam velit eu venenatis accumsan. Integer imperdiet, eros sit amet dignissim volutpat, tortor enim varius turpis, vel viverra ante mauris at felis. Mauris sed accumsan sapien. Interdum et malesuada fames ac ante ipsum primis in faucibus. Ut vel magna commodo, facilisis turpis eu, semper mi. Nulla massa risus, bibendum a magna molestie, gravida maximus nunc.</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Here is my fiddle that may just work for you as it did for me. https://jsfiddle.net/Larry_Robertson/62LLjapm/
Remove the below code it will work
super.onReceivedSslError(view, handler, error);
Are you looking for something like this?
COLUMN_NAMES=['A','B','C','D','E','F','G']
df = pd.DataFrame(columns=COLUMN_NAMES)
df.columns
Index(['A', 'B', 'C', 'D', 'E', 'F', 'G'], dtype='object')
PROJECT eliminates columns while SELECT eliminates rows.
this works fine for me
DataTable DT = new DataTable();
DT = DT.AsEnumerable().Select(R =>
{
R["Campo1"] = valor;
return (R);
}).ToArray().CopyToDataTable();
Call list()
on the dictionary instead:
keys = list(test)
In Python 3, the dict.keys()
method returns a dictionary view object, which acts as a set. Iterating over the dictionary directly also yields keys, so turning a dictionary into a list results in a list of all the keys:
>>> test = {'foo': 'bar', 'hello': 'world'}
>>> list(test)
['foo', 'hello']
>>> list(test)[0]
'foo'
If ds is the DataSet, you can access the CustomerID column of the first row in the first table with something like:
DataRow dr = ds.Tables[0].Rows[0];
Console.WriteLine(dr["CustomerID"]);
First: your code did not work because you were using the positional operator $
which only identifies an element to update in an array but does not even explicitly specify its position in the array.
What you need is the filtered positional operator $[<identifier>]
. It would update all elements that match an array filter condition.
Solution:
db.collection.update({"events.profile":10}, { $set: { "events.$[elem].handled" : 0 } },
{
multi: true,
arrayFilters: [ { "elem.profile": 10 } ]
})
What the code does:
{"events.profile":10}
filters your collection and return the documents matching the filter
The $set
update operator: modifies matching fields of documents it acts on.
{multi:true}
It makes .update()
modifies all documents matching the filter hence behaving like updateMany()
{ "events.$[elem].handled" : 0 } and arrayFilters: [ { "elem.profile": 10 } ]
This technique involves the use of the filtered positional array with arrayFilters. the filtered positional array here $[elem]
acts as a placeholder for all elements in the array fields that match the conditions specified in the array filter.
I needed to print important warning about skipped tests exactly when PyTest
muted literally everything.
I didn't want to fail a test to send a signal, so I did a hack as follow:
def test_2_YellAboutBrokenAndMutedTests():
import atexit
def report():
print C_patch.tidy_text("""
In silent mode PyTest breaks low level stream structure I work with, so
I cannot test if my functionality work fine. I skipped corresponding tests.
Run `py.test -s` to make sure everything is tested.""")
if sys.stdout != sys.__stdout__:
atexit.register(report)
The atexit
module allows me to print stuff after PyTest
released the output streams. The output looks as follow:
============================= test session starts ==============================
platform linux2 -- Python 2.7.3, pytest-2.9.2, py-1.4.31, pluggy-0.3.1
rootdir: /media/Storage/henaro/smyth/Alchemist2-git/sources/C_patch, inifile:
collected 15 items
test_C_patch.py .....ssss....s.
===================== 10 passed, 5 skipped in 0.15 seconds =====================
In silent mode PyTest breaks low level stream structure I work with, so
I cannot test if my functionality work fine. I skipped corresponding tests.
Run `py.test -s` to make sure everything is tested.
~/.../sources/C_patch$
Message is printed even when PyTest
is in silent mode, and is not printed if you run stuff with py.test -s
, so everything is tested nicely already.
As of September 2016 this addon is the best to disable CORS: https://github.com/fredericlb/Force-CORS/releases
In the options panel you can configure which header to inject and specific website to have it enabled automatically.
Sometimes in order to write less code it is used to have SQL server set fields like date, time and ID on insert by setting the default value for fields to GETDATE()
or NEWID()
.
In such cases Auto Generated Value property of those fields in entity classes should be set to true.
This way you do not need to set values in code (preventing energy consumption!!!) and never see that exception.
On Amazon ec2 with Ubuntu + nginx + php7, I had the same issues, solved it using:
sudo apt-get install php7.0-zip
A container's logs can be found in :
/var/lib/docker/containers/<container id>/<container id>-json.log
(if you use the default log format which is json)
This is rather a method than just a single script but gives you much more flexibility.
First of all There are 3 objects:
ColumnActionList
] -> holds data as
parameter proc_PivotPrepare
] -> prepares our dataproc_PivotExecute
] -> execute the scriptCREATE TYPE [dbo].[ColumnActionList] AS TABLE ( [ID] [smallint] NOT NULL, [ColumnName] nvarchar NOT NULL, [Action] nchar NOT NULL ); GO
CREATE PROCEDURE [dbo].[proc_PivotPrepare]
(
@DB_Name nvarchar(128),
@TableName nvarchar(128)
)
AS
SELECT @DB_Name = ISNULL(@DB_Name,db_name())
DECLARE @SQL_Code nvarchar(max)
DECLARE @MyTab TABLE (ID smallint identity(1,1), [Column_Name] nvarchar(128), [Type] nchar(1), [Set Action SQL] nvarchar(max));
SELECT @SQL_Code = 'SELECT [<| SQL_Code |>] = '' '' '
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''-----| Declare user defined type [ID] / [ColumnName] / [PivotAction] '' '
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''DECLARE @ColumnListWithActions ColumnActionList;'''
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''-----| Set [PivotAction] (''''S'''' as default) to select dimentions and values '' '
+ 'UNION ALL '
+ 'SELECT ''-----|'''
+ 'UNION ALL '
+ 'SELECT ''-----| ''''S'''' = Stable column || ''''D'''' = Dimention column || ''''V'''' = Value column '' '
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''INSERT INTO @ColumnListWithActions VALUES ('' + CAST( ROW_NUMBER() OVER (ORDER BY [NAME]) as nvarchar(10)) + '', '' + '''''''' + [NAME] + ''''''''+ '', ''''S'''');'''
+ 'FROM [' + @DB_Name + '].sys.columns '
+ 'WHERE object_id = object_id(''[' + @DB_Name + ']..[' + @TableName + ']'') '
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''-----| Execute sp_PivotExecute with parameters: columns and dimentions and main table name'' '
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''EXEC [dbo].[sp_PivotExecute] @ColumnListWithActions, ' + '''''' + @TableName + '''''' + ';'''
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
EXECUTE SP_EXECUTESQL @SQL_Code;
GO
CREATE PROCEDURE [dbo].[sp_PivotExecute]
(
@ColumnListWithActions ColumnActionList ReadOnly
,@TableName nvarchar(128)
)
AS
--#######################################################################################################################
--###| Step 1 - Select our user-defined-table-variable into temp table
--#######################################################################################################################
IF OBJECT_ID('tempdb.dbo.#ColumnListWithActions', 'U') IS NOT NULL DROP TABLE #ColumnListWithActions;
SELECT * INTO #ColumnListWithActions FROM @ColumnListWithActions;
--#######################################################################################################################
--###| Step 2 - Preparing lists of column groups as strings:
--#######################################################################################################################
DECLARE @ColumnName nvarchar(128)
DECLARE @Destiny nchar(1)
DECLARE @ListOfColumns_Stable nvarchar(max)
DECLARE @ListOfColumns_Dimension nvarchar(max)
DECLARE @ListOfColumns_Variable nvarchar(max)
--############################
--###| Cursor for List of Stable Columns
--############################
DECLARE ColumnListStringCreator_S CURSOR FOR
SELECT [ColumnName]
FROM #ColumnListWithActions
WHERE [Action] = 'S'
OPEN ColumnListStringCreator_S;
FETCH NEXT FROM ColumnListStringCreator_S
INTO @ColumnName
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @ListOfColumns_Stable = ISNULL(@ListOfColumns_Stable, '') + ' [' + @ColumnName + '] ,';
FETCH NEXT FROM ColumnListStringCreator_S INTO @ColumnName
END
CLOSE ColumnListStringCreator_S;
DEALLOCATE ColumnListStringCreator_S;
--############################
--###| Cursor for List of Dimension Columns
--############################
DECLARE ColumnListStringCreator_D CURSOR FOR
SELECT [ColumnName]
FROM #ColumnListWithActions
WHERE [Action] = 'D'
OPEN ColumnListStringCreator_D;
FETCH NEXT FROM ColumnListStringCreator_D
INTO @ColumnName
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @ListOfColumns_Dimension = ISNULL(@ListOfColumns_Dimension, '') + ' [' + @ColumnName + '] ,';
FETCH NEXT FROM ColumnListStringCreator_D INTO @ColumnName
END
CLOSE ColumnListStringCreator_D;
DEALLOCATE ColumnListStringCreator_D;
--############################
--###| Cursor for List of Variable Columns
--############################
DECLARE ColumnListStringCreator_V CURSOR FOR
SELECT [ColumnName]
FROM #ColumnListWithActions
WHERE [Action] = 'V'
OPEN ColumnListStringCreator_V;
FETCH NEXT FROM ColumnListStringCreator_V
INTO @ColumnName
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @ListOfColumns_Variable = ISNULL(@ListOfColumns_Variable, '') + ' [' + @ColumnName + '] ,';
FETCH NEXT FROM ColumnListStringCreator_V INTO @ColumnName
END
CLOSE ColumnListStringCreator_V;
DEALLOCATE ColumnListStringCreator_V;
SELECT @ListOfColumns_Variable = LEFT(@ListOfColumns_Variable, LEN(@ListOfColumns_Variable) - 1);
SELECT @ListOfColumns_Dimension = LEFT(@ListOfColumns_Dimension, LEN(@ListOfColumns_Dimension) - 1);
SELECT @ListOfColumns_Stable = LEFT(@ListOfColumns_Stable, LEN(@ListOfColumns_Stable) - 1);
--#######################################################################################################################
--###| Step 3 - Preparing table with all possible connections between Dimension columns excluding NULLs
--#######################################################################################################################
DECLARE @DIM_TAB TABLE ([DIM_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @DIM_TAB
SELECT [DIM_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName] FROM #ColumnListWithActions WHERE [Action] = 'D';
DECLARE @DIM_ID smallint;
SELECT @DIM_ID = 1;
DECLARE @SQL_Dimentions nvarchar(max);
IF OBJECT_ID('tempdb.dbo.##ALL_Dimentions', 'U') IS NOT NULL DROP TABLE ##ALL_Dimentions;
SELECT @SQL_Dimentions = 'SELECT [xxx_ID_xxx] = ROW_NUMBER() OVER (ORDER BY ' + @ListOfColumns_Dimension + '), ' + @ListOfColumns_Dimension
+ ' INTO ##ALL_Dimentions '
+ ' FROM (SELECT DISTINCT' + @ListOfColumns_Dimension + ' FROM ' + @TableName
+ ' WHERE ' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @DIM_ID) + ' IS NOT NULL ';
SELECT @DIM_ID = @DIM_ID + 1;
WHILE @DIM_ID <= (SELECT MAX([DIM_ID]) FROM @DIM_TAB)
BEGIN
SELECT @SQL_Dimentions = @SQL_Dimentions + 'AND ' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @DIM_ID) + ' IS NOT NULL ';
SELECT @DIM_ID = @DIM_ID + 1;
END
SELECT @SQL_Dimentions = @SQL_Dimentions + ' )x';
EXECUTE SP_EXECUTESQL @SQL_Dimentions;
--#######################################################################################################################
--###| Step 4 - Preparing table with all possible connections between Stable columns excluding NULLs
--#######################################################################################################################
DECLARE @StabPos_TAB TABLE ([StabPos_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @StabPos_TAB
SELECT [StabPos_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName] FROM #ColumnListWithActions WHERE [Action] = 'S';
DECLARE @StabPos_ID smallint;
SELECT @StabPos_ID = 1;
DECLARE @SQL_MainStableColumnTable nvarchar(max);
IF OBJECT_ID('tempdb.dbo.##ALL_StableColumns', 'U') IS NOT NULL DROP TABLE ##ALL_StableColumns;
SELECT @SQL_MainStableColumnTable = 'SELECT xxx_ID_xxx = ROW_NUMBER() OVER (ORDER BY ' + @ListOfColumns_Stable + '), ' + @ListOfColumns_Stable
+ ' INTO ##ALL_StableColumns '
+ ' FROM (SELECT DISTINCT' + @ListOfColumns_Stable + ' FROM ' + @TableName
+ ' WHERE ' + (SELECT [ColumnName] FROM @StabPos_TAB WHERE [StabPos_ID] = @StabPos_ID) + ' IS NOT NULL ';
SELECT @StabPos_ID = @StabPos_ID + 1;
WHILE @StabPos_ID <= (SELECT MAX([StabPos_ID]) FROM @StabPos_TAB)
BEGIN
SELECT @SQL_MainStableColumnTable = @SQL_MainStableColumnTable + 'AND ' + (SELECT [ColumnName] FROM @StabPos_TAB WHERE [StabPos_ID] = @StabPos_ID) + ' IS NOT NULL ';
SELECT @StabPos_ID = @StabPos_ID + 1;
END
SELECT @SQL_MainStableColumnTable = @SQL_MainStableColumnTable + ' )x';
EXECUTE SP_EXECUTESQL @SQL_MainStableColumnTable;
--#######################################################################################################################
--###| Step 5 - Preparing table with all options ID
--#######################################################################################################################
DECLARE @FULL_SQL_1 NVARCHAR(MAX)
SELECT @FULL_SQL_1 = ''
DECLARE @i smallint
IF OBJECT_ID('tempdb.dbo.##FinalTab', 'U') IS NOT NULL DROP TABLE ##FinalTab;
SELECT @FULL_SQL_1 = 'SELECT t.*, dim.[xxx_ID_xxx] '
+ ' INTO ##FinalTab '
+ 'FROM ' + @TableName + ' t '
+ 'JOIN ##ALL_Dimentions dim '
+ 'ON t.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = 1) + ' = dim.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = 1);
SELECT @i = 2
WHILE @i <= (SELECT MAX([DIM_ID]) FROM @DIM_TAB)
BEGIN
SELECT @FULL_SQL_1 = @FULL_SQL_1 + ' AND t.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @i) + ' = dim.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @i)
SELECT @i = @i +1
END
EXECUTE SP_EXECUTESQL @FULL_SQL_1
--#######################################################################################################################
--###| Step 6 - Selecting final data
--#######################################################################################################################
DECLARE @STAB_TAB TABLE ([STAB_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @STAB_TAB
SELECT [STAB_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName]
FROM #ColumnListWithActions WHERE [Action] = 'S';
DECLARE @VAR_TAB TABLE ([VAR_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @VAR_TAB
SELECT [VAR_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName]
FROM #ColumnListWithActions WHERE [Action] = 'V';
DECLARE @y smallint;
DECLARE @x smallint;
DECLARE @z smallint;
DECLARE @FinalCode nvarchar(max)
SELECT @FinalCode = ' SELECT ID1.*'
SELECT @y = 1
WHILE @y <= (SELECT MAX([xxx_ID_xxx]) FROM ##FinalTab)
BEGIN
SELECT @z = 1
WHILE @z <= (SELECT MAX([VAR_ID]) FROM @VAR_TAB)
BEGIN
SELECT @FinalCode = @FinalCode + ', [ID' + CAST((@y) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @VAR_TAB WHERE [VAR_ID] = @z) + '] = ID' + CAST((@y + 1) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @VAR_TAB WHERE [VAR_ID] = @z)
SELECT @z = @z + 1
END
SELECT @y = @y + 1
END
SELECT @FinalCode = @FinalCode +
' FROM ( SELECT * FROM ##ALL_StableColumns)ID1';
SELECT @y = 1
WHILE @y <= (SELECT MAX([xxx_ID_xxx]) FROM ##FinalTab)
BEGIN
SELECT @x = 1
SELECT @FinalCode = @FinalCode
+ ' LEFT JOIN (SELECT ' + @ListOfColumns_Stable + ' , ' + @ListOfColumns_Variable
+ ' FROM ##FinalTab WHERE [xxx_ID_xxx] = '
+ CAST(@y as varchar(10)) + ' )ID' + CAST((@y + 1) as varchar(10))
+ ' ON 1 = 1'
WHILE @x <= (SELECT MAX([STAB_ID]) FROM @STAB_TAB)
BEGIN
SELECT @FinalCode = @FinalCode + ' AND ID1.' + (SELECT [ColumnName] FROM @STAB_TAB WHERE [STAB_ID] = @x) + ' = ID' + CAST((@y+1) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @STAB_TAB WHERE [STAB_ID] = @x)
SELECT @x = @x +1
END
SELECT @y = @y + 1
END
SELECT * FROM ##ALL_Dimentions;
EXECUTE SP_EXECUTESQL @FinalCode;
From executing the first query (by passing source DB and table name) you will get a pre-created execution query for the second SP, all you have to do is define is the column from your source: + Stable + Value (will be used to concentrate values based on that) + Dim (column you want to use to pivot by)
Names and datatypes will be defined automatically!
I cant recommend it for any production environments but does the job for adhoc BI requests.
Using color function to print text with colors
Code:
enum Color {
RED("\033[0;31m"), // RED
GREEN("\033[0;32m"), // GREEN
YELLOW("\033[0;33m"), // YELLOW
BLUE("\033[0;34m"), // BLUE
MAGENTA("\033[0;35m"), // MAGENTA
CYAN("\033[0;36m"), // CYAN
private final String code
Color(String code) {
this.code = code;
}
@Override
String toString() {
return code
}
}
def color = { color, txt ->
def RESET_COLOR = "\033[0m"
return "${color}${txt}${RESET_COLOR}"
}
Usage:
test {
println color(Color.CYAN, 'testing')
}
I came across same old issue and found below code more understandable which is in a way per above solutions.
std::set<int*>::iterator beginIt = listOfInts.begin();
while(beginIt != listOfInts.end())
{
// Use your member
std::cout<<(*beginIt)<<std::endl;
// delete the object
delete (*beginIt);
// erase item from vector
listOfInts.erase(beginIt );
// re-calculate the begin
beginIt = listOfInts.begin();
}
If installed as an admin, use:-
uname - admin
pw - the passkey that was generated during installation
Get the number of days between dates, inclusive.
public static List<Date> getDaysBetweenDates(Date startdate, Date enddate)
{
List<Date> dates = new ArrayList<Date>();
Calendar calendar = new GregorianCalendar();
calendar.setTime(startdate);
while (calendar.getTime().before(enddate))
{
Date result = calendar.getTime();
dates.add(result);
calendar.add(Calendar.DATE, 1);
}
return dates;
}
While exporting your source into a jar, make sure you select runnable jar option from the options. Then select if you want to package all the dependency jars or just include them directly in the jar file. It depends on the project that you are working on.
You then run the jar directly by java -jar example.jar.
This will get you the tables in foreign key order and avoid dropping some of the tables created by SQL Server. The t.Ordinal
value will slice the tables into dependency layers.
WITH TablesCTE(SchemaName, TableName, TableID, Ordinal) AS
(
SELECT OBJECT_SCHEMA_NAME(so.object_id) AS SchemaName,
OBJECT_NAME(so.object_id) AS TableName,
so.object_id AS TableID,
0 AS Ordinal
FROM sys.objects AS so
WHERE so.type = 'U'
AND so.is_ms_Shipped = 0
AND OBJECT_NAME(so.object_id)
LIKE 'MyPrefix%'
UNION ALL
SELECT OBJECT_SCHEMA_NAME(so.object_id) AS SchemaName,
OBJECT_NAME(so.object_id) AS TableName,
so.object_id AS TableID,
tt.Ordinal + 1 AS Ordinal
FROM sys.objects AS so
INNER JOIN sys.foreign_keys AS f
ON f.parent_object_id = so.object_id
AND f.parent_object_id != f.referenced_object_id
INNER JOIN TablesCTE AS tt
ON f.referenced_object_id = tt.TableID
WHERE so.type = 'U'
AND so.is_ms_Shipped = 0
AND OBJECT_NAME(so.object_id)
LIKE 'MyPrefix%'
)
SELECT DISTINCT t.Ordinal, t.SchemaName, t.TableName, t.TableID
FROM TablesCTE AS t
INNER JOIN
(
SELECT
itt.SchemaName AS SchemaName,
itt.TableName AS TableName,
itt.TableID AS TableID,
Max(itt.Ordinal) AS Ordinal
FROM TablesCTE AS itt
GROUP BY itt.SchemaName, itt.TableName, itt.TableID
) AS tt
ON t.TableID = tt.TableID
AND t.Ordinal = tt.Ordinal
ORDER BY t.Ordinal DESC, t.TableName ASC
As others Mentioned, you can use the @SuppressFBWarnings
Annotation.
If you don't want or can't add another Dependency to your code, you can add the Annotation to your Code yourself, Findbugs dosn't care in which Package the Annotation is.
@Retention(RetentionPolicy.CLASS)
public @interface SuppressFBWarnings {
/**
* The set of FindBugs warnings that are to be suppressed in
* annotated element. The value can be a bug category, kind or pattern.
*
*/
String[] value() default {};
/**
* Optional documentation of the reason why the warning is suppressed
*/
String justification() default "";
}
Source: https://sourceforge.net/p/findbugs/feature-requests/298/#5e88
I think the root for this confusion is well explained in this wikipedia article.
While the IANA-registered MIME type for ICO files is image/vnd.microsoft.icon, it was submitted to IANA in 2003 by a third party and is not recognised by Microsoft software, which uses image/x-icon instead.
If even the inventor of the ICO format does not use the official MIME type, I will use image/x-icon
, too.
As of HTML5 browsers one can use inputElement.form
- the value of the attribute must be an id of a <form>
element in the same document.
More info on MDN.
I had this problem using Meteor and Ngrok, while trying to login with Google.
I put the Ngrok URL in the Google Developer Console as redirect URLs, and went to the Ngrok URL page. The thing was that I didn't use Meteor's ROOT_URL
when executing the app, so any redirect would go to localhost:3000
insted of the Ngrok URL.
Just fixed it by adding the Ngrok URL as ROOT_URL
on Meteor's configuration or by exporting it before executing the app on the terminal like: export ROOT_URL=https://my_ngrok_url
SELECT student, SUM(mark1+mark2+mark3+....+markn) AS Total FROM your_table
Here is a version, basically the same as a couple of the other answers, but that you can copy paste into your SQL server Management Studio to test, (and without generating any unwanted tables), thanks to some inline values.
WITH [TestData]([ID],[SKU],[PRODUCT]) AS
(
SELECT *
FROM (
VALUES
(1, 'FOO-23', 'Orange'),
(2, 'BAR-23', 'Orange'),
(3, 'FOO-24', 'Apple'),
(4, 'FOO-25', 'Orange')
)
AS [TestData]([ID],[SKU],[PRODUCT])
)
SELECT * FROM [TestData] WHERE [ID] IN
(
SELECT MIN([ID])
FROM [TestData]
GROUP BY [PRODUCT]
)
Result
ID SKU PRODUCT
1 FOO-23 Orange
3 FOO-24 Apple
I have ignored the following ...
WHERE ([SKU] LIKE 'FOO-%')
as its only part of the authors faulty code and not part of the question. It's unlikely to be helpful to people looking here.
Use the session_set_cookie_params
funciton for make this.
Is necessary calling this function before session_start()
call.
Try this:
$lifetime = strtotime('+30 minutes', 0);
session_set_cookie_params($lifetime);
session_start();
See more in: http://php.net/manual/function.session-set-cookie-params.php
If you're using pure JS you can simply do it like:
var input = document.getElementById('myInput');
if(input.value.length == 0)
input.value = "Empty";
Here's a demo: http://jsfiddle.net/nYtm8/
In Python 3, TemporaryDirectory in the tempfile module can be used.
This is straight from the examples:
import tempfile
with tempfile.TemporaryDirectory() as tmpdirname:
print('created temporary directory', tmpdirname)
# directory and contents have been removed
If you would like to keep the directory a bit longer, you could do something like this:
import tempfile
temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
# use temp_dir, and when done:
temp_dir.cleanup()
The documentation also says that "On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem." So at the end of the program, for example, Python will clean up the directory if it wasn't explicitly removed. Python's unittest
may complain of ResourceWarning: Implicitly cleaning up <TemporaryDirectory...
if you rely on this, though.
Following on @Arne Mertz's answer, as of C++11 std::ios_base::failure
inherits from system_error
(see http://www.cplusplus.com/reference/ios/ios_base/failure/), which contains both the error code and message that strerror(errno)
would return.
std::ifstream f;
// Set exceptions to be thrown on failure
f.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try {
f.open(fileName);
} catch (std::system_error& e) {
std::cerr << e.code().message() << std::endl;
}
This prints No such file or directory.
if fileName
doesn't exist.
As of Swift 3 / 4 / 5, this is done as follows.
To add a new element to the end of an Array.
anArray.append("This String")
To append a different Array to the end of your Array.
anArray += ["Moar", "Strings"]
anArray.append(contentsOf: ["Moar", "Strings"])
To insert a new element into your Array.
anArray.insert("This String", at: 0)
To insert the contents of a different Array into your Array.
anArray.insert(contentsOf: ["Moar", "Strings"], at: 0)
More information can be found in the "Collection Types" chapter of "The Swift Programming Language", starting on page 110.
Use the convenience methods .first()
and .last()
:
MyModel.objects.filter(blah=blah).first()
They both swallow the resulting exception and return None
if the queryset returns no objects.
These were added in Django 1.6, which was released in Nov 2013.
With AppCompat 22, the FAB is supported for older devices.
Add the new support library in your build.gradle(app):
compile 'com.android.support:design:22.2.0'
Then you can use it in your xml:
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:src="@android:drawable/ic_menu_more"
app:elevation="6dp"
app:pressedTranslationZ="12dp" />
To use elevation
and pressedTranslationZ
properties, namespace app
is needed, so add this namespace to your layout:
xmlns:app="http://schemas.android.com/apk/res-auto"
What do you want to search near that known place?
For example if you want to search a restaurant near a known place you can use the parameters "q=" and "near=" and construct this URL: maps.google.com/?q=restaurant&near=47.154719,27.60551
For a list of complete parameters you can see this: https://web.archive.org/web/20070708030513/http://mapki.com/wiki/Google_Map_Parameters
Depending on what is the format you want your information in you can add at the end of the url the parameter output like this: maps.google.com/?q=restaurant&near=47.154719,27.60551&output=kml
For more types of output format you can read chapter 2 of this: http://csie-tw.blogspot.de/2009/06/android-driving-direction-route-path.html
Most likely, you want
SELECT username
FROM dba_users
That will show you all the users in the system (and thus all the potential schemas). If your definition of "schema" allows for a schema to be empty, that's what you want. However, there can be a semantic distinction where people only want to call something a schema if it actually owns at least one object so that the hundreds of user accounts that will never own any objects are excluded. In that case
SELECT username
FROM dba_users u
WHERE EXISTS (
SELECT 1
FROM dba_objects o
WHERE o.owner = u.username )
Assuming that whoever created the schemas was sensible about assigning default tablespaces and assuming that you are not interested in schemas that Oracle has delivered, you can filter out those schemas by adding predicates on the default_tablespace
, i.e.
SELECT username
FROM dba_users
WHERE default_tablespace not in ('SYSTEM','SYSAUX')
or
SELECT username
FROM dba_users u
WHERE EXISTS (
SELECT 1
FROM dba_objects o
WHERE o.owner = u.username )
AND default_tablespace not in ('SYSTEM','SYSAUX')
It is not terribly uncommon to come across a system where someone has incorrectly given a non-system user a default_tablespace
of SYSTEM
, though, so be certain that the assumptions hold before trying to filter out the Oracle-delivered schemas this way.
site-packages
is the target directory of manually built Python packages. When you build and install Python packages from source (using distutils, probably by executing python setup.py install
), you will find the installed modules in site-packages
by default.
There are standard locations:
prefix/lib/pythonX.Y/site-packages
exec-prefix/lib/pythonX.Y/site-packages
prefix\Lib\site-packages
1 Pure means that the module uses only Python code. Non-pure can contain C/C++ code as well.
site-packages
is by default part of the Python search path, so modules installed there can be imported easily afterwards.
Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.
You can use the for..in TypeScript operator to access the index when dealing with collections.
var test = [7,8,9];
for (var i in test) {
console.log(i + ': ' + test[i]);
}
Output:
0: 7
1: 8
2: 9
See Demo
SimpleDateFormat
sdf=new SimpleDateFormat("dd/MM/YYYY hh:mm:ss");
String dateString=sdf.format(date);
It will give the output 28/09/2013 09:57:19
as you expected.
Problem. My stored Claws Mail messages are wrapped as follows, and I am trying to extract the Subject lines:
Subject: [SLC38A9 lysosomal arginine sensor; mTORC1 pathway] Key molecular
link in major cell growth pathway: Findings point to new potential
therapeutic target in pancreatic cancer [mTORC1 Activator SLC38A9 Is
Required to Efflux Essential Amino Acids from Lysosomes and Use Protein as
a Nutrient] [Re: Nutrient sensor in key growth-regulating metabolic pathway
identified [Lysosomal amino acid transporter SLC38A9 signals arginine
sufficiency to mTORC1]]
Message-ID: <[email protected]>
Per A2 in this thread, How to use sed/grep to extract text between two words? the first expression, below, "works" as long as the matched text does not contain a newline:
grep -o -P '(?<=Subject: ).*(?=molecular)' corpus/01
[SLC38A9 lysosomal arginine sensor; mTORC1 pathway] Key
However, despite trying numerous variants (.+?; /s; ...
), I could not get these to work:
grep -o -P '(?<=Subject: ).*(?=link)' corpus/01
grep -o -P '(?<=Subject: ).*(?=therapeutic)' corpus/01
etc.
Solution 1.
Per Extract text between two strings on different lines
sed -n '/Subject: /{:a;N;/Message-ID:/!ba; s/\n/ /g; s/\s\s*/ /g; s/.*Subject: \|Message-ID:.*//g;p}' corpus/01
which gives
[SLC38A9 lysosomal arginine sensor; mTORC1 pathway] Key molecular link in major cell growth pathway: Findings point to new potential therapeutic target in pancreatic cancer [mTORC1 Activator SLC38A9 Is Required to Efflux Essential Amino Acids from Lysosomes and Use Protein as a Nutrient] [Re: Nutrient sensor in key growth-regulating metabolic pathway identified [Lysosomal amino acid transporter SLC38A9 signals arginine sufficiency to mTORC1]]
Solution 2.*
Per How can I replace a newline (\n) using sed?
sed ':a;N;$!ba;s/\n/ /g' corpus/01
will replace newlines with a space.
Chaining that with A2 in How to use sed/grep to extract text between two words?, we get:
sed ':a;N;$!ba;s/\n/ /g' corpus/01 | grep -o -P '(?<=Subject: ).*(?=Message-ID:)'
which gives
[SLC38A9 lysosomal arginine sensor; mTORC1 pathway] Key molecular link in major cell growth pathway: Findings point to new potential therapeutic target in pancreatic cancer [mTORC1 Activator SLC38A9 Is Required to Efflux Essential Amino Acids from Lysosomes and Use Protein as a Nutrient] [Re: Nutrient sensor in key growth-regulating metabolic pathway identified [Lysosomal amino acid transporter SLC38A9 signals arginine sufficiency to mTORC1]]
This variant removes double spaces:
sed ':a;N;$!ba;s/\n/ /g; s/\s\s*/ /g' corpus/01 | grep -o -P '(?<=Subject: ).*(?=Message-ID:)'
giving
[SLC38A9 lysosomal arginine sensor; mTORC1 pathway] Key molecular link in major cell growth pathway: Findings point to new potential therapeutic target in pancreatic cancer [mTORC1 Activator SLC38A9 Is Required to Efflux Essential Amino Acids from Lysosomes and Use Protein as a Nutrient] [Re: Nutrient sensor in key growth-regulating metabolic pathway identified [Lysosomal amino acid transporter SLC38A9 signals arginine sufficiency to mTORC1]]
A simple tkinter code for Python 3 for setting background image .
from tkinter import *
from tkinter import messagebox
top = Tk()
C = Canvas(top, bg="blue", height=250, width=300)
filename = PhotoImage(file = "C:\\Users\\location\\imageName.png")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
C.pack()
top.mainloop
A Simple and an easy way
var cusid_ele = document.getElementsByClassName('custid');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
item.innerHTML = 'this is value';
}
Another issue you have to take care of: If your generated file names are not the default id_rsa
and id_rsa.pub
.
You have to create the .ssh/config file and define manually which id file you are going to use with the connection.
An example is here:
Host remote_host_name
HostName 172.xx.xx.xx
User my_user
IdentityFile /home/my_user/.ssh/my_user_custom
There is a solution to this if you really need a static access to the current context. In Startup.Configure(….)
app.Use(async (httpContext, next) =>
{
CallContext.LogicalSetData("CurrentContextKey", httpContext);
try
{
await next();
}
finally
{
CallContext.FreeNamedDataSlot("CurrentContextKey");
}
});
And when you need it you can get it with :
HttpContext context = CallContext.LogicalGetData("CurrentContextKey") as HttpContext;
I hope that helps. Keep in mind this workaround is when you don’t have a choice. The best practice is to use de dependency injection.
You could capture the (2001)
part and replace the rest with nothing.
public static string extractYearString(string input) {
return input.replaceAll(".*\(([0-9]{4})\).*", "$1");
}
var subject = "(2001) (asdf) (dasd1123_asd 21.01.2011 zqge)(dzqge) name (20019)";
var result = extractYearString(subject);
System.out.println(result); // <-- "2001"
.*\(([0-9]{4})\).*
means
.*
match anything\(
match a (
character(
begin capture[0-9]{4}
any single digit four times)
end capture\)
match a )
character.*
anything (rest of string)To get fixed padding, I will set layout to java.awt.GridBagLayout
with one cell.
You can then set padding for each cell. Then you can insert inner JPanel
to that cell and (if you need) delegate proper JPanel
methods to the inner JPanel
.
If you use Hadoop version 2.6.1 above, while the command works, it complains that its depreciated. I actually could not use the hadoop dfsadmin -safemode leave
because I was running Hadoop in a Docker container and that command magically fails when run in the container, so what I did was this. I checked doc and found dfs.safemode.threshold.pct
in documentation that says
Specifies the percentage of blocks that should satisfy the minimal replication requirement defined by dfs.replication.min. Values less than or equal to 0 mean not to wait for any particular percentage of blocks before exiting safemode. Values greater than 1 will make safe mode permanent.
so I changed the hdfs-site.xml
into the following (In older Hadoop versions, apparently you need to do it in hdfs-default.xml
:
<configuration>
<property>
<name>dfs.safemode.threshold.pct</name>
<value>0</value>
</property>
</configuration>
Use a computed column instead. It is almost always a better idea to use a computed column than a trigger.
See Example below of a computed column using the UPPER function:
create table #temp (test varchar (10), test2 AS upper(test))
insert #temp (test)
values ('test')
select * from #temp
And not to sound like a broken record or anything, but this is critically important. Never write a trigger that will not work correctly on multiple record inserts/updates/deletes. This is an extremely poor practice as sooner or later one of these will happen and your trigger will cause data integrity problems asw it won't fail precisely it will only run the process on one of the records. This can go a long time until someone discovers the mess and by themn it is often impossible to correctly fix the data.
You are correct with your observation.
If x == 0.0
, then abs(x) * epsilon
is zero and you're testing whether abs(y) <= 0.0
.
If y == 0.0
then you're testing abs(x) <= abs(x) * epsilon
which means either epsilon >= 1
(it isn't) or x == 0.0
.
So either is_equal(val, 0.0)
or is_equal(0.0, val)
would be pointless, and you could just say val == 0.0
. If you want to only accept exactly +0.0
and -0.0
.
The FAQ's recommendation in this case is of limited utility. There is no "one size fits all" floating-point comparison. You have to think about the semantics of your variables, the acceptable range of values, and the magnitude of error introduced by your computations. Even the FAQ mentions a caveat, saying this function is not usually a problem "when the magnitudes of x and y are significantly larger than epsilon, but your mileage may vary".
i was facing lot of issues when i was trying other solution...... After lot of R&D now i got solution
create custom_spinner.xml in layout folder and paste this code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorGray">
<TextView
android:id="@+id/tv_spinnervalue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/colorWhite"
android:gravity="center"
android:layout_alignParentLeft="true"
android:textSize="@dimen/_18dp"
android:layout_marginTop="@dimen/_3dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="@drawable/men_icon"/>
</RelativeLayout>
in your activity
Spinner spinner =(Spinner)view.findViewById(R.id.sp_colorpalates);
String[] years = {"1996","1997","1998","1998"};
spinner.setAdapter(new SpinnerAdapter(this, R.layout.custom_spinner, years));
create a new class of adapter
public class SpinnerAdapter extends ArrayAdapter<String> {
private String[] objects;
public SpinnerAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
this.objects=objects;
}
@Override
public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
private View getCustomView(final int position, View convertView, ViewGroup parent) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_spinner, parent, false);
final TextView label=(TextView)row.findViewById(R.id.tv_spinnervalue);
label.setText(objects[position]);
return row;
}
}
Defining insertable=false, updatable=false
is useful when you need to map a field more than once in an entity, typically:
This is IMO not a semantical thing, but definitely a technical one.
You could use a shortcut library to handle the browser specific stuff.
shortcut.add("Ctrl+S",function() {
alert("Hi there!");
});
One way to do this is to use String.Substring
together with String.IndexOf
:
int index = str.IndexOf('-');
string sub;
if (index >= 0)
{
sub = str.Substring(0, index);
}
else
{
sub = ... // handle strings without the dash
}
Starting at position 0, return all text up to, but not including, the dash.
For Beginner Like Me. Just Do it what I say.From your Android Project.
app -> res -> values -> style.xml
replace this code
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
Enjoy.
Marc Gravell's answer should work for you. myDictionary.Keys
returns an object that implements ICollection<TKey>
, IEnumerable<TKey>
and their non-generic counterparts.
I just wanted to add that if you plan on accessing the value as well, you could loop through the dictionary like this (modified example):
Dictionary<string, int> data = new Dictionary<string, int>();
data.Add("abc", 123);
data.Add("def", 456);
foreach (KeyValuePair<string, int> item in data)
{
Console.WriteLine(item.Key + ": " + item.Value);
}