Try:
String str = "my string \n my other string";
When printed you will get:
my string
my other string
If buttonSearch has no code, and only action is to return dialog result then:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
DialogResult = DialogResult.OK;
}
Use event.preventDefault()
inside user defined function
<form onsubmit="userFunction(event)"> ...
function userFunction(ev)
{
if(!event.target.send.checked)
{
console.log('form NOT submit on "Enter" key')
ev.preventDefault();
}
}
_x000D_
Open chrome console> network tab to see
<form onsubmit="userFunction(event)" action="/test.txt">
<input placeholder="type and press Enter" /><br>
<input type="checkbox" name="send" /> submit on enter
</form>
_x000D_
Use ng-submit and just wrap both inputs in separate form tags:
<div ng-controller="mycontroller">
<form ng-submit="myFunc()">
<input type="text" ng-model="name" <!-- Press ENTER and call myFunc --> />
</form>
<br />
<form ng-submit="myFunc()">
<input type="text" ng-model="email" <!-- Press ENTER and call myFunc --> />
</form>
</div>
Wrapping each input field in its own form tag allows ENTER to invoke submit on either form. If you use one form tag for both, you will have to include a submit button.
You can try:
selenium.keyPress("id="", "\\13");
I found this to be more cross-browser compatible:
$(document).keypress(function(event) {
var keycode = event.keyCode || event.which;
if(keycode == '13') {
alert('You pressed a "enter" key in somewhere');
}
});
I added a button of type "submit" as first element of the form and made it invisible (width:0;height:0;padding:0;margin:0;border-style:none;font-size:0;
). Works like a refresh of the site, i.e. I don't do anything when the button is pressed except that the site is loaded again. For me works fine...
This doesn't sound intuitive but select the column you're having the issue with and use "text to column" and just press finish. This is the suggested answer from Excel help as well. For some reason in converts text to numbers.
You can Use KeyPress instead of KeyUp or KeyDown its more efficient and here's how to handle
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true;
button1.PerformClick();
}
}
hope it works
Sometime I will try 1000 times in my onDestroy()/contextDestroyed()
@Override
protected void onDestroy() {
boolean retry = true;
int counter = 0;
while(retry && counter<1000)
{
counter++;
try{thread.setRunnung(false);
thread.join();
retry = false;
thread = null; //garbage can coll
}catch(InterruptedException e){e.printStackTrace();}
}
}
FLAG_ACTIVITY_REORDER_TO_FRONT: If set in an Intent passed to Context.startActivity(), this flag will cause the launched activity to be brought to the front of its task's history stack if it is already running.
Intent i = new Intent(context, AActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
<li style="background-color: #ffffff;"><a href="/<%=logo_marka_url%>"><img border="0" style="border-radius:5px;background: url(images/picture.jpg') 50% 50% no-repeat;width:150px;height:80px;" src="images/clearpixel.gif"/></a></li>
Other Sample Box Center Image and Background Color
1.First clearpixel fix image area 2.style center image area box 3.li background or div color style
sub uniq {
return keys %{{ map { $_ => 1 } @_ }};
}
my @my_array = ("a","a","b","b","c");
#print join(" ", @my_array), "\n";
my $a = join(" ", uniq(@my_array));
my @b = split(/ /,$a);
my $count = $#b;
<input type="button" value="..." onClick="fbLikeDump(); WriteCookie();" />
As already mentioned its just a facade and it helps to switch between different logger implementation easily. For example if you want to use log4j implementation.
A sample code would looks like below.
If you use maven get the dependencies
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.6</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
Have the below in log4j.properties in location src/main/resources/log4j.properties
log4j.rootLogger=DEBUG, STDOUT, file
log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=mylogs.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{dd-MM-yyyy HH:mm:ss} %-5p %c{1}:%L - %m%n
Hello world code below would prints in console and to a log file as per above configuration.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HelloWorld {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(HelloWorld.class);
logger.info("Hello World");
}
}
Many problem for this, with my problem is missing '/' example: jquery-1.10.2.js:8720 XMLHttpRequest cannot load http://localhost:xxxProduct/getList_tagLabels/ It's must be: http://localhost:xxx/Product/getList_tagLabels/
I hope this help for who meet this problem.
Ok, when you know for sure other applications that used the same process worked; on your new application make sure you have the data access reference and the three dll files...
I downloaded ODAC1120320Xcopy_32bit this from the Oracle site:
http://www.oracle.com/technetwork/database/windows/downloads/utilsoft-087491.html
Reference: Oracle.DataAccess.dll (ODAC1120320Xcopy_32bit\odp.net4\odp.net\bin\4\Oracle.DataAccess.dll)
Include these 3 files within your project:
When I tried to create another application with the correct reference and files I would receive that error message.
The fix: Highlighted all three of the files and selected "Copy To Output" = Copy if newer. I did copy if newer since one of the dll's is above 100MB and any updates I do will not copy those files again.
I also ran into a registry error, this fixed it.
public void updateRegistryForOracleNLS()
{
RegistryKey oracle = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\ORACLE");
oracle.SetValue("NLS_LANG", "AMERICAN_AMERICA.WE8MSWIN1252");
}
For the Oracle nls_lang list, see this site: https://docs.oracle.com/html/B13804_02/gblsupp.htm
After that, everything worked smooth.
I hope it helps.
You need to query the data dictionary, specifically the USER_CONS_COLUMNS
view to see the table columns and corresponding constraints:
SELECT *
FROM user_cons_columns
WHERE table_name = '<your table name>';
FYI, unless you specifically created your table with a lower case name (using double quotes) then the table name will be defaulted to upper case so ensure it is so in your query.
If you then wish to see more information about the constraint itself query the USER_CONSTRAINTS
view:
SELECT *
FROM user_constraints
WHERE table_name = '<your table name>'
AND constraint_name = '<your constraint name>';
If the table is held in a schema that is not your default schema then you might need to replace the views with:
all_cons_columns
and
all_constraints
adding to the where clause:
AND owner = '<schema owner of the table>'
I dont think there is any sdk support for sending mms in android. Look here Atleast I havent found yet. But a guy claimed to have it. Have a look at this post.
To open the google maps app in android:-
geo:<lat>,<lng>?z=<zoom>
open app with marker for give location:-
geo:<lat>,<lng>?q=<lat>,<lng>(Label,Name)
open google map in ios:-
comgooglemaps://?q=<lat>,<lng>
open google maps in browser with following parameters:-
http://maps.google.com/maps?z=12&t=m&q=<lat>,<lng>
z
is the zoom level (1-21)t
is the map type ("m" map, "k" satellite, "h" hybrid, "p" terrain, "e" GoogleEarth)q
is the search queryI'm not sure if my answer is direct answer to original question, but as I suppose a lot of people come here to just find a way to tell their IDEs to understand types, I'll share what I found.
If you want to tell VSCode to understand your types, do as follows. Please pay attention that js
runtime and NodeJS
does not care about these types at all.
1- Create a file with .d.ts
ending: e.g: index.d.ts
. You can create this file in another folder. for example: types/index.d.ts
2- Suppose we want to have a function called view
. Add these lines to index.d.ts
:
/**
* Use express res.render function to render view file inside layout file.
*
* @param {string} view The path of the view file, relative to view root dir.
* @param {object} options The options to send to view file for ejs to use when rendering.
* @returns {Express.Response.render} .
*/
view(view: string, options?: object): Express.Response.render;
3- Create a jsconfig.json
file in you project's root. (It seems that just creating this file is enough for VSCode to search for your types).
Now suppose we want to add this type to another library types. (As my own situation). We can use some ts
keywords. And as long as VSCode understands ts
we have no problem with it.
For example if you want to add this view
function to response from expressjs, change index.d.ts
file as follows:
export declare global {
namespace Express {
interface Response {
/**
* Use express res.render function to render view file inside layout file.
*
* @param {string} view The path of the view file, relative to view root dir.
* @param {object} options The options to send to view file for ejs to use when rendering.
* @returns {Express.Response.render} .
*/
view(view: string, options?: object): Express.Response.render;
}
}
}
You want rows where that condition is true so you need a comma:
data[data$Ozone > 14, ]
Try running below command (Works on both windows and linux)
isql -v
You can use DataFrame.any
with parameter axis=1
for check at least one True
in row by DataFrame.isna
with boolean indexing
:
df1 = df[df.isna().any(axis=1)]
d = {'filename': ['M66_MI_NSRh35d32kpoints.dat', 'F71_sMI_DMRI51d.dat', 'F62_sMI_St22d7.dat', 'F41_Car_HOC498d.dat', 'F78_MI_547d.dat'], 'alpha1': [0.8016, 0.0, 1.721, 1.167, 1.897], 'alpha2': [0.9283, 0.0, 3.833, 2.809, 5.459], 'gamma1': [1.0, np.nan, 0.23748000000000002, 0.36419, 0.095319], 'gamma2': [0.074804, 0.0, 0.15, 0.3, np.nan], 'chi2min': [39.855990000000006, 1e+25, 10.91832, 7.966335000000001, 25.93468]}
df = pd.DataFrame(d).set_index('filename')
print (df)
alpha1 alpha2 gamma1 gamma2 chi2min
filename
M66_MI_NSRh35d32kpoints.dat 0.8016 0.9283 1.000000 0.074804 3.985599e+01
F71_sMI_DMRI51d.dat 0.0000 0.0000 NaN 0.000000 1.000000e+25
F62_sMI_St22d7.dat 1.7210 3.8330 0.237480 0.150000 1.091832e+01
F41_Car_HOC498d.dat 1.1670 2.8090 0.364190 0.300000 7.966335e+00
F78_MI_547d.dat 1.8970 5.4590 0.095319 NaN 2.593468e+01
Explanation:
print (df.isna())
alpha1 alpha2 gamma1 gamma2 chi2min
filename
M66_MI_NSRh35d32kpoints.dat False False False False False
F71_sMI_DMRI51d.dat False False True False False
F62_sMI_St22d7.dat False False False False False
F41_Car_HOC498d.dat False False False False False
F78_MI_547d.dat False False False True False
print (df.isna().any(axis=1))
filename
M66_MI_NSRh35d32kpoints.dat False
F71_sMI_DMRI51d.dat True
F62_sMI_St22d7.dat False
F41_Car_HOC498d.dat False
F78_MI_547d.dat True
dtype: bool
df1 = df[df.isna().any(axis=1)]
print (df1)
alpha1 alpha2 gamma1 gamma2 chi2min
filename
F71_sMI_DMRI51d.dat 0.000 0.000 NaN 0.0 1.000000e+25
F78_MI_547d.dat 1.897 5.459 0.095319 NaN 2.593468e+01
I work with Windows7.
Control Panel - Region and Language - Administrative - Language for non-Unicode programs.
After I set "Change system locale" to English(United States). My default encoding of vs2010 change to Windows-1252
. It was gb2312
before.
I created a new .cpp
file for a C++ project, after checking in the new file to TFS the encoding show Windows-1252 from the properties page of the file.
just take the string and use the JavaScriptSerializer to deserialize it into a native object. For example, having this json:
string json = "[{Name:'John Simith',Age:35},{Name:'Pablo Perez',Age:34}]";
You'd need to create a C# class called, for example, Person defined as so:
public class Person
{
public int Age {get;set;}
public string Name {get;set;}
}
You can now deserialize the JSON string into an array of Person by doing:
JavaScriptSerializer js = new JavaScriptSerializer();
Person [] persons = js.Deserialize<Person[]>(json);
Here's a link to JavaScriptSerializer documentation.
Note: my code above was not tested but that's the idea Tested it. Unless you are doing something "exotic", you should be fine using the JavascriptSerializer.
Shortcut to Navigation Bar is Ctrl+F2. Takes you to the types dropdown first. Press tab to go to method dropdown, and then enter on a method to go to that one.
Other than explicitly copying, another approach is to make the object immutable (no set
or other mutator methods). In this way the question never arises. Immutability becomes more difficult with larger objects, but that other side of that is that it pushes you in the direction of splitting into coherent small objects and composites.
I tried using it and didn't work, guess it's just the modal versioin.
Although, it worked as this:
$("#myModal").on("hide.bs.modal", function () {
// put your default event here
});
Just to update the answer =)
Fast Forward to 2018 and we are still having this issue!
When I had this issue with Android Studio Canary 3.2
today, this is what I did:
I went to
File -> Settings -> Plugins
On the plugins list, I disabled Android Support
by unchecking it.
Then, I selected Apply and then, OK.
After this I restarted Android Studio
.
On restart, I repeated the process:
File -> Settings -> Plugins
But this time, on the plugins list, I enabled Android Support
by checking it.
Then I restarted.
When Android Studio
came on, I allowed Gradle
do its thing, then I did:
File -> Sync Project with Gradle Files
When this was done, I reopened my xml files or refreshed them anyhow possible and everything was fine.
Yeah long route, but on a day when I have to deliver at work? It sure works!
TLDR: Just disable and re-enable Android Support and you will be fine
You can also use the bin
function with method = "content"
from the OneR
package for that:
library(OneR)
das$wt_2 <- as.numeric(bin(das$wt, nbins = 3, method = "content"))
das
## anim wt wt_2
## 1 1 181.0 1
## 2 2 179.0 1
## 3 3 180.5 1
## 4 4 201.0 2
## 5 5 201.5 2
## 6 6 245.0 2
## 7 7 246.4 3
## 8 8 189.3 1
## 9 9 301.0 3
## 10 10 354.0 3
## 11 11 369.0 3
## 12 12 205.0 2
## 13 13 199.0 1
## 14 14 394.0 3
## 15 15 231.3 2
git config --global core.editor "code --wait"
OR
git config --global core.editor "code -w"
Check
git config --global e
Your configuration will open in Visual Studio Code
Here's an example...
static class Program
{
[DllImport("user32.dll")]
public static extern int SetForegroundWindow(IntPtr hWnd);
[STAThread]
static void Main()
{
while(true)
{
Process [] processes = Process.GetProcessesByName("iexplore");
foreach(Process proc in processes)
{
SetForegroundWindow(proc.MainWindowHandle);
SendKeys.SendWait("{F5}");
}
Thread.Sleep(5000);
}
}
}
a better one... less anoying...
static class Program
{
const UInt32 WM_KEYDOWN = 0x0100;
const int VK_F5 = 0x74;
[DllImport("user32.dll")]
static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);
[STAThread]
static void Main()
{
while(true)
{
Process [] processes = Process.GetProcessesByName("iexplore");
foreach(Process proc in processes)
PostMessage(proc.MainWindowHandle, WM_KEYDOWN, VK_F5, 0);
Thread.Sleep(5000);
}
}
}
Perl way (sorry mom, i'll never do it in production).
import re
def html2text(html):
res = re.sub('<.*?>', ' ', html, flags=re.DOTALL | re.MULTILINE)
res = re.sub('\n+', '\n', res)
res = re.sub('\r+', '', res)
res = re.sub('[\t ]+', ' ', res)
res = re.sub('\t+', '\t', res)
res = re.sub('(\n )+', '\n ', res)
return res
f = open('test.txt','r')
for line in f.xreadlines():
print line
f.close()
This piece of code:
for s in ("fukushima", "123 is a number", ""):
print s.ljust(20), s[0].isdigit() if s else False
prints out the following:
fukushima False
123 is a number True
False
I was able to get this to work...
SELECT CAST('<![CDATA[' + LargeTextColumn + ']]>' AS XML) FROM TableName;
I figured out a simplest way. You don't need to install package ThenInclude.EF or you don't need to use ThenInclude for all nested navigation properties. Just do like as shown below, EF will take care rest for you. example:
var thenInclude = context.One.Include(x => x.Twoes.Threes.Fours.Fives.Sixes)
.Include(x=> x.Other)
.ToList();
With an iterator you can handle always the element which comes to order, not a specified index. So, you should not be troubled with the above matter.
Iterator itr = list.iterator();
String strElement = "";
while(itr.hasNext()){
strElement = (String)itr.next();
if(strElement.equals("2"))
{
itr.remove();
}
// Use a HTTP request to a well known server that echo's back the public IP address
void GetPublicIP(CString & csIP)
{
// Initialize COM
bool bInit = false;
if (SUCCEEDED(CoInitialize(NULL)))
{
// COM was initialized
bInit = true;
// Create a HTTP request object
MSXML2::IXMLHTTPRequestPtr HTTPRequest;
HRESULT hr = HTTPRequest.CreateInstance("MSXML2.XMLHTTP");
if (SUCCEEDED(hr))
{
// Build a request to a web site that returns the public IP address
VARIANT Async;
Async.vt = VT_BOOL;
Async.boolVal = VARIANT_FALSE;
CComBSTR ccbRequest = L"http://whatismyipaddress.com/";
// Open the request
if (SUCCEEDED(HTTPRequest->raw_open(L"GET",ccbRequest,Async)))
{
// Send the request
if (SUCCEEDED(HTTPRequest->raw_send()))
{
// Get the response
CString csRequest = HTTPRequest->GetresponseText();
// Parse the IP address
CString csMarker = "<!-- contact us before using a script to get your IP address -->";
int iPos = csRequest.Find(csMarker);
if (iPos == -1)
return;
iPos += csMarker.GetLength();
int iPos2 = csRequest.Find(csMarker,iPos);
if (iPos2 == -1)
return;
// Build the IP address
int nCount = iPos2 - iPos;
csIP = csRequest.Mid(iPos,nCount);
}
}
}
}
// Unitialize COM
if (bInit)
CoUninitialize();
}
enum A {a,b,c}
enum B extends A {d}
/*B is {a,b,c,d}*/
can be written as:
public enum All {
a (ClassGroup.A,ClassGroup.B),
b (ClassGroup.A,ClassGroup.B),
c (ClassGroup.A,ClassGroup.B),
d (ClassGroup.B)
...
How it can be useful: Let say we want something like: We have events and we are using enums. Those enums can be grouped by similar processing. If we have operation with many elements, then some events starts operation, some are just step and other end the operation. To gather such operation and avoid long switch case we can group them as in example and use:
if(myEvent.is(State_StatusGroup.START)) makeNewOperationObject()..
if(myEnum.is(State_StatusGroup.STEP)) makeSomeSeriousChanges()..
if(myEnum.is(State_StatusGroup.FINISH)) closeTransactionOrSomething()..
Example:
public enum AtmOperationStatus {
STARTED_BY_SERVER (State_StatusGroup.START),
SUCCESS (State_StatusGroup.FINISH),
FAIL_TOKEN_TIMEOUT (State_StatusGroup.FAIL,
State_StatusGroup.FINISH),
FAIL_NOT_COMPLETE (State_StatusGroup.FAIL,
State_StatusGroup.STEP),
FAIL_UNKNOWN (State_StatusGroup.FAIL,
State_StatusGroup.FINISH),
(...)
private AtmOperationStatus(StatusGroupInterface ... pList){
for (StatusGroupInterface group : pList){
group.addMember(this);
}
}
public boolean is(StatusGroupInterface with){
for (AtmOperationStatus eT : with.getMembers()){
if( eT .equals(this)) return true;
}
return false;
}
// Each group must implement this interface
private interface StatusGroupInterface{
EnumSet<AtmOperationStatus> getMembers();
void addMember(AtmOperationStatus pE);
}
// DEFINING GROUPS
public enum State_StatusGroup implements StatusGroupInterface{
START, STEP, FAIL, FINISH;
private List<AtmOperationStatus> members = new LinkedList<AtmOperationStatus>();
@Override
public EnumSet<AtmOperationStatus> getMembers() {
return EnumSet.copyOf(members);
}
@Override
public void addMember(AtmOperationStatus pE) {
members.add(pE);
}
static { // forcing initiation of dependent enum
try {
Class.forName(AtmOperationStatus.class.getName());
} catch (ClassNotFoundException ex) {
throw new RuntimeException("Class AtmEventType not found", ex);
}
}
}
}
//Some use of upper code:
if (p.getStatus().is(AtmOperationStatus.State_StatusGroup.FINISH)) {
//do something
}else if (p.getStatus().is(AtmOperationStatus.State_StatusGroup.START)) {
//do something
}
Add some more advanced:
public enum AtmEventType {
USER_DEPOSIT (Status_EventsGroup.WITH_STATUS,
Authorization_EventsGroup.USER_AUTHORIZED,
ChangedMoneyAccountState_EventsGroup.CHANGED,
OperationType_EventsGroup.DEPOSIT,
ApplyTo_EventsGroup.CHANNEL),
SERVICE_DEPOSIT (Status_EventsGroup.WITH_STATUS,
Authorization_EventsGroup.TERMINAL_AUTHORIZATION,
ChangedMoneyAccountState_EventsGroup.CHANGED,
OperationType_EventsGroup.DEPOSIT,
ApplyTo_EventsGroup.CHANNEL),
DEVICE_MALFUNCTION (Status_EventsGroup.WITHOUT_STATUS,
Authorization_EventsGroup.TERMINAL_AUTHORIZATION,
ChangedMoneyAccountState_EventsGroup.DID_NOT_CHANGED,
ApplyTo_EventsGroup.DEVICE),
CONFIGURATION_4_C_CHANGED(Status_EventsGroup.WITHOUT_STATUS,
ApplyTo_EventsGroup.TERMINAL,
ChangedMoneyAccountState_EventsGroup.DID_NOT_CHANGED),
(...)
At above if we have some fail (myEvent.is(State_StatusGroup.FAIL)) then iterating by previous events we can easily check if we must revert money transfer by:
if(myEvent2.is(ChangedMoneyAccountState_EventsGroup.CHANGED)) rollBack()..
It can be useful for:
- including explicite meta-data about processing logic, less to remember
- implementing some of multi-inheritance
- we don't want to use class structures, ex. for sending short status messages
Use this...
$('#cat_icon').click(function () {
$('#categories').toggle("slow");
//$('#cat_icon').hide();
});
$('.panel_title').click(function () {
$('#categories').toggle("slow");
//$('#cat_icon').show();
});
See this Example
Greetings.
I successfully imported lodash in my project with the following commands:
npm install lodash --save
typings install lodash --save
Then i imported it in the following way:
import * as _ from 'lodash';
and in systemjs.config.js i defined this:
map: { 'lodash' : 'node_modules/lodash/lodash.js' }
If you just want the first key from a dictionary you should use what many have suggested before
first = next(iter(prices))
However if you want the first and keep the rest as a list you could use the values unpacking operator
first, *rest = prices
The same is applicable on values by replacing prices
with prices.values()
and for both key and value you can even use unpacking assignment
>>> (product, price), *rest = prices.items()
>>> product
'banana'
>>> price
4
Note: You might be tempted to use
first, *_ = prices
to just get the first key, but I would generally advice against this usage unless the dictionary is very short since it loops over all keys and creating a list for therest
has some overhead.
Note: As mentioned by others insertion order is preserved from python 3.7 (or technically 3.6) and above whereas earlier implementations should be regarded as undefined order.
I wish comments had proper code text formatting, because I think @1_CR 's answer needs more bumps, and I would like to augment his answer. Anyway, He led me to the following technique; it will use cStringIO if available (BUT NOTE: cStringIO and StringIO are not the same, because you cannot subclass cStringIO... it is a built-in... but for basic operations the syntax will be identical, so you can do this):
try:
import cStringIO
StringIO = cStringIO
except ImportError:
import StringIO
for line in StringIO.StringIO(variable_with_multiline_string):
pass
print line.strip()
I would encapsulate setTimeOut in a Promise for code consistency with other asynchronous tasks : Demo in Fiddle
function sleep(ms)
{
return(new Promise(function(resolve, reject) {
setTimeout(function() { resolve(); }, ms);
}));
}
Used like that :
sleep(2000).then(function() {
// Do something
});
It is easy to remember syntax if you used to use Promises.
1) you can float the image to the left:
<img style="float:left" src="http://i.imgur.com/hCrQkJi.png">
2)You can use an HTML table to place elements on one line.
Code below
<div class="navigation-bar">
<div id="navigation-container">
<table>
<tr>
<td><img src="http://i.imgur.com/hCrQkJi.png"></td>
<td><ul>
<li><a href="#">Home</a></li>
<li><a href="#">Projects</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Get in Touch</a></li>
</ul>
</td></tr></table>
</div>
As per the docs select, the following piece of code worked for me.
<div ng-controller="ExampleController">
<form name="myForm">
<label for="mySelect">Make a choice:</label>
<select name="mySelect" id="mySelect"
ng-options="option.name for option in data.availableOptions track by option.id"
ng-model="data.selectedOption"></select>
</form>
<hr>
<tt>option = {{data.selectedOption}}</tt><br/>
</div>
I use these two .gitconfig settings:
[log]
date = relative
[format]
pretty = format:%h %Cblue%ad%Creset %ae %Cgreen%s%Creset
%ad is the author date, which can be overidden by --date
or the option specified in the [log] stanza in .gitconfig.
I like the relative date because it gives an immediate feeling of when stuff was comitted.
Output looks like this:
6c3e1a2 2 hours ago [email protected] lsof is a dependency now.
0754f18 11 hours ago [email protected] Properly unmount, so detaching works.
336a3ac 13 hours ago [email protected] Show ami registration command if auto register fails
be2ad45 17 hours ago [email protected] Fixes #6. Sao Paolo region is included as well.
5aed68e 17 hours ago [email protected] Shorten while loops
This is all of course in color, so it is easy to distinguish the various parts of a log line.
Also it is the default when typing git log
because of the [format] section.
2014 UPDATE: Since git now supports padding I have a nice amendment to the version above:
pretty = format:%C(yellow)%h %Cblue%>(12)%ad %Cgreen%<(7)%aN%Cred%d %Creset%s
This right aligns the relative dates and left aligns committer names, meaning you get a column-like look that is easy on the eyes.
Screenshot2016 UPDATE: Since GPG commit signing is becoming a thing, I thought I'd update this post with a version that includes signature verification (in the screenshot it's the magenta letter right after the commit). A short explanation of the flag:
%G?: show "G" for a good (valid) signature, "B" for a bad signature, "U" for a good signature with unknown validity and "N" for no signature
Other changes include:
git log -g
now contains the reflog selector.3 years, 4..
)%<(7,trunc)
or check out the git .mailmap feature to shorten commiter names)Here's the config:
pretty = format:%C(auto,yellow)%h%C(auto,magenta)% G? %C(auto,blue)%>(12,trunc)%ad %C(auto,green)%<(7,trunc)%aN%C(auto,reset)%s%C(auto,red)% gD% D
All in all column alignment is now preserved a lot better at the expense of some (hopefully) useless characters. Feel free to edit if you have any improvements, I'd love to make the message color depend on whether a commit is signed, but it doesn't seem like that is possible atm.
ScreenshotTo check if it is empty:
var str = "Hello World!";
var n = str.length;
if(n === ''){alert("THE STRING str is EMPTY");}
To check if it isn't empty
var str = "Hello World!";
var n = str.length;
if(n != ''){alert("THE STRING str isn't EMPTY");}
This is a small modification that I made to the function of pomber; To be able to take an Array of Objects instead of an object alone and also you can activate index. also the "Keys" can be assigned by an array
function renameKeys(arrayObject, newKeys, index = false) {
let newArray = [];
arrayObject.forEach((obj,item)=>{
const keyValues = Object.keys(obj).map((key,i) => {
return {[newKeys[i] || key]:obj[key]}
});
let id = (index) ? {'ID':item} : {};
newArray.push(Object.assign(id, ...keyValues));
});
return newArray;
}
test
const obj = [{ a: "1", b: "2" }, { a: "5", b: "4" } ,{ a: "3", b: "0" }];
const newKeys = ["A","C"];
const renamedObj = renameKeys(obj, newKeys);
console.log(renamedObj);
Using the .EditedFormattedValue property solves the problem
To be notified each time a checkbox in a cell toggles a value when clicked, you can use the CellContentClick event and access the preliminary cell value .EditedFormattedValue.
As the event is fired the .EditedFormattedValue is not yet applied visually to the checkbox and not yet committed to the .Value property.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var checkbox = dataGridView1.CurrentCell as DataGridViewCheckBoxCell;
bool isChecked = (bool)checkbox.EditedFormattedValue;
}
The event fires on each Click and the .EditedFormattedValue toggles
Convert the UTC datetime to America/Denver
// create a $dt object with the UTC timezone
$dt = new DateTime('2016-12-12 12:12:12', new DateTimeZone('UTC'));
// change the timezone of the object without changing it's time
$dt->setTimezone(new DateTimeZone('America/Denver'));
// format the datetime
$dt->format('Y-m-d H:i:s T');
time()
returns the unix timestamp, which is a number, it has no timezone.
date('Y-m-d H:i:s T')
returns the date in the current locale timezone.
gmdate('Y-m-d H:i:s T')
returns the date in UTC
date_default_timezone_set()
changes the current locale timezone
to change a time in a timezone
// create a $dt object with the America/Denver timezone
$dt = new DateTime('2016-12-12 12:12:12', new DateTimeZone('America/Denver'));
// change the timezone of the object without changing it's time
$dt->setTimezone(new DateTimeZone('UTC'));
// format the datetime
$dt->format('Y-m-d H:i:s T');
here you can see all the available timezones
https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
here are all the formatting options
http://php.net/manual/en/function.date.php
Update PHP timezone DB (in linux)
sudo pecl install timezonedb
Just pass your regression model into the following function:
plot_coeffs <- function(mlr_model) {
coeffs <- coefficients(mlr_model)
mp <- barplot(coeffs, col="#3F97D0", xaxt='n', main="Regression Coefficients")
lablist <- names(coeffs)
text(mp, par("usr")[3], labels = lablist, srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
}
Use as follows:
model <- lm(Petal.Width ~ ., data = iris)
plot_coeffs(model)
We can declare static methods with same signature in subclass, but it is not considered overriding as there won’t be any run-time polymorphism.Because since all static members of a class are loaded at the time of class loading so it decide at compile time(overriding at run time) Hence the answer is ‘No’.
Modern answer: use java.time, the modern Java date and time API, for your date and time work. Back in 2011 it was right to use the Timestamp
class, but since JDBC 4.2 it is no longer advised.
For your work we need a time zone and a couple of formatters. We may as well declare them static:
static ZoneId zone = ZoneId.of("America/Marigot");
static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm xx");
Now the code could be for example:
while(resultSet.next()) {
ZonedDateTime dtStart = resultSet.getObject("dtStart", OffsetDateTime.class)
.atZoneSameInstant(zone);
// I would like to then have the date and time
// converted into the formats mentioned...
String dateFormatted = dtStart.format(dateFormatter);
String timeFormatted = dtStart.format(timeFormatter);
System.out.format("Date: %s; time: %s%n", dateFormatted, timeFormatted);
}
Example output (using the time your question was asked):
Date: 09/20/2011; time: 18:13 -0400
In your database timestamp with time zone
is recommended for timestamps. If this is what you’ve got, retrieve an OffsetDateTime
as I am doing in the code. I am also converting the retrieved value to the user’s time zone before formatting date and time separately. As time zone I supplied America/Marigot as an example, please supply your own. You may also leave out the time zone conversion if you don’t want any, of course.
If the datatype in SQL is a mere timestamp
without time zone, retrieve a LocalDateTime
instead. For example:
ZonedDateTime dtStart = resultSet.getObject("dtStart", LocalDateTime.class)
.atZone(zone);
No matter the details I trust you to do similarly for dtEnd
.
I wasn’t sure what you meant by the xx
in HH:MM xx
. I just left it in the format pattern string, which yields the UTC offset in hours and minutes without colon.
Link: Oracle tutorial: Date Time explaining how to use java.time.
I've never used it but Trilead, a free ISAPI filter which enables .htaccess based control, looks like what you want.
This should work (at least with TkAgg):
wm = plt.get_current_fig_manager()
wm.window.state('zoomed')
(adopted from the above and Using Tkinter, is there a way to get the usable screen size without visibly zooming a window?)
It looks like you're running into permission issues. If you are installing npm-packages
then it might possible that you are getting an EACCES
error when trying to install a package globally. This means you do not have permission to write to the directories npm
uses to store global packages and commands.
Try running commands: sudo chmod u+x -R 775 ~/.npm
and sudo chown $USER -R ~/.npm
or you can just run any npm
command with sudo
, that should get resolve your issue.
If you are installing an npm-package
locally, then you should be in your local project directory and can try running sudo npm install <pkg-name>
command to install required package. the purpose of using sudo
is that it will change your owner permissions so you can make your current user authorized to run npm
commands.
I'd recommend you to take a look at https://docs.npmjs.com/getting-started/fixing-npm-permissions
check whether there is a comma at the end.
},
{
name: '???. ??????? ?? ?????. ?3/?',
data: graph_high3,
dataGrouping: {
units: groupingUnits,
groupPixelWidth: 40,
approximation: "average",
enabled: true,
units: [[
'minute',
[1]
]]
}
} // if , - SCRIPT5007
I think this script is what exactly you need
var t = document.getElementById('myTable');
var r =document.createElement('TR');
t.tBodies[0].appendChild(r)
See here: Search Path
Summary:
#include <stdio.h>
When the include file is in brackets the preprocessor first searches in paths specified via the -I flag. Then it searches the standard include paths (see the above link, and use the -v flag to test on your system).
#include "myFile.h"
When the include file is in quotes the preprocessor first searches in the current directory, then paths specified by -iquote, then -I paths, then the standard paths.
-nostdinc can be used to prevent the preprocessor from searching the standard paths at all.
Environment variables can also be used to add search paths.
When compiling if you use the -v flag you can see the search paths used.
Used this approach for array of bytes:
Initially:
byte[] bytes = new byte[0];
Whenever required (Need to provide original length for extending):
Array.Resize<byte>(ref bytes, bytes.Length + requiredSize);
Reset:
Array.Resize<byte>(ref bytes, 0);
Typed List Method
Initially:
List<byte> bytes = new List<byte>();
Whenever required:
bytes.AddRange(new byte[length]);
Release/Clear:
bytes.Clear()
I know I'm coming to this late, but what the heck.
I've got almost the exact same code as Kris, using just one Activity but with 2 different layouts/views, and I want to switch between the layouts at will.
As a test, I added 2 menu options, each one switches the view:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
setContentView(R.layout.main);
return true;
case R.id.item2:
setContentView(R.layout.alternate);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Note, I've got one Activity class. This works perfectly. So I have no idea why people are suggesting using different Activities / Intents. Maybe someone can explain why my code works and Kris's didn't.
Since MySQL 5.7 you can do a DROP USER IF EXISTS test
More info: http://dev.mysql.com/doc/refman/5.7/en/drop-user.html
An MSI is a Windows Installer database. Windows Installer (a service installed with Windows) uses this to install software on your system (i.e. copy files, set registry values, etc...).
A setup.exe may either be a bootstrapper or a non-msi installer. A non-msi installer will extract the installation resources from itself and manage their installation directly. A bootstrapper will contain an MSI instead of individual files. In this case, the setup.exe will call Windows Installer to install the MSI.
Some reasons you might want to use a setup.exe:
Depends on a lot of factors... List implementation, CPU architecture, JVM, loop semantics, complexity of equals method, etc... By the time the list gets big enough to effectively benchmark (1000+ elements), Hash-based binary lookups beat linear searches hands-down, and the difference only scales up from there.
Hope this helps!
I would like to add an example of prototypical inheritance with javascript to @Scott Driscoll answer. We'll be using classical inheritance pattern with Object.create() which is a part of EcmaScript 5 specification.
First we create "Parent" object function
function Parent(){
}
Then add a prototype to "Parent" object function
Parent.prototype = {
primitive : 1,
object : {
one : 1
}
}
Create "Child" object function
function Child(){
}
Assign child prototype (Make child prototype inherit from parent prototype)
Child.prototype = Object.create(Parent.prototype);
Assign proper "Child" prototype constructor
Child.prototype.constructor = Child;
Add method "changeProps" to a child prototype, which will rewrite "primitive" property value in Child object and change "object.one" value both in Child and Parent objects
Child.prototype.changeProps = function(){
this.primitive = 2;
this.object.one = 2;
};
Initiate Parent (dad) and Child (son) objects.
var dad = new Parent();
var son = new Child();
Call Child (son) changeProps method
son.changeProps();
Check the results.
Parent primitive property did not change
console.log(dad.primitive); /* 1 */
Child primitive property changed (rewritten)
console.log(son.primitive); /* 2 */
Parent and Child object.one properties changed
console.log(dad.object.one); /* 2 */
console.log(son.object.one); /* 2 */
Working example here http://jsbin.com/xexurukiso/1/edit/
More info on Object.create here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/create
An independent parent is the best practice for sharing configuration and options across otherwise uncoupled components. Apache has a parent pom project to share legal notices and some common packaging options.
If your top-level project has real work in it, such as aggregating javadoc or packaging a release, then you will have conflicts between the settings needed to do that work and the settings you want to share out via parent. A parent-only project avoids that.
A common pattern (ignoring #1 for the moment) is have the projects-with-code use a parent project as their parent, and have it use the top-level as a parent. This allows core things to be shared by all, but avoids the problem described in #2.
The site plugin will get very confused if the parent structure is not the same as the directory structure. If you want to build an aggregate site, you'll need to do some fiddling to get around this.
Apache CXF is an example the pattern in #2.
They often forget that iterator
must convert to const_iterator
but not the other way around. Here is a way to do that:
template<class T, class Tag = void>
class IntrusiveSlistIterator
: public std::iterator<std::forward_iterator_tag, T>
{
typedef SlistNode<Tag> Node;
Node* node_;
public:
IntrusiveSlistIterator(Node* node);
T& operator*() const;
T* operator->() const;
IntrusiveSlistIterator& operator++();
IntrusiveSlistIterator operator++(int);
friend bool operator==(IntrusiveSlistIterator a, IntrusiveSlistIterator b);
friend bool operator!=(IntrusiveSlistIterator a, IntrusiveSlistIterator b);
// one way conversion: iterator -> const_iterator
operator IntrusiveSlistIterator<T const, Tag>() const;
};
In the above notice how IntrusiveSlistIterator<T>
converts to IntrusiveSlistIterator<T const>
. If T
is already const
this conversion never gets used.
Sass is a CSS pre-processor with syntax advancements. Style sheets in the advanced syntax are processed by the program, and turned into regular CSS style sheets. However, they do not extend the CSS standard itself.
CSS variables are supported and can be utilized but not as well as pre-processor variables.
For the difference between SCSS and Sass, this text on the Sass documentation page should answer the question:
There are two syntaxes available for Sass. The first, known as
SCSS (Sassy CSS)
and used throughout this reference, is an extension of the syntax of CSS. This means that every valid CSS stylesheet is a valid SCSS file with the same meaning. This syntax is enhanced with the Sass features described below. Files using this syntax have the .scss extension.The second and older syntax, known as the
indented syntax (or sometimes just “Sass”)
, provides a more concise way of writing CSS. It uses indentation rather than brackets to indicate nesting of selectors, and newlines rather than semicolons to separate properties. Files using this syntax have the .sass extension.
However, all this works only with the Sass pre-compiler
which in the end creates CSS. It is not an extension to the CSS standard itself.
Try Collections.shuffle(list).If usage of this method is barred for solving the problem, then one can look at the actual implementation.
You can use relative rules:
table td + td + td + td + td {
border: none;
}
This only works if the number of columns isn't determined at runtime.
You can run the below command.
nohup <your command> & > <outputfile> 2>&1 &
e.g. I have a nohup command inside script
./Runjob.sh > sparkConcuurent.out 2>&1
Inserting \n
p="${var1}\n${var2}"
echo -e "${p}"
Inserting a new line in the source code
p="${var1}
${var2}"
echo "${p}"
Using $'\n'
(only bash and zsh)
p="${var1}"$'\n'"${var2}"
echo "${p}"
\n
p="${var1}\n${var2}"
echo -e "${p}"
echo -e
interprets the two characters "\n"
as a new line.
var="a b c"
first_loop=true
for i in $var
do
p="$p\n$i" # Append
unset first_loop
done
echo -e "$p" # Use -e
Avoid extra leading newline
var="a b c"
first_loop=1
for i in $var
do
(( $first_loop )) && # "((...))" is bash specific
p="$i" || # First -> Set
p="$p\n$i" # After -> Append
unset first_loop
done
echo -e "$p" # Use -e
Using a function
embed_newline()
{
local p="$1"
shift
for i in "$@"
do
p="$p\n$i" # Append
done
echo -e "$p" # Use -e
}
var="a b c"
p=$( embed_newline $var ) # Do not use double quotes "$var"
echo "$p"
var="a b c"
for i in $var
do
p="$p
$i" # New line directly in the source code
done
echo "$p" # Double quotes required
# But -e not required
Avoid extra leading newline
var="a b c"
first_loop=1
for i in $var
do
(( $first_loop )) && # "((...))" is bash specific
p="$i" || # First -> Set
p="$p
$i" # After -> Append
unset first_loop
done
echo "$p" # No need -e
Using a function
embed_newline()
{
local p="$1"
shift
for i in "$@"
do
p="$p
$i" # Append
done
echo "$p" # No need -e
}
var="a b c"
p=$( embed_newline $var ) # Do not use double quotes "$var"
echo "$p"
$'\n'
(less portable)bash and zsh interprets $'\n'
as a new line.
var="a b c"
for i in $var
do
p="$p"$'\n'"$i"
done
echo "$p" # Double quotes required
# But -e not required
Avoid extra leading newline
var="a b c"
first_loop=1
for i in $var
do
(( $first_loop )) && # "((...))" is bash specific
p="$i" || # First -> Set
p="$p"$'\n'"$i" # After -> Append
unset first_loop
done
echo "$p" # No need -e
Using a function
embed_newline()
{
local p="$1"
shift
for i in "$@"
do
p="$p"$'\n'"$i" # Append
done
echo "$p" # No need -e
}
var="a b c"
p=$( embed_newline $var ) # Do not use double quotes "$var"
echo "$p"
a
b
c
Special thanks to contributors of this answer: kevinf, Gordon Davisson, l0b0, Dolda2000 and tripleee.
EDIT
for
loop in above bash snippets.I'm using 960.gs for layout so my solution is as follows:
$(window).bind(
'resize',
function() {
// Grid ids we are using
$("#demogr, #allergygr, #problemsgr, #diagnosesgr, #medicalhisgr").setGridWidth(
$(".grid_5").width());
$("#clinteamgr, #procedgr").setGridWidth(
$(".grid_10").width());
}).trigger('resize');
// Here we set a global options
jQuery.extend(jQuery.jgrid.defaults, {
// altRows:true,
autowidth : true,
beforeSelectRow : function(rowid, e) { // disable row highlighting onclick
return false;
},
datatype : "jsonstring",
datastr : grdata, // JSON object generated by another function
gridview : false,
height : '100%',
hoverrows : false,
loadonce : true,
sortable : false,
jsonReader : {
repeatitems : false
}
});
// Demographics Grid
$("#demogr").jqGrid( {
caption : "Demographics",
colNames : [ 'Info', 'Data' ],
colModel : [ {
name : 'Info',
width : "30%",
sortable : false,
jsonmap : 'ITEM'
}, {
name : 'Description',
width : "70%",
sortable : false,
jsonmap : 'DESCRIPTION'
} ],
jsonReader : {
root : "DEMOGRAPHICS",
id : "DEMOID"
}
});
// Other grids defined below...
I have tried this with your data and it is working :
%pyspark
import pandas as pd
from pyspark.sql import SQLContext
print sc
df = pd.read_csv("test.csv")
print type(df)
print df
sqlCtx = SQLContext(sc)
sqlCtx.createDataFrame(df).show()
You can use pure DOM. See http://www.w3schools.com/htmldom/prop_select_selectedindex.asp
document.getElementById('dropdown').selectedIndex = 1;
but jQuery can help:
$('#dropdown').selectedIndex = 1;
It is entirely dependent on how your data is sorted to begin with. If you think it will be pseudo-random then your best bet is to either pick a random selection or choose the middle.
String sql = "select count(*) from message";
ps = cn.prepareStatement(sql);
rs = ps.executeQuery();
int rowCount = 0;
while(rs.next()) {
rowCount = Integer.parseInt(rs.getString("count(*)"));
System.out.println(Integer.parseInt(rs.getString("count(*)")));
}
System.out.println("Count : " + rowCount);
Maybe you can create an array like this:
var myList = new Array();
myList.push('Hello');
myList.push('bye');
for (var i = 0; i < myList .length; i ++ ){
window.console.log(myList[i]);
}
You also can use Gnuplot
which is also available from gretl
. Put your x y z data on a text file an insert the following
splot 'test.txt' using 1:2:3 with points palette pointsize 3 pointtype 7
Then you can set labels, etc. using
set xlabel "xxx" rotate parallel
set ylabel "yyy" rotate parallel
set zlabel "zzz" rotate parallel
set grid
show grid
unset key
public enum MyEnum
{
[Description("Option One")]
Option_One
}
public static string ToDescriptionString(this Enum This)
{
Type type = This.GetType();
string name = Enum.GetName(type, This);
MemberInfo member = type.GetMembers()
.Where(w => w.Name == name)
.FirstOrDefault();
DescriptionAttribute attribute = member != null
? member.GetCustomAttributes(true)
.Where(w => w.GetType() == typeof(DescriptionAttribute))
.FirstOrDefault() as DescriptionAttribute
: null;
return attribute != null ? attribute.Description : name;
}
take a look at the plyr
package. Specifically, ddply
ddply(df, .(group), summarise, mean=mean(dt), sum=sum(dt))
I like to use this sort of process to parse commands as strings into enumerations. I normally have one of the enumerations as "unknown" so it helps to have that returned when the others are not found (even on a case insensitive basis) rather than null (that meaning there is no value). Hence I use this approach.
static <E extends Enum<E>> Enum getEnumValue(String what, Class<E> enumClass) {
Enum<E> unknown=null;
for (Enum<E> enumVal: enumClass.getEnumConstants()) {
if (what.compareToIgnoreCase(enumVal.name()) == 0) {
return enumVal;
}
if (enumVal.name().compareToIgnoreCase("unknown") == 0) {
unknown=enumVal;
}
}
return unknown;
}
Just use an <a>
by itself, set it to display: block;
and set width
and height
. Get rid of the <span>
and <div>
. This is the semantic way to do it. There is no need to wrap things in <divs>
(or any element) for layout. That is what CSS is for.
Demo: http://jsfiddle.net/ThinkingStiff/89Enq/
HTML:
<a id="music" href="Music.html">Music I Like</a>
CSS:
#music {
background-color: black;
color: white;
display: block;
height: 40px;
line-height: 40px;
text-decoration: none;
width: 100px;
text-align: center;
}
Output:
I'm kind of surprised no one mentioned this yet; I use it nearly every day:
git reset --hard @{u}
Basically, @{u}
is just shorthand for the upstream branch that your current branch is tracking. For example, this typically equates to origin/[my-current-branch-name]
. It's nice because it's branch agnostic.
Make sure to git fetch
first to get the latest copy of the remote branch.
Array of arrays (jagged arrays) are faster than multi-dimensional arrays and can be used more effectively. Multidimensional arrays have nicer syntax.
If you write some simple code using jagged and multidimensional arrays and then inspect the compiled assembly with an IL disassembler you will see that the storage and retrieval from jagged (or single dimensional) arrays are simple IL instructions while the same operations for multidimensional arrays are method invocations which are always slower.
Consider the following methods:
static void SetElementAt(int[][] array, int i, int j, int value)
{
array[i][j] = value;
}
static void SetElementAt(int[,] array, int i, int j, int value)
{
array[i, j] = value;
}
Their IL will be the following:
.method private hidebysig static void SetElementAt(int32[][] 'array',
int32 i,
int32 j,
int32 'value') cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: ldelem.ref
IL_0003: ldarg.2
IL_0004: ldarg.3
IL_0005: stelem.i4
IL_0006: ret
} // end of method Program::SetElementAt
.method private hidebysig static void SetElementAt(int32[0...,0...] 'array',
int32 i,
int32 j,
int32 'value') cil managed
{
// Code size 10 (0xa)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: ldarg.2
IL_0003: ldarg.3
IL_0004: call instance void int32[0...,0...]::Set(int32,
int32,
int32)
IL_0009: ret
} // end of method Program::SetElementAt
When using jagged arrays you can easily perform such operations as row swap and row resize. Maybe in some cases usage of multidimensional arrays will be more safe, but even Microsoft FxCop tells that jagged arrays should be used instead of multidimensional when you use it to analyse your projects.
getWindow().addFlags(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
To increase the phpMyAdmin
Session Timeout, open config.inc.php
in the root phpMyAdmin
directory and add this setting (anywhere).
$cfg['LoginCookieValidity'] = <your_new_timeout>;
Where <your_new_timeout>
is some number larger than 1800.
Note:
Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.
I have been using generic-pool with redis connections in my app - I highly recommend it. Its generic and I definitely know it works with mysql so I don't think you'll have any problems with it and mongo
On iOS5 only if you plan to let the users zoom the webview contents (e.i.: double tap) the bounce setting isn't enough. You need to set also alwaysBounceHorizontal and alwaysBounceVertical properties to NO, else when they zoom-out (another double tap...) to default it will bounce again.
Since PyYAML's yaml.load()
function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:
import yaml
with open('tree.yaml', 'r') as f:
doc = yaml.load(f)
To access branch1 text
you would use:
txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"
because, in your YAML document, the value of the branch1
key is under the treeroot
key.
By using the requestInterceptor, it worked for me:
const ui = SwaggerUIBundle({
...
requestInterceptor: (req) => {
req.headers.Authorization = "Bearer " + req.headers.Authorization;
return req;
},
...
});
You can replace the items at specific position using set method of ArrayList as below:
list.set( your_index, your_item );
But the element should be present at the index you are passing inside set() method else it will throw exception.
For me this works fine, I used ImageBackground to set background image:
import React from 'react';
import { SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, Image, ImageBackground } from 'react-native';
const App: () => React$Node = () => {
return (
<>
<StatusBar barStyle="dark-content" />
<View style={styles.container}>
<ImageBackground source={require('./Assets.xcassets/AppBackGround.imageset/2x.png')} style={styles.backgroundImage}>
<View style={styles.sectionContainer}>
<Text style={styles.title}>Marketing at the speed of today</Text>
</View>
</ImageBackground>
</View>
</>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
fontFamily: "-apple-system, BlinkMacSystemFont Segoe UI",
justifyContent: "center",
alignItems: "center",
},
backgroundImage: {
flex: 1,
resizeMode: 'cover',
height: '100%',
width: '100%'
},
title:{
color: "#9A9A9A",
fontSize: 24,
justifyContent: "center",
alignItems: "center",
},
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
});
export default App;
Open a terminal and take a look at:
/Applications/Python 3.6/Install Certificates.command
Python 3.6 on MacOS uses an embedded version of OpenSSL, which does not use the system certificate store. More details here.
(To be explicit: MacOS users can probably resolve by opening Finder and double clicking Install Certificates.command)
Be sure to test any solution across different Reader preferences. A site visitor may have their browser set to open the PDF in Reader/Acrobat as opposed to the browser, e.g., by disabling the Acrobat plugin in Firefox..
I can't be sure of my results, because I have two different Acrobat plugins that Firefox recognizes due to my having different versions of Adobe Acrobat and Adobe Reader, but it does appear that you at least need to test what happens if a website visitor has their browser set to not open the PDF in the browser. It could be quite annoying when they look at what appears to be an otherwise usable web page and their browser is nagging them to open a PDF file that they think they didn't request. In some cases, the PDF file spontaneously opened in Adobe Reader, not the browser, and in other cases the browser threw up a dialog saying the file didn't exist.
I ran into such mismatches with iframe and object both, different issues for different code.
This is for simple HTML code. I haven't tried the suggested frameworks.
Intent intent = new Intent(this, MembersLocation.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("type",type);
intent.putExtra("sender",sender);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri Emergency_sound_uri=Uri.parse("android.resource://"+getPackageName()+"/raw/emergency_sound");
// Uri Default_Sound_uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if(type.equals("emergency"))
{
playSound=Emergency_sound_uri;
}
else
{
playSound= Settings.System.DEFAULT_NOTIFICATION_URI;
}
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(body)
.setSound(playSound, AudioManager.STREAM_NOTIFICATION)
.setAutoCancel(true)
.setColor(getColor(R.color.dark_red))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent);
// notificationBuilder.setOngoing(true);//for Android notification swipe delete disabling...
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_HIGH);
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build();
channel.setSound(Emergency_sound_uri, att);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
if (notificationManager != null) {
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
I would suggest sticking to option 2 (I'm always using it for queries any more complex than SELECT * FROM table
) and if you want to print it in a nice way you may always use a separate module.
Can't figure out why, but in some circumstances if you have bound DataTimePicker and BindingSource contol is postioned to a new record, setting to Value property doesn't affect to bound field, so when you try to commit changes via EndEdit() method of BindingSource, you receive Null value doesn't allowed error. I managed this problem setting direct DataRow field.
Amazon EC2 instances are just virtual machines so you would setup SSL the same way you would set it up on any server.
You don't mention what platform you are on, so it difficult to give any more information.
What if you want to do a comparison for values that ARE NOT equal? Just using a "NOT" in front of the previously mentioned comparisons does not work. The best I could come up with is:
(Field1 <> Field2) OR (NULLIF(Field1, Field2) IS NOT NULL) OR (NULLIF(Field2, Field1) IS NOT NULL)
@Query("select b.equipSealRegisterId from EquipSealRegister b where b.sealName like %?1% and b.deleteFlag = '0'" )
List<String>findBySeal(String sealname);
I have tried this code and it works.
This issue comes when postgres doesn't shut down properly. Here is how I resolved this issue in three simple steps.
Step 1: Go to your postgres directory
Mac Users will find this in /usr/local/var/postgres
, others might look at /usr/var/postgres/
.
Step 2: Remove .pid
file by running this command.
rm postmaster.pid
Step 3: Restart your server
Mac Users
brew services restart postgresql
Linux Users
sudo service postgresql restart
Finally restart your app and you are good to go.
This is basically the same answer provided by Evert, but extended to show-off
some cool options of fill_between
from matplotlib import pyplot as pl
import numpy as np
pl.clf()
pl.hold(1)
x = np.linspace(0, 30, 100)
y = np.sin(x) * 0.5
pl.plot(x, y, '-k')
x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape) +.1
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#CC4F1B')
pl.fill_between(x, y-error, y+error,
alpha=0.5, edgecolor='#CC4F1B', facecolor='#FF9848')
y = np.cos(x/6*np.pi)
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#1B2ACC')
pl.fill_between(x, y-error, y+error,
alpha=0.2, edgecolor='#1B2ACC', facecolor='#089FFF',
linewidth=4, linestyle='dashdot', antialiased=True)
y = np.cos(x/6*np.pi) + np.sin(x/3*np.pi)
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#3F7F4C')
pl.fill_between(x, y-error, y+error,
alpha=1, edgecolor='#3F7F4C', facecolor='#7EFF99',
linewidth=0)
pl.show()
Consider this one: https://github.com/NanoHttpd/nanohttpd. Very small, written in Java. I used it without any problem.
Another approach in spark 2.1.0
is to use --conf spark.driver.userClassPathFirst=true
during spark-submit which changes the priority of dependency load, and thus the behavior of the spark-job, by giving priority to the jars the user is adding to the class-path with the --jars
option.
this works fine for me
<Link to={`link`} target="_blank">View</Link>
You need to include a declaration of the printf()
function.
#include <stdio.h>
#----- Define parameters -----#
#----- Get current date ----#
$Now = Get-Date
$Days = "15" #----- define amount of days ----#
$Targetfolder = "C:\Logs" #----- define folder where files are located ----#
$Extension = "*.log" #----- define extension ----#
$Lastwrite = $Now.AddDays(-$Days)
#----- Get files based on lastwrite filter and specified folder ---#
$Files = Get-Children $Targetfolder -include $Extension -Recurse | where {$_.LastwriteTime -le "$Lastwrite"}
foreach ($File in $Files)
{
if ($File -ne $Null)
{
write-host "Deleting File $File" backgroundcolor "DarkRed"
Remove-item $File.Fullname | out-null
}
else
write-host "No more files to delete" -forgroundcolor "Green"
}
}
Yes, you can use the ALTER TABLE t AUTO_INCREMENT = 42
statement. However, you need to be aware that this will cause the rebuilding of your entire table, at least with InnoDB and certain MySQL versions. If you have an already existing dataset with millions of rows, it could take a very long time to complete.
In my experience, it's better to do the following:
BEGIN WORK;
-- You may also need to add other mandatory columns and values
INSERT INTO t (id) VALUES (42);
ROLLBACK;
In this way, even if you're rolling back the transaction, MySQL will keep the auto-increment value, and the change will be applied instantly.
You can verify this by issuing a SHOW CREATE TABLE t
statement. You should see:
> SHOW CREATE TABLE t \G
*************************** 1. row ***************************
Table: t
Create Table: CREATE TABLE `t` (
...
) ENGINE=InnoDB AUTO_INCREMENT=43 ...
for Swift 3.1 or later
firstly add protocol UITextFieldDelegate
like:-
class PinCodeViewController: UIViewController, UITextFieldDelegate {
.....
.....
.....
}
after that create your UITextField and set delegate
Complete Exp: -
import UIKit
class PinCodeViewController: UIViewController, UITextFieldDelegate {
let pinCodetextField: UITextField = {
let tf = UITextField()
tf.placeholder = "please enter your pincode"
tf.font = UIFont.systemFont(ofSize: 15)
tf.borderStyle = UITextBorderStyle.roundedRect
tf.autocorrectionType = UITextAutocorrectionType.no
tf.keyboardType = UIKeyboardType.numberPad
tf.clearButtonMode = UITextFieldViewMode.whileEditing;
tf.contentVerticalAlignment = UIControlContentVerticalAlignment.center
return tf
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(pinCodetextField)
//----- setup your textfield anchor or position where you want to show it-----
// after that
pinCodetextField.delegate = self // setting the delegate
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return !(textField.text?.characters.count == 6 && string != "")
} // this is return the maximum characters in textfield
}
#include<stdio.h>
int main() {
int num; //given integer
int reminder;
int rev=0; //To reverse the given integer
int count=1;
printf("Enter the integer:");
scanf("%i",&num);
/*First while loop will reverse the number*/
while(num!=0)
{
reminder=num%10;
rev=rev*10+reminder;
num/=10;
}
/*Second while loop will give the number from left to right*/
while(rev!=0)
{
reminder=rev%10;
printf("The %d digit is %d\n",count, reminder);
rev/=10;
count++; //to give the number from left to right
}
return (EXIT_SUCCESS);}
I would stick with the $null
check since any value other than ''
(empty string), 0
, $false
and $null
will pass the check: if ($ie) {...}
.
There are multiple places where Linux can have limits on the number of file descriptors you are allowed to open.
You can check the following:
cat /proc/sys/fs/file-max
That will give you the system wide limits of file descriptors.
On the shell level, this will tell you your personal limit:
ulimit -n
This can be changed in /etc/security/limits.conf - it's the nofile param.
However, if you're closing your sockets correctly, you shouldn't receive this unless you're opening a lot of simulataneous connections. It sounds like something is preventing your sockets from being closed appropriately. I would verify that they are being handled properly.
As @Bozho says, you probably want to use getScaledInstance
.
To understand how grph.scale(2.0, 2.0)
works however, you could have a look at this code:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
class Main {
public static void main(String[] args) throws IOException {
final int SCALE = 2;
Image img = new ImageIcon("duke.png").getImage();
BufferedImage bi = new BufferedImage(SCALE * img.getWidth(null),
SCALE * img.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
Graphics2D grph = (Graphics2D) bi.getGraphics();
grph.scale(SCALE, SCALE);
// everything drawn with grph from now on will get scaled.
grph.drawImage(img, 0, 0, null);
grph.dispose();
ImageIO.write(bi, "png", new File("duke_double_size.png"));
}
}
Given duke.png:
it produces duke_double_size.png:
The mySQL client by default attempts to connect through a local file called a socket instead of connecting to the loopback address (127.0.0.1) for localhost.
The default location of this socket file, at least on OSX, is /tmp/mysql.sock
.
QUICK, LESS ELEGANT SOLUTION
Create a symlink to fool the OS into finding the correct socket.
ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp
PROPER SOLUTION
Change the socket path defined in the startMysql.sh
file in /Applications/MAMP/bin
.
The easiest way to do this is to use the Joda DateTime class and specify both the timestamp in milliseconds and the DateTimeZone you want.
I strongly recommend avoiding the built-in Java Date and Calendar classes; they're terrible.
You need to clone in ssh not in https.
For that you need to set your ssh keys. I have prepared this little script that automates this:
#!/usr/bin/env bash
email="$1"
hostname="$2"
hostalias="$hostname"
keypath="$HOME/.ssh/${hostname}_rsa"
ssh-keygen -t rsa -C $email -f $keypath
if [ $? -eq 0 ]; then
cat >> ~/.ssh/config <<EOF
Host $hostalias
Hostname $hostname *.$hostname
User git
IdentitiesOnly yes
IdentityFile $keypath
EOF
fi
and run it like
bash script.sh [email protected] github.com
Change your remote url
git remote set-url origin [email protected]:user/foo.git
Add content of ~/.ssh/github.com_rsa.pub
to your ssh keys on github.com
Check connection
ssh -T [email protected]
ggplot
allows you to have multiple layers, and that is what you should take advantage of here.
In the plot created below, you can see that there are two geom_line
statements hitting each of your datasets and plotting them together on one plot. You can extend that logic if you wish to add any other dataset, plot, or even features of the chart such as the axis labels.
library(ggplot2)
jobsAFAM1 <- data.frame(
data_date = runif(5,1,100),
Percent.Change = runif(5,1,100)
)
jobsAFAM2 <- data.frame(
data_date = runif(5,1,100),
Percent.Change = runif(5,1,100)
)
ggplot() +
geom_line(data = jobsAFAM1, aes(x = data_date, y = Percent.Change), color = "red") +
geom_line(data = jobsAFAM2, aes(x = data_date, y = Percent.Change), color = "blue") +
xlab('data_date') +
ylab('percent.change')
This answer from another forum solved the problem.
(substitute your own range for the "I:I" shown here)
Re: CountA not working in VBA
Should be:
Nonblank = Application.WorksheetFunction.CountA(Range("I:I"))
You have to refer to ranges in the vba format, not the in-excel format.
This is a pithy solution.
import datetime
todayDate = datetime.date.today()
if todayDate.day > 25:
todayDate += datetime.timedelta(7)
print todayDate.replace(day=1)
One thing to note with the original code example is that using timedelta(30)
will cause trouble if you are testing the last day of January. That is why I am using a 7-day delta.
If you are using postgres use text wherever you can, unless you have a size constraint since there is no performance penalty for text vs varchar
There is no performance difference among these three types, apart from increased storage space when using the blank-padded type, and a few extra CPU cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, there is no such advantage in PostgreSQL; in fact character(n) is usually the slowest of the three because of its additional storage costs. In most situations text or character varying should be used instead
clc;
data = [1 2 3 4 5]
LCM=1;
for i=1:1:length(data)
LCM = lcm(LCM,data(i))
end
It's possible to do with just one image file using the ColorFilter method. However, ColorFilter expects to work with ImageViews and not Buttons, so you have to transform your buttons into ImageViews. This isn't a problem if you're using images as your buttons anyway, but it's more annoying if you had text... Anyway, assuming you find a way around the problem with text, here's the code to use:
ImageView button = (ImageView) findViewById(R.id.button);
button.setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
That applies a red overlay to the button (the color code is the hex code for fully opaque red - first two digits are transparency, then it's RR GG BB.).
Your condition is right (though you should drop the == true
). What is happening is that the scanner will keep going until it reaches the end of the input. Try Ctrl+D, or pipe the input from a file (java myclass < input.txt
).
I had to turn off my personal firewall and Windows firewall as well, and it worked in the end.
DON'T FORGET THE cut
or select
EVENTS!
The accepted answer is almost perfect, but it forgets about the cut
and select
events.
cut
is fired when the user cuts text (CTRL + X or via right click)
select
is fired when the user selects a browser-suggested option
You should add them too, as such:
$("#myTextBox").on("change paste keyup cut select", function() {
//Do your function
});
Also, when checking for the last image, you must compare with imgArray.length-1
because, for example, when array length is 2 then I will take the values 0 and 1, it won't reach the value 2, so you must compare with length-1 not with length, here is the fixed line:
if(i == imgArray.length-1)
You can run this Powershell script as administrator to enable FL:
Set-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name ForceLog -Value 1 -Type DWord
Set-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name LogFailures -Value 1 -Type DWord
Set-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name LogResourceBinds -Value 1 -Type DWord
Set-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name LogPath -Value 'C:\FusionLog\' -Type String
mkdir C:\FusionLog -Force
and this one to disable:
Remove-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name ForceLog
Remove-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name LogFailures
Remove-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name LogResourceBinds
Remove-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name LogPath
SQLAlchemy introduced that in version 1.0.0
:
Bulk operations - SQLAlchemy docs
With these operations, you can now do bulk inserts or updates!
For instance (if you want the lowest overhead for simple table INSERTs), you can use Session.bulk_insert_mappings()
:
loadme = [(1, 'a'),
(2, 'b'),
(3, 'c')]
dicts = [dict(bar=t[0], fly=t[1]) for t in loadme]
s = Session()
s.bulk_insert_mappings(Foo, dicts)
s.commit()
Or, if you want, skip the loadme
tuples and write the dictionaries directly into dicts
(but I find it easier to leave all the wordiness out of the data and load up a list of dictionaries in a loop).
The second argument of date
is a UNIX timestamp, not a database timestamp string.
You need to convert your database timestamp with strtotime.
<?= date("c", strtotime($post[3])) ?>
To return a value from a VBScript function, assign the value to the name of the function, like this:
Function getNumber
getNumber = "423"
End Function
Update
Inspired by Daniel's code above and the fact that this is WAY! more interesting to me now then the actual work I have to do, i created a hopefully full-proof function to find the first blank row in a sheet. Improvements welcome! Otherwise, this is going to my library :) Hopefully others benefit as well.
Function firstBlankRow(ws As Worksheet) As Long
'returns the row # of the row after the last used row
'Or the first row with no data in it
Dim rngSearch As Range, cel As Range
With ws
Set rngSearch = .UsedRange.Columns(1).Find("") '-> does blank exist in the first column of usedRange
If Not rngSearch Is Nothing Then
Set rngSearch = .UsedRange.Columns(1).SpecialCells(xlCellTypeBlanks)
For Each cel In rngSearch
If Application.WorksheetFunction.CountA(cel.EntireRow) = 0 Then
firstBlankRow = cel.Row
Exit For
End If
Next
Else '-> no blanks in first column of used range
If Application.WorksheetFunction.CountA(Cells(.Rows.Count, 1).EntireRow) = 0 Then '-> is the last row of the sheet blank?
'-> yeap!, then no blank rows!
MsgBox "Whoa! All rows in sheet are used. No blank rows exist!"
Else
'-> okay, blank row exists
firstBlankRow = .UsedRange.SpecialCells(xlCellTypeBlanks).Row + 1
End If
End If
End With
End Function
Original Answer
To find the first blank in a sheet, replace this part of your code:
Cells(1, 1).Select
For Each Cell In ws.UsedRange.Cells
If Cell.Value = "" Then Cell = Num
MsgBox "Checking cell " & Cell & " for value."
Next
With this code:
With ws
Dim rngBlanks As Range, cel As Range
Set rngBlanks = Intersect(.UsedRange, .Columns(1)).Find("")
If Not rngBlanks Is Nothing Then '-> make sure blank cell exists in first column of usedrange
'-> find all blank rows in column A within the used range
Set rngBlanks = Intersect(.UsedRange, .Columns(1)).SpecialCells(xlCellTypeBlanks)
For Each cel In rngBlanks '-> loop through blanks in column A
'-> do a countA on the entire row, if it's 0, there is nothing in the row
If Application.WorksheetFunction.CountA(cel.EntireRow) = 0 Then
num = cel.Row
Exit For
End If
Next
Else
num = usedRange.SpecialCells(xlCellTypeLastCell).Offset(1).Row
End If
End With
To add on to the other answers here, if you would like to create a new object of a third different type with a where clause (e.g. one that is not your Entity Framework object) you can do this:
public IEnumerable<ThirdNonEntityClass> demoMethod(IEnumerable<int> property1Values)
{
using(var entityFrameworkObjectContext = new EntityFrameworkObjectContext )
{
var result = entityFrameworkObjectContext.SomeClass
.Join(entityFrameworkObjectContext.SomeOtherClass,
sc => sc.property1,
soc => soc.property2,
(sc, soc) => new {sc, soc})
.Where(s => propertyValues.Any(pvals => pvals == es.sc.property1)
.Select(s => new ThirdNonEntityClass
{
dataValue1 = s.sc.dataValueA,
dataValue2 = s.soc.dataValueB
})
.ToList();
}
return result;
}
Pay special attention to the intermediate object that is created in the Where and Select clauses.
Note that here we also look for any joined objects that have a property1 that matches one of the ones in the input list.
I know this is a bit more complex than what the original asker was looking for, but hopefully it will help someone.
There are helper classes in bootstrap 3 with contextual colors please use these classes in html attributes.
<p class="text-muted">...</p>
<p class="text-primary">...</p>
<p class="text-success">...</p>
<p class="text-info">...</p>
<p class="text-warning">...</p>
<p class="text-danger">...</p>
Reference: http://getbootstrap.com/css/#type
use MAX
in your SELECT
to return on value.. EXAMPLE
INSERT INTO school_year_studentid (student_id,syr_id) VALUES
((SELECT MAX(student_id) FROM student), (SELECT MAX(syr_id) FROM school_year))
instead of
INSERT INTO school_year_studentid (student_id,syr_id) VALUES
((SELECT (student_id) FROM student), (SELECT (syr_id) FROM school_year))
try it without MAX it will more than one value
The fastest way it is to use the Oracle collect function.
You can also do this:
select *
2 from (
3 select deptno,
4 case when row_number() over (partition by deptno order by ename)=1
5 then stragg(ename) over
6 (partition by deptno
7 order by ename
8 rows between unbounded preceding
9 and unbounded following)
10 end enames
11 from emp
12 )
13 where enames is not null
Visit the site ask tom and search on 'stragg' or 'string concatenation' . Lots of examples. There is also a not-documented oracle function to achieve your needs.
A CRLF is two characters, of course, the CR and the LF. However, `n
consists of both. For example:
PS C:\> $x = "Hello
>> World"
PS C:\> $x
Hello
World
PS C:\> $x.contains("`n")
True
PS C:\> $x.contains("`r")
False
PS C:\> $x.replace("o`nW","o There`nThe W")
Hello There
The World
PS C:\>
I think you're running into problems with the `r
. I was able to remove the `r
from your example, use only `n
, and it worked. Of course, I don't know exactly how you generated the original string so I don't know what's in there.
For compiling a c program on your latest macOS just type the following in terminal after saving the file with a .c extension and on reaching the path where the file is saved :
cc yourfilename.c
Once you have checked all the errors after compilation (if any), type the following for executing the code :
./a.out
These commands are tested on macOS Mojave and are working perfectly fine, cheers coding!
As many people here have pointed out, arrays in C#, as well as in most other common languages, are statically sized. If you're looking for something more like PHP's arrays, which I'm just going to guess you are, since it's a popular language with dynamically sized (and typed!) arrays, you should use an ArrayList:
var mahByteArray = new ArrayList<byte>();
If you have a byte array from elsewhere, you can use the AddRange function.
mahByteArray.AddRange(mahOldByteArray);
Then you can use Add() and Insert() to add elements.
mahByteArray.Add(0x00); // Adds 0x00 to the end.
mahByteArray.Insert(0, 0xCA) // Adds 0xCA to the beginning.
Need it back in an array? .ToArray() has you covered!
mahOldByteArray = mahByteArray.ToArray();
define() is part of the AMD spec of js
See:
Edit: Also see Claudio's answer below. Likely the more relevant explanation.
size_t
is a very readable way to specify the size dimension of an item - length of a string, amount of bytes a pointer takes, etc.
It's also portable across platforms - you'll find that 64bit and 32bit both behave nicely with system functions and size_t
- something that unsigned int
might not do (e.g. when should you use unsigned long
Had similar issue on osx and Nexus 5 (A6.0.1). I did get the authorization pop-up and confirmed it, despite that Android Studio nor any other IDE could connect to device.
Turned out my Nexus (rooted) was missing key files.
Push key from computer to Android device:
cd ~/.android && adb push adbkey.pub /data/misc/adb/adb_keys
When using Windows, the comparison is cut short: memcache
appears to be the only client available.
If your input always has a time zone of "zulu" ("Z" = UTC), then you can use DateTimeFormatter.ISO_INSTANT
(implicitly):
final Instant parsed = Instant.parse(dateTime);
If time zone varies and has the form of "+01:00" or "+01:00:00" (when not "Z"), then you can use DateTimeFormatter.ISO_OFFSET_DATE_TIME
:
DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final ZonedDateTime parsed = ZonedDateTime.parse(dateTime, formatter);
If neither is the case, you can construct a DateTimeFormatter
in the same manner as DateTimeFormatter.ISO_OFFSET_DATE_TIME
is constructed.
Your current pattern has several problems:
ResolverStyle.STRICT
);yyyy
instead of uuuu
(yyyy
will not work in strict mode);hh
instead of 24-hour HH
;S
for fractional seconds, but input has three.The SQL Server login required is DOMAIN\machinename$
. This is the how the calling NT AUTHORITY\NETWORK SERVICE
appears to SQL Server (and file servers etc)
In SQL,
CREATE LOGIN [XYZ\Gandalf$] FROM WINDOWS
An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.
There are different types of joins available in SQL:
INNER JOIN: returns rows when there is a match in both tables.
LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table.
RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table.
FULL JOIN: It combines the results of both left and right outer joins.
The joined table will contain all records from both the tables and fill in NULLs for missing matches on either side.
SELF JOIN: is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement.
CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more joined tables.
WE can take each first four joins in Details :
We have two tables with the following values.
TableA
id firstName lastName
.......................................
1 arun prasanth
2 ann antony
3 sruthy abc
6 new abc
TableB
id2 age Place
................
1 24 kerala
2 24 usa
3 25 ekm
5 24 chennai
....................................................................
INNER JOIN
Note :it gives the intersection of the two tables, i.e. rows they have common in TableA and TableB
Syntax
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
INNER JOIN TableB
ON TableA.id = TableB.id2;
Result Will Be
firstName lastName age Place
..............................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
LEFT JOIN
Note : will give all selected rows in TableA, plus any common selected rows in TableB.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
LEFT JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
LEFT JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
new abc NULL NULL
RIGHT JOIN
Note : will give all selected rows in TableB, plus any common selected rows in TableA.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
RIGHT JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
RIGHT JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
NULL NULL 24 chennai
FULL JOIN
Note :It will return all selected values from both tables.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
FULL JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
FULL JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
new abc NULL NULL
NULL NULL 24 chennai
Interesting Fact
For INNER joins the order doesn't matter
For (LEFT, RIGHT or FULL) OUTER joins,the order matter
Better to go check this Link it will give you interesting details about join order
Have you tried
SELECT DATEADD(mi, -15,'2000-01-01 08:30:00')
DATEDIFF is the difference between 2 dates.
Work out what specific properties of a list
you want the items to have. Do they need to be indexable? Sliceable? Do they need an .append()
method?
Look up the abstract base class which describes that particular type in the collections
module.
Use isinstance
:
isinstance(x, collections.MutableSequence)
You might ask "why not just use type(x) == list
?" You shouldn't do that, because then you won't support things that look like lists. And part of the Python mentality is duck typing:
I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck
In other words, you shouldn't require that the objects are list
s, just that they have the methods you will need. The collections
module provides a bunch of abstract base classes, which are a bit like Java interfaces. Any type that is an instance of collections.Sequence
, for example, will support indexing.
This is Code for converting the image of any type(for example PNG, JPG, JPEG) to byte array
public static byte[] imageConversion(string imageName){
//Initialize a file stream to read the image file
FileStream fs = new FileStream(imageName, FileMode.Open, FileAccess.Read);
//Initialize a byte array with size of stream
byte[] imgByteArr = new byte[fs.Length];
//Read data from the file stream and put into the byte array
fs.Read(imgByteArr, 0, Convert.ToInt32(fs.Length));
//Close a file stream
fs.Close();
return imageByteArr
}
@chakrit's accepted answer is a solid way to do it yourself. If, however, you're looking for a packaged solution, I recommend taking a look at underscore.string, as @mlunoe pointed out. Using underscore.string, the code would be:
function endsWithHash(str) {
return _.str.endsWith(str, '#');
}
Forget it; this might work with Outlook or maybe even GMail but you won't be able to get this working properly supporting most other E-mail clients out there (and there's a shitton of 'em).
You're better of using a simple PHP script (check out PHPMailer) or use a hosted solution (Google "email form hosted", "free email form hosting" or something similar)
By the way, you are looking for the term "Percent-encoding" (also called url-encoding and Javascript uses encodeUri/encodeUriComponent (make sure you understand the differences!)). You will need to encode a whole lot more than just newlines.
try
{
}
catch (Exception err)
{
if (err is Web2PDFException)
DoWhatever();
}
but there is probably a better way of doing whatever it is you want.
Better to first compress catalog on remote server:
tar czfP backup.tar.gz /path/to/catalog
Secondly, download from remote:
scp [email protected]:/path/to/backup.tar.gz .
At the end, extract the files:
tar -xzvf backup.tar.gz
If you want to terminate the thread, then just returning is fine. You do NOT need to call Thread.currentThread().interrupt()
(it will not do anything bad though. It's just that you don't need to.) This is because interrupt()
is basically used to notify the owner of the thread (well, not 100% accurate, but sort of). Because you are the owner of the thread, and you decided to terminate the thread, there is no one to notify, so you don't need to call it.
By the way, why in the first case we need to use currentThread? Is Thread does not refer to the current thread?
Yes, it doesn't. I guess it can be confusing because e.g. Thread.sleep() affects the current thread, but Thread.sleep() is a static method.
If you are NOT the owner of the thread (e.g. if you have not extended Thread
and coded a Runnable
etc.) you should do
Thread.currentThread().interrupt();
return;
This way, whatever code that called your runnable will know the thread is interrupted = (normally) should stop whatever it is doing and terminate. As I said earlier, it is just a mechanism of communication though. The owner might simply ignore the interrupted status and do nothing.. but if you do set the interrupted status, somebody might thank you for that in the future.
For the same reason, you should never do
Catch(InterruptedException ie){
//ignore
}
Because if you do, you are stopping the message there. Instead one should do
Catch(InterruptedException ie){
Thread.currentThread().interrupt();//preserve the message
return;//Stop doing whatever I am doing and terminate
}
make sure you have mapped the y: drive, or copy all the files to local dir c:/local
c:/local> copy *.* c:/newfile.txt
git reset --hard
This is to revert all your local changes to the origin head
I think I have a solution to what the originator of this inquiry wanted in simple form. It works for me and actually it is the reason I came on here to begin with. I believe just using parentheses around the column like '%text%' in combination with OR
s will do it.
select * from tableName
where (sameColumnName like '%findThis%' or sameColumnName like '%andThis%' or
sameColumnName like '%thisToo%' or sameColumnName like '%andOneMore%')
.compare()
returns an integer, which is a measure of the difference between the two strings.
0
indicates that the two strings compare as equal. operator==
simply returns a boolean, indicating whether the strings are equal or not.
If you don't need the extra detail, you may as well just use ==
.
There is a free open source tool called Anchore that you can use to scan container images. This command will allow you to list all files in a container image
anchore-cli image content myrepo/app:latest files
public void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.main);
super.onCreate(savedInstanceState);
mybtn = (Button)findViewById(R.id.mybtn);
txtView=(TextView)findViewById(R.id.txtView);
mybtn .setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
txtView.SetText("Your Message");
}
});
}
I have built a performance framework that manipulates and graphs millions of datasets, and even then, the javascript calculation latency was on order of tens of milliseconds. Unless you're worried about going over the array size limit, I don't think you have much to worry about.
To consider multiple column.
Sort and give unique list based on column 1 and column 3:
sort -u -t : -k 1,1 -k 3,3 test.txt
-t :
colon is separator-k 1,1 -k 3,3
based on column 1 and column 3You can also try this :
var string = "border-radius:10px 20px 30px 40px";_x000D_
var numbers = string.match(/\d+/g).map(Number);_x000D_
console.log(numbers)
_x000D_
You could also put non-breaking spaces (&nbsp;) in lieu of the spaces so that they're forced to stay together.
How do I wrap this line of text
- asked by Peter 2 days ago
The Path class is very useful here.
You get two methods called
that could solve your issue
So for example you could write: (if you don't mind the exact file name)
using(StreamWriter sw = new StreamWriter(Path.GetTempFileName()))
{
sw.WriteLine("Your error message");
}
Or if you need to set your file name
string myTempFile = Path.Combine(Path.GetTempPath(), "SaveFile.txt");
using(StreamWriter sw = new StreamWriter(myTempFile))
{
sw.WriteLine("Your error message");
}
Jasypt provides the org.jasypt.properties.EncryptableProperties class for loading, managing and transparently decrypting encrypted values in .properties files, allowing the mix of both encrypted and not-encrypted values in the same file.
http://www.jasypt.org/encrypting-configuration.html
By using an org.jasypt.properties.EncryptableProperties object, an application would be able to correctly read and use a .properties file like this:
datasource.driver=com.mysql.jdbc.Driver
datasource.url=jdbc:mysql://localhost/reportsdb
datasource.username=reportsUser
datasource.password=ENC(G6N718UuyPE5bHyWKyuLQSm02auQPUtm)
Note that the database password is encrypted (in fact, any other property could also be encrypted, be it related with database configuration or not).
How do we read this value? like this:
/*
* First, create (or ask some other component for) the adequate encryptor for
* decrypting the values in our .properties file.
*/
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword("jasypt"); // could be got from web, env variable...
/*
* Create our EncryptableProperties object and load it the usual way.
*/
Properties props = new EncryptableProperties(encryptor);
props.load(new FileInputStream("/path/to/my/configuration.properties"));
/*
* To get a non-encrypted value, we just get it with getProperty...
*/
String datasourceUsername = props.getProperty("datasource.username");
/*
* ...and to get an encrypted value, we do exactly the same. Decryption will
* be transparently performed behind the scenes.
*/
String datasourcePassword = props.getProperty("datasource.password");
// From now on, datasourcePassword equals "reports_passwd"...
You'll need to join twice:
SELECT home.*, away.*, g.network, g.date_start
FROM game AS g
INNER JOIN team AS home
ON home.importid = g.home
INNER JOIN team AS away
ON away.importid = g.away
ORDER BY g.date_start DESC
LIMIT 7
Junit is included by default with Eclipse (at least the Java EE version I'm sure). You may just need to add the view to your perspective.
I did my own version for bootstrap 4. If you want to use it u can check. https://github.com/AmagiTech/amagibootstrapsearchmodalforselect
amagiDropdown(
{
elementId: 'commonWords',
searchButtonInnerHtml: 'Search',
closeButtonInnerHtml: 'Close',
title: 'Search and Choose',
bodyMessage: 'Please firstly search with textbox below later double click the option you choosed.'
});
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="form-group">
<label for="commonWords">Favorite Word</label>
<select id="commonWords">
<option value="1">claim – I claim to be a fast reader, but actually I am average.</option><option value="2" selected>be – Will you be my friend?</option><option value="3">and – You and I will always be friends.</option>
</select>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://rawcdn.githack.com/AmagiTech/amagibootstrapsearchmodalforselect/9c7fdf8903b3529ba54b2db46d8f15989abd1bd1/amagidropdown.js"></script>
_x000D_
You cannot return anonymous types. Can you create a model that can be returned? Otherwise, you must use an object
.
Here is an article written by Jon Skeet on the subject
Code from the article:
using System;
static class GrottyHacks
{
internal static T Cast<T>(object target, T example)
{
return (T) target;
}
}
class CheesecakeFactory
{
static object CreateCheesecake()
{
return new { Fruit="Strawberry", Topping="Chocolate" };
}
static void Main()
{
object weaklyTyped = CreateCheesecake();
var stronglyTyped = GrottyHacks.Cast(weaklyTyped,
new { Fruit="", Topping="" });
Console.WriteLine("Cheesecake: {0} ({1})",
stronglyTyped.Fruit, stronglyTyped.Topping);
}
}
Or, here is another similar article
Or, as others are commenting, you could use dynamic
Yes, it will serialize and deserialize a List<>. Just make sure you use the [XmlArray] attribute if in doubt.
[Serializable]
public class A
{
[XmlArray]
public List<string> strings;
}
This works with both Serialize() and Deserialize().
If the asp button is inside <a href="#"> </a>
tag then also the Click
event will not raise.
Hope it's useful to some one.
For me in windows server 2012 R2 I solved it by removing the duplicates from web.config file i found this line duplicated twice i removed one line and kept the other line
<add name="CrystalImageHandler.aspx_GET" verb="GET" path="CrystalImageHandler.aspx" type="CrystalDecisions.Web.CrystalImageHandler, CrystalDecisions.Web, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" preCondition="integratedMode"/></handlers><validation validateIntegratedModeConfiguration="false"/>
use default_scope in rails 3
ActiveRecord obscures the difference between defaulting defined in the database (schema) and defaulting done in the application (model). During initialization, it parses the database schema and notes any default values specified there. Later, when creating objects, it assigns those schema-specified default values without touching the database.
If your service is going to be part of you application then you are making it way more complex than it needs to be. Since you have a simple use case of getting some data from a RESTful Web Service, you should look into ResultReceiver and IntentService.
This Service + ResultReceiver pattern works by starting or binding to the service with startService() when you want to do some action. You can specify the operation to perform and pass in your ResultReceiver (the activity) through the extras in the Intent.
In the service you implement onHandleIntent to do the operation that is specified in the Intent. When the operation is completed you use the passed in ResultReceiver to send a message back to the Activity at which point onReceiveResult will be called.
So for example, you want to pull some data from your Web Service.
I know you mentioned you didn't want a code base but the open source Google I/O 2010 app uses a service in this way I am describing.
Updated to add sample code:
The activity.
public class HomeActivity extends Activity implements MyResultReceiver.Receiver {
public MyResultReceiver mReceiver;
public void onCreate(Bundle savedInstanceState) {
mReceiver = new MyResultReceiver(new Handler());
mReceiver.setReceiver(this);
...
final Intent intent = new Intent(Intent.ACTION_SYNC, null, this, QueryService.class);
intent.putExtra("receiver", mReceiver);
intent.putExtra("command", "query");
startService(intent);
}
public void onPause() {
mReceiver.setReceiver(null); // clear receiver so no leaks.
}
public void onReceiveResult(int resultCode, Bundle resultData) {
switch (resultCode) {
case RUNNING:
//show progress
break;
case FINISHED:
List results = resultData.getParcelableList("results");
// do something interesting
// hide progress
break;
case ERROR:
// handle the error;
break;
}
}
The Service:
public class QueryService extends IntentService {
protected void onHandleIntent(Intent intent) {
final ResultReceiver receiver = intent.getParcelableExtra("receiver");
String command = intent.getStringExtra("command");
Bundle b = new Bundle();
if(command.equals("query") {
receiver.send(STATUS_RUNNING, Bundle.EMPTY);
try {
// get some data or something
b.putParcelableArrayList("results", results);
receiver.send(STATUS_FINISHED, b)
} catch(Exception e) {
b.putString(Intent.EXTRA_TEXT, e.toString());
receiver.send(STATUS_ERROR, b);
}
}
}
}
ResultReceiver extension - edited about to implement MyResultReceiver.Receiver
public class MyResultReceiver implements ResultReceiver {
private Receiver mReceiver;
public MyResultReceiver(Handler handler) {
super(handler);
}
public void setReceiver(Receiver receiver) {
mReceiver = receiver;
}
public interface Receiver {
public void onReceiveResult(int resultCode, Bundle resultData);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (mReceiver != null) {
mReceiver.onReceiveResult(resultCode, resultData);
}
}
}
How to cancel AsyncTask
Full answer is here - Android AsyncTask Example
AsyncTask provides a better cancellation strategy, to terminate currently running task.
cancel(boolean mayInterruptIfitRunning)
myTask.cancel(false)- It makes isCancelled returns true. Helps to cancel the task.
myTask.cancel(true) – It also makes isCancelled() returns true, interrupt the background thread and relieves resources .
It is considered as an arrogant way, If there is any thread.sleep() method performing in background thread, cancel(true) will interrupt background thread at that time. But cancel(false) will wait for it and cancel task when that method completes.
If you invoke cancel() and doInBackground() hasn’t begun execute yet. onCancelled() will invoke.
After invoking cancel(…) you should check value returned by isCancelled() on doInbackground() periodically. just like shown below.
protected Object doInBackground(Params… params) {
while (condition)
{
...
if (isCancelled())
break;
}
return null;
}
In Windows 10, I had to run the windows command prompt (cmd) as administrator. Doing that solved this problem for me.
As always, you should question whether you truly need a mutable map.
Immutable maps are trivial to build:
val map = Map(
"mykey" -> "myval",
"myotherkey" -> "otherval"
)
Mutable maps are no different when first being built:
val map = collection.mutable.Map(
"mykey" -> "myval",
"myotherkey" -> "otherval"
)
map += "nextkey" -> "nextval"
In both of these cases, inference will be used to determine the correct type parameters for the Map instance.
You can also hold an immutable map in a var
, the variable will then be updated with a new immutable map instance every time you perform an "update"
var map = Map(
"mykey" -> "myval",
"myotherkey" -> "otherval"
)
map += "nextkey" -> "nextval"
If you don't have any initial values, you can use Map.empty:
val map : Map[String, String] = Map.empty //immutable
val map = Map.empty[String,String] //immutable
val map = collection.mutable.Map.empty[String,String] //mutable
I've found that when posting from HTTP to HTTPS, the $_POST
comes empty.
This happened while testing the form, but took me a while until I realize that.
Solve problem with two method parse common
public <T> T jsonToObject(String json, Class<T> type) {
T target = null;
try {
target = objectMapper.readValue(json, type);
} catch (Jsenter code hereonProcessingException e) {
e.printStackTrace();
}
return target;
}
public <T> T jsonToObject(String json, TypeReference<T> type) {
T target = null;
try {
target = objectMapper.readValue(json, type);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return target;
}
Something like this?
The idea is to wrap the <table>
in a non-statically positioned <div>
which has an overflow:auto
CSS property. Then position the elements in the <thead>
absolutely.
#table-wrapper {_x000D_
position:relative;_x000D_
}_x000D_
#table-scroll {_x000D_
height:150px;_x000D_
overflow:auto; _x000D_
margin-top:20px;_x000D_
}_x000D_
#table-wrapper table {_x000D_
width:100%;_x000D_
_x000D_
}_x000D_
#table-wrapper table * {_x000D_
background:yellow;_x000D_
color:black;_x000D_
}_x000D_
#table-wrapper table thead th .text {_x000D_
position:absolute; _x000D_
top:-20px;_x000D_
z-index:2;_x000D_
height:20px;_x000D_
width:35%;_x000D_
border:1px solid red;_x000D_
}
_x000D_
<div id="table-wrapper">_x000D_
<div id="table-scroll">_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th><span class="text">A</span></th>_x000D_
<th><span class="text">B</span></th>_x000D_
<th><span class="text">C</span></th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr> <td>1, 0</td> <td>2, 0</td> <td>3, 0</td> </tr>_x000D_
<tr> <td>1, 1</td> <td>2, 1</td> <td>3, 1</td> </tr>_x000D_
<tr> <td>1, 2</td> <td>2, 2</td> <td>3, 2</td> </tr>_x000D_
<tr> <td>1, 3</td> <td>2, 3</td> <td>3, 3</td> </tr>_x000D_
<tr> <td>1, 4</td> <td>2, 4</td> <td>3, 4</td> </tr>_x000D_
<tr> <td>1, 5</td> <td>2, 5</td> <td>3, 5</td> </tr>_x000D_
<tr> <td>1, 6</td> <td>2, 6</td> <td>3, 6</td> </tr>_x000D_
<tr> <td>1, 7</td> <td>2, 7</td> <td>3, 7</td> </tr>_x000D_
<tr> <td>1, 8</td> <td>2, 8</td> <td>3, 8</td> </tr>_x000D_
<tr> <td>1, 9</td> <td>2, 9</td> <td>3, 9</td> </tr>_x000D_
<tr> <td>1, 10</td> <td>2, 10</td> <td>3, 10</td> </tr>_x000D_
<!-- etc... -->_x000D_
<tr> <td>1, 99</td> <td>2, 99</td> <td>3, 99</td> </tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>_x000D_
</div>
_x000D_
List<String> items = Arrays.asList(commaSeparated.split(","));
That should work for you.
JObject.ContainsKey(string propertyName)
has been made as public method in 11.0.1 release
Documentation - https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_ContainsKey.htm
The problem with a LEFT JOIN is that if there are no appointments, it will still return one row with a null, which when aggregated by COUNT will become 1, and it will appear that the person has one appointment when actually they have none. I think this will give the correct results:
SELECT person.person_id,
(SELECT COUNT(*) FROM appointment WHERE person.person_id = appointment.person_id) AS 'Appointments'
FROM person;
To do this, stop the click on the child using .stopPropagation:
$(".example").click(function(){
$(this).fadeOut("fast");
}).children().click(function(e) {
return false;
});
This will stop the child clicks from bubbling up past their level so the parent won't receive the click.
.not()
is used a bit differently, it filters elements out of your selector, for example:
<div class="bob" id="myID"></div>
<div class="bob"></div>
$(".bob").not("#myID"); //removes the element with myID
For clicking, your problem is that the click on a child bubbles up to the parent, not that you've inadvertently attached a click handler to the child.
I have some general thoughts about the implementation of Task
:
using
.ConfigureAwait
was introduced in 4.5. Task
was introduced in 4.0. Task.ContinueWith
they do not b/c it was realised context switch is expensive and it is turned off by default.I have got a few posts on the subject but my take - in addition to Tugberk's nice answer - is that you should turn all APIs asynchronous and ideally flow the context . Since you are doing async, you can simply use continuations instead of waiting so no deadlock will be cause since no wait is done in the library and you keep the flowing so the context is preserved (such as HttpContext).
Problem is when a library exposes a synchronous API but uses another asynchronous API - hence you need to use Wait()
/Result
in your code.
I believe this answer is better:
https://unix.stackexchange.com/questions/12593/how-to-remove-all-the-files-in-a-directory
If your top-level directory is called
images
, then runrm -r images/*
. This uses the shell glob operator*
to runrm -r
on every file or directory within images.
basically you go up one level, and then say delete everything inside X directory. This way you are still specifying what folder should have its content deleted, which is safer than just saying 'delete everything here", while preserving the original folder, (which sometimes you want to because you aren't allowed or just don't want to modify the folder's existing permissions)
When you use an async function like
async () => {
try {
const response = await fetch(`https://www.reddit.com/r/${subreddit}.json`);
const json = await response.json();
setPosts(json.data.children.map(it => it.data));
} catch (e) {
console.error(e);
}
}
it returns a promise and useEffect
doesn't expect the callback function to return Promise, rather it expects that nothing is returned or a function is returned.
As a workaround for the warning you can use a self invoking async function.
useEffect(() => {
(async function() {
try {
const response = await fetch(
`https://www.reddit.com/r/${subreddit}.json`
);
const json = await response.json();
setPosts(json.data.children.map(it => it.data));
} catch (e) {
console.error(e);
}
})();
}, []);
or to make it more cleaner you could define a function and then call it
useEffect(() => {
async function fetchData() {
try {
const response = await fetch(
`https://www.reddit.com/r/${subreddit}.json`
);
const json = await response.json();
setPosts(json.data.children.map(it => it.data));
} catch (e) {
console.error(e);
}
};
fetchData();
}, []);
the second solution will make it easier to read and will help you write code to cancel previous requests if a new one is fired or save the latest request response in state
or alternatively you could not bother coding for it and use the 'conditional formatting' function in Excel which will set the background colour and font colour based on cell value.
There are only two variables here so set the default to yellow and then overwrite when the value is greater than or less than your threshold values.
test -z
returns true if the parameter is empty (see man sh
or man test
).
This worked for me :
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),R.layout.simple_spinner_item,areas);
Spinner areasSpinner = (Spinner) view.findViewById(R.id.area_spinner);
areasSpinner.setAdapter(adapter);
and in my layout folder I created simple_spinner_item
:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
// add custom fields here
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:paddingLeft="?android:attr/listPreferredItemPaddingLeft"
android:paddingRight="?android:attr/listPreferredItemPaddingRight" />
If useful, try this:
BufferedImage imgBuffer = ImageIO.read(new File("c:\\image.bmp"));
byte[] pixels = (byte[])imgBuffer.getRaster().getDataElements(0, 0, imgBuffer.getWidth(), imgBuffer.getHeight(), null);
Look at this tutorial or this one, they are both pretty simple. If you are interested in an alternative this is how you do file I/O in C.
Some things to keep in mind, use single quotes '
when dealing with single characters, and double "
for strings. Also it is a bad habit to use global variables when not necessary.
Have fun!
var tds = document.getElementById("ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a").getElementsByTagName("td");
time = tds[0].firstChild.value;
address = tds[3].firstChild.value;
If you don't want to change much, use below code inside onClick()method.
this.props.history.push('/');
I had this problem when I was trying to use the range.AddComment() function. I was able to solve this by calling range.ClearComment() before adding the comment.
The best way to do this is using WordPress class to authenticate users. Here is my solutions:
1. Include following WordPress PHP file:
include_once(dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . "wp-includes" . DIRECTORY_SEPARATOR . "class-phpass.php");
2. Create an object of PasswordHash
class:
$wp_hasher = new PasswordHash(8, true);
3. call CheckPassword
function to authenticate user:
$check = $wp_hasher->CheckPassword($password, $row['user_pass']);
4. check $check
variable:
if($check) {
echo "password is correct";
} else {
echo "password is incorrect";
}
Please Note that: $password
is the un-hashed password in clear text whereas $row['user_pass']
is the hashed password that you need to fetch from the database.
From the link in the error message:
This occurs when the default configuration files log4j.properties and log4j.xml can not be found and the application performs no explicit configuration. log4j uses Thread.getContextClassLoader().getResource() to locate the default configuration files and does not directly check the file system. Knowing the appropriate location to place log4j.properties or log4j.xml requires understanding the search strategy of the class loader in use. log4j does not provide a default configuration since output to the console or to the file system may be prohibited in some environments. Also see FAQ: Why can't log4j find my properties in a J2EE or WAR application?.
The configuration file cannot be found. Are you using xml or a property file??
Also, use logback!
since most of the devices use eMMC,the file system android uses is ext4,except for the firmware.refer-http://android-developers.blogspot.com/2010/12/saving-data-safely.html
Here is the filesystem on galaxy s4:
/system ext4
/data ext4
/cache ext4
/firmware vfat
/data/media /mnt/shell/emulated sdcardfs
The detailed output is as follows:
/dev/block/platform/msm_sdcc.1/by-name/system /system ext4 ro,seclabel,relatime, data=ordered 0 0
/dev/block/platform/msm_sdcc.1/by-name/userdata /data ext4 rw,seclabel,nosuid,no dev,noatime,discard,journal_checksum,journal_async_commit,noauto_da_alloc,data=o rdered 0 0
/dev/block/platform/msm_sdcc.1/by-name/cache /cache ext4 rw,seclabel,nosuid,node v,noatime,discard,journal_checksum,journal_async_commit,noauto_da_alloc,data=ord ered 0 0
/dev/block/platform/msm_sdcc.1/by-name/efs /efs ext4 rw,seclabel,nosuid,nodev,no atime,discard,journal_checksum,journal_async_commit,noauto_da_alloc,errors=panic ,data=ordered 0 0
/dev/block/platform/msm_sdcc.1/by-name/persdata /persdata/absolute ext4 rw,secla bel,nosuid,nodev,relatime,data=ordered 0 0
/dev/block/platform/msm_sdcc.1/by-name/apnhlos /firmware vfat ro,context=u:objec t_r:firmware:s0,relatime,uid=1000,gid=1000,fmask=0337,dmask=0227,codepage=cp437, iocharset=iso8859-1,shortname=lower,errors=remount-ro 0 0
/dev/block/platform/msm_sdcc.1/by-name/mdm /firmware-mdm vfat ro,context=u:objec t_r:firmware:s0,relatime,uid=1000,gid=1000,fmask=0337,dmask=0227,codepage=cp437, iocharset=iso8859-1,shortname=lower,errors=remount-ro 0 0
/data/media /mnt/shell/emulated sdcardfs rw,nosuid,nodev,relatime,uid=1023,gid=1 023 0 0
I think leverage this functionality using Java
long time= System.currentTimeMillis();
this will return current time in milliseconds mode . this will surely work
long time= System.currentTimeMillis();
android.util.Log.i("Time Class ", " Time value in millisecinds "+time);
Here is my logcat using the above function
05-13 14:38:03.149: INFO/Time Class(301): Time value in millisecinds 1368436083157
If you got any doubt with millisecond value .Check Here
EDIT : Time Zone I used to demo the code IST(+05:30) ,So if you check milliseconds
that mentioned in log to match with time in log you might get a different value based your system timezone
EDIT: This is easy approach .but if you need time zone or any other details I think this won't be enough Also See this approach using android api support
My solution was to make all the parents 100% and set a specific percentage for each row:
html, body,div[class^="container"] ,.column {
height: 100%;
}
.row0 {height: 10%;}
.row1 {height: 40%;}
.row2 {height: 50%;}
Abstract your initialization into a method, and call the method from mounted
and wherever else you want.
new Vue({
methods:{
init(){
//call API
//Setup game
}
},
mounted(){
this.init()
}
})
Then possibly have a button in your template to start over.
<button v-if="playerWon" @click="init">Play Again</button>
In this button, playerWon
represents a boolean value in your data that you would set when the player wins the game so the button appears. You would set it back to false in init
.
Java 8 alternative one-liner for merging two maps:
defaultMap.forEach((k, v) -> destMap.putIfAbsent(k, v));
The same with method reference:
defaultMap.forEach(destMap::putIfAbsent);
Or idemponent for original maps solution with third map:
Map<String, Integer> map3 = new HashMap<String, Integer>(map2);
map1.forEach(map3::putIfAbsent);
And here is a way to merge two maps into fast immutable one with Guava that does least possible intermediate copy operations:
ImmutableMap.Builder<String, Integer> builder = ImmutableMap.<String, Integer>builder();
builder.putAll(map1);
map2.forEach((k, v) -> {if (!map1.containsKey(k)) builder.put(k, v);});
ImmutableMap<String, Integer> map3 = builder.build();
See also Merge two maps with Java 8 for cases when values present in both maps need to be combined with mapping function.
If you are really about to work on multi-gigabyte text files then do not use PowerShell. Even if you find a way to read it faster processing of huge amount of lines will be slow in PowerShell anyway and you cannot avoid this. Even simple loops are expensive, say for 10 million iterations (quite real in your case) we have:
# "empty" loop: takes 10 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) {} }
# "simple" job, just output: takes 20 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i } }
# "more real job": 107 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i.ToString() -match '1' } }
UPDATE: If you are still not scared then try to use the .NET reader:
$reader = [System.IO.File]::OpenText("my.log")
try {
for() {
$line = $reader.ReadLine()
if ($line -eq $null) { break }
# process the line
$line
}
}
finally {
$reader.Close()
}
UPDATE 2
There are comments about possibly better / shorter code. There is nothing wrong with the original code with for
and it is not pseudo-code. But the shorter (shortest?) variant of the reading loop is
$reader = [System.IO.File]::OpenText("my.log")
while($null -ne ($line = $reader.ReadLine())) {
$line
}