I know it's been a while, but I thought i would update the answer since there are new (faster and simpler) ways to solve this problem.
Since ECMAscript 5.1 yo can use the isArray()
method avaiable in the Array
class.
Yo can see it's documentation in MDN here.
I think you shouldn't have a compatibility problem nowadays, but just in case, if you add this to your code you should be always safe that Array.isArray()
is polyfilled:
if (!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
You need to include a body with the request. Angular removes the content-type header otherwise.
Add data: ''
to the argument to $http
.
If you are using Razor, you cannot access the field directly, but you can manage its value.
The idea is that the first Microsoft approach drive the developers away from Web Development and make it easy for Desktop programmers (for example) to make web applications.
Meanwhile, the web developers, did not understand this tricky strange way of ASP.NET.
Actually this hidden input is rendered on client-side, and the ASP has no access to it (it never had). However, in time you will see its a piratical way and you may rely on it, when you get use with it. The web development differs from the Desktop or Mobile.
The model is your logical unit, and the hidden field (and the whole view page) is just a representative view of the data. So you can dedicate your work on the application or domain logic and the view simply just serves it to the consumer - which means you need no detailed access and "brainstorming" functionality in the view.
The controller actually does work you need for manage the hidden or general setup. The model serves specific logical unit properties and functionality and the view just renders it to the end user, simply said. Read more about MVC.
Model
public class MyClassModel
{
public int Id { get; set; }
public string Name { get; set; }
public string MyPropertyForHidden { get; set; }
}
This is the controller aciton
public ActionResult MyPageView()
{
MyClassModel model = new MyClassModel(); // Single entity, strongly-typed
// IList model = new List<MyClassModel>(); // or List, strongly-typed
// ViewBag.MyHiddenInputValue = "Something to pass"; // ...or using ViewBag
return View(model);
}
The view is below
//This will make a Model property of the View to be of MyClassModel
@model MyNamespace.Models.MyClassModel // strongly-typed view
// @model IList<MyNamespace.Models.MyClassModel> // list, strongly-typed view
// ... Some Other Code ...
@using(Html.BeginForm()) // Creates <form>
{
// Renders hidden field for your model property (strongly-typed)
// The field rendered to server your model property (Address, Phone, etc.)
Html.HiddenFor(model => Model.MyPropertyForHidden);
// For list you may use foreach on Model
// foreach(var item in Model) or foreach(MyClassModel item in Model)
}
// ... Some Other Code ...
The view with ViewBag:
// ... Some Other Code ...
@using(Html.BeginForm()) // Creates <form>
{
Html.Hidden(
"HiddenName",
ViewBag.MyHiddenInputValue,
new { @class = "hiddencss", maxlength = 255 /*, etc... */ }
);
}
// ... Some Other Code ...
We are using Html Helper to render the Hidden field or we could write it by hand - <input name=".." id=".." value="ViewBag.MyHiddenInputValue">
also.
The ViewBag is some sort of data carrier to the view. It does not restrict you with model - you can place whatever you like.
SELECT author FROM lyrics WHERE author LIKE 'B%';
Make sure you have an index on author
, though!
What you can do to resolve your conflict is
svn resolve --accept working -R <path>
where <path>
is where you have your conflict (can be the root of your repo).
Explanations:
resolve
asks svn
to resolve the conflictaccept working
specifies to keep your working files-R
stands for recursiveHope this helps.
EDIT:
To sum up what was said in the comments below:
<path>
should be the directory in conflict (C:\DevBranch\
in the case of the OP)svn switch
commandSwitch working copy to new branch/tag
option at branch creationI have added below code to terminate tasks you can use it. You may change the retry numbers.
package com.xxx.test.schedulers;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import com.xxx.core.XProvLogger;
@Component
class ContextClosedHandler implements ApplicationListener<ContextClosedEvent> , ApplicationContextAware,BeanPostProcessor{
private ApplicationContext context;
public Logger logger = XProvLogger.getInstance().x;
public void onApplicationEvent(ContextClosedEvent event) {
Map<String, ThreadPoolTaskScheduler> schedulers = context.getBeansOfType(ThreadPoolTaskScheduler.class);
for (ThreadPoolTaskScheduler scheduler : schedulers.values()) {
scheduler.getScheduledExecutor().shutdown();
try {
scheduler.getScheduledExecutor().awaitTermination(20000, TimeUnit.MILLISECONDS);
if(scheduler.getScheduledExecutor().isTerminated() || scheduler.getScheduledExecutor().isShutdown())
logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has stoped");
else{
logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has not stoped normally and will be shut down immediately");
scheduler.getScheduledExecutor().shutdownNow();
logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has shut down immediately");
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Map<String, ThreadPoolTaskExecutor> executers = context.getBeansOfType(ThreadPoolTaskExecutor.class);
for (ThreadPoolTaskExecutor executor: executers.values()) {
int retryCount = 0;
while(executor.getActiveCount()>0 && ++retryCount<51){
try {
logger.info("Executer "+executor.getThreadNamePrefix()+" is still working with active " + executor.getActiveCount()+" work. Retry count is "+retryCount);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(!(retryCount<51))
logger.info("Executer "+executor.getThreadNamePrefix()+" is still working.Since Retry count exceeded max value "+retryCount+", will be killed immediately");
executor.shutdown();
logger.info("Executer "+executor.getThreadNamePrefix()+" with active " + executor.getActiveCount()+" work has killed");
}
}
@Override
public void setApplicationContext(ApplicationContext context)
throws BeansException {
this.context = context;
}
@Override
public Object postProcessAfterInitialization(Object object, String arg1)
throws BeansException {
return object;
}
@Override
public Object postProcessBeforeInitialization(Object object, String arg1)
throws BeansException {
if(object instanceof ThreadPoolTaskScheduler)
((ThreadPoolTaskScheduler)object).setWaitForTasksToCompleteOnShutdown(true);
if(object instanceof ThreadPoolTaskExecutor)
((ThreadPoolTaskExecutor)object).setWaitForTasksToCompleteOnShutdown(true);
return object;
}
}
My favourite is to extend jQuery with this tiny convenience:
$.fn.exists = function () {
return this.length !== 0;
}
Used like:
$("#notAnElement").exists();
More explicit than using length.
You are getting something wrong... RTSP is a realtime streaming protocol. Meaning, you can stream whatever you want in real time. So you can use it to stream LIVE content (no matter what it is, video, audio, text, presentation...). RTP is a transport protocol which is used to transport media data which is negotiated over RTSP.
You use RTSP to control media transmission over RTP. You use it to setup, play, pause, teardown the stream...
So, if you want your server to just start streaming when the URL is requested, you can implement some sort of RTP-only server. But if you want more control and if you are streaming live video, you must use RTSP, because it transmits SDP and other important decoding data.
Read the documents I linked here, they are a good starting point.
If your question about <input type="date">
field, here is script for getting filed value=""
attribute:
(new Date()).toISOString().split('T')[0]
You can use the Intl object (ecma-402) to get data-date-pattern=""
:
(new Intl.DateTimeFormat()).resolved.pattern // "M/d/y" for "en-US" in Google Chrome
And finnaly, to format date in current l10n, data-date=""
:
(new Intl.DateTimeFormat()).format(new Date());
Polyfill: https://github.com/andyearnshaw/Intl.js/issues/129
You can use the try
-except
-else
clause , this will catch any conversion/ value errors raised when the value passed cannot be converted to a float
def try_parse_float(item):
result = None
try:
float(item)
except:
pass
else:
result = float(item)
return result
with a form, just set method
to "post"
<form action="blah.php" method="post">
<input type="text" name="data" value="mydata" />
<input type="submit" />
</form>
This is how I implemented a move element extension method. It handles moving before/after and to the extremes for elements pretty well.
public static void MoveElement<T>(this IList<T> list, int fromIndex, int toIndex)
{
if (!fromIndex.InRange(0, list.Count - 1))
{
throw new ArgumentException("From index is invalid");
}
if (!toIndex.InRange(0, list.Count - 1))
{
throw new ArgumentException("To index is invalid");
}
if (fromIndex == toIndex) return;
var element = list[fromIndex];
if (fromIndex > toIndex)
{
list.RemoveAt(fromIndex);
list.Insert(toIndex, element);
}
else
{
list.Insert(toIndex + 1, element);
list.RemoveAt(fromIndex);
}
}
You must build parent module before doing child module.
Simplify or break apart the function so that it doesn't require nine arguments (or ignore pylint, but dodges like the ones you're proposing defeat the purpose of a lint tool).
EDIT: if it's a temporary measure, disable the warning for the particular function in question using a comment as described here: http://lists.logilab.org/pipermail/python-projects/2006-April/000664.html
Later, you can grep for all of the disabled warnings.
You may go with this way: ( a general example )
insert into QualityAssuranceDB.dbo.Customers (columnA, ColumnB)
Select columnA, columnB from DeveloperDB.dbo.Customers
Also if you need to generate the column names as well to put in insert clause, use:
select (name + ',') as TableColumns from sys.columns
where object_id = object_id('YourTableName')
Copy the result and paste into query window to represent your table column names and even this will exclude the identity column as well:
select (name + ',') as TableColumns from sys.columns
where object_id = object_id('YourTableName') and is_identity = 0
Remember the script to copy rows will work if the databases belongs to the same location.
You can Try This.
select * into <Destination_table> from <Servername>.<DatabaseName>.dbo.<sourceTable>
Server name is optional if both DB is in same server.
It's possible to change the path fill color of the svg. See below for the CSS snippet:
To apply the color for all the path: svg > path{ fill: red }
To apply for the first d path: svg > path:nth-of-type(1){ fill: green }
To apply for the second d path: svg > path:nth-of-type(2){ fill: green}
To apply for the different d path, change only the path number:
svg > path:nth-of-type(${path_number}){ fill: green}
To support the CSS in Angular 2 to 8, use the encapsulation concept:
:host::ng-deep svg path:nth-of-type(1){
fill:red;
}
For Visual Studio 2017, press Ctrl + ..
I think the easiest is to use Fastlane:
sudo gem install fastlane -NV
hash -r # for bash
rehash # for zsh
fastlane sigh resign ./path/app.ipa --signing_identity "Apple Distribution: Company Name" -p "my.mobileprovision"
When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:
MS SQL Server 2012 Schema Setup:
Query 1:
CREATE TABLE #Names
(
Name1 VARCHAR(100),
Name2 VARCHAR(100)
)
INSERT INTO #Names
(Name1, Name2)
VALUES
('Matt', 'Matthew'),
('Matt', 'Marshal'),
('Matt', 'Mattison')
SELECT * FROM #NAMES
| NAME1 | NAME2 |
--------------------
| Matt | Matthew |
| Matt | Marshal |
| Matt | Mattison |
Here a SSMS 2012 screenshot:
TL;DR Use Cmd/Ctrl+Shift+P
then Package Control: Install Package
, then Print to HTML
and install it. Use Alt+Shift+P
to print.
My favorite tool for printing from Sublime Text is Print to HTML package. You can "print" a selection or a whole file - via the web browser.
This opens your browser print dialog (Chrome for me) with the selected text neatly in the print dialog window and syntax highlighting intact. There you can choose a printer or export to PDF, and print.
Install the "Print to HTML" package using the package manager.
Ctrl + Shift + P
=> Gives a list of commands.install
"Package Control: Install Package
"print to
"Print to HTML
". Select that, and it is being installed.Alt+Shift+P
If you define words as "sequences of characters delimited by space"... Use strrpos()
to find the last space in the string, shorten to that position, trim the result.
A big selection would be:
gg=G
It is really fast, and everything gets indented ;-)
These steps worked for me when the error showed that the Filter class was missing (as reported in this false-diplicated question: JUnit: NoClassDefFoundError: org/junit/runner/manipulation/Filter ):
Thanks to these answers for giving me the hint for this solution: https://stackoverflow.com/a/34067333/5538923 and https://stackoverflow.com/a/39987979/5538923).
The following script solved my problem:
// Fake localStorage implementation.
// Mimics localStorage, including events.
// It will work just like localStorage, except for the persistant storage part.
var fakeLocalStorage = function() {
var fakeLocalStorage = {};
var storage;
// If Storage exists we modify it to write to our fakeLocalStorage object instead.
// If Storage does not exist we create an empty object.
if (window.Storage && window.localStorage) {
storage = window.Storage.prototype;
} else {
// We don't bother implementing a fake Storage object
window.localStorage = {};
storage = window.localStorage;
}
// For older IE
if (!window.location.origin) {
window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
var dispatchStorageEvent = function(key, newValue) {
var oldValue = (key == null) ? null : storage.getItem(key); // `==` to match both null and undefined
var url = location.href.substr(location.origin.length);
var storageEvent = document.createEvent('StorageEvent'); // For IE, http://stackoverflow.com/a/25514935/1214183
storageEvent.initStorageEvent('storage', false, false, key, oldValue, newValue, url, null);
window.dispatchEvent(storageEvent);
};
storage.key = function(i) {
var key = Object.keys(fakeLocalStorage)[i];
return typeof key === 'string' ? key : null;
};
storage.getItem = function(key) {
return typeof fakeLocalStorage[key] === 'string' ? fakeLocalStorage[key] : null;
};
storage.setItem = function(key, value) {
dispatchStorageEvent(key, value);
fakeLocalStorage[key] = String(value);
};
storage.removeItem = function(key) {
dispatchStorageEvent(key, null);
delete fakeLocalStorage[key];
};
storage.clear = function() {
dispatchStorageEvent(null, null);
fakeLocalStorage = {};
};
};
// Example of how to use it
if (typeof window.localStorage === 'object') {
// Safari will throw a fit if we try to use localStorage.setItem in private browsing mode.
try {
localStorage.setItem('localStorageTest', 1);
localStorage.removeItem('localStorageTest');
} catch (e) {
fakeLocalStorage();
}
} else {
// Use fake localStorage for any browser that does not support it.
fakeLocalStorage();
}
It checks if localStorage exists and can be used and in the negative case, it creates a fake local storage and uses it instead of the original localStorage. Please let me know if you need further information.
Set this in the constructor:
public class SearchModel
{
public bool IsMale { get; set; }
public bool IsFemale { get; set; }
public SearchModel()
{
IsMale = true;
IsFemale = true;
}
}
Then pass it to the view in your GET action:
[HttpGet]
public ActionResult Search()
{
return new View(new SearchModel());
}
Check if there is any conflict in your IIS authentication. i.e. you enable the anonymous authentication and ASP.NET impersonation both might cause the error also.
You could pass in the command-line option -v
with a variable name (v
) and a value (=
) of the environment variable ("${v}"
):
% awk -vv="${v}" 'BEGIN { print v }'
123test
Or to make it clearer (with far fewer v
s):
% environment_variable=123test
% awk -vawk_variable="${environment_variable}" 'BEGIN { print awk_variable }'
123test
This is the first of my two answers to the question.
If you want fine control over the namespaces - for example if you want to omit some of them but not others, or if you want to replace one namespace with another, you can do this using XmlAttributeOverrides.
Suppose you have this type definition:
// explicitly specify a namespace for this type,
// to be used during XML serialization.
[XmlRoot(Namespace="urn:Abracadabra")]
public class MyTypeWithNamespaces
{
// private fields backing the properties
private int _Epoch;
private string _Label;
// explicitly define a distinct namespace for this element
[XmlElement(Namespace="urn:Whoohoo")]
public string Label
{
set { _Label= value; }
get { return _Label; }
}
// this property will be implicitly serialized to XML using the
// member name for the element name, and inheriting the namespace from
// the type.
public int Epoch
{
set { _Epoch= value; }
get { return _Epoch; }
}
}
And this serialization pseudo-code:
var o2= new MyTypeWithNamespaces() { ..initializers...};
ns.Add( "", "urn:Abracadabra" );
XmlSerializer s2 = new XmlSerializer(typeof(MyTypeWithNamespaces));
s2.Serialize(System.Console.Out, o2, ns);
You would get something like this XML:
<MyTypeWithNamespaces xmlns="urn:Abracadabra">
<Label xmlns="urn:Whoohoo">Cimsswybclaeqjh</Label>
<Epoch>97</Epoch>
</MyTypeWithNamespaces>
Notice that there is a default namespace on the root element, and there is also a distinct namespace on the "Label" element. These namespaces were dictated by the attributes decorating the type, in the code above.
The Xml Serialization framework in .NET includes the possibility to explicitly override the attributes that decorate the actual code. You do this with the XmlAttributesOverrides class and friends. Suppose I have the same type, and I serialize it this way:
// instantiate the container for all attribute overrides
XmlAttributeOverrides xOver = new XmlAttributeOverrides();
// define a set of XML attributes to apply to the root element
XmlAttributes xAttrs1 = new XmlAttributes();
// define an XmlRoot element (as if [XmlRoot] had decorated the type)
// The namespace in the attribute override is the empty string.
XmlRootAttribute xRoot = new XmlRootAttribute() { Namespace = ""};
// add that XmlRoot element to the container of attributes
xAttrs1.XmlRoot= xRoot;
// add that bunch of attributes to the container holding all overrides
xOver.Add(typeof(MyTypeWithNamespaces), xAttrs1);
// create another set of XML Attributes
XmlAttributes xAttrs2 = new XmlAttributes();
// define an XmlElement attribute, for a type of "String", with no namespace
var xElt = new XmlElementAttribute(typeof(String)) { Namespace = ""};
// add that XmlElement attribute to the 2nd bunch of attributes
xAttrs2.XmlElements.Add(xElt);
// add that bunch of attributes to the container for the type, and
// specifically apply that bunch to the "Label" property on the type.
xOver.Add(typeof(MyTypeWithNamespaces), "Label", xAttrs2);
// instantiate a serializer with the overrides
XmlSerializer s3 = new XmlSerializer(typeof(MyTypeWithNamespaces), xOver);
// serialize
s3.Serialize(System.Console.Out, o2, ns2);
The result looks like this;
<MyTypeWithNamespaces>
<Label>Cimsswybclaeqjh</Label>
<Epoch>97</Epoch>
</MyTypeWithNamespaces>
You have stripped the namespaces.
A logical question is, can you strip all namespaces from arbitrary types during serialization, without going through the explicit overrides? The answer is YES, and how to do it is in my next response.
If you are migrating from XML-based to Java-based configuration and you have removed the need for web.xml by implementing WebApplicationInitializer, simply remove the requirement for the web.xml file to be present.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
...
</configuration>
On a fresh install on CENTOS7 I have tried the above methods (edit phpMyAdmin.conf and add Require all granted), it still does'nt work. Here is the solution : install the mod_php module :
$ sudo yum install php
then restart httpd :
$ sudo systemctl restart httpd
and voila !
When running python (cpython) on windows the <built-in function system>
os.system will execute under the curtains _wsystem while if you're using a non-windows os, it'll use system.
On contrary, Popen should use CreateProcess on windows and _posixsubprocess.fork_exec in posix-based operating-systems.
That said, an important piece of advice comes from os.system docs, which says:
The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.
Web Call Server (Flashphoner)
Re-Streaming RTSP to WebRTC (Native browser feature for Chrome and FF either on Android or desktop)
Re-Streaming RTSP to Websockets (iOS Safari and Chrome/FF Desktop)
Take a look at this article.
I regularly use IntelliJ, PHPStorm and WebStorm. Would love to only use IntelliJ. As pointed out by the vendor the "Open Directory" functionality not being in IntelliJ is painful.
Now for the rub part; I have tried using IntelliJ as my single IDE and have found performance to be terrible compared to the lighter weight versions. Intellisense is almost useless in IntelliJ compared to WebStorm.
you can try this simple 12 line of code for delete folder or folder files... happy coding... ;) :)
function deleteAll($str) {
if (is_file($str)) {
return unlink($str);
}
elseif (is_dir($str)) {
$scan = glob(rtrim($str,'/').'/*');
foreach($scan as $index=>$path) {
$this->deleteAll($path);
}
return @rmdir($str);
}
}
Don't care if you are a moderator. I wrote my text towards my audience not as a technical writer
All you guys need to learn to navigate with tools that predate GPS. Something like a sextant, octant, backstaff or an astrolabe.
If you have receive the signal from 3 different locations then you only need to measure the signal strength and make a ratio from those locations. Simple triangle calculation where a2+b2=c2. The stronger the signal strength the closer the device is to the receiver.
#!/usr/bin/env python
import Tkinter as tk
from Tkinter import *
class windowclass():
def __init__(self,master):
self.master = master
self.frame = tk.Frame(master)
self.lbl = Label(master , text = "Label")
self.lbl.pack()
self.btn = Button(master , text = "Button" , command = self.command )
self.btn.pack()
self.frame.pack()
def command(self):
print 'Button is pressed!'
self.newWindow = tk.Toplevel(self.master)
self.app = windowclass1(self.newWindow)
class windowclass1():
def __init__(self , master):
self.master = master
self.frame = tk.Frame(master)
master.title("a")
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25 , command = self.close_window)
self.quitButton.pack()
self.frame.pack()
def close_window(self):
self.master.destroy()
root = Tk()
root.title("window")
root.geometry("350x50")
cls = windowclass(root)
root.mainloop()
Another option (If you are using ASP.Net razor view) is, On your view you can do
<div>@String.Format("{0:C}", Model.total)</div>
This would format it correctly. note (item.total is double/decimal)
if in jQuery you can also use Regex
$(".totalSum").text('$' + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());
your best bet is to use a javascript framework like jquery or prototype, but, failing that, you should use:
if (foo.addEventListener)
foo.addEventListener('click',doit,false); //everything else
else if (foo.attachEvent)
foo.attachEvent('onclick',doit); //IE only
edit:
also, your function is a little off. it should be
var doit = function(){
alert('hello world!');
}
If you have the element in scroll view then you can also solve this issue as :
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/ed_password"
android:inputType="textPassword"
android:focusable="true"
android:imeOptions="actionNext"
android:nextFocusDown="@id/ed_confirmPassword" />
and in your activity:
edPassword.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_NEXT) {
focusOnView(scroll,edConfirmPassword);
return true;
}
return false;
}
});
public void focusOnView(ScrollView scrollView, EditText viewToScrollTo){
scrollView.post(new Runnable() {
@Override
public void run() {
scrollView.smoothScrollTo(0, viewToScrollTo.getBottom());
viewToScrollTo.requestFocus();
}
});
}
This works reliably for me. Cell borders and height added for effect and clarity:
<table>_x000D_
<tr>_x000D_
<td style="text-align:right; border: thin solid; height:50px">Some label:</td>_x000D_
<td style="border: thin solid;">_x000D_
<input type="checkbox" checked="checked" id="chk1" style="cursor:pointer; "><label for="chk1" style="margin-top:auto; margin-left:5px; margin-bottom:auto; cursor:pointer;">Check Me</label>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Two things you can do here:
Just for info, here is the stacktrace that I got from the example of code I posted at the end:
Thread [AWT-EventQueue-0] (Suspended (breakpoint at line 15 in TestPaint))
TestPaint.paintComponent(Graphics) line: 15
TestPaint(JComponent).paint(Graphics) line: 1054
JPanel(JComponent).paintChildren(Graphics) line: 887
JPanel(JComponent).paint(Graphics) line: 1063
JLayeredPane(JComponent).paintChildren(Graphics) line: 887
JLayeredPane(JComponent).paint(Graphics) line: 1063
JLayeredPane.paint(Graphics) line: 585
JRootPane(JComponent).paintChildren(Graphics) line: 887
JRootPane(JComponent).paintToOffscreen(Graphics, int, int, int, int, int, int) line: 5228
RepaintManager$PaintManager.paintDoubleBuffered(JComponent, Image, Graphics, int, int, int, int) line: 1482
RepaintManager$PaintManager.paint(JComponent, JComponent, Graphics, int, int, int, int) line: 1413
RepaintManager.paint(JComponent, JComponent, Graphics, int, int, int, int) line: 1206
JRootPane(JComponent).paint(Graphics) line: 1040
GraphicsCallback$PaintCallback.run(Component, Graphics) line: 39
GraphicsCallback$PaintCallback(SunGraphicsCallback).runOneComponent(Component, Rectangle, Graphics, Shape, int) line: 78
GraphicsCallback$PaintCallback(SunGraphicsCallback).runComponents(Component[], Graphics, int) line: 115
JFrame(Container).paint(Graphics) line: 1967
JFrame(Window).paint(Graphics) line: 3867
RepaintManager.paintDirtyRegions(Map<Component,Rectangle>) line: 781
RepaintManager.paintDirtyRegions() line: 728
RepaintManager.prePaintDirtyRegions() line: 677
RepaintManager.access$700(RepaintManager) line: 59
RepaintManager$ProcessingRunnable.run() line: 1621
InvocationEvent.dispatch() line: 251
EventQueue.dispatchEventImpl(AWTEvent, Object) line: 705
EventQueue.access$000(EventQueue, AWTEvent, Object) line: 101
EventQueue$3.run() line: 666
EventQueue$3.run() line: 664
AccessController.doPrivileged(PrivilegedAction<T>, AccessControlContext) line: not available [native method]
ProtectionDomain$1.doIntersectionPrivilege(PrivilegedAction<T>, AccessControlContext, AccessControlContext) line: 76
EventQueue.dispatchEvent(AWTEvent) line: 675
EventDispatchThread.pumpOneEventForFilters(int) line: 211
EventDispatchThread.pumpEventsForFilter(int, Conditional, EventFilter) line: 128
EventDispatchThread.pumpEventsForHierarchy(int, Conditional, Component) line: 117
EventDispatchThread.pumpEvents(int, Conditional) line: 113
EventDispatchThread.pumpEvents(Conditional) line: 105
EventDispatchThread.run() line: 90
The Graphics parameter comes from here:
RepaintManager.paintDirtyRegions(Map) line: 781
The snippet involved is the following:
Graphics g = JComponent.safelyGetGraphics(
dirtyComponent, dirtyComponent);
// If the Graphics goes away, it means someone disposed of
// the window, don't do anything.
if (g != null) {
g.setClip(rect.x, rect.y, rect.width, rect.height);
try {
dirtyComponent.paint(g); // This will eventually call paintComponent()
} finally {
g.dispose();
}
}
If you take a look at it, you will see that it retrieve the graphics from the JComponent itself (indirectly with javax.swing.JComponent.safelyGetGraphics(Component, Component)
) which itself takes it eventually from its first "Heavyweight parent" (clipped to the component bounds) which it self takes it from its corresponding native resource.
Regarding the fact that you have to cast the Graphics
to a Graphics2D
, it just happens that when working with the Window Toolkit, the Graphics
actually extends Graphics2D
, yet you could use other Graphics
which do "not have to" extends Graphics2D
(it does not happen very often but AWT/Swing allows you to do that).
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
class TestPaint extends JPanel {
public TestPaint() {
setBackground(Color.WHITE);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(0, 0, getWidth(), getHeight());
}
public static void main(String[] args) {
JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setSize(300, 300);
jFrame.add(new TestPaint());
jFrame.setVisible(true);
}
}
I think this is the easy way to open a URL using this function
webbrowser.open_new_tab(url)
Javascript is single threaded, hence the page blocking behaviour. You can use the deferred/promise approach suggested by others, but the most basic way would be to use window.setTimeout
. E.g.
function checkFlag() {
if(flag == false) {
window.setTimeout(checkFlag, 100); /* this checks the flag every 100 milliseconds*/
} else {
/* do something*/
}
}
checkFlag();
Here is a good tutorial with further explanation: Tutorial
EDIT
As others pointed out, the best way would be to re-structure your code to use callbacks. However, this answer should give you an idea how you can 'simulate' an asynchronous behaviour with window.setTimeout
.
If you want your block to return a useful value (e.g. when using #map
, #inject
, etc.), next
and break
also accept an argument.
Consider the following:
def contrived_example(numbers)
numbers.inject(0) do |count, x|
if x % 3 == 0
count + 2
elsif x.odd?
count + 1
else
count
end
end
end
The equivalent using next
:
def contrived_example(numbers)
numbers.inject(0) do |count, x|
next count if x.even?
next (count + 2) if x % 3 == 0
count + 1
end
end
Of course, you could always extract the logic needed into a method and call that from inside your block:
def contrived_example(numbers)
numbers.inject(0) { |count, x| count + extracted_logic(x) }
end
def extracted_logic(x)
return 0 if x.even?
return 2 if x % 3 == 0
1
end
An R solution using nested loops:
# Create phone pad
two <- c("A", "B", "C")
three <- c("D", "E", "F")
four <- c("G", "H", "I")
five <- c("J", "K", "L")
six <- c("M", "N", "O", "P")
seven <- c("Q", "R", "S")
eight <- c("T", "U", "V")
nine <- c("W", "X", "Y", "Z")
# Choose three numbers
number_1 <- two
number_2 <- three
number_3 <- six
# create an object to save the combinations to
combinations <- NULL
# Loop through the letters in number_1
for(i in number_1){
# Loop through the letters in number_2
for(j in number_2){
# Loop through the letters in number_3
for(k in number_3){
# Add each of the letters to the combinations object
combinations <- c(combinations, paste0(i, j, k))
}
}
}
# Print all of the possible combinations
combinations
I posted another, more bizarre R solution using more loops and sampling on my blog.
@inoabrian solution above worked for me. I ran into a situation where I would refresh my page and my hidden element would reappear on my page. Here's what I did to resolve it.
export class FooterComponent implements OnInit {
public showJoinTodayBtn: boolean = null;
ngOnInit() {
if (condition is true) {
this.showJoinTodayBtn = true;
} else {
this.showJoinTodayBtn = false;
}
}
In addition to Christopher's answer.
If you need to count total size of versioned bucket use:
aws s3api list-object-versions --bucket BUCKETNAME --output json --query "[sum(Versions[].Size)]"
It counts both Latest and Archived versions.
I was able to resolve my problem of the missing acceleration with the following workflow on Windows 10, Lenovo, Intel Core i7 CPU:
Changed to the HAXM setup folder: C:\Users\\AppData\Local\Android\Sdk\extras\intel\Hardware_Accelerated_Execution_Manager
Opened a cmd (MS-DOS) shell Window and executed haxm_check.exe
to check whether CPU supports HAXM - it outputs in my case:
VT support -- yes
NX support -- yes
So, I knew this most be a setup problem. So, I started the setup program intelhaxm-android.exe
in the same folder with Admin account and removed the installed components. After that, I've attempted to re-install with the same setup program and got this output:
So, I went into the CPU section of the BIOS and turned on acceleration/Virtualization - went back to the setup program and re-ran it, this time I was pleased to see this output:
After that, I restarted Android Studio and used Tools>AVD Manager to define a new image for an emulator. I was then able to see the emulator starting up succesfully by clicking the play button in the list of emulators in the AVD Manager's list:
or by - Opening a sample project that compiles OK - using File > Sync Project with Gradle Files (to build all artifacts) - Select the app item in the Android (TW) and click Run > Run 'app' - Select the previously configured Emaulator showed me this :-)
Hope this helps to troubleshoot others with their problems that are really caused by a bad setup implementation since the missing acceleration option was silently swallowed by the Android Studio setup program ... :-(
Just use below method with two Date
objects. If you want to pass current date, just pass new Date()
as a second parameter as it is initialised with current time.
public String getDateDiffString(Date dateOne, Date dateTwo)
{
long timeOne = dateOne.getTime();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
return "dateTwo is " + delta + " days after dateOne";
}
else {
delta *= -1;
return "dateTwo is " + delta + " days before dateOne";
}
}
Also, apart from from number of days, if, you want other parameter difference too, use below snippet,
int year = delta / 365;
int rest = delta % 365;
int month = rest / 30;
rest = rest % 30;
int weeks = rest / 7;
int days = rest % 7;
P.S Code is entirely taken from an SO answer.
I did a quick experiment after looking at a number of potential solutions all over the place. This is what I ended up with:
Use a FULL OUTER JOIN:
select
a.col_a,
a.col_b,
b.col_c
from
(select col_a,col_bfrom tab1) a
join
(select col_a,col_cfrom tab2) b
on a.col_a= b.col_a
If you are using Dot.Net then the code you need is
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)
Click my name if you want the code to delete these files plus FireFox temp files and Flash shared object/Flash Cookies
Assuming SQL Server 2000, the following StackOverflow question should address your problem.
If using SQL Server 2005/2008, you can use the following code (taken from here):
select cast(replace(cast(myntext as nvarchar(max)),'find','replace') as ntext)
from myntexttable
This problem was created by a regression in a recent release. You can find the pull request that fixes this problem at https://github.com/facebook/react-native-fbsdk/pull/339
Within Nano use Ctrl+O to save and Ctrl+X to exit if you were wondering
Need help reading and writing text file using vbscript - Dev Shed
VBScript - FileSystemObject
http://ezinearticles.com/?VBScript---FileSystemObject&id=294348
You could also use a StringVar
variable, even if it's not strictly necessary:
v = StringVar()
e = Entry(master, textvariable=v)
e.pack()
v.set("a default value")
s = v.get()
For more information, see this page on effbot.org.
To translate your *nix style command script to windows/command batch style it would go like this:
SET PROJ_HOME=%USERPROFILE%/proj/111
SET PROJECT_BASEDIR=%PROJ_HOME%/exercises/ex1
mkdir "%PROJ_HOME%"
mkdir on windows doens't have a -p parameter : from the MKDIR /? help:
MKDIR creates any intermediate directories in the path, if needed.
which basically is what mkdir -p (or --parents for purists) on *nix does, as taken from the man guide
In tandem with what Pedro Fontez said a few replies up, you seemed to never call the sys module initially, nor did you manage to stick the required () at the end of sys.exit:
so:
import sys
and when finished:
sys.exit()
OpenJDK is a reference model and open source, while Oracle JDK is an implementation of the OpenJDK and is not open source. Oracle JDK is more stable than OpenJDK.
OpenJDK is released under GPL v2 license whereas Oracle JDK is licensed under Oracle Binary Code License Agreement.
OpenJDK and Oracle JDK have almost the same code, but Oracle JDK has more classes and some bugs fixed.
So if you want to develop enterprise/commercial software I would suggest to go for Oracle JDK, as it is thoroughly tested and stable.
I have faced lot of problems with application crashes using OpenJDK, which are fixed just by switching to Oracle JDK
If you have an AMD Ryzen processor in your computer you need the following setup requirements to be in place:
Note:There is Hyper-V features... You should enable Windows Hypervisor Platform not Hyper-V. Windows Hypervisor Platform is at the bottom
After conditions done avd x86 work without haxm install
In PhoneGap 3.4.0 you can call:
cordova build android --release
If you have set up the 'ant.properties' file in 'platforms/android' directory like the following:
key.store=/Path/to/KeyStore/myapp-release-key.keystore
key.alias=myapp
Then you will be prompted for your keystore password and the output file (myapp-release.apk) ends up in the 'platforms/android/ant-build' directory already signed and aligned and ready to deploy.
You should need to convert your PHP array to javascript array using PHP syntax json_encode. json_encode convert PHP array to JSON string
Single Dimension PHP array to javascript array
<?php
var $itemsarray= array("Apple", "Bear", "Cat", "Dog");
?>
<script>
var items= <?php echo json_encode($itemsarray); ?>;
console.log(items[2]); // Output: Bear
// OR
alert(items[0]); // Output: Apple
</script>
Multi Dimension PHP array to javascript array
<?php
var $itemsarray= array(
array('name'='Apple', 'price'=>'12345'),
array('name'='Bear', 'price'=>'13344'),
array('name'='Potato', 'price'=>'00440')
);
?>
<script>
var items= <?php echo json_encode($itemsarray); ?>;
console.log(items[1][name]); // Output: Bear
// OR
alert(items[0][price]); // Output: Apple
</script>
For more detail, you can also check php array to javascript array
Here's a pure jQuery solution, but it's rather messy:
var div_height = $(this).height();
var vertical_div_top_position = $(this).offset().top;
var lastchild_height = $(this).children('p:last-child').height();
var vertical_lastchild_top_position = $(this).children('p:last-child').offset().top;
var vertical_lastchild_bottom_position = lastchild_height + vertical_lastchild_top_position;
var real_height = vertical_lastchild_bottom_position - vertical_div_top_position;
if (real_height > div_height){
//overflow div
}
Abstract classes and interfaces are semantically different, although their usage can overlap.
An abstract class is generally used as a building basis for similar classes. Implementation that is common for the classes can be in the abstract class.
An interface is generally used to specify an ability for classes, where the classes doesn't have to be very similar.
Use the AutoSize and AutoSizeMode properties.
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.autosize.aspx
An example:
private void Form1_Load(object sender, EventArgs e)
{
// no smaller than design time size
this.MinimumSize = new System.Drawing.Size(this.Width, this.Height);
// no larger than screen size
this.MaximumSize = new System.Drawing.Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, (int)System.Windows.SystemParameters.PrimaryScreenHeight);
this.AutoSize = true;
this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
// rest of your code here...
}
Use the PS command in a little different way to ignore child process as well:
ps -eaf | grep -v grep | grep $PROCESS | grep -v $$
try the following query:
SELECT ID,
Name
INTO #tempTable
FROM Table
SELECT *
FROM #tempTable
WHERE ID = 1
It doesn't need to declare table.
Show as decimal Select ifnull(format(100.00, 1, 'en_US'), 0) 100.0
Show as Percentage Select concat(ifnull(format(100.00, 0, 'en_US'), 0), '%') 100%
You can use the mixin make-col-ready
and set the gutter width to zero:
@include make-col-ready(0);
The scp operation is separate from your ssh login. You will need to issue an ssh command similar to the following one assuming jdoe is account with which you log into the remote system and that the remote system is example.com:
scp [email protected]:/somedir/table /home/me/Desktop/.
The scp command issued from the system where /home/me/Desktop resides is followed by the userid for the account on the remote server. You then add a ":" followed by the directory path and file name on the remote server, e.g., /somedir/table. Then add a space and the location to which you want to copy the file. If you want the file to have the same name on the client system, you can indicate that with a period, i.e. "." at the end of the directory path; if you want a different name you could use /home/me/Desktop/newname, instead. If you were using a nonstandard port for SSH connections, you would need to specify that port with a "-P n" (capital P), where "n" is the port number. The standard port is 22 and if you aren't specifying it for the SSH connection then you won't need that.
To have the code within one line, try this:
startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:123456789")));
along with the proper manifest permission:
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
Hope this helps!
For me that function worked:
private static JSONObject concatJSONS(JSONObject json, JSONObject obj) {
JSONObject result = new JSONObject();
for(Object key: json.keySet()) {
System.out.println("adding " + key + " to result json");
result.put(key, json.get(key));
}
for(Object key: obj.keySet()) {
System.out.println("adding " + key + " to result json");
result.put(key, obj.get(key));
}
return result;
}
(notice) - this implementation of concataion of json is for import org.json.simple.JSONObject;
Do you mean that for a select element with an id of "next" you need to perform some specific script?
$("#next").change(function(){
//enter code here
});
You can try this:
Me.cbo1.Text = Me.Cbo1.Items(0).Tostring
I see the question is about Express Edition, but this topic is easy to pop up in Google Search, and doesn't have a solution for other editions.
So. If you run into this problem with any VS Edition except Express, you can rerun installation and include MFC files.
A full example ?. Run this code : (NB: This example is best run in the console and not from within an IDE, since the System.console() method might return null in that case.)
import java.io.Console;
public class Main {
public void passwordExample() {
Console console = System.console();
if (console == null) {
System.out.println("Couldn't get Console instance");
System.exit(0);
}
console.printf("Testing password%n");
char[] passwordArray = console.readPassword("Enter your secret password: ");
console.printf("Password entered was: %s%n", new String(passwordArray));
}
public static void main(String[] args) {
new Main().passwordExample();
}
}
did you try this ?
$("#yourdiv").load(url, function(){
your functions goes here !!!
});
I'm assuming you mean that you don't care which row is used to obtain the title
, id
, and commentname
values (you have "rob" for all of the rows, but I don't know if that is actually something that would be enforced or not in your data model). If so, then you can use windowing functions to return the first row for a given email address:
select
id,
title,
email,
commentname
from
(
select
*,
row_number() over (partition by email order by id) as RowNbr
from YourTable
) source
where RowNbr = 1
I see this is a little old, but there might be a better solution here.
When you want a string, but you want the string to only match certain values, you can use enums.
For example:
enum Fruit {
Orange = "Orange",
Apple = "Apple",
Banana = "Banana"
}
let myFruit: Fruit = Fruit.Banana;
Now you'll know that no matter what, myFruit will always be the string "Banana" (Or whatever other enumerable value you choose). This is useful for many things, whether it be grouping similar values like this, or mapping user-friendly values to machine-friendly values, all while enforcing and restricting the values the compiler will allow.
1st. uninstall antivirus.
I had avast but I believe AVG also affects it and probably many more, just turning off the the anti virus dose not work, it has to be completely uninstalled and then the computer restarted, then run the install of the Intel HAXM, once this is complete the anti virus can be reinstalled like normal.
2nd. turn off hyper-V.
This is a setting only found on the windows Pro and enterprise, this is used to create windows mobile apps, but is you are using other software's like HAXM this needs to be off, to do this go to, control panel, all control panel items, Programs and Features, turn windows features on or off. then un-tick hyper-V
read
won't read from a pipe (or possibly the result is lost because the pipe creates a subshell). You can, however, use a here string in Bash:
$ read a b c <<< $(echo 1 2 3)
$ echo $a $b $c
1 2 3
But see @chepner's answer for information about lastpipe
.
Not glob
, but here's another way using a list comprehension:
extensions = 'txt mdown markdown'.split()
projectFiles = [f for f in os.listdir(projectDir)
if os.path.splitext(f)[1][1:] in extensions]
The image trick is cool but in my tests it was loading before some ajax calls I wanted to be complete.
The proper solution in 2017 is to use a worker (http://caniuse.com/#feat=webworkers).
The worker will look like:
/**
* This function performs a synchronous request
* and returns an object contain informations about the download
* time and size
*/
function measure(filename) {
var xhr = new XMLHttpRequest();
var measure = {};
xhr.open("GET", filename + '?' + (new Date()).getTime(), false);
measure.start = (new Date()).getTime();
xhr.send(null);
measure.end = (new Date()).getTime();
measure.len = parseInt(xhr.getResponseHeader('Content-Length') || 0);
measure.delta = measure.end - measure.start;
return measure;
}
/**
* Requires that we pass a base url to the worker
* The worker will measure the download time needed to get
* a ~0KB and a 100KB.
* It will return a string that serializes this informations as
* pipe separated values
*/
onmessage = function(e) {
measure0 = measure(e.data.base_url + '/test/0.bz2');
measure100 = measure(e.data.base_url + '/test/100K.bz2');
postMessage(
measure0.delta + '|' +
measure0.len + '|' +
measure100.delta + '|' +
measure100.len
);
};
The js file that will invoke the Worker:
var base_url = PORTAL_URL + '/++plone++experimental.bwtools';
if (typeof(Worker) === 'undefined') {
return; // unsupported
}
w = new Worker(base_url + "/scripts/worker.js");
w.postMessage({
base_url: base_url
});
w.onmessage = function(event) {
if (event.data) {
set_cookie(event.data);
}
};
Code taken from a Plone package I wrote:
You can also use the helper method Exists over the Mongo operator $exists
ME.find()
.exists('pictures')
.where('pictures').ne([])
.sort('-created')
.limit(10)
.exec(function(err, results){
...
});
Here is a more easy solution. just remove the "navbar-nav" class and add "nav-justified".
I know this is very late, but maybe this will help someone else.
I use a Cancel button to return to the referring url. In the View, try adding this:
@{
ViewBag.Title = "Page title";
Layout = "~/Views/Shared/_Layout.cshtml";
if (Request.UrlReferrer != null)
{
string returnURL = Request.UrlReferrer.ToString();
ViewBag.ReturnURL = returnURL;
}
}
Then you can set your buttons href like this:
<a href="@ViewBag.ReturnURL" class="btn btn-danger">Cancel</a>
Other than that, the update by Jason Enochs works great!
You can also use the good old micro clearfix for this.
#container::before, #container::after{
content: ' ';
display: table;
}
See updated fiddle: http://jsfiddle.net/XB9wX/97/
I belive this is the easiest way:
org.apache.commons.io.FileUtils.readFileToByteArray(file);
Adding one more point to the answer.
.EqualsTo()
method gives you provision to compare against culture and case sensitive.
Reference ServiceBase
to your class and put the below code in the OnStart
event:
Constants.TimeIntervalValue = 1
(hour)..Ideally you should set this value in config file.
StartSendingMails = function name you want to run in the application.
protected override void OnStart(string[] args)
{
// It tells in what interval the service will run each time.
Int32 timeInterval = Int32.Parse(Constants.TimeIntervalValue) * 60 * 60 * 1000;
base.OnStart(args);
TimerCallback timerDelegate = new TimerCallback(StartSendingMails);
serviceTimer = new Timer(timerDelegate, null, 0, Convert.ToInt32(timeInterval));
}
This operator allows you to determine the type of an object.
It returns a boolean
value.
For example
package test;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
public class instanceoftest
{
public static void main(String args[])
{
Map m=new HashMap();
System.out.println("Returns a boolean value "+(m instanceof Map));
System.out.println("Returns a boolean value "+(m instanceof HashMap));
System.out.println("Returns a boolean value "+(m instanceof Object));
System.out.println("Returns a boolean value "+(m instanceof Date));
}
}
the output is:
Returns a boolean value true
Returns a boolean value true
Returns a boolean value true
Returns a boolean value false
The request is printed in a request.txt with details
$ch = curl_init();
$f = fopen('request.txt', 'w');
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_VERBOSE => 1,
CURLOPT_STDERR => $f,
));
$response = curl_exec($ch);
fclose($f);
curl_close($ch);
You can also use curl_getinfo() function.
You don't need to use JsonObject
. You should be using Gson to convert to/from JSON strings and your own Java objects.
See the Gson User Guide:
(Serialization)
Gson gson = new Gson(); gson.toJson(1); // prints 1 gson.toJson("abcd"); // prints "abcd" gson.toJson(new Long(10)); // prints 10 int[] values = { 1 }; gson.toJson(values); // prints [1]
(Deserialization)
int one = gson.fromJson("1", int.class); Integer one = gson.fromJson("1", Integer.class); Long one = gson.fromJson("1", Long.class); Boolean false = gson.fromJson("false", Boolean.class); String str = gson.fromJson("\"abc\"", String.class); String anotherStr = gson.fromJson("[\"abc\"]", String.class)
Using the FM
format model modifier to get close, as you won't get the trailing zeros after the decimal separator; but you will still get the separator itself, e.g. 50.
. You can use rtrim
to get rid of that:
select to_char(a, '99D90'),
to_char(a, '90D90'),
to_char(a, 'FM90D99'),
rtrim(to_char(a, 'FM90D99'), to_char(0, 'D'))
from (
select 50 a from dual
union all select 50.57 from dual
union all select 5.57 from dual
union all select 0.35 from dual
union all select 0.4 from dual
)
order by a;
TO_CHA TO_CHA TO_CHA RTRIM(
------ ------ ------ ------
.35 0.35 0.35 0.35
.40 0.40 0.4 0.4
5.57 5.57 5.57 5.57
50.00 50.00 50. 50
50.57 50.57 50.57 50.57
Note that I'm using to_char(0, 'D')
to generate the character to trim, to match the decimal separator - so it looks for the same character, ,
or .
, as the first to_char
adds.
The slight downside is that you lose the alignment. If this is being used elsewhere it might not matter, but it does then you can also wrap it in an lpad
, which starts to make it look a bit complicated:
...
lpad(rtrim(to_char(a, 'FM90D99'), to_char(0, 'D')), 6)
...
TO_CHA TO_CHA TO_CHA RTRIM( LPAD(RTRIM(TO_CHAR(A,'FM
------ ------ ------ ------ ------------------------
.35 0.35 0.35 0.35 0.35
.40 0.40 0.4 0.4 0.4
5.57 5.57 5.57 5.57 5.57
50.00 50.00 50. 50 50
50.57 50.57 50.57 50.57 50.57
If you have a handle to an existing fragment you can just replace it with the fragment's ID.
Example in Kotlin:
fun aTestFuction() {
val existingFragment = MyExistingFragment() //Get it from somewhere, this is a dirty example
val newFragment = MyNewFragment()
replaceFragment(existingFragment, newFragment, "myTag")
}
fun replaceFragment(existing: Fragment, new: Fragment, tag: String? = null) {
supportFragmentManager.beginTransaction().replace(existing.id, new, tag).commit()
}
You could use gettimeofday at the start and end of your method and then difference the two return structs. You'll get a structure like the following:
struct timeval {
time_t tv_sec;
suseconds_t tv_usec;
}
EDIT: As the two comments below suggest, clock_gettime(CLOCK_MONOTONIC) is a much better choice if you have it available, which should be almost everywhere these days.
EDIT: Someone else commented that you can also use modern C++ with std::chrono::high_resolution_clock, but that isn't guaranteed to be monotonic. Use steady_clock instead.
Use pandas.Series.dt.day_name()
, since pandas.Timestamp.weekday_name
has been deprecated:
import pandas as pd
df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])
df['day_of_week'] = df['my_dates'].dt.day_name()
Output:
my_dates myvals day_of_week
0 2015-01-01 1 Thursday
1 2015-01-02 2 Friday
2 2015-01-03 3 Saturday
As user jezrael points out below, dt.weekday_name
was added in version 0.18.1
Pandas Docs
import pandas as pd
df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])
df['day_of_week'] = df['my_dates'].dt.weekday_name
Output:
my_dates myvals day_of_week
0 2015-01-01 1 Thursday
1 2015-01-02 2 Friday
2 2015-01-03 3 Saturday
Use this:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.dayofweek.html
See this:
Get weekday/day-of-week for Datetime column of DataFrame
If you want a string instead of an integer do something like this:
import pandas as pd
df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])
df['day_of_week'] = df['my_dates'].dt.dayofweek
days = {0:'Mon',1:'Tues',2:'Weds',3:'Thurs',4:'Fri',5:'Sat',6:'Sun'}
df['day_of_week'] = df['day_of_week'].apply(lambda x: days[x])
Output:
my_dates myvals day_of_week
0 2015-01-01 1 Thurs
1 2015-01-02 2 Fri
2 2015-01-01 3 Thurs
I found this old Thread while google'ing for generate_204 as Android seems to use this to determine if the wlan is open (response 204 is received) closed (no response at all) or blocked (redirect to captive portal is present). In that case a notification is shown that a log-in to WiFi is required...
If the formula already exists in a cell you can fill it down as follows:
On Mac, use CMD instead of CTRL.
An alternative if the formula is in the first cell of a column:
i don't know if it's the answer to your question but you can try setting the background color in the xml layout like this. It is easy, it always works
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="0xfff00000"
>
<TextView
android:id="@+id/text_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
You can also do more fancy things with backgrounds by creating an xml background file with gradients which are cool and semi transparent, and refer to it for other use see example below:
the background.xml layout
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<gradient
android:angle="90"
android:startColor="#f0000000"
android:endColor="#ff444444"
android:type="linear" />
</shape>
</item>
</selector>
your layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@layout/background"
>
<TextView
android:id="@+id/text_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
There is the option to use OleDB
and use the Excel sheets like datatables in a database...
Just an example.....
string con =
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\temp\test.xls;" +
@"Extended Properties='Excel 8.0;HDR=Yes;'";
using(OleDbConnection connection = new OleDbConnection(con))
{
connection.Open();
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
using(OleDbDataReader dr = command.ExecuteReader())
{
while(dr.Read())
{
var row1Col0 = dr[0];
Console.WriteLine(row1Col0);
}
}
}
This example use the Microsoft.Jet.OleDb.4.0
provider to open and read the Excel file. However, if the file is of type xlsx (from Excel 2007 and later), then you need to download the Microsoft Access Database Engine components and install it on the target machine.
The provider is called Microsoft.ACE.OLEDB.12.0;
. Pay attention to the fact that there are two versions of this component, one for 32bit and one for 64bit. Choose the appropriate one for the bitness of your application and what Office version is installed (if any). There are a lot of quirks to have that driver correctly working for your application. See this question for example.
Of course you don't need Office installed on the target machine.
While this approach has some merits, I think you should pay particular attention to the link signaled by a comment in your question Reading excel files from C#. There are some problems regarding the correct interpretation of the data types and when the length of data, present in a single excel cell, is longer than 255 characters
I was working with ng-grid
and needed to to multiple column sorting on an array of records returned from an API, so I came up with this nifty, dynamic multi-sort function.
First of all, ng-grid
fires an "event" for "ngGridSorted" and passes this structure back, describing the sort:
sortData = {
columns: DOM Element,
directions: [], //Array of string values desc or asc. Each index relating to the same index of fields
fields: [], //Array of string values
};
So I built a function that will dynamically generate a sort function based on the sortData
as shown above (Don't be scared by the scroll bar! It's only about 50 lines long! Also, I'm sorry about the slop. It prevented a horizontal scrollbar!):
function SortingFunction(sortData)
{
this.sortData = sortData;
this.sort = function(a, b)
{
var retval = 0;
if(this.sortData.fields.length)
{
var i = 0;
/*
Determine if there is a column that both entities (a and b)
have that are not exactly equal. The first one that we find
will be the column we sort on. If a valid column is not
located, then we will return 0 (equal).
*/
while( ( !a.hasOwnProperty(this.sortData.fields[i])
|| !b.hasOwnProperty(this.sortData.fields[i])
|| (a.hasOwnProperty(this.sortData.fields[i])
&& b.hasOwnProperty(this.sortData.fields[i])
&& a[this.sortData.fields[i]] === b[this.sortData.fields[i]])
) && i < this.sortData.fields.length){
i++;
}
if(i < this.sortData.fields.length)
{
/*
A valid column was located for both entities
in the SortData. Now perform the sort.
*/
if(this.sortData.directions
&& i < this.sortData.directions.length
&& this.sortData.directions[i] === 'desc')
{
if(a[this.sortData.fields[i]] > b[this.sortData.fields[i]])
retval = -1;
else if(a[this.sortData.fields[i]] < b[this.sortData.fields[i]])
retval = 1;
}
else
{
if(a[this.sortData.fields[i]] < b[this.sortData.fields[i]])
retval = -1;
else if(a[this.sortData.fields[i]] > b[this.sortData.fields[i]])
retval = 1;
}
}
}
return retval;
}.bind(this);
}
I then sort the results of my API (results
) like so:
results.sort(new SortingFunction(sortData).sort);
I hope somebody else enjoys this solution as much as I do! Thanks!
Just
$("#your_item").trigger("click");
using .trigger() you can simulate many type of events, just passing it as the parameter.
I finally found the problem. The error was not the good one.
Apparently, Ole DB source have a bug that might make it crash and throw that error. I replaced the OLE DB destination with a OLE DB Command with the insert statement in it and it fixed it.
The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/
Strange Bug, Hope it will help other people.
See this; run
sudo update-java-alternatives --list
to list off all the Java installations on a machine by name and directory, and then run
sudo update-java-alternatives --set [JDK/JRE name e.g. java-8-oracle]
to choose which JRE/JDK to use.
If you want to use different JDKs/JREs for each Java task, you can run update-alternatives to configure one java executable at a time; you can run
sudo update-alternatives --config java[Tab]
to see the Java commands that can be configured (java, javac, javah, javaws, etc). And then
sudo update-alternatives --config [javac|java|javadoc|etc.]
will associate that Java task/command to a particular JDK/JRE.
You may also need to set JAVA_HOME for some applications: from this answer you can use
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")
for JREs, or
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:jre/bin/java::")
for JDKs.
you could connect all the data you need from the file to a single string, and in the excel sheet seperate it with text to column. here is an example i did for same issue, enjoy:
Sub CP()
Dim ToolFile As String
Cells(3, 2).Select
For i = 0 To 5
r = ActiveCell.Row
ToolFile = Cells(r, 7).Value
On Error Resume Next
ActiveCell.Value = CP_getdatta(ToolFile)
'seperate data by "-"
Selection.TextToColumns Destination:=Range("C3"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
:="-", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
Cells(r + 1, 2).Select
Next
End Sub
Function CP_getdatta(ToolFile As String) As String
Workbooks.Open Filename:=ToolFile, UpdateLinks:=False, ReadOnly:=True
Range("A56000").Select
Selection.End(xlUp).Select
x = CStr(ActiveCell.Value)
ActiveCell.Offset(0, 20).Select
Selection.End(xlToLeft).Select
While IsNumeric(ActiveCell.Value) = False
ActiveCell.Offset(0, -1).Select
Wend
' combine data to 1 string
CP_getdatta = CStr(x & "-" & ActiveCell.Value)
ActiveWindow.Close False
End Function
If you search for an image base-64 converter, you can embed some small image texture files as code into your @import url('')
section of code. It will look like a lot of code; but at least all your data is now stored locally - rather than having to call a separate resource to load the image.
Example link: http://www.base64-image.de/
When I take a file from my own inventory of a simple icon in PNG format, and convert it to base-64, it looks like this in my CSS:
url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAm0SURBVHjaRFdLrF1lFf72++xzzj33nMPt7QuhxNJCY4smGomKCQlWxMSJgQ4dyEATE3FCSDRxjnHiwMTUAdHowIGJOqBEg0RDCCESKIgCWtqCfd33eeyz39vvW/vcctvz2nv/61/rW9/61vqd7CIewMT5VlnChf059t40QBwB7io+vjx3kczb++D9Tof3x1xWNu39hP9nHhxH62t0u7zWb9rFtl73G1veXamrs98rf+5Pbjnnnv5p+IPNiQvXreF7AZ914bgOv/PBOIDH767HH/DgO4F9d7hLHPkYrIRw+d1x2/sufBRViboCgkCvBmmWcw2v5zWStABv4+iBOe49enXqb2x4a79+wYfidx2XRgP4vm8QBLTgBx4CLva4QRjyO+9FUUjndD1ATJjkgNaEoW/R6ZmyqgxFvU3nCTzaqLhzURSoGWJ82cN9d3r3+Z5TV6srni30fAdNXSP0a3ToiCHvVuh1mQsua+gl98Zqz0PNEIOAv4OidZToNU1OG8TAbUC7qGirdV6bV0SGa3gvISKrPUcoFj5xt/S4xDtktFVZMRrXItDiKAxRFiVh9HH2y+s05OHVizvod+mJ4yEnebSOROCzAfJ5ZgRxGHmXzwQ+U+aKFJ5oQ8fllGfp0XM+f0OsaaoaHnPq8U4YtFAqz0rL+riDR7+4guPrGaK4i8+dWMdotYdBf8CIPaatgzCKEHdi7hPRTg9uvIoLL76DC39+DcN+F4s8ZaAOCkYfEOmCQenPl3ftho4xmxcYfcmcCZGAMALjUYBvf2WM3//pDcwZoVKSzyNUowHGa2Pc0R9iOFjFcMSHhwxtQHNjDye+8Bht1Hj+wpsCy3i0N19gY3sPZ+5ty8uXVyFh8jyXm7EW+RkwZ47jmjNFJXKEGJ06g8ebDi5vptjYnWJvj68iR87vO2R3b0bHtmck4jYOjVYQuR8gHr2L73z3NN68eBm3NqbGo7gTMoAu6qatbV8wi70iiCL2/ZaQIfPZYf59eiBYcfdXMbj7NJ55+Cf4x1sfYkUiYSZ3jbie267LyKFPfXKI809/BjsfXMPpPMPjZ4/g2fNvg5mywEaDFa5JSNpGDihSMZU64Dlkr2uElCqVJFhJV4UEsMLXacTdIY4cSCwNYrdSKEOeZ1Q2Qv7n6iZ+99IlPHCwwot/3cDxU/dynWdk3v9ToJVs101lP1zWrgzJjGwpFULBzWs0t6WwINNd3HnwgPHGZbUIpZIIqFpqcqcbx2R4jJcv3sLdD6Z4+587JG6Fg+MAl6+1xAZajShLiR/Z4Wszwh9zw7gTWemYoFgZtvxgUsyJcOl5oOtcW0uwpHKMTrbmSYLVfoyk6OLUqZM4uNbF1asf4cBKTkHKuGll61MqYl0JXXrU68ao5RjRUNk5vpQtMkmuyQ1Yrb7H15qRJwj2hUvpkxPUfTpeSX+ZljTNMZmXOHLsJJ48t4KbWzso329w4ZUNOuuaGrpMiVBw95uPR0csWhrsdTv2aSXK+vYIPfK/86m/8VpDKe7cblAtOjClExpCQtfSJMVOcBL+I9/A0bMP4cFP32NaoHQrCD2vunddzwTbUqA8Rp2gLUEJDKOS5ktmceMScP1dNpQCi6Tk3gGBabBIMxmhdtS2eV21FRGFEa5f36Ht+4HRw7jnzEOMlmsXKbI8NxQkAf5w6FD3QyNU20Rqay5Mj5GwMS9ZDTf/S+MhTnyiD9w1RK/XwTvv7xqRxKG8rFoSEzUJmch2a3PXCtVY3+tzuwZ50d7LGYhs+8qnOlrJHRtGpM3F8IqkUDRMLzepceNGQjHZxFPfHGJ1MKMTx/DMDz1c/rCy3NdNc1u+hYQSu8gFc2R9Qn8qaVF5v71rhV+r+ZA46myN8iiPJcl+YAQTS8TByZ6Dm9cb7O7usgNu4+T2BJvbazQxREG9EHo5YVUqFWmWMx3FhPc3IG3O0tIqQMaLggZj64aQ5toEo1w7hDLJarBCrBv2SUb1gpSOTCYNtjYqE5QgcrC7UxtitfX/wHIqIs+ThTnuqP8vrvPu83wdxtbNErMkp050DLGcPNCw4jtUuR7FQ4YWWYlzjw5wZJSwZoXEzEpuPkvRFBk0FtQFiZext6eOkdV1GBFTFAStFoiA83RBljfoRZzR/vdvDhA7eOftGerSMfbnRMcjlWwCExOlhjVFZJIU+PqXYqyevAJc2cJ8K8KlzRDFSoXd6RCDO2GbiS83FyusdTJewxP7ha7LeJoVbU/gJr6zg/zyFYRHZnj9YorabTki5CRGxgFYvgoSMVBxYpYGWB0dZ+ncg9d/VeKRJ1/FGtuxmF4pHyp7Qd9McezoHTh8IG51QE6oFMtWB+KY82J3gX+9N8MJ9xZeeSNDh2gusgwpn8mLZXUIxsDGk8aYmU83We8sn/EYvf4Yp08cZvPpGbzyuVr2CxMvEyENpLCB0+Y93q8KDbcVIke8qXGpW+Kt9xc2U+oZIZCXRTsRzea+abgm2YybTKc587YH8LNOGoyHKrvISrGNHuaIUNPoXTF9FYlbL0tRk9WMLD60RpImFCmOYn95rcH2XoW1VXc5Z/LVOK0QZWllRhSWCDWdpsg/ShAOK+xMBtie5lailSlcKzgWad1+qnekWWojuSon10heB3jqCYpYlmD98AjPPbdLojsMsK0UNSH9k5KqB1tX23dCjeTGjRzhdoED4QTff2Idh8YhK8CxuVgGoDLT6KZzAk8navN1vocimZCYKdaHCe5f2+AGfTz7h5zzAW2NQrKfaRJqFZYtXkLEN83tIcdwTbJXthwMj64jM/hdPPZZ1rWXstY9SjbTxTyio5ZI/uocEPF3OCIAh0kEcifZQbO7wT4Q4Jd/3MbPfnuNLbnHlFXYP1KpAjTsiEu+8uiYmHh2FPvx+Q8NSqFScEaUUtoMQQLoWXmuKbu2SmjssKH7MqrkNstzXcnjWsXX0YN944/WFrJlnbO2IWY5lMIOEMkiMxk9cdchu6nGUi6xUr4ko4I9YxmpWozNS/0vjBeVafx+dNZofHdZ722FqOKKsp2GHBNspaCq/e0pdSByLRKeifhZW3cET0U6SIg03ZglqgEV7TGMMxQluzQnijLntdCMS2Z1DlyQS1nRmGhlWeu8KsRxWjscF3itcfz+ILv5tc9vYGui+a6FUP0ey8OymF812qD1WPOATkeSUxMgpklqaNMQS6soVSGu1Xpp3ZTNLsBSQ9oUSIPuO9aQsKj8H/2i+M14cIVV5UZZThrWikhQtOdEhxOqH1ZQI6PysyQdO93q/KdeHbC/hp2P+aG3PG1aiCVahDWIm49p77RHf/LHfeFlvPR/AQYAyMIq/fJRUogAAAAASUVORK5CYII=')
With your texture images, you'll want to employ a similar process.
This question is kind of old and in July 2011 Google released the Compatibility Package, revision 3) which includes the ViewPager
that works with Android 1.6 upwards. The GestureListener
answers posted for this question don't feel very elegant on Android. If you're looking for the code used in switching between photos in the Android Gallery or switching views in the new Play Market app then it's definitely ViewPager
.
Here's some links for more info:
A probably convenient way to enter multi-line strings is by using macro's. This only works if quotes and parentheses are balanced and it does not contain 'top level' comma's:
#define MULTI_LINE_STRING(a) #a
const char *text = MULTI_LINE_STRING(
Using this trick(,) you don't need to use quotes.
Though newlines and multiple white spaces
will be replaced by a single whitespace.
);
printf("[[%s]]\n",text);
Compiled with gcc 4.6 or g++ 4.6, this produces: [[Using this trick(,) you don't need to use quotes. Though newlines and multiple white spaces will be replaced by a single whitespace.]]
Note that the ,
cannot be in the string, unless it is contained within parenthesis or quotes. Single quotes is possible, but creates compiler warnings.
Edit: As mentioned in the comments, #define MULTI_LINE_STRING(...) #__VA_ARGS__
allows the use of ,
.
In PowerShell, the "sc" command is an alias for the Set-Content cmdlet. You can workaround this using the following syntax:
sc.exe config Service obj= user password= pass
Specyfying the .exe extension, PowerShell bypasses the alias lookup.
HTH
protocol AttributedStringComponent {
var text: String { get }
func getAttributes() -> [NSAttributedString.Key: Any]?
}
// MARK: String extensions
extension String: AttributedStringComponent {
var text: String { self }
func getAttributes() -> [NSAttributedString.Key: Any]? { return nil }
}
extension String {
func toAttributed(with attributes: [NSAttributedString.Key: Any]?) -> NSAttributedString {
.init(string: self, attributes: attributes)
}
}
// MARK: NSAttributedString extensions
extension NSAttributedString: AttributedStringComponent {
var text: String { string }
func getAttributes() -> [Key: Any]? {
if string.isEmpty { return nil }
var range = NSRange(location: 0, length: string.count)
return attributes(at: 0, effectiveRange: &range)
}
}
extension NSAttributedString {
convenience init?(from attributedStringComponents: [AttributedStringComponent],
defaultAttributes: [NSAttributedString.Key: Any],
joinedSeparator: String = " ") {
switch attributedStringComponents.count {
case 0: return nil
default:
var joinedString = ""
typealias SttributedStringComponentDescriptor = ([NSAttributedString.Key: Any], NSRange)
let sttributedStringComponents = attributedStringComponents.enumerated().flatMap { (index, component) -> [SttributedStringComponentDescriptor] in
var components = [SttributedStringComponentDescriptor]()
if index != 0 {
components.append((defaultAttributes,
NSRange(location: joinedString.count, length: joinedSeparator.count)))
joinedString += joinedSeparator
}
components.append((component.getAttributes() ?? defaultAttributes,
NSRange(location: joinedString.count, length: component.text.count)))
joinedString += component.text
return components
}
let attributedString = NSMutableAttributedString(string: joinedString)
sttributedStringComponents.forEach { attributedString.addAttributes($0, range: $1) }
self.init(attributedString: attributedString)
}
}
}
let defaultAttributes = [
.font: UIFont.systemFont(ofSize: 16, weight: .regular),
.foregroundColor: UIColor.blue
] as [NSAttributedString.Key : Any]
let marketingAttributes = [
.font: UIFont.systemFont(ofSize: 20.0, weight: .bold),
.foregroundColor: UIColor.black
] as [NSAttributedString.Key : Any]
let attributedStringComponents = [
"pay for",
NSAttributedString(string: "one",
attributes: marketingAttributes),
"and get",
"three!\n".toAttributed(with: marketingAttributes),
"Only today!".toAttributed(with: [
.font: UIFont.systemFont(ofSize: 16.0, weight: .bold),
.foregroundColor: UIColor.red
])
] as [AttributedStringComponent]
let attributedText = NSAttributedString(from: attributedStringComponents, defaultAttributes: defaultAttributes)
do not forget to paste the solution code here
import UIKit
class ViewController: UIViewController {
private weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: .init(x: 40, y: 40, width: 300, height: 80))
label.numberOfLines = 2
view.addSubview(label)
self.label = label
let defaultAttributes = [
.font: UIFont.systemFont(ofSize: 16, weight: .regular),
.foregroundColor: UIColor.blue
] as [NSAttributedString.Key : Any]
let marketingAttributes = [
.font: UIFont.systemFont(ofSize: 20.0, weight: .bold),
.foregroundColor: UIColor.black
] as [NSAttributedString.Key : Any]
let attributedStringComponents = [
"pay for",
NSAttributedString(string: "one",
attributes: marketingAttributes),
"and get",
"three!\n".toAttributed(with: marketingAttributes),
"Only today!".toAttributed(with: [
.font: UIFont.systemFont(ofSize: 16.0, weight: .bold),
.foregroundColor: UIColor.red
])
] as [AttributedStringComponent]
label.attributedText = NSAttributedString(from: attributedStringComponents, defaultAttributes: defaultAttributes)
label.textAlignment = .center
}
}
iterate through the array and check its name value.
RPC Stubs
If you want to use an older version of .net, create your own flag and cast it.
//
// Summary:
// Specifies the security protocols that are supported by the Schannel security
// package.
[Flags]
private enum MySecurityProtocolType
{
//
// Summary:
// Specifies the Secure Socket Layer (SSL) 3.0 security protocol.
Ssl3 = 48,
//
// Summary:
// Specifies the Transport Layer Security (TLS) 1.0 security protocol.
Tls = 192,
//
// Summary:
// Specifies the Transport Layer Security (TLS) 1.1 security protocol.
Tls11 = 768,
//
// Summary:
// Specifies the Transport Layer Security (TLS) 1.2 security protocol.
Tls12 = 3072
}
public Session()
{
System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType)(MySecurityProtocolType.Tls12 | MySecurityProtocolType.Tls11 | MySecurityProtocolType.Tls);
}
As to why this still exists - MS doesn't consider it a priority, and values backwards compatibility over advancing their OS (at least in this instance).
A workaround I use is to use the "short names" for the directories in the path, instead of their standard, human-readable versions. So e.g. for C:\Program Files\
I would use C:\PROGRA~1\
You can find the short name equivalents using dir /x
.
In java.lang.String
, the replace
method either takes a pair of char's or a pair of CharSequence
's (of which String is a subclass, so it'll happily take a pair of String's). The replace
method will replace all occurrences of a char or CharSequence
. On the other hand, the first String
arguments of replaceFirst
and replaceAll
are regular expressions (regex). Using the wrong function can lead to subtle bugs.
The shortest way I've found is this one:
MultiValueMap<String, String> queryParams =
UriComponentsBuilder.fromUriString(url).build().getQueryParams();
UPDATE: UriComponentsBuilder
comes from Spring. Here the link.
Make it
float b= 3.6f;
A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d
The solution for us was the opposite. We disabled hardware acceleration on the WebView only (rather than on the entire app in the manifest) by using this code:
if (Build.VERSION.SDK_INT >= 11){
webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
CSS3 animations are smoother now. We are using Android 4.0.
More info here: https://code.google.com/p/android/issues/detail?id=17352
with many functions in matlab, you don't need to iterate at all.
for example, to multiply by it's position in the list:
m = [1:numel(list)]';
elm = list.*m;
vectorized algorithms in matlab are in general much faster.
If you want to submit files using ajax use "jquery.form.js" This submits all form elements easily.
Samples http://jquery.malsup.com/form/#ajaxSubmit
rough view :
<form id='AddPhotoForm' method='post' action='../photo/admin_save_photo.php' enctype='multipart/form-data'>
<script type="text/javascript">
function showResponseAfterAddPhoto(responseText, statusText)
{
information= responseText;
callAjaxtolist();
$("#AddPhotoForm").resetForm();
$("#photo_msg").html('<div class="album_msg">Photo uploaded Successfully...</div>');
};
$(document).ready(function(){
$('.add_new_photo_div').live('click',function(){
var options = {success:showResponseAfterAddPhoto};
$("#AddPhotoForm").ajaxSubmit(options);
});
});
</script>
It means that you have to have PHP installed as a module in Apache, instead of starting it as a CGI script.
just sudo pip install packagename
Despite NylonSmile
's answer, which is "sort of" correct.. I was unable to overwrite files, in this manner..
echo "i know about Pipes, girlfriend" > thatAnswer
zsh: file exists: thatAnswer
to solve my issues.. I had to use... >!
, รก la..
[[ $FORCE_IT == 'YES' ]] && echo "$@" >! "$X" || echo "$@" > "$X"
Obviously, be careful with this...
I have been using this one....
/^[\w._-]+[+]?[\w._-]+@[\w.-]+\.[a-zA-Z]{2,6}$/
It allows that +
before @
([email protected])
As I commented above, problem seems to be the conversion from PIL internal list format to a standard python list type. I've found that Image.tostring() is much faster, and depending on your needs it might be enough. In my case, I needed to calculate the CRC32 digest of image data, and it suited fine.
If you need to perform more complex calculations, tom10 response involving numpy might be what you need.
Visually you can open "SQL Server Configuration Manager" and check properties of "Network Configuration":
You override $today
in the if statement.
if($dd<10){$dd='0'+dd} if($mm<10){$mm='0'+$mm} $today = $dd+'/'+$mm+'/'+$yyyy;
It is then not a Date() object anymore - hence the error.
I had a similar issue. The root cause was that the sending IP was not in the range of white-listed IPs on the receiving server. So, all requests for communication were killed by the receiving site.
using python this is what I ended up with
import os
os.popen(' '.join([
self._ghostscriptPath + 'gswin32c.exe',
'-q',
'-dNOPAUSE',
'-dBATCH',
'-r300',
'-sDEVICE=tiff12nc',
'-sPAPERSIZE=a4',
'-sOutputFile=%s %s' % (tifDest, pdfSource),
]))
If the page elements and their background images are already in the DOM (i.e. you are not creating/changing them dynamically), then their background images will already be loaded. At that point, you may want to look at compression methods :)
In Java 6, there is a method doing exactly what you want:
private static final byte[] CDRIVES = javax.xml.bind.DatatypeConverter.parseHexBinary("e04fd020ea3a6910a2d808002b30309d")
Alternatively you could use Google Guava:
import com.google.common.io.BaseEncoding;
private static final byte[] CDRIVES = BaseEncoding.base16().lowerCase().decode("E04FD020ea3a6910a2d808002b30309d".toLowerCase());
The Guava method is overkill, when you are using small arrays. But Guava has also versions that can parse input streams. This is a nice feature when dealing with big hexadecimal inputs.
Use :
<select onchange="myFunction()">
function myFunction() {
document.querySelectorAll("input[type=submit]")[0].click();
}
This tool appears to serve your purposes: http://www.nirsoft.net/utils/chrome_cache_view.html
Well, simple but important question. Functional JS definitely lacks a generic unfold method under the Array object since we may need to create an array of numeric items not only simple [1,2,3,...,111]
but a series resulting from a function, may be like x => x*2
instead of x => x
Currently, to perform this job we have to rely on the Array.prototype.map()
method. However in order to use Array.prototype.map()
we need to know the size of the array in advance. Well still.. if we don't know the size, then we can utilize Array.prototype.reduce()
but Array.prototype.reduce()
is intended for reducing (folding) not unfolding right..?
So obviously we need an Array.unfold()
tool in functional JS. This is something that we can simply implement ourselves just like;
Array.unfold = function(p,f,t,s){
var res = [],
runner = v => p(v,res.length-1,res) ? [] : (res.push(f(v)),runner(t(v)), res);
return runner(s);
};
Arrays.unfold(p,f,t,v)
takes 4 arguments.
p
function takes 3 arguments like many array functors do. The value, the index and the currently resulting array. It shall return a Boolean value. When it returns a true
the recursive iteration stops.f
.So if we intend to create an array filled with a series like 1,4,9,16,25...n^2 we can simply do like.
Array.unfold = function(p,f,t,s){_x000D_
var res = [],_x000D_
runner = v => p(v,res.length-1,res) ? [] : (res.push(f(v)),runner(t(v)), res);_x000D_
return runner(s);_x000D_
};_x000D_
_x000D_
var myArr = Array.unfold((_,i) => i >= 9, x => Math.pow(x,2), x => x+1, 1);_x000D_
console.log(myArr);
_x000D_
You want the value set, not the key set:
for (TypeValue name: this.example.values()) {
System.out.println(name);
}
The code you give wouldn't even compile, which may be worth mentioning in future questions - "doesn't seem to work" is a bit vague!
The following code snippet enables/disables a button depending on whether at least one checkbox on the page has been checked.
$('input[type=checkbox]').change(function () {
$('#test > tbody tr').each(function () {
if ($('input[type=checkbox]').is(':checked')) {
$('#btnexcellSelect').removeAttr('disabled');
} else {
$('#btnexcellSelect').attr('disabled', 'disabled');
}
if ($(this).is(':checked')){
console.log( $(this).attr('id'));
}else{
console.log($(this).attr('id'));
}
});
});
Here is demo in JSFiddle.
Rename your variable name
to myname
, bacause name
is a generic property of window
and is not writable in the same window.
And replace
onclick='myfunction(\''" + name + "'\')'
With
onclick='myfunction(myname)'
Working example:
var myname = "Mathew";_x000D_
document.write('<button id="button" type="button" onclick="myfunction(myname);">click</button>');_x000D_
function myfunction(name) {_x000D_
alert(name);_x000D_
}
_x000D_
Besides the session cookie (which is kind of standard), I don't want to use extra cookies.
I found a solution which works for me when building a Single Page Web Application (SPA), with many AJAX requests. Note: I am using server side Java and client side JQuery, but no magic things so I think this principle can be implemented in all popular programming languages.
My solution without extra cookies is simple:
Store the CSRF token which is returned by the server after a succesful login in a global variable (if you want to use web storage instead of a global thats fine of course). Instruct JQuery to supply a X-CSRF-TOKEN header in each AJAX call.
The main "index" page contains this JavaScript snippet:
// Intialize global variable CSRF_TOKEN to empty sting.
// This variable is set after a succesful login
window.CSRF_TOKEN = '';
// the supplied callback to .ajaxSend() is called before an Ajax request is sent
$( document ).ajaxSend( function( event, jqXHR ) {
jqXHR.setRequestHeader('X-CSRF-TOKEN', window.CSRF_TOKEN);
});
On successul login, create a random (and long enough) CSRF token, store this in the server side session and return it to the client. Filter certain (sensitive) incoming requests by comparing the X-CSRF-TOKEN header value to the value stored in the session: these should match.
Sensitive AJAX calls (POST form-data and GET JSON-data), and the server side filter catching them, are under a /dataservice/* path. Login requests must not hit the filter, so these are on another path. Requests for HTML, CSS, JS and image resources are also not on the /dataservice/* path, thus not filtered. These contain nothing secret and can do no harm, so this is fine.
@WebFilter(urlPatterns = {"/dataservice/*"})
...
String sessionCSRFToken = req.getSession().getAttribute("CSRFToken") != null ? (String) req.getSession().getAttribute("CSRFToken") : null;
if (sessionCSRFToken == null || req.getHeader("X-CSRF-TOKEN") == null || !req.getHeader("X-CSRF-TOKEN").equals(sessionCSRFToken)) {
resp.sendError(401);
} else
chain.doFilter(request, response);
}
SELECT * FROM (
SELECT
Row_Number() Over (Order by (Select 1)) as RawKey,
*
FROM [Alzh].[dbo].[DM_THD_TRANS_FY14]
) AS foo
WHERE RawKey between 17210400 and 17210500
Easiest implementation.
<script>
$( ".selectpicker" ).change(function() {
alert( "Handler for .change() called." );
});
</script>
Did you tried JQuery's scrollTo
method? http://demos.flesler.com/jquery/scrollTo/
Or you can extend JQuery and add your custom mentod:
jQuery.fn.extend({
scrollToMe: function () {
var x = jQuery(this).offset().top - 100;
jQuery('html,body').animate({scrollTop: x}, 400);
}});
Then you can call this method like:
$("#header").scrollToMe();
A simple, easy, hands-on, way to get you out of hot water, especially if you're not so comfortable with git:
View the log of your file
git log myFile.js
commit 1023057173029091u23f01w276931f7f42595f84f Author: kmiklas Date: Tue Aug 7 09:29:34 2018 -0400
JIRA-12345 - Refactor with new architecture.
Note hash of file:
1023057173029091u23f01w276931f7f42595f84f
Show the file using the hash. Make sure it's what you want:
git show 1023057173029091u23f01w276931f7f42595f84f:./myFile.js
Redirect file to a local copy
git show 1023057173029091u23f01w276931f7f42595f84f:./myFile.js > myFile.07aug2018.js
Back up your current file.
cp myFile.js myFile.bak.js
Open both files in your favorite text editor.
vim myFile.js
vim myFile.07aug2018.js
Copy n' paste code from myFile.07aug2018.js to myFile.js, and save.
Commit and push myFile.js
Again view the log, and confirm that your file is properly in place.
Tell your clients to pull the latest, happily watch it work with the old version in place.
Not the sexiest, or most git-centric solution, and definitely a "manual" reset/reversion, but it works. It requires minimal knowledge of git, and doesn't disturb the commit history.
In Ruby, any variable whose name starts with a capital letter is a constant and you can only assign to it once. Choose one of these alternatives:
class MyClass
MYCONSTANT = "blah"
def mymethod
MYCONSTANT
end
end
class MyClass
def mymethod
my_constant = "blah"
end
end
The line in the theme style works fine, yet that replaces the animation with a white screen. Especially on a slower phone - it is really annoying. So, if you want an instant transition - you could use this in the theme style:
<item name="android:windowAnimationStyle">@null</item>
<item name="android:windowDisablePreview">true</item>
actually I think your code is just fine.. you can save those values as strings (TEXT) just like you did.. (if you want to)
and you probably get the error for the System.currentTimeMillis() that might be too big for INTEGER
If it does not work by using the click()
method like suggested in the accepted answer, then you can try this:
//trigger second button
$("#second").mousedown();
$("#second").mouseup();
Using 'minifyEnabled'
instead of 'runProguard'
works properly.
Previous code:
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
Current code:
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
Hope this helps.
You can take the SelectedItem
and cast it back to your class
and access its properties
.
MessageBox.Show(((ComboboxItem)ComboBox_Countries_In_Silvers.SelectedItem).Value);
Edit You can try using DataTextField and DataValueField, I used it with DataSource.
ComboBox_Servers.DataTextField = "Text";
ComboBox_Servers.DataValueField = "Value";
Warn/confirm User if Back button is Pressed is as below.
window.onbeforeunload = function() { return "Your work will be lost."; };
You can get more information using below mentioned links.
Disable Back Button in Browser using JavaScript
I hope this will help to you.
Check if /usr/bin has 'javac'. If not you have installed JRE & have to install jdk dev version like "java-1.8.0-openjdk-devel.x86_64"
This issue happens if this project is being used by another project. Make sure you copy the app setting keys to the parent project's app.config or web.config.
To recursively show how an object is different with other you can use _.reduce combined with _.isEqual and _.isPlainObject. In this case you can compare how a is different with b or how b is different with a:
var a = {prop1: {prop1_1: 'text 1', prop1_2: 'text 2', prop1_3: [1, 2, 3]}, prop2: 2, prop3: 3};_x000D_
var b = {prop1: {prop1_1: 'text 1', prop1_3: [1, 2]}, prop2: 2, prop3: 4};_x000D_
_x000D_
var diff = function(obj1, obj2) {_x000D_
return _.reduce(obj1, function(result, value, key) {_x000D_
if (_.isPlainObject(value)) {_x000D_
result[key] = diff(value, obj2[key]);_x000D_
} else if (!_.isEqual(value, obj2[key])) {_x000D_
result[key] = value;_x000D_
}_x000D_
return result;_x000D_
}, {});_x000D_
};_x000D_
_x000D_
var res1 = diff(a, b);_x000D_
var res2 = diff(b, a);_x000D_
console.log(res1);_x000D_
console.log(res2);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
url ='http://www.test.com/page/TEST2'.split('/')[4]
print url
Output: TEST2
.
you just make a list of lists like so:
List<List<string>> results = new List<List<string>>();
and then it's just a matter of using the functionality you want
results.Add(new List<string>()); //adds a new list to your list of lists
results[0].Add("this is a string"); //adds a string to the first list
results[0][0]; //gets the first string in your first list
I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy
and JoinColumn
were not working).
I think you were trying to do a bi-directional relationships.
First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post
side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:
(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
private List<Post> posts;
}
public class Post {
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="user_id")
private User user;
}
By doing so, the table for Post
will have a column user_id
which store the relationship. Hibernate is getting the relationship by the user
in Post
(Instead of posts
in User
. You will notice the difference if you have Post
's user
but missing User
's posts
).
You have mentioned mappedBy
and JoinColumn
is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.
Edit:
Just a bit extra information on the use of mappedBy
as it is usually confusing at first. In mappedBy
, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.
The main difference is when compiled in debug mode, pdb files are also created which allow debugging (so you can step through the code when its running). This however means that the code isn't optimized as much.
Dim pos, arr, val
arr=Array(1,2,4,5)
val = 4
pos=Application.Match(val, arr, False)
if not iserror(pos) then
Msgbox val & " is at position " & pos
else
Msgbox val & " not found!"
end if
Updated to show using Match (with .Index) to find a value in a dimension of a two-dimensional array:
Dim arr(1 To 10, 1 To 2)
Dim x
For x = 1 To 10
arr(x, 1) = x
arr(x, 2) = 11 - x
Next x
Debug.Print Application.Match(3, Application.Index(arr, 0, 1), 0)
Debug.Print Application.Match(3, Application.Index(arr, 0, 2), 0)
EDIT: it's worth illustrating here what @ARich pointed out in the comments - that using Index()
to slice an array has horrible performance if you're doing it in a loop.
In testing (code below) the Index() approach is almost 2000-fold slower than using a nested loop.
Sub PerfTest()
Const VAL_TO_FIND As String = "R1800:C8"
Dim a(1 To 2000, 1 To 10)
Dim r As Long, c As Long, t
For r = 1 To 2000
For c = 1 To 10
a(r, c) = "R" & r & ":C" & c
Next c
Next r
t = Timer
Debug.Print FindLoop(a, VAL_TO_FIND), Timer - t
' >> 0.00781 sec
t = Timer
Debug.Print FindIndex(a, VAL_TO_FIND), Timer - t
' >> 14.18 sec
End Sub
Function FindLoop(arr, val) As Boolean
Dim r As Long, c As Long
For r = 1 To UBound(arr, 1)
For c = 1 To UBound(arr, 2)
If arr(r, c) = val Then
FindLoop = True
Exit Function
End If
Next c
Next r
End Function
Function FindIndex(arr, val)
Dim r As Long
For r = 1 To UBound(arr, 1)
If Not IsError(Application.Match(val, Application.Index(arr, r, 0), 0)) Then
FindIndex = True
Exit Function
End If
Next r
End Function
<bookstore>
<book location="US">A1</book>
<category>
<book location="US">B1</book>
<book location="FIN">B2</book>
</category>
<section>
<book location="FIN">C1</book>
<book location="US">C2</book>
</section>
</bookstore>
So Given the above; you can select the first book with
(//book[@location='US'])[1]
And this will find the first one anywhere that has a location US. [A1]
//book[@location='US']
Would return the node set with all books with location US. [A1,B1,C2]
(//category/book[@location='US'])[1]
Would return the first book location US that exists in a category anywhere in the document. [B1]
(/bookstore//book[@location='US'])[1]
will return the first book with location US that exists anywhere under the root element bookstore; making the /bookstore part redundant really. [A1]
In direct answer:
/bookstore/book[@location='US'][1]
Will return you the first node for book element with location US that is under bookstore [A1]
Incidentally if you wanted, in this example to find the first US book that was not a direct child of bookstore:
(/bookstore/*//book[@location='US'])[1]
Make a surrounding div-tag, and set for it display: grid
in its style attribute.
<div style='display: grid;
text-align: center;
background-color: antiquewhite'
>
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
</div>
The text-align property is set only to show, that the text in the regular table cells are affected by it, even though it is set on the surrounding div. The same with the background-color but it is hard to say which element actually holds the background-color.
Other alternative:
JAXBElement<String> element = new JAXBElement<>(new QName("Your localPart"),
String.class, "Your message");
Then:
System.out.println(element.getValue()); // Result: Your message
-Xmn : the size of the heap for the young generation Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor" .
Good size is 33%
For adding a new column to an existing CSV file(with headers), if the column to be added has small enough number of values, here is a convenient function (somewhat similar to @joaquin's solution). The function takes the
def add_col_to_csv(csvfile,fileout,new_list):
with open(csvfile, 'r') as read_f, \
open(fileout, 'w', newline='') as write_f:
csv_reader = csv.reader(read_f)
csv_writer = csv.writer(write_f)
i = 0
for row in csv_reader:
row.append(new_list[i])
csv_writer.writerow(row)
i += 1
Example:
new_list1 = ['test_hdr',4,4,5,5,9,9,9]
add_col_to_csv('exists.csv','new-output.csv',new_list1)
check if curl module is available
$ ls -la /etc/php5/mods-available/
enable the curl module
$ sudo php5enmod curl
For a FAB looking button this style on a MaterialButton
:
<com.google.android.material.button.MaterialButton
style="@style/Widget.MaterialComponents.ExtendedFloatingActionButton"
app:cornerRadius="28dp"
android:layout_width="56dp"
android:layout_height="56dp"
android:text="1" />
Result:
If you change the size be careful to use half of the button size as app:cornerRadius
.
I think this is worthy of a separate answer: although internally unicode data is stored as UTF-16 in Sql Server this is the Little Endian flavour, so if you're calling the database from an external system, you probably need to specify UTF-16LE.
If you are using Retrofit library then you can directly pass header to api request using @Header
annotation without use of Interceptor. Here is example that shows how to add header to Retrofit api request.
@POST(apiURL)
void methodName(
@Header(HeadersContract.HEADER_AUTHONRIZATION) String token,
@Header(HeadersContract.HEADER_CLIENT_ID) String token,
@Body TypedInput body,
Callback<String> callback);
Hope it helps!
Solution utilizing JS Map:
const merge = (arr1, arr2, prop) => {
const resultMap = new Map(arr1.map((item) => [item[prop], item]));
arr2.forEach((item) => {
const mapItem = resultMap.get(item[prop]);
if (mapItem) Object.assign(mapItem, item);
else resultMap.set(item[prop], item);
});
return [...resultMap.values()];
};
const arr1 = new Array({name: "lang", value: "English"}, {name: "age", value: "18"});
const arr2 = new Array({name : "childs", value: '5'}, {name: "lang", value: "German"});
console.log(merge(arr1, arr2, "name"));
Which produces:
It could be doing the temp table renaming if you are trying to add a column to the beginning of the table (as this is easier than altering the order). Also, if there is data in the Employees table, it has to do insert select * so it can calculate the EmployeeID.
If you can't use rgba
due to browser support, and you don't want to include a semi-transparent white PNG, you will have to create two positioned elements. One for the white box, with opacity, and one for the overlaid text, solid.
body { background: red; }_x000D_
_x000D_
.box { position: relative; z-index: 1; }_x000D_
.box .back {_x000D_
position: absolute; z-index: 1;_x000D_
top: 0; left: 0; width: 100%; height: 100%;_x000D_
background: white; opacity: 0.75;_x000D_
}_x000D_
.box .text { position: relative; z-index: 2; }_x000D_
_x000D_
body.browser-ie8 .box .back { filter: alpha(opacity=75); }
_x000D_
<!--[if lt IE 9]><body class="browser-ie8"><![endif]-->_x000D_
<!--[if gte IE 9]><!--><body><!--<![endif]-->_x000D_
<div class="box">_x000D_
<div class="back"></div>_x000D_
<div class="text">_x000D_
Lorem ipsum dolor sit amet blah blah boogley woogley oo._x000D_
</div>_x000D_
</div>_x000D_
</body>
_x000D_
Good answers from gdw2 and d5e5. To make it a little simpler here are the recommendations pulled together in a single series of commands:
sqlite> .mode csv
sqlite> .output test.csv
sqlite> select * from tbl1;
sqlite> .output stdout
toggleClass works too:
$(window).on("scroll", function() {
$("nav").toggleClass("shrink", $(this).scrollTop() > 50)
});
I was getting the same error
ERROR: Repository not found.
fatal: The remote end hung up unexpectedly
and I had created the repository on Github and cloned it locally.
I was able to solve by opening .git/config and removing the [remote "origin"]
section.
[remote "origin"]
url = [email protected]:alexagui/my_project.git
fetch = +refs/heads/*:refs/remotes/origin/*
then I ran the following (again)
git remote add origin [email protected]:alexagui/my_project.git
git push -u origin master
and this time I was able to push to the repository.
DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.
That is, try adding -lpthread
to your command line.
If you are sure that it is not a typo spelling-wise, perhaps it is a typo case-wise.
What collation are you using? Check it.
Something I found was that all the fields have to match EXACTLY.
For example, sending 'cat dog' is not the same as sending 'catdog'.
What I did to troubleshoot this was to script out the FK code from the table I was inserting data into, take note of the "Foreign Key" that had the constraints (in my case there were 2) and make sure those 2 fields values matched EXACTLY as they were in the table that was throwing the FK Constraint error.
Once I fixed the 2 fields giving my problems, life was good!
If you need a better explanation, let me know.
^\w{0,10}$ # allows words of up to 10 characters.
^\w{5,}$ # allows words of more than 4 characters.
^\w{5,10}$ # allows words of between 5 and 10 characters.
(left, upper, right, lower) means two points,
with an 800x600 pixel image, the image's left upper point is (0, 0), the right lower point is (800, 600).
So, for cutting the image half:
from PIL import Image
img = Image.open("ImageName.jpg")
img_left_area = (0, 0, 400, 600)
img_right_area = (400, 0, 800, 600)
img_left = img.crop(img_left_area)
img_right = img.crop(img_right_area)
img_left.show()
img_right.show()
The Python Imaging Library uses a Cartesian pixel coordinate system, with (0,0) in the upper left corner. Note that the coordinates refer to the implied pixel corners; the centre of a pixel addressed as (0, 0) actually lies at (0.5, 0.5).
Coordinates are usually passed to the library as 2-tuples (x, y). Rectangles are represented as 4-tuples, with the upper left corner given first. For example, a rectangle covering all of an 800x600 pixel image is written as (0, 0, 800, 600).
At a very high level:
Abstraction of any kind comes down to separating concerns. "Client" code of an abstraction doesn't care how the contract exposed by the abstraction is fulfilled. You usually don't care if a string class uses a null-terminated or buffer-length-tracked internal storage implementation, for example. Encapsulation hides the details, but by making classes/methods/etc. abstract, you allow the implementation to change or for new implementations to be added without affecting the client code.
Assuming you have your hidden input in a jQuery object $myHidden
, you then use JavaScript (not jQuery) to get the part after ?
:
var myVal = $myHidden.val ();
var tmp = myVal.substr ( myVal.indexOf ( '?' ) + 1 ); // tmp now contains whatever is after ?
It was giving Illegal Exception.
My workaround with code:
public void dofirst(){
System.setProperty("webdriver.chrome.driver","D:\\Softwares\\selenium\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.facebook.com");
}
When you do not know the exact length of non-nil bytes in the array, you can trim it first:
string(bytes.Trim(arr, "\x00"))
Documentation of Math.round
says:
Returns the result of rounding the argument to an integer. The result is equivalent to
(int) Math.floor(f+0.5)
.
No need to cast to int
. Maybe it was changed from the past.
If you assume what you are sorting are just numbers and only their values identify/distinguish them (e.g. elements with same value are identicle), then the stability-issue of sorting is meaningless.
However, objects with same priority in sorting may be distinct, and sometime their relative order is meaningful information. In this case, unstable sort generates problems.
For example, you have a list of data which contains the time cost [T] of all players to clean a maze with Level [L] in a game. Suppose we need to rank the players by how fast they clean the maze. However, an additional rule applies: players who clean the maze with higher-level always have a higher rank, no matter how long the time cost is.
Of course you might try to map the paired value [T,L] to a real number [R] with some algorithm which follows the rules and then rank all players with [R] value.
However, if stable sorting is feasible, then you may simply sort the entire list by [T] (Faster players first) and then by [L]. In this case, the relative order of players (by time cost) will not be changed after you grouped them by level of maze they cleaned.
PS: of course the approach to sort twice is not the best solution to the particular problem but to explain the question of poster it should be enough.
The reason you're seeing that error is because document.getElementsByName
returns a NodeList
of elements. And a NodeList
of elements does not have a .value
property.
Use this instead:
document.getElementsByName("acc")[0].value
I have just asked the Spring Cloud
guys and thought I should share the info I have here.
bootstrap.yml
is loaded before application.yml
.
It is typically used for the following:
spring.application.name
and spring.cloud.config.server.git.uri
inside bootstrap.yml
encryption/decryption
informationTechnically, bootstrap.yml
is loaded by a parent Spring ApplicationContext
. That parent ApplicationContext
is loaded before the one that uses application.yml
.
I do also have a huge masochistic streak as that I've written yet another JSON parser. This one uses a procedural approach. It uses a similat SQL hierarchy list table to store the parsed data. Also in the package are:
Please feel free to use and have fun with it
http://www.codeproject.com/Articles/1000953/JSON-for-Sql-Server-Part
All the other answers are correct, however, you might have problems if you're trying to check directory in a user's home directory. Make sure you expand the relative path before checking:
File.exists? '~/exists'
=> false
File.directory? '~/exists'
=> false
File.exists? File.expand_path('~/exists')
=> true
I think most of the people replying here didn't quite understand the question, or else I might be mistaken.
The question is "how to check whether or not a selector exists in jQuery."
Most people have taken this for "how to check whether an element exists in the DOM using jQuery." Hardly interchangeable.
jQuery allows you to create custom selectors, but see here what happens when you try to use on e before initializing it;
$(':YEAH');
"Syntax error, unrecognized expression: YEAH"
After running into this, I realized it was simply a matter of checking
if ($.expr[':']['YEAH']) {
// Query for your :YEAH selector with ease of mind.
}
Cheers.
I was able to bypass this error by invoking PowerShell like this:
powershell -executionpolicy bypass -File .\MYSCRIPT.ps1
That is, I added the -executionpolicy bypass
to the way I invoked the script.
This worked on Windows 7 Service Pack 1. I am new to PowerShell, so there could be caveats to doing that that I am not aware of.
[Edit 2017-06-26] I have continued to use this technique on other systems including Windows 10 and Windows 2012 R2 without issue.
Here is what I am using now. This keeps me from accidentally running the script by clicking on it. When I run it in the scheduler I add one argument: "scheduler" and that bypasses the prompt.
This also pauses the window at the end so I can see the output of PowerShell.
if NOT "%1" == "scheduler" (
@echo looks like you started the script by clicking on it.
@echo press space to continue or control C to exit.
pause
)
C:
cd \Scripts
powershell -executionpolicy bypass -File .\rundps.ps1
set psexitcode=%errorlevel%
if NOT "%1" == "scheduler" (
@echo Powershell finished. Press space to exit.
pause
)
exit /b %psexitcode%
So, based on the 'button in header' solution, here is a clean and minimalist implementation:
Here is the code:
@interface MyTableViewController ()
@property (nonatomic, strong) NSMutableIndexSet *collapsedSections;
@end
...
@implementation MyTableViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (!self)
return;
self.collapsedSections = [NSMutableIndexSet indexSet];
return self;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// if section is collapsed
if ([self.collapsedSections containsIndex:section])
return 0;
// if section is expanded
#warning incomplete implementation
return [super tableView:tableView numberOfRowsInSection:section];
}
- (IBAction)toggleSectionHeader:(UIView *)sender
{
UITableView *tableView = self.tableView;
NSInteger section = sender.tag;
MyTableViewHeaderFooterView *headerView = (MyTableViewHeaderFooterView *)[self tableView:tableView viewForHeaderInSection:section];
if ([self.collapsedSections containsIndex:section])
{
// section is collapsed
headerView.button.selected = YES;
[self.collapsedSections removeIndex:section];
}
else
{
// section is expanded
headerView.button.selected = NO;
[self.collapsedSections addIndex:section];
}
[tableView beginUpdates];
[tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView endUpdates];
}
@end
I edited you fiddle
you just need to add z-index
to the front element and position it accordingly.
Just want to add one more way. Found it elsewhere, and is quite simple. Say I want to pass yes for all the prompts at command line for a command "execute_command", Then I would simply pipe yes to it.
yes | execute_command
This will use yes as the answer to all yes/no prompts.
You can create custom background for your text view. Steps 1. Go to your project. 2. Go to resources and right click to drawable. 3. Click on New -> Drawable Resource File 4. Give name to you file 5. Paste following code in the file
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="1dp" android:color="@color/colorBlack" />
<padding android:left="1dp"
android:top="1dp"
android:right="1dp"
android:bottom="1dp" />
<corners android:radius="6dp" />
<solid android:color="#ffffffff" />
For your text view where you want to use it as backgroud,
android:background="@drawable/your_fileName"