An option for delegates in C++ that is not otherwise mentioned here is to do it C style using a function ptr and a context argument. This is probably the same pattern that many asking this question are trying to avoid. But, the pattern is portable, efficient, and is usable in embedded and kernel code.
class SomeClass
{
in someMember;
int SomeFunc( int);
static void EventFunc( void* this__, int a, int b, int c)
{
SomeClass* this_ = static_cast< SomeClass*>( this__);
this_->SomeFunc( a );
this_->someMember = b + c;
}
};
void ScheduleEvent( void (*delegateFunc)( void*, int, int, int), void* delegateContext);
...
SomeClass* someObject = new SomeObject();
...
ScheduleEvent( SomeClass::EventFunc, someObject);
...
If you have two columns with the same name. One simple way is to manually rename the columns like this:-
df.columns = ['column1', 'column2', 'column3']
Then you can drop via column index as you requested, like this:-
df.drop(df.columns[1], axis=1, inplace=True)
df.column[1]
will drop index 1.
Remember axis 1 = columns and axis 0 = rows.
If you are doing it before the setContentView()
method call, then the values will be null.
This will result in null:
super.onCreate(savedInstanceState);
Button btn = (Button)findViewById(R.id.btnAddContacts);
String text = (String) btn.getText();
setContentView(R.layout.main_contacts);
while this will work fine:
super.onCreate(savedInstanceState);
setContentView(R.layout.main_contacts);
Button btn = (Button)findViewById(R.id.btnAddContacts);
String text = (String) btn.getText();
TempData
is a bucket where you can dump data that is only needed for the following request. That is, anything you put into TempData is discarded after the next request completes. This is useful for one-time messages, such as form validation errors. The important thing to take note of here is that this applies to the next request in the session, so that request can potentially happen in a different browser window or tab.
To answer your specific question: there's no right way to use it. It's all up to usability and convenience. If it works, makes sense and others are understanding it relatively easy, it's good. In your particular case, the passing of a parameter this way is fine, but it's strange that you need to do that (code smell?). I'd rather keep a value like this in resources (if it's a resource) or in the database (if it's a persistent value). From your usage, it seems like a resource, since you're using it for the page title.
Hope this helps.
If You Have Multiple li
elements inside an li
element then this will definitely help you, and i have checked it and it works....
<script>
$("li").on('click', function() {
alert(this.id);
return false;
});
</script>
You turn off pack_propagate
by setting pack_propagate(0)
Turning off pack_propagate
here basically says don't let the widgets inside the frame control it's size. So you've set it's width and height to be 500. Turning off propagate stills allows it to be this size without the widgets changing the size of the frame to fill their respective width / heights which is what would happen normally
To turn off resizing the root window, you can set root.resizable(0, 0)
, where resizing is allowed in the x
and y
directions respectively.
To set a maxsize to window, as noted in the other answer you can set the maxsize
attribute or minsize
although you could just set the geometry of the root window and then turn off resizing. A bit more flexible imo.
Whenever you set grid
or pack
on a widget it will return None
. So, if you want to be able to keep a reference to the widget object you shouldn't be setting a variabe to a widget where you're calling grid
or pack
on it. You should instead set the variable to be the widget Widget(master, ....)
and then call pack
or grid
on the widget instead.
import tkinter as tk
def startgame():
pass
mw = tk.Tk()
#If you have a large number of widgets, like it looks like you will for your
#game you can specify the attributes for all widgets simply like this.
mw.option_add("*Button.Background", "black")
mw.option_add("*Button.Foreground", "red")
mw.title('The game')
#You can set the geometry attribute to change the root windows size
mw.geometry("500x500") #You want the size of the app to be 500x500
mw.resizable(0, 0) #Don't allow resizing in the x or y direction
back = tk.Frame(master=mw,bg='black')
back.pack_propagate(0) #Don't allow the widgets inside to determine the frame's width / height
back.pack(fill=tk.BOTH, expand=1) #Expand the frame to fill the root window
#Changed variables so you don't have these set to None from .pack()
go = tk.Button(master=back, text='Start Game', command=startgame)
go.pack()
close = tk.Button(master=back, text='Quit', command=mw.destroy)
close.pack()
info = tk.Label(master=back, text='Made by me!', bg='red', fg='black')
info.pack()
mw.mainloop()
Use <br/>
. For example:
Change log, upgrade version
Dependency | Old version | New version |
---------- | ----------- | -----------
Spring Boot | `1.3.5.RELEASE` | `1.4.3.RELEASE`
Gradle | `2.13` | `3.2.1`
Gradle plugin <br/>`com.gorylenko.gradle-git-properties` | `1.4.16` | `1.4.17`
`org.webjars:requirejs` | `2.2.0` | `2.3.2`
`org.webjars.npm:stompjs` | `2.3.3` | `2.3.3`
`org.webjars.bower:sockjs-client` | `1.1.0` | `1.1.1`
We can take a simple example.
Consider a table named TableA
with the following values:
id firstname lastname Mark
-------------------------------------------------------------------
1 arun prasanth 40
2 ann antony 45
3 sruthy abc 41
6 new abc 47
1 arun prasanth 45
1 arun prasanth 49
2 ann antony 49
GROUP BY
The SQL GROUP BY clause can be used in a SELECT statement to collect data across multiple records and group the results by one or more columns.
In more simple words GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.
Syntax:
SELECT expression1, expression2, ... expression_n,
aggregate_function (aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1, expression2, ... expression_n;
We can apply GROUP BY
in our table:
select SUM(Mark)marksum,firstname from TableA
group by id,firstName
Results:
marksum firstname
----------------
94 ann
134 arun
47 new
41 sruthy
In our real table we have 7 rows and when we apply GROUP BY id
, the server group the results based on id
:
In simple words:
here
GROUP BY
normally reduces the number of rows returned by rolling them up and calculatingSum()
for each row.
PARTITION BY
Before going to PARTITION BY, let us look at the OVER
clause:
According to the MSDN definition:
OVER clause defines a window or user-specified set of rows within a query result set. A window function then computes a value for each row in the window. You can use the OVER clause with functions to compute aggregated values such as moving averages, cumulative aggregates, running totals, or a top N per group results.
PARTITION BY will not reduce the number of rows returned.
We can apply PARTITION BY in our example table:
SELECT SUM(Mark) OVER (PARTITION BY id) AS marksum, firstname FROM TableA
Result:
marksum firstname
-------------------
134 arun
134 arun
134 arun
94 ann
94 ann
41 sruthy
47 new
Look at the results - it will partition the rows and returns all rows, unlike GROUP BY.
mine was:
<youtube-player
[videoId]="'paxSz8UblDs'"
[playerVars]="playerVars"
[width]="291"
[height]="194">
</youtube-player>
I just removed the line with playerVars, and it worked without errors on console.
All this can be done in one simple line:
string jsonString = JsonConvert.SerializeObject(yourObject, Formatting.Indented);
Are you testing this in local files or off a Web server? Files in different directories are considered different domains for cross-domain rules, so if you're testing locally you could be hitting cross-domain restrictions.
Otherwise, it would probably help to be pointed to a URL where the problem occurs.
Also, I'd suggest looking at the Firefox error console to see if any CSS syntax errors or other errors are reported.
Also, I'd note you probably want font-weight:bold in the second @font-face rule.
This is copied from above, but condensed slightly and re-written in semantic terms. Note: #Container
has display: flex;
and flex-direction: column;
, while the columns have flex: 3;
and flex: 2;
(where "One value, unitless number" determines the flex-grow
property) per MDN flex
docs.
#Container {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 600px;_x000D_
width: 580px;_x000D_
}_x000D_
_x000D_
.Content {_x000D_
display: flex;_x000D_
flex: 1;_x000D_
}_x000D_
_x000D_
#Detail {_x000D_
flex: 3;_x000D_
background-color: lime;_x000D_
}_x000D_
_x000D_
#ThumbnailContainer {_x000D_
flex: 2;_x000D_
background-color: black;_x000D_
}
_x000D_
<div id="Container">_x000D_
<div class="Content">_x000D_
<div id="Detail"></div>_x000D_
<div id="ThumbnailContainer"></div>_x000D_
</div>_x000D_
</div>
_x000D_
Try this:
var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));
This should return true
.
UPDATED: Added isNaN
check to handle the case commented by Julian H. Lam
You could use tabs instead of spaces between columns, and/or set maximum size for a column in format strings ...
It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap
object and draw into that using the Graphics.CopyFromScreen
method.
Sample code:
using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0, 0,
bmpScreenCapture.Size,
CopyPixelOperation.SourceCopy);
}
Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.
I had the same problem on Windows 7 64-bit Pro. I adjusted network adapters binding using Control panel but nothing changed. Also metrics where showing that Win should use Ethernet adapter as primary, but it didn't.
Then a tried to uninstall Ethernet adapter driver and then install it again (without restart) and then I checked metrics for sure.
After this, Windows started prioritize Ethernet adapter.
If your app is launched from device, not IDE, you can do later in menu: Run
- Attach Debugger to Android Process
.
This can be useful when debugging notifications on closed application.
Flexbox spec editor here.
This is an encouraged use of flexbox, but there are a few things you should tweak for best behavior.
Don't use prefixes. Unprefixed flexbox is well-supported across most browsers. Always start with unprefixed, and only add prefixes if necessary to support it.
Since your header and footer aren't meant to flex, they should both have flex: none;
set on them. Right now you have a similar behavior due to some overlapping effects, but you shouldn't rely on that unless you want to accidentally confuse yourself later. (Default is flex:0 1 auto
, so they start at their auto height and can shrink but not grow, but they're also overflow:visible
by default, which triggers their default min-height:auto
to prevent them from shrinking at all. If you ever set an overflow
on them, the behavior of min-height:auto
changes (switching to zero rather than min-content) and they'll suddenly get squished by the extra-tall <article>
element.)
You can simplify the <article>
flex
too - just set flex: 1;
and you'll be good to go. Try to stick with the common values in https://drafts.csswg.org/css-flexbox/#flex-common unless you have a good reason to do something more complicated - they're easier to read and cover most of the behaviors you'll want to invoke.
Use position:fixed
, as previously stated, IE6 doesn't recognize position:fixed
, but with some css magic you can get IE6 to behave:
html, body {
height: 100%;
overflow:auto;
}
body #fixedElement {
position:fixed !important;
position: absolute; /*ie6 */
bottom: 0;
}
The !important
flag makes it so you don't have to use a conditional comment for IE. This will have #fixedElement
use position:fixed
in all browsers but IE, and in IE
, position:absolute
will take effect with bottom:0
. This will simulate position:fixed
for IE6
I assume you are using windows. Open the command prompt and type ipconfig
and find out your local address (on your pc) it should look something like 192.168.1.13
or 192.168.0.5
where the end digit is the one that changes. It should be next to IPv4 Address.
If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13
If you have a virtual host then you will need root to edit the hosts file.
If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.
See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.
Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).
If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow
to allow,deny
in the httpd.conf
file. You can access this by the WAMP menu.
To eliminate possible causes of the issue for now set your config file to
<Directory />
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
<RequireAll>
Require all granted
</RequireAll>
</Directory>
As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.
Config file that fixed the problem:
https://gist.github.com/samvaughton/6790739
Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.
You are getting confused with transclude: true
, which would append the inner content.
replace: true
means that the content of the directive template will replace the element that the directive is declared on, in this case the <div myd1>
tag.
http://plnkr.co/edit/k9qSx15fhSZRMwgAIMP4?p=preview
For example without replace:true
<div myd1><span class="replaced" myd1="">directive template1</span></div>
and with replace:true
<span class="replaced" myd1="">directive template1</span>
As you can see in the latter example, the div tag is indeed replaced.
If all the staged files were actually committed, then the branch can simply be reset e.g. from your GUI with about three mouse clicks: Branch, Reset, Yes!
So what I often do in practice to revert unwanted local changes is to commit all the good stuff, and then reset the branch.
If the good stuff is committed in a single commit, then you can use "amend last commit" to bring it back to being staged or unstaged if you'd ultimately like to commit it a little differently.
This might not be the technical solution you are looking for to your problem, but I find it a very practical solution. It allows you to discard unstaged changes selectively, resetting the changes you don't like and keeping the ones you do.
So in summary, I simply do commit, branch reset, and amend last commit.
Note that numeric objects in R are stored with double precision, which gives you (roughly) 16 decimal digits of precision - the rest will be noise. I grant that the number shown above is probably just for an example, but it is 22 digits long.
Hey guys so i think i found a fix. This is working for me on iphone and android at the moment. Its a mash up of hours upon hours of searching, reading and testing. So if you see parts of your code in here credit goes to you lol.
@media only screen and (max-device-width:768px){
body.modal-open {
// block scroll for mobile;
// causes underlying page to jump to top;
// prevents scrolling on all screens
overflow: hidden;
position: fixed;
}
}
body.viewport-lg {
// block scroll for desktop;
// will not jump to top;
// will not prevent scroll on mobile
position: absolute;
}
body {
overflow-x: hidden;
overflow-y: scroll !important;
}
The reason the media specific is on there is on a desktop i was having issues with when the modal would open all content on the page would shift from centered to left. Looked like crap. So this targets up to tablet size devices where you would need to scroll. There is still a slight shift on mobile and tablet but its really not much. Let me know if this works for you guys. Hopefully this puts the nail in the coffin
With git there is a https format
https://github.com/equivalent/we_demand_serverless_ruby.git
This format accepts User + password
https://bot-user:[email protected]/equivalent/we_demand_serverless_ruby.git
So what you can do is create a new user that will be used just as a bot,
add only enough permissions that he can just read the repository you
want to load in NPM modules and just have that directly in your
packages.json
Github > Click on Profile > Settings > Developer settings > Personal access tokens > Generate new token
In Select Scopes part, check the on repo: Full control of private repositories
This is so that token can access private repos that user can see
Now create new group in your organization, add this user to the group and add only repositories that you expect to be pulled this way (READ ONLY permission !)
You need to be sure to push this config only to private repo
Then you can add this to your / packages.json (bot-user is name of user, xxxxxxxxx is the generated personal token)
// packages.json
{
// ....
"name_of_my_lib": "https://bot-user:[email protected]/ghuser/name_of_my_lib.git"
// ...
}
https://blog.eq8.eu/til/pull-git-private-repo-from-github-from-npm-modules-or-bundler.html
The onMessageReceived
method is fired only when app is in foreground or the notification payload only contains the data type.
From the Firebase docs
For downstream messaging, FCM provides two types of payload: notification and data.
For notification type, FCM automatically displays the message to end-user devices on behalf of the client app. Notifications have a predefined set of user-visible keys.
For data type, client app is responsible for processing data messages. Data messages have only custom key-value pairs.Use notifications when you want FCM to handle displaying a notification on your client app's behalf. Use data messages when you want your app to handle the display or process the messages on your Android client app, or if you want to send messages to iOS devices when there is a direct FCM connection.
Further down the docs
App behaviour when receiving messages that include both notification and data payloads depends on whether the app is in the background or the foreground—essentially, whether or not it is active at the time of receipt.
When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification.
When in the foreground, your app receives a message object with both payloads available.
If you are using the firebase console to send notifications, the payload will always contain the notification type. You have to use the Firebase API to send the notification with only the data type in the notification payload. That way your app is always notified when a new notification is received and the app can handle the notification payload.
If you want to play notification sound when app is in background using the conventional method, you need to add the sound parameter to the notification payload.
This works for me:
File file = new File("c:\\myjar.jar");
URL url = file.toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass("com.mypackage.myclass");
It's an iterator returned by the filter function.
If you want a list, just do
list(filter(f, range(2, 25)))
Nonetheless, you can just iterate over this object with a for
loop.
for e in filter(f, range(2, 25)):
do_stuff(e)
Also available using one of the serializer settings overloads:
var json = JsonConvert.SerializeObject(someObject, new JsonSerializerSettings() { DateFormatString = "yyyy-MM-ddThh:mm:ssZ" });
Or
var json = JsonConvert.SerializeObject(someObject, Formatting.Indented, new JsonSerializerSettings() { DateFormatString = "yyyy-MM-ddThh:mm:ssZ" });
Overloads taking a Type are also available.
If you want you can use the recommended Bootstrap plugin to dynamize your custom file input: https://www.npmjs.com/package/bs-custom-file-input
This plugin can be use with or without jQuery and works with React an Angular
The only winning move is not to play.
No infinite variability for you. Only finite variability.
In the SQL you have a clause like this:
and ( {1}==0 or b.CompanyId in ({2},{3},{4},{5},{6}) )
In the C# code you do something like this:
int origCount = idList.Count;
if (origCount > 5) {
throw new Exception("You may only specify up to five originators to filter on.");
}
while (idList.Count < 5) { idList.Add(-1); } // -1 is an impossible value
return ExecuteQuery<PublishDate>(getValuesInListSQL,
origCount,
idList[0], idList[1], idList[2], idList[3], idList[4]);
So basically if the count is 0 then there is no filter and everything goes through. If the count is higher than 0 the then the value must be in the list, but the list has been padded out to five with impossible values (so that the SQL still makes sense)
Sometimes the lame solution is the only one that actually works.
Great and exhaustive answerby @Kev!
Since I did long processing only in one admin page in a WebForms application I used the code option. But to allow a temporary quick fix on production I used the config version in a <location>
tag in web.config. This way my admin/processing page got enough time, while pages for end users and such kept their old time out behaviour.
Below I gave the config for you Googlers needing the same quick fix. You should ofcourse use other values than my '4 hour' example, but DO note that the session timeOut
is in minutes, while the request executionTimeout
is in seconds!
And - since it's 2015 already - for a NON- quickfix you should use .Net 4.5's async/await now if at all possible, instead of the .NET 2.0's ASYNC page that was state of the art when KEV answered in 2010 :).
<configuration>
...
<compilation debug="false" ...>
... other stuff ..
<location path="~/Admin/SomePage.aspx">
<system.web>
<sessionState timeout="240" />
<httpRuntime executionTimeout="14400" />
</system.web>
</location>
...
</configuration>
The System.Math.Round
method uses the Double
structure, which, as others have pointed out, is prone to floating point precision errors. The simple solution I found to this problem when I encountered it was to use the System.Decimal.Round
method, which doesn't suffer from the same problem and doesn't require redifining your variables as decimals:
Decimal.Round(0.575, 2, MidpointRounding.AwayFromZero)
Result: 0.58
https://www.programmableweb.com/ -- Great collection of all category API's across web. It not only show cases the API's , but also Developers who use those API's in their applications and code samples, rating of the API and much more. They have more than apis they also have sdk and libraries too.
You can't run the request from a browser, it will timeout waiting for the server running the CURL request to respond. The browser is probably timing out in 1-2 minutes, the default network timeout.
You need to run it from the command line/terminal.
In Python, to represent the absence of a value, you can use the None value (types.NoneType.None) for objects and "" (or len() == 0) for strings. Therefore:
if yourObject is None: # if yourObject == None:
...
if yourString == "": # if yourString.len() == 0:
...
Regarding the difference between "==" and "is", testing for object identity using "==" should be sufficient. However, since the operation "is" is defined as the object identity operation, it is probably more correct to use it, rather than "==". Not sure if there is even a speed difference.
Anyway, you can have a look at:
You need to call finish()
from the UI thread, not a background thread. The way to do this is to declare a Handler and ask the Handler to run a Runnable on the UI thread. For example:
public class LoadingScreen extends Activity{
private LoadingScreen loadingScreen;
Intent i = new Intent(this, HomeScreen.class);
Handler handler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new Handler();
setContentView(R.layout.loading);
CountDownTimer timer = new CountDownTimer(10000, 1000) //10seceonds Timer
{
@Override
public void onTick(long l)
{
}
@Override
public void onFinish()
{
handler.post(new Runnable() {
public void run() {
loadingScreen.finishActivity(0);
startActivity(i);
}
});
};
}.start();
}
}
mvn install
is the option that is most often used.
mvn package
is seldom used, only if you're debugging some issue with the maven build process.
See: http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html
Note that mvn package
will only create a jar file.
mvn install
will do that and install the jar (and class etc.) files in the proper places if other code depends on those jars.
I usually do a mvn clean install
; this deletes the target
directory and recreates all jars in that location.
The clean helps with unneeded or removed stuff that can sometimes get in the way.
Rather then debug (some of the time) just start fresh all of the time.
If you just want to disable App Transport Policy for local dev servers then the following solutions work well. It's useful when you're unable, or it's impractical, to set up HTTPS (e.g. when using the Google App Engine dev server).
As others have said though, ATP should definitely not be turned off for production apps.
Copy your Plist file and NSAllowsArbitraryLoads. Use this Plist for debugging.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Alternatively, you can use a single plist file and exclude specific servers. However, it doesn't look like you can exclude IP 4 addresses so you might need to use the server name instead (found in System Preferences -> Sharing, or configured in your local DNS).
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>server.local</key>
<dict/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
Typically, you'd use the NODE_ENV
variable to take special actions when you develop, test and debug your code. For example to produce detailed logging and debug output which you don't want in production. Express itself behaves differently depending on whether NODE_ENV
is set to production
or not. You can see this if you put these lines in an Express app, and then make a HTTP GET request to /error
:
app.get('/error', function(req, res) {
if ('production' !== app.get('env')) {
console.log("Forcing an error!");
}
throw new Error('TestError');
});
app.use(function (req, res, next) {
res.status(501).send("Error!")
})
Note that the latter app.use()
must be last, after all other method handlers!
If you set NODE_ENV
to production
before you start your server, and then send a GET /error
request to it, you should not see the text Forcing an error!
in the console, and the response should not contain a stack trace in the HTML body (which origins from Express).
If, instead, you set NODE_ENV
to something else before starting your server, the opposite should happen.
In Linux, set the environment variable NODE_ENV like this:
export NODE_ENV='value'
Swing + SwingX + Miglayout is my combination of choice. Miglayout is so much simpler than Swings perceived 200 different layout managers and much more powerful. Also, it provides you with the ability to "debug" your layouts, which is especially handy when creating complex layouts.
isinstance()
In your case, isinstance("this is a string", str)
will return True
.
You may also want to read this: http://www.canonical.org/~kragen/isinstance/
Try
select * from dataset
where id = 2
order by date limit 1
Been a while since I did sql, so this might need some tweaking.
A primary key is the key that uniquely identifies a record and is used in all indexes. This is why you can't have more than one. It is also generally the key that is used in joining to child tables but this is not a requirement. The real purpose of a PK is to make sure that something allows you to uniquely identify a record so that data changes affect the correct record and so that indexes can be created.
However, you can put multiple fields in one primary key (a composite PK). This will make your joins slower (espcially if they are larger string type fields) and your indexes larger but it may remove the need to do joins in some of the child tables, so as far as performance and design, take it on a case by case basis. When you do this, each field itself is not unique, but the combination of them is. If one or more of the fields in a composite key should also be unique, then you need a unique index on it. It is likely though that if one field is unique, this is a better candidate for the PK.
Now at times, you have more than one candidate for the PK. In this case you choose one as the PK or use a surrogate key (I personally prefer surrogate keys for this instance). And (this is critical!) you add unique indexes to each of the candidate keys that were not chosen as the PK. If the data needs to be unique, it needs a unique index whether it is the PK or not. This is a data integrity issue. (Note this is also true anytime you use a surrogate key; people get into trouble with surrogate keys because they forget to create unique indexes on the candidate keys.)
There are occasionally times when you want more than one surrogate key (which are usually the PK if you have them). In this case what you want isn't more PK's, it is more fields with autogenerated keys. Most DBs don't allow this, but there are ways of getting around it. First consider if the second field could be calculated based on the first autogenerated key (Field1 * -1 for instance) or perhaps the need for a second autogenerated key really means you should create a related table. Related tables can be in a one-to-one relationship. You would enforce that by adding the PK from the parent table to the child table and then adding the new autogenerated field to the table and then whatever fields are appropriate for this table. Then choose one of the two keys as the PK and put a unique index on the other (the autogenerated field does not have to be a PK). And make sure to add the FK to the field that is in the parent table. In general if you have no additional fields for the child table, you need to examine why you think you need two autogenerated fields.
$configValue = Mage::getStoreConfig('sectionName/groupName/fieldName');
sectionName, groupName and fieldName are present in etc/system.xml file of your module.
The above code will automatically fetch config value of currently viewed store.
If you want to fetch config value of any other store than the currently viewed store then you can specify store ID as the second parameter to the getStoreConfig
function as below:
$store = Mage::app()->getStore(); // store info
$configValue = Mage::getStoreConfig('sectionName/groupName/fieldName', $store);
//Properly Formatted
<script type="text/Javascript">
$(function ()
{
$('<div>').dialog({
modal: true,
open: function ()
{
$(this).load('mypage.html');
},
height: 400,
width: 600,
title: 'Ajax Page'
});
});
file__IO = input('\nEnter file name here to analize with path:: ')
with open(file__IO, 'r') as f:
data = f.read()
line = data.splitlines()
words = data.split()
spaces = data.split(" ")
charc = (len(data) - len(spaces))
print('\n Line number ::', len(line), '\n Words number ::', len(words), '\n Spaces ::', len(spaces), '\n Charecters ::', (len(data)-len(spaces)))
I tried this code & it works as expected.
$url = "https://chart.googleapis....";
$json = file_get_contents($url);
Now you can either echo the $json variable, if you just want to display the output, or you can decode it, and do something with it, like so:
$data = json_decode($json);
var_dump($data);
static void Main(string[] args)
{
//---listen at the specified IP and port no.---
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
Console.WriteLine("Listening...");
listener.Start();
while (true)
{
//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received : " + dataReceived);
//---write back the text to the client---
Console.WriteLine("Sending back : " + dataReceived);
nwStream.Write(buffer, 0, bytesRead);
client.Close();
}
listener.Stop();
Console.ReadLine();
}
In addition to @Nudier Mena answer, keep a while loop to keep the server in listening mode. So that we can have multiple instance of client connected.
You could use sp_executesql
instead of exec
. That allows you to specify an output parameter.
declare @out_var varchar(max);
execute sp_executesql
N'select @out_var = ''hello world''',
N'@out_var varchar(max) OUTPUT',
@out_var = @out_var output;
select @out_var;
This prints "hello world".
Answering the "usefulness" part of the question:
One rather subtle gotcha of using FileChannel
over FileOutputStream
is that performing any of its blocking operations (e.g. read()
or write()
) from a thread that's in interrupted state will cause the channel to close abruptly with java.nio.channels.ClosedByInterruptException
.
Now, this could be a good thing if whatever the FileChannel
was used for is part of the thread's main function, and design took this into account.
But it could also be pesky if used by some auxiliary feature such as a logging function. For example, you can find your logging output suddenly closed if the logging function happens to be called by a thread that's also interrupted.
It's unfortunate this is so subtle because not accounting for this can lead to bugs that affect write integrity.[1][2]
If i want to run command promt in silent mode, then there is a simple vbs command:
Set ws=CreateObject("WScript.Shell")
ws.Run "TASKKILL.exe /F /IM iexplore.exe"
if i wanted to open an url in cmd silently, then here is a code:
Set WshShell = WScript.CreateObject("WScript.Shell")
Return = WshShell.Run("iexplore.exe http://otaxi.ge/log/index.php", 0)
'wait 10 seconds
WScript.sleep 10000
Set ws=CreateObject("WScript.Shell")
ws.Run "TASKKILL.exe /F /IM iexplore.exe"
I very recently had the some problem and just figured out how to do this. Assuming you have three classes, Primary, B, C and that B,C have a foreign key to primary
class PrimaryForm(ModelForm):
class Meta:
model = Primary
class BForm(ModelForm):
class Meta:
model = B
exclude = ('primary',)
class CForm(ModelForm):
class Meta:
model = C
exclude = ('primary',)
def generateView(request):
if request.method == 'POST': # If the form has been submitted...
primary_form = PrimaryForm(request.POST, prefix = "primary")
b_form = BForm(request.POST, prefix = "b")
c_form = CForm(request.POST, prefix = "c")
if primary_form.is_valid() and b_form.is_valid() and c_form.is_valid(): # All validation rules pass
print "all validation passed"
primary = primary_form.save()
b_form.cleaned_data["primary"] = primary
b = b_form.save()
c_form.cleaned_data["primary"] = primary
c = c_form.save()
return HttpResponseRedirect("/viewer/%s/" % (primary.name))
else:
print "failed"
else:
primary_form = PrimaryForm(prefix = "primary")
b_form = BForm(prefix = "b")
c_form = Form(prefix = "c")
return render_to_response('multi_model.html', {
'primary_form': primary_form,
'b_form': b_form,
'c_form': c_form,
})
This method should allow you to do whatever validation you require, as well as generating all three objects on the same page. I have also used javascript and hidden fields to allow the generation of multiple B,C objects on the same page.
For Angular 7, I followed these steps to directly import json data:
In tsconfig.app.json:
add "resolveJsonModule": true
in "compilerOptions"
In a service or component:
import * as exampleData from '../example.json';
And then
private example = exampleData;
Try with this
Response.Clear();
Response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.pptx;", getLegalFileName(CurrentPresentation.Presentation_NM)));
Response.Flush();
Response.BinaryWrite(masterPresentation.ToArray());
Response.End();
A simple python version of the code that find a pair sum of zero and can be modify to find k:
def sumToK(lst):
k = 0 # <- define the k here
d = {} # build a dictionary
# build the hashmap key = val of lst, value = i
for index, val in enumerate(lst):
d[val] = index
# find the key; if a key is in the dict, and not the same index as the current key
for i, val in enumerate(lst):
if (k-val) in d and d[k-val] != i:
return True
return False
The run time complexity of the function is O(n) and Space: O(n) as well.
class Program
{
Variable va = new Variable();
static void Main(string[] args)
{
va.name = "Stackoverflow";
}
}
Encapsulation is hiding the implementation details which may or may not be for generic or specialized behavior(s).
Abstraction is providing a generalization (say, over a set of behaviors).
Here's a good read: Abstraction, Encapsulation, and Information Hiding by Edward V. Berard of the Object Agency.
Try setting 'clientCredentialType' to 'Windows' instead of 'Ntlm'.
I think that this is what the server is expecting - i.e. when it says the server expects "Negotiate,NTLM", that actually means Windows Auth, where it will try to use Kerberos if available, or fall back to NTLM if not (hence the 'negotiate')
I'm basing this on somewhat reading between the lines of: Selecting a Credential Type
The reason csv
doesn't support that is because variable-length lines are not really supported on most filesystems. What you should do instead is collect all the data in lists, then call zip()
on them to transpose them after.
>>> l = [('Result_1', 'Result_2', 'Result_3', 'Result_4'), (1, 2, 3, 4), (5, 6, 7, 8)]
>>> zip(*l)
[('Result_1', 1, 5), ('Result_2', 2, 6), ('Result_3', 3, 7), ('Result_4', 4, 8)]
And this is if copying a single property to another list is needed:
targetList.AddRange(sourceList.Select(i => i.NeededProperty));
float : 23 bits of significand, 8 bits of exponent, and 1 sign bit.
double : 52 bits of significand, 11 bits of exponent, and 1 sign bit.
Try this:
scanf("%[^\n]s",name);
\n
just sets the delimiter for the scanned string.
I think your co-worker is right as long as he does not enter in the process to write executable code in the header. The right balance, I think, is to follow the path indicated by GNAT Ada where the .ads file gives a perfectly adequate interface definition of the package for its users and for its childs.
By the way Ted, have you had a look on this forum to the recent question on the Ada binding to the CLIPS library you wrote several years ago and which is no more available (relevant Web pages are now closed). Even if made to an old Clips version, this binding could be a good start example for somebody willing to use the CLIPS inference engine within an Ada 2012 program.
You can use Calendar class :
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -7);
System.out.println("Date = "+ cal.getTime());
But as @Sean Patrick Floyd mentioned , Joda-time is the best Java library for Date.
I was also stuck on this problem then I saw that the ids of the modal are the same. You need different ids of modals if you want multiple modals. I used dynamic id. Here is my code in haml
:
.modal.hide.fade{"id"=> discount.id,"aria-hidden" => "true", "aria-labelledby" => "myModalLabel", :role => "dialog", :tabindex => "-1"}
you can do this
<div id="<%= some.id %>" class="modal hide fade in">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Header</h3>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<input type="submit" class="btn btn-success" value="Save" />
</div>
</div>
and your links to modal will be
<a data-toggle="modal" data-target="#" href='"#"+<%= some.id %>' >Open modal</a>
<a data-toggle="modal" data-target="#myModal" href='"#"+<%= some.id %>' >Open modal</a>
<a data-toggle="modal" data-target="#myModal" href='"#"+<%= some.id %>' >Open modal</a>
I hope this will work for you.
Do I really have to first convert it into an array of arrays of key-value pairs?
No, an iterator of key-value pair arrays is enough. You can use the following to avoid creating the intermediate array:
function* entries(obj) {
for (let key in obj)
yield [key, obj[key]];
}
const map = new Map(entries({foo: 'bar'}));
map.get('foo'); // 'bar'
I encountered difficulties with Roi-Kyi Bryant's solution when multiple add-ins tried to modify the ribbon. I also don't have admin access on my work-computer, which ruled out installing the Custom UI Editor
. So, if you're in the same boat as me, here's an alternative example to customising the ribbon using only Excel. Note, my solution is derived from the Microsoft guide.
.xlam
files, Chart Tools.xlam
and Priveleged UDFs.xlam
, to demonstrate how multiple add-ins can interact with the Ribbon. customUI
and _rels
folder.customUI
folder, create a customUI.xml
file. The customUI.xml
file details how Excel files interact with the ribbon. Part 2 of the Microsoft guide covers the elements in the customUI.xml
file.My customUI.xml
file for Chart Tools.xlam
looks like this
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" xmlns:x="sao">
<ribbon>
<tabs>
<tab idQ="x:chartToolsTab" label="Chart Tools">
<group id="relativeChartMovementGroup" label="Relative Chart Movement" >
<button id="moveChartWithRelativeLinksButton" label="Copy and Move" imageMso="ResultsPaneStartFindAndReplace" onAction="MoveChartWithRelativeLinksCallBack" visible="true" size="normal"/>
<button id="moveChartToManySheetsWithRelativeLinksButton" label="Copy and Distribute" imageMso="OutlineDemoteToBodyText" onAction="MoveChartToManySheetsWithRelativeLinksCallBack" visible="true" size="normal"/>
</group >
<group id="chartDeletionGroup" label="Chart Deletion">
<button id="deleteAllChartsInWorkbookSharingAnAddressButton" label="Delete Charts" imageMso="CancelRequest" onAction="DeleteAllChartsInWorkbookSharingAnAddressCallBack" visible="true" size="normal"/>
</group>
</tab>
</tabs>
</ribbon>
</customUI>
My customUI.xml
file for Priveleged UDFs.xlam
looks like this
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" xmlns:x="sao">
<ribbon>
<tabs>
<tab idQ="x:privelgedUDFsTab" label="Privelged UDFs">
<group id="privelgedUDFsGroup" label="Toggle" >
<button id="initialisePrivelegedUDFsButton" label="Activate" imageMso="TagMarkComplete" onAction="InitialisePrivelegedUDFsCallBack" visible="true" size="normal"/>
<button id="deInitialisePrivelegedUDFsButton" label="De-Activate" imageMso="CancelRequest" onAction="DeInitialisePrivelegedUDFsCallBack" visible="true" size="normal"/>
</group >
</tab>
</tabs>
</ribbon>
</customUI>
.zip
to their file name. In my case, I renamed Chart Tools.xlam
to Chart Tools.xlam.zip
, and Privelged UDFs.xlam
to Priveleged UDFs.xlam.zip
..zip
file, and navigate to the _rels
folder. Copy the .rels
file to the _rels
folder you created in Step 3. Edit each .rels
file with a text editor. From the Microsoft guideBetween the final
<Relationship>
element and the closing<Relationships>
element, add a line that creates a relationship between the document file and the customization file. Ensure that you specify the folder and file names correctly.
<Relationship Type="http://schemas.microsoft.com/office/2006/
relationships/ui/extensibility" Target="/customUI/customUI.xml"
Id="customUIRelID" />
My .rels
file for Chart Tools.xlam
looks like this
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
<Relationship Type="http://schemas.microsoft.com/office/2006/relationships/ui/extensibility" Target="/customUI/customUI.xml" Id="chartToolsCustomUIRel" />
</Relationships>
My .rels
file for Priveleged UDFs
looks like this.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
<Relationship Type="http://schemas.microsoft.com/office/2006/relationships/ui/extensibility" Target="/customUI/customUI.xml" Id="privelegedUDFsCustomUIRel" />
</Relationships>
.rels
files in each .zip
file with the .rels
file/files you modified in the previous step..customUI
folder you created into the home directory of the .zip
file/files..zip
file extension from the Excel files you created..xlam
files, back in Excel, add them to your Excel add-ins.onAction
keywords in my buttons. The onAction
keyword indicates that, when the containing element is triggered, the Excel application will trigger the sub-routine encased in quotation marks directly after the onAction
keyword. This is known as a callback. In my .xlam
files, I have a module called CallBacks
where I've included my callback sub-routines.My CallBacks
module for Chart Tools.xlam
looks like
Option Explicit
Public Sub MoveChartWithRelativeLinksCallBack(ByRef control As IRibbonControl)
MoveChartWithRelativeLinks
End Sub
Public Sub MoveChartToManySheetsWithRelativeLinksCallBack(ByRef control As IRibbonControl)
MoveChartToManySheetsWithRelativeLinks
End Sub
Public Sub DeleteAllChartsInWorkbookSharingAnAddressCallBack(ByRef control As IRibbonControl)
DeleteAllChartsInWorkbookSharingAnAddress
End Sub
My CallBacks
module for Priveleged UDFs.xlam
looks like
Option Explicit
Public Sub InitialisePrivelegedUDFsCallBack(ByRef control As IRibbonControl)
ThisWorkbook.InitialisePrivelegedUDFs
End Sub
Public Sub DeInitialisePrivelegedUDFsCallBack(ByRef control As IRibbonControl)
ThisWorkbook.DeInitialisePrivelegedUDFs
End Sub
Different elements have a different callback sub-routine signature. For buttons, the required sub-routine parameter is ByRef control As IRibbonControl
. If you don't conform to the required callback signature, you will receive an error while compiling your VBA project/projects. Part 3 of the Microsoft guide defines all the callback signatures.
Here's what my finished example looks like
Some closing tips
idQ
and xlmns:
keyword. In my example, the Chart Tools.xlam
and Priveleged UDFs.xlam
both have access to the elements with idQ
's equal to x:chartToolsTab
and x:privelgedUDFsTab
. For this to work, the x:
is required, and, I've defined its namespace in the first line of my customUI.xml
file, <customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" xmlns:x="sao">
. The section Two Ways to Customize the Fluent UI in the Microsoft guide gives some more details.isMSO
keyword. The section Two Ways to Customize the Fluent UI in the Microsoft guide gives some more details.For adding margins to specified cells, you can use this custom flow layout. https://github.com/voyages-sncf-technologies/VSCollectionViewCellInsetFlowLayout/
extension ViewController : VSCollectionViewDelegateCellInsetFlowLayout
{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForItemAt indexPath: IndexPath) -> UIEdgeInsets {
if indexPath.item == 0 {
return UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)
}
return UIEdgeInsets.zero
}
}
t
refers to the text mode. There is no difference between r
and rt
or w
and wt
since text mode is the default.
Documented here:
Character Meaning
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newlines mode (deprecated)
The default mode is 'r'
(open for reading text, synonym of 'rt'
).
Try this markdown:
![alt text](http://url/to/img.png)
I think you can link directly to the raw version of an image if it's stored in your repository. i.e.
![alt text](https://github.com/[username]/[reponame]/blob/[branch]/image.jpg?raw=true)
As Selman22 said, you are overriding the default object.Equals
method, which accepts an object obj
and not a safe compile time type.
In order for that to happen, make your type implement IEquatable<Box>
:
public class Box : IEquatable<Box>
{
double height, length, breadth;
public static bool operator ==(Box obj1, Box obj2)
{
if (ReferenceEquals(obj1, obj2))
{
return true;
}
if (ReferenceEquals(obj1, null))
{
return false;
}
if (ReferenceEquals(obj2, null))
{
return false;
}
return obj1.Equals(obj2);
}
public static bool operator !=(Box obj1, Box obj2)
{
return !(obj1 == obj2);
}
public bool Equals(Box other)
{
if (ReferenceEquals(other, null))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return height.Equals(other.height)
&& length.Equals(other.length)
&& breadth.Equals(other.breadth);
}
public override bool Equals(object obj)
{
return Equals(obj as Box);
}
public override int GetHashCode()
{
unchecked
{
int hashCode = height.GetHashCode();
hashCode = (hashCode * 397) ^ length.GetHashCode();
hashCode = (hashCode * 397) ^ breadth.GetHashCode();
return hashCode;
}
}
}
Another thing to note is that you are making a floating point comparison using the equality operator and you might experience a loss of precision.
http://jsfiddle.net/kkobold/qMQL5/
#header {_x000D_
width: 100%;_x000D_
background-color: red;_x000D_
height: 30px;_x000D_
}_x000D_
_x000D_
#container {_x000D_
width: 300px;_x000D_
background-color: #ffcc33;_x000D_
margin: auto;_x000D_
}_x000D_
#first {_x000D_
width: 100px;_x000D_
float: left;_x000D_
height: 300px;_x000D_
background-color: blue;_x000D_
}_x000D_
#second {_x000D_
width: 200px;_x000D_
float: left;_x000D_
height: 300px;_x000D_
background-color: green;_x000D_
}_x000D_
#clear {_x000D_
clear: both;_x000D_
}
_x000D_
<div id="header"></div>_x000D_
<div id="container">_x000D_
<div id="first"></div>_x000D_
<div id="second"></div>_x000D_
<div id="clear"></div>_x000D_
</div>
_x000D_
jQuery is simply supporting the way CSS is written.
Also, it ensures that no matter how a browser returns a value, it will be understood
jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both .css('background-color') and .css('backgroundColor').
You can try ppss. ppss is rather powerful - you can even create a mini-cluster. xargs -P can also be useful if you've got a batch of embarrassingly parallel processing to do.
I haven't had any problems with this code:
private bool IsValidPath(string path, bool exactPath = true)
{
bool isValid = true;
try
{
string fullPath = Path.GetFullPath(path);
if (exactPath)
{
string root = Path.GetPathRoot(path);
isValid = string.IsNullOrEmpty(root.Trim(new char[] { '\\', '/' })) == false;
}
else
{
isValid = Path.IsPathRooted(path);
}
}
catch(Exception ex)
{
isValid = false;
}
return isValid;
}
For example these would return false:
IsValidPath("C:/abc*d");
IsValidPath("C:/abc?d");
IsValidPath("C:/abc\"d");
IsValidPath("C:/abc<d");
IsValidPath("C:/abc>d");
IsValidPath("C:/abc|d");
IsValidPath("C:/abc:d");
IsValidPath("");
IsValidPath("./abc");
IsValidPath("/abc");
IsValidPath("abc");
IsValidPath("abc", false);
And these would return true:
IsValidPath(@"C:\\abc");
IsValidPath(@"F:\FILES\");
IsValidPath(@"C:\\abc.docx\\defg.docx");
IsValidPath(@"C:/abc/defg");
IsValidPath(@"C:\\\//\/\\/\\\/abc/\/\/\/\///\\\//\defg");
IsValidPath(@"C:/abc/def~`!@#$%^&()_-+={[}];',.g");
IsValidPath(@"C:\\\\\abc////////defg");
IsValidPath(@"/abc", false);
Btw, you cannot encrypt with DSA, only sign. Although they are mathematically equivalent (more or less) you cannot use DSA in practice as an encryption scheme, only as a digital signature scheme.
I had my Apache service not start same as MySQL one. Please follow these steps if none of above tips works :
Note: Ports 80 and 443 must be unused by any program.
If it is in use . Just edit ports. There is a lot of tutorials about that .
I have answered a similar question here.
I know you have already said position: absolute;
is inconvenient, but it works. See below for further information on fixing the resize issue.
Also see this jsFiddle for a demo, although I have only added WebKit prefixes so open in Chrome.
You basically have two issues which I will deal with separately.
position: relative;
on the parent of the child.position: absolute;
on the child.overflow-y: auto;
on the scrollable div.height: 0;
See this answer for more information on the scrolling issue.
You need to enclose multiple conditions in braces due to operator precedence and use the bitwise and (&
) and or (|
) operators:
foo = df[(df['column1']==value) | (df['columns2'] == 'b') | (df['column3'] == 'c')]
If you use and
or or
, then pandas is likely to moan that the comparison is ambiguous. In that case, it is unclear whether we are comparing every value in a series in the condition, and what does it mean if only 1 or all but 1 match the condition. That is why you should use the bitwise operators or the numpy np.all
or np.any
to specify the matching criteria.
There is also the query method: http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.query.html
but there are some limitations mainly to do with issues where there could be ambiguity between column names and index values.
Laravel's Autoload is a bit different:
1) It will in fact use Composer for some stuff
2) It will call Composer with the optimize flag
3) It will 'recompile' loads of files creating the huge bootstrap/compiled.php
4) And also will find all of your Workbench packages and composer dump-autoload them, one by one.
I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server
argument.
$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
Get-ADUser -Server $dc.HostName[0] `
-Filter { EmailAddress -Like "*Smith_Karla*" } `
-Properties EmailAddress
All of your Laravel files should be in one location. Laravel is exposing its public folder to server. That folder represents some kind of front-controller to whole application. Depending on you server configuration, you have to point your server path to that folder. As I can see there is www site on your picture. www is default root directory on Unix/Linux machines. It is best to take a look inside you server configuration and search for root directory location. As you can see, Laravel has already file called .htaccess, with some ready Apache configuration.
To export data to csv/excel from Kibana follow the following steps:-
Click on Visualize Tab & select a visualization (if created). If not created create a visualziation.
Click on caret symbol (^) which is present at the bottom of the visualization.
Then you will get an option of Export:Raw Formatted as the bottom of the page.
Please find below attached image showing Export option after clicking on caret symbol.
Answering the additional question:
my following test code for typeid does not output the correct type name. what's wrong?
There isn't anything wrong. What you see is the string representation of the type name. The standard C++ doesn't force compilers to emit the exact name of the class, it is just up to the implementer(compiler vendor) to decide what is suitable. In short, the names are up to the compiler.
These are two different tools. typeof
returns the type of an expression, but it is not standard. In C++0x there is something called decltype
which does the same job AFAIK.
decltype(0xdeedbeef) number = 0; // number is of type int!
decltype(someArray[0]) element = someArray[0];
Whereas typeid
is used with polymorphic types. For example, lets say that cat
derives animal
:
animal* a = new cat; // animal has to have at least one virtual function
...
if( typeid(*a) == typeid(cat) )
{
// the object is of type cat! but the pointer is base pointer.
}
Item[] newItemList = new Item[itemList.length+1];
//for loop to go thorough the list one by one
for(int i=0; i< itemList.length;i++){
//value is stored here in the new list from the old one
newItemList[i]=itemList[i];
}
//all the values of the itemLists are stored in a bigger array named newItemList
itemList=newItemList;
If you are developing for Windows, the com0com project might be, what you are looking for.
It provides pairs of virtual COM ports that are linked via a nullmodem connetion. You can then use your favorite terminal application or whatever you like to send data to one COM port and recieve from the other one.
As Thomas pointed out the project lacks of a signed driver, which is especially problematic on certain Windows version (e.g. Windows 7 x64).
There are a couple of unofficial com0com versions around that do contain a signed driver. One recent verion (3.0.0.0) can be downloaded e.g. from here.
In Eclipse
, right click on the xsd
file you want to get --> Generate --> Java... --> Generator: "Schema to JAXB Java Classes".
I just faced the same problem, I had a bunch of xsd
files, only one of them being the XML Root Element
and it worked well what I explained above in Eclipse
Since you are using C++11, lambda-expression is a nice&clean solution.
class blub {
void test() {}
public:
std::thread spawn() {
return std::thread( [this] { this->test(); } );
}
};
since this->
can be omitted, it could be shorten to:
std::thread( [this] { test(); } )
or just (deprecated)
std::thread( [=] { test(); } )
I repeatedly had the same challenge sometime ago. This problem occurs mostly when you are trying to pull from the remote repository and you have some files on your local instance conflicting with the remote version, if you are using git from an IDE such as IntelliJ, you will be prompted and allowed to make a choice if you want to retain your own changes or you prefer the changes in the remote version to overwrite yours'. If you don't make any choice then you fall into this conflict. all you need to do is run:
git merge --abort # The unresolved conflict will be cleared off
And you can continue what you were doing before the break.
Copy-pasted from here:
/* localtime example */
#include <stdio.h>
#include <time.h>
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) );
return 0;
}
(just add void
to the main()
arguments list in order for this to work in C)
There are many reasons, but perhaps the most important one is that those functions encourage insecure programming practices because they do not support prepared statements. Prepared statements help prevent SQL injection attacks.
When using mysql_*
functions, you have to remember to run user-supplied parameters through mysql_real_escape_string()
. If you forget in just one place or if you happen to escape only part of the input, your database may be subject to attack.
Using prepared statements in PDO
or mysqli
will make it so that these sorts of programming errors are more difficult to make.
This question may be a little old, but because I think the "right" answer here is only one way which can lead to some issues hidden Issues later in your code. Even if there is a little Controversy, Checked Exceptions exist for a reason.
The most elegant way in my opinion can you find was given by Misha here Aggregate runtime exceptions in Java 8 streams by just performing the actions in "futures". So you can run all the working parts and collect not working Exceptions as a single one. Otherwise you could collect them all in a List and process them later.
A similar approach comes from Benji Weber. He suggests to create an own type to collect working and not working parts.
Depending on what you really want to achieve a simple mapping between the input values and Output Values occurred Exceptions may also work for you.
If you don't like any of these ways consider using (depending on the Original Exception) at least an own exception.
Issue :
configure: error: no acceptable C compiler found in $PATH
Fixed the issue by executing the following command:
yum install gcc
to install gcc.
Open a visual command console (Visual Studio Command Prompt)
dumpbin /ARCHIVEMEMBERS openssl.x86.lib
or
lib /LIST openssl.x86.lib
or just open it with 7-zip :) its an AR archive
As Blazemonger said, #parent, .panel and .collapse have to be direct descendants. However, if You can't change Your html, You can do workaround using bootstrap events and methods with the following code:
$('#your-parent .collapse').on('show.bs.collapse', function (e) {
var actives = $('#your-parent').find('.in, .collapsing');
actives.each( function (index, element) {
$(element).collapse('hide');
})
})
Since the question mentioned third-party libraries and not all packages then you probably want to fall back to using wildcards.
A use case being: I just want to update all my packages that are obtained from the Github VCS, then you would just say:
go get -u github.com/... // ('...' being the wildcard).
This would go ahead and only update your github packages in the current $GOPATH
Same applies for within a VCS too, say you want to only upgrade all the packages from ogranizaiton A's repo's since as they have released a hotfix you depend on:
go get -u github.com/orgA/...
Try this!
1 - Install dependencies for show save/open file pop-up
npm install file-saver --save
npm install @types/file-saver --save
2- Create a service with this function to recive the data
downloadFile(id): Observable<Blob> {
let options = new RequestOptions({responseType: ResponseContentType.Blob });
return this.http.get(this._baseUrl + '/' + id, options)
.map(res => res.blob())
.catch(this.handleError)
}
3- In the component parse the blob with 'file-saver'
import {saveAs as importedSaveAs} from "file-saver";
this.myService.downloadFile(this.id).subscribe(blob => {
importedSaveAs(blob, this.fileName);
}
)
This works for me!
Thanks all for your help but it is not complicated as it seems; almost everything is handled internally by SpringBoot.
In my case I want to use Mysql and Mongodb and the solution was to use EnableMongoRepositories
and EnableJpaRepositories
annotations on to my application class.
@SpringBootApplication
@EnableTransactionManagement
@EnableMongoRepositories(includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MongoRepository))
@EnableJpaRepositories(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MongoRepository))
class TestApplication { ...
NB: All mysql entities have to extend JpaRepository
and mongo enities have to extend MongoRepository
.
The datasource configs are straight forward as presented by spring documentation:
//mysql db config
spring.datasource.url= jdbc:mysql://localhost:3306/tangio
spring.datasource.username=test
spring.datasource.password=test
#mongodb config
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=tangio
spring.data.mongodb.username=tangio
spring.data.mongodb.password=tangio
spring.data.mongodb.repositories.enabled=true
do wget -r -l0 www.oldsite.com
Then just find www.oldsite.com
would reveal all urls, I believe.
Alternatively, just serve that custom not-found page on every 404 request! I.e. if someone used the wrong link, he would get the page telling that page wasn't found, and making some hints about site's content.
I'd do it like this:
f = open('test.txt')
l = [l for l in f.readlines() if l.strip()]
f.close()
print l
I know this post is really old, but I have to reply because although BalusC's answer is marked as correct, it's not completely correct.
You have to write the query adding "[]" to foo like this:
foo[]=val1&foo[]=val2&foo[]=val3
iCalendar was based on a vCalendar and Outlook 2007 handles both formats well so it doesn't really matters which one you choose.
I'm not sure if this stands for Outlook 2003. I guess you should give it a try.
Outlook's default calendar format is iCalendar (*.ics
)
Complate Angular Way ( Set/Get value by Id ):
// In Html tag
<button (click) ="setValue()">Set Value</button>
<input type="text" #userNameId />
// In component .ts File
export class testUserClass {
@ViewChild('userNameId') userNameId: ElementRef;
ngAfterViewInit(){
console.log(this.userNameId.nativeElement.value );
}
setValue(){
this.userNameId.nativeElement.value = "Sample user Name";
}
}
GIT_SSH_COMMAND="ssh -i /path/to/git-private-access-key" git clone $git_repo
or
export GIT_SSH_COMMAND="ssh -i /path/to/git-private-access-key"
git clone REPO
git push
you can use np.int_
:
>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x
array([[ 1. , 2.3],
[ 1.3, 2.9]])
>>> np.int_(x)
array([[1, 2],
[1, 2]])
If youre in .NET I recommend the HTML agility pack, very robust even with malformed HTML.
Then you can use XPath.
Depending on your Color Model, there are different methods to create a darker (shaded) or lighter (tinted) color:
RGB
:
To shade:
newR = currentR * (1 - shade_factor)
newG = currentG * (1 - shade_factor)
newB = currentB * (1 - shade_factor)
To tint:
newR = currentR + (255 - currentR) * tint_factor
newG = currentG + (255 - currentG) * tint_factor
newB = currentB + (255 - currentB) * tint_factor
More generally, the color resulting in layering a color RGB(currentR,currentG,currentB)
with a color RGBA(aR,aG,aB,alpha)
is:
newR = currentR + (aR - currentR) * alpha
newG = currentG + (aG - currentG) * alpha
newB = currentB + (aB - currentB) * alpha
where (aR,aG,aB) = black = (0,0,0)
for shading, and (aR,aG,aB) = white = (255,255,255)
for tinting
HSV
or HSB
:
Value
/ Brightness
or increase the Saturation
Saturation
or increase the Value
/ Brightness
HSL
:
Lightness
Lightness
There exists formulas to convert from one color model to another. As per your initial question, if you are in RGB
and want to use the HSV
model to shade for example, you can just convert to HSV
, do the shading and convert back to RGB
. Formula to convert are not trivial but can be found on the internet. Depending on your language, it might also be available as a core function :
RGB
has the advantage of being really simple to implement, but:
HSV
or HSB
is kind of complex because you need to play with two parameters to get what you want (Saturation
& Value
/ Brightness
)HSL
is the best from my point of view:
50%
means an unaltered Hue>50%
means the Hue is lighter (tint)<50%
means the Hue is darker (shade)Lightness
part)I don't know if this converted from VB to C# ok but if you don't want quotes around your numbers, you might compare the data type as follows..
public string DataTableToCSV(DataTable dt)
{
StringBuilder sb = new StringBuilder();
if (dt == null)
return "";
try {
// Create the header row
for (int i = 0; i <= dt.Columns.Count - 1; i++) {
// Append column name in quotes
sb.Append("\"" + dt.Columns[i].ColumnName + "\"");
// Add carriage return and linefeed if last column, else add comma
sb.Append(i == dt.Columns.Count - 1 ? "\n" : ",");
}
foreach (DataRow row in dt.Rows) {
for (int i = 0; i <= dt.Columns.Count - 1; i++) {
// Append value in quotes
//sb.Append("""" & row.Item(i) & """")
// OR only quote items that that are equivilant to strings
sb.Append(object.ReferenceEquals(dt.Columns[i].DataType, typeof(string)) || object.ReferenceEquals(dt.Columns[i].DataType, typeof(char)) ? "\"" + row[i] + "\"" : row[i]);
// Append CR+LF if last field, else add Comma
sb.Append(i == dt.Columns.Count - 1 ? "\n" : ",");
}
}
return sb.ToString;
} catch (Exception ex) {
// Handle the exception however you want
return "";
}
}
org.json.simple.JSONArray resultantJson = new org.json.simple.JSONArray();
org.json.JSONArray o1 = new org.json.JSONArray("[{\"one\":[],\"two\":\"abc\"}]");
org.json.JSONArray o2 = new org.json.JSONArray("[{\"three\":[1,2],\"four\":\"def\"}]");
resultantJson.addAll(o1.toList());
resultantJson.addAll(o2.toList());
Here is a simple example:
package main
import "fmt"
func plusTwo() (func(v int) (int)) {
return func(v int) (int) {
return v+2
}
}
func plusX(x int) (func(v int) (int)) {
return func(v int) (int) {
return v+x
}
}
func main() {
p := plusTwo()
fmt.Printf("3+2: %d\n", p(3))
px := plusX(3)
fmt.Printf("3+3: %d\n", px(3))
}
I was searching why % doesn't seem to work. So, I tested out using 100vh instead of just setting it at 100% it seems that 100vh works really well across almost all browsers/devices.
example: you want to only display the top div to the user before it scrolls, like a hero banner module. But, at the top of the page is a navbar which is 68px in height. The following doesn't work for me at all doing just %
height: calc(100% - 68px);
There's was no change. The page just stayed the same. However, when swapping this to "vh" instead it works great! The div block you assign it too will stay on the viewer's device hight only. Until they decide to scroll down the page.
height: calc(100vh - 68px);
Change the +/- to include how big your header is on the top. If your navbar is say 120px in height then change 68px to 120px.
Hope this helps anyone who cannot get this working with using normal height: calc();
If you are using a simulator in Android Studio on Mac you can go to View -> Tool Windows -> Device File Explorer
. Here you can use a finder-like structure.
If you only need to compare schemas (not data), and have access to Perl, mysqldiff might work. I've used it because it lets you compare local databases to remote databases (via SSH), so you don't need to bother dumping any data.
http://adamspiers.org/computing/mysqldiff/
It will attempt to generate SQL queries to synchronize two databases, but I don't trust it (or any tool, actually). As far as I know, there's no 100% reliable way to reverse-engineer the changes needed to convert one database schema to another, especially when multiple changes have been made.
For example, if you change only a column's type, an automated tool can easily guess how to recreate that. But if you also move the column, rename it, and add or remove other columns, the best any software package can do is guess at what probably happened. And you may end up losing data.
I'd suggest keeping track of any schema changes you make to the development server, then running those statements by hand on the live server (or rolling them into an upgrade script or migration). It's more tedious, but it'll keep your data safe. And by the time you start allowing end users access to your site, are you really going to be making constant heavy database changes?
You can use following formulas.
For Excel 2007 or later:
=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")
For Excel 2003:
=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))
Note, that
List!A:C
in VLOOKUP
and returns value from column ? 3
VLOOKUP
equals to FALSE
, in that case VLOOKUP
will only find an exact match, and the values in the first column of List!A:C
do not need to be sorted (opposite to case when you're using TRUE
).boolean
can only be true
or false
because it's a primitive datatype (+ a boolean
variables default value is false
). You can use the class Boolean
instead if you want to use null
values. Boolean is a reference type, that's the reason you can assign null
to a Boolean "variable". Example:
Boolean testvar = null;
if (testvar == null) { ...}
works perfekt for me:
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
CTEditor ctEdit = Element as CTEditor;
if (ctEdit == null) return;
if (e.PropertyName == "Text")
{
double xHeight = Element.Height;
double aHaight = Control.Height;
double height;
Control.Measure(LayoutParams.MatchParent,LayoutParams.WrapContent);
height = Control.MeasuredHeight;
height = xHeight / aHaight * height;
if (Element.HeightRequest != height)
Element.HeightRequest = height;
}
}
With MacOS Catalina, your iPhone will be displayed in the 'Locations' sidebar of Finder windows (as long as you've got the Finder preferences set up to show external devices) - you can then access the files via the 'Files' option which is available from the bar near the top of the window, just below the title (in my case I had to click the '>' at the right).
Hope this will help you. Assumed that login form has: username and password inputs.
if(isset($_POST['username']) && trim($_POST['username']) != "" && isset($_POST['password']) && trim($_POST['password']) != ""){
//login
} else {
//register
}
In App Delegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
forBarMetrics:UIBarMetricsDefault];
NSString *identifier;
BOOL isSaved = [[NSUserDefaults standardUserDefaults] boolForKey:@"loginSaved"];
if (isSaved)
{
//identifier=@"homeViewControllerId";
UIWindow* mainWindow=[[[UIApplication sharedApplication] delegate] window];
UITabBarController *tabBarVC =
[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"TabBarVC"];
mainWindow.rootViewController=tabBarVC;
}
else
{
identifier=@"loginViewControllerId";
UIStoryboard * storyboardobj=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
UIViewController *screen = [storyboardobj instantiateViewControllerWithIdentifier:identifier];
UINavigationController *navigationController=[[UINavigationController alloc] initWithRootViewController:screen];
self.window.rootViewController = navigationController;
[self.window makeKeyAndVisible];
}
return YES;
}
view controller.m In view did load
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
UIBarButtonItem* barButton = [[UIBarButtonItem alloc] initWithTitle:@"Logout" style:UIBarButtonItemStyleDone target:self action:@selector(logoutButtonClicked:)];
[self.navigationItem setLeftBarButtonItem:barButton];
}
In logout button action
-(void)logoutButtonClicked:(id)sender{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert" message:@"Do you want to logout?" preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"Logout" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:NO forKey:@"loginSaved"];
[[NSUserDefaults standardUserDefaults] synchronize];
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
UIStoryboard * storyboardobj=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
UIViewController *screen = [storyboardobj instantiateViewControllerWithIdentifier:@"loginViewControllerId"];
[appDelegate.window setRootViewController:screen];
}]];
[alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self dismissViewControllerAnimated:YES completion:nil];
}]];
dispatch_async(dispatch_get_main_queue(), ^ {
[self presentViewController:alertController animated:YES completion:nil];
});}
actually I found a novel solution that really helped me out, If you are especially concerned with the index of a certain value in a list or data set, you can just set the value of dictionary to that Index!:
Just watch:
list = ['a', 'b', 'c']
dictionary = {}
counter = 0
for i in list:
dictionary[i] = counter
counter += 1
print(dictionary) # dictionary = {'a':0, 'b':1, 'c':2}
Now through the power of hashmaps you can pull the index your entries in constant time (aka a whole lot faster)
best answer written by Dmitri Korotkevitch:
Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.
If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:
Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode
Go to security/logins, open SA login properties
a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password
b. Assign password to SA user
c. Open "Status" tab and enable login.
I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.
Go to Google Cloud Console, select the project then IAM and Admin and Settings
now SHUT DOWN
Then you have to wait for the project deletion.
find_java.exe doesn't seem to like the openjdk "java -version" output. I edited find_java.bat like this:
for /f %%a in ('%~dps0\find_java.exe -s') do set java_exe=%%a
set java_exe="C:\Program Files (x86)\AdoptOpenJDK\jdk-8.0.242.08-hotspot\bin\java.exe"
rem ...
for /f %%a in ('%~dps0\find_java.exe -s -w') do set javaw_exe=%%a
set javaw_exe="C:\Program Files (x86)\AdoptOpenJDK\jdk-8.0.242.08-hotspot\bin\javaw.exe"
SELECT id FROM tbl GROUP BY cat HAVING MAX(date)
As stated here about hot_standby_feedback = on
:
Well, the disadvantage of it is that the standby can bloat the master, which might be surprising to some people, too
And here:
With what setting of max_standby_streaming_delay? I would rather default that to -1 than default hot_standby_feedback on. That way what you do on the standby only affects the standby
So I added
max_standby_streaming_delay = -1
And no more pg_dump
error for us, nor master bloat :)
For AWS RDS instance, check http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Appendix.PostgreSQL.CommonDBATasks.html
try the following as there will be no varchar conversion
SELECT Subject, CAST(DeliveryDate AS DATE)
from Email_Administration
where MerchantId =@ MerchantID
To delete a specify container
docker container rm container_id
If the container is running, you have to stop it before to delete it
docker container stop container_id
And this command is to delete all existing containers
docker container rm $(docker container -a -q)
I would also like to mention a new functionality of AngularJS ng-repeat
, namely, special repeat start and end points. That functionality was added in order to repeat a series of HTML elements instead of just a single parent HTML element.
In order to use repeater start and end points you have to define them by using ng-repeat-start
and ng-repeat-end
directives respectively.
The ng-repeat-start
directive works very similar to ng-repeat
directive. The difference is that is will repeat all the HTML elements (including the tag it's defined on) up to the ending HTML tag where ng-repeat-end
is placed (including the tag with ng-repeat-end
).
Sample code (from a controller):
// ...
$scope.users = {};
$scope.users["182982"] = {name:"John", age: 30};
$scope.users["198784"] = {name:"Antonio", age: 32};
$scope.users["119827"] = {name:"Stephan", age: 18};
// ...
Sample HTML template:
<div ng-repeat-start="(id, user) in users">
==== User details ====
</div>
<div>
<span>{{$index+1}}. </span>
<strong>{{id}} </strong>
<span class="name">{{user.name}} </span>
<span class="age">({{user.age}})</span>
</div>
<div ng-if="!$first">
<img src="/some_image.jpg" alt="some img" title="some img" />
</div>
<div ng-repeat-end>
======================
</div>
Output would look similar to the following (depending on HTML styling):
==== User details ====
1. 119827 Stephan (18)
======================
==== User details ====
2. 182982 John (30)
[sample image goes here]
======================
==== User details ====
3. 198784 Antonio (32)
[sample image goes here]
======================
As you can see, ng-repeat-start
repeats all HTML elements (including the element with ng-repeat-start
). All ng-repeat
special properties (in this case $first
and $index
) also work as expected.
To convert time in millis directly to minutes: second format you can use this
String durationText = DateUtils.formatElapsedTime(timeInMillis / 1000));
This will return a string with time in proper formatting. It worked for me.
What are the problems of static and stack?
The problem with "static" allocation is that the allocation is made at compile-time: you can't use it to allocate some variable number of data, the number of which isn't known until run-time.
The problem with allocating on the "stack" is that the allocation is destroyed as soon as the subroutine which does the allocation returns.
I could write an entire application without allocate variables in the heap?
Perhaps but not a non-trivial, normal, big application (but so-called "embedded" programs might be written without the heap, using a subset of C++).
What garbage collector does ?
It keeps watching your data ("mark and sweep") to detect when your application is no longer referencing it. This is convenient for the application, because the application doesn't need to deallocate the data ... but the garbage collector might be computationally expensive.
Garbage collectors aren't a usual feature of C++ programming.
What could you do manipulating the memory by yourself that you couldn't do using this garbage collector?
Learn the C++ mechanisms for deterministic memory deallocation:
According To Apple you don't need an import for swift files in the Same Target. I finally got it working by adding my swift file to both my regular target and test target. Then I used the bridging header for test to make sure my ObjC files that I referenced in my regular bridging header were available. Ran like a charm now.
import XCTest
//Optionally you can import the whole Objc Module by doing #import ModuleName
class HHASettings_Tests: XCTestCase {
override func setUp() {
let x : SettingsTableViewController = SettingsTableViewController()
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
SO make sure PrimeNumberModel has a target of your test Target. Or High6 solution of importing your whole module will work
Following is the most performant way to find the next AUTO_INCREMENT
value for a table. This is quick even on databases housing millions of tables, because it does not require querying the potentially large information_schema
database.
mysql> SHOW TABLE STATUS LIKE 'table_name';
// Look for the Auto_increment column
However, if you must retrieve this value in a query, then to the information_schema
database you must go.
SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND TABLE_NAME = 'TableName';
updated on May 26-2018
If the external library is in a folder that is under the project then
File -> Settings -> Project -> Project structure -> select the folder and Mark as Sources!
If not, add content root, and do similar things.
Because you can ask the server to prepend a prefix to the returned JSON object. E.g
function_prefix(json_object);
in order for the browser to eval
"inline" the JSON string as an expression. This trick makes it possible for the server to "inject" javascript code directly in the Client browser and this with bypassing the "same origin" restrictions.
In other words, you can achieve cross-domain data exchange.
Normally, XMLHttpRequest
doesn't permit cross-domain data-exchange directly (one needs to go through a server in the same domain) whereas:
<script src="some_other_domain/some_data.js&prefix=function_prefix
>` one can access data from a domain different than from the origin.
Also worth noting: even though the server should be considered as "trusted" before attempting that sort of "trick", the side-effects of possible change in object format etc. can be contained. If a function_prefix
(i.e. a proper js function) is used to receive the JSON object, the said function can perform checks before accepting/further processing the returned data.
this works:
CSS:
.show_hide {
display:none;
}
.plus:after {
content:" +";
}
.minus:after {
content:" -";
}
jQuery:
$(document).ready(function(){
$(".slidingDiv").hide();
$(".show_hide").addClass("plus").show();
$('.show_hide').toggle(
function(){
$(".slidingDiv").slideDown();
$(this).addClass("minus");
$(this).removeClass("plus");
},
function(){
$(".slidingDiv").slideUp();
$(this).addClass("plus");
$(this).removeClass("minus");
}
);
});
HTML:
<a href="#" class="show_hide">Show/hide</a>
<div class="slidingDiv" style="display: block;">
Check out the updated jQuery plugin for doing this: <a href="http://papermashup.com/jquery-show-hide-plugin/" class="show_hide" target="_blank" style="display: inline;">jQuery Show / Hide Plugin</a>
</div>
in the CSS, instead of content:" +";
You can put an background-image
(with background-position:right center;
and background-repeat:no-repeat
and maybe making the .show_hide
displayed as block and give him a width, so that the bg-image is not overlayed by the link-text itself).
this query return last record for every Form_id:
SELECT m1.*
FROM messages m1 LEFT JOIN messages m2
ON (m1.Form_id = m2.Form_id AND m1.id < m2.id)
WHERE m2.id IS NULL;
You can use Perl for that:
perl -ane 'print "$F[1] $F[0]\n"' < file.txt
The advantage of running perl is that (if you know Perl) you can do much more computation on F than rearranging columns.
New Excel versions
=IF(ISNA(VLOOKUP(A1,B,B,1,FALSE)),"",A1)
Older Excel versions
=IF(ISNA(VLOOKUP(A1;B:B;1;FALSE));"";A1)
That is: "If the value of A1 exists in the B column, display it here. If it doesn't exist, leave it empty."
If you are trying to prevent a request from running too long, then setting a timeout in Tomcat will not help you. As Chris says, you can set the global timeout value for Tomcat. But, from The Apache Tomcat Connector - Generic HowTo Timeouts, see the Reply Timeout section:
JK can also use a timeout on request replies. This timeout does not measure the full processing time of the response. Instead it controls, how much time between consecutive response packets is allowed.
In most cases, this is what one actually wants. Consider for example long running downloads. You would not be able to set an effective global reply timeout, because downloads could last for many minutes. Most applications though have limited processing time before starting to return the response. For those applications you could set an explicit reply timeout. Applications that do not harmonise with reply timeouts are batch type applications, data warehouse and reporting applications which are expected to observe long processing times.
If JK aborts waiting for a response, because a reply timeout fired, there is no way to stop processing on the backend. Although you free processing resources in your web server, the request will continue to run on the backend - without any way to send back a result once the reply timeout fired.
So Tomcat will detect that the servlet has not responded within the timeout and will send back a response to the user, but will not stop the thread running. I don't think you can achieve what you want to do.
String str, str1;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a String : ");
str = sc.nextLine();
str1 = str.replaceAll("[aeiouAEIOU]", "");
System.out.print(str1);
This is the normal behavior and the reason is that your sqlCommandHandlerService.persist
method needs a TX when being executed (because it is marked with @Transactional
annotation). But when it is called inside processNextRegistrationMessage
, because there is a TX available, the container doesn't create a new one and uses existing TX. So if any exception occurs in sqlCommandHandlerService.persist
method, it causes TX to be set to rollBackOnly
(even if you catch the exception in the caller and ignore it).
To overcome this you can use propagation levels for transactions. Have a look at this to find out which propagation best suits your requirements.
Well after a colleague came to me with a couple of questions about a similar situation, I feel this needs a bit of clarification.
Although propagations solve such issues, you should be VERY careful about using them and do not use them unless you ABSOLUTELY understand what they mean and how they work. You may end up persisting some data and rolling back some others where you don't expect them to work that way and things can go horribly wrong.
Within code you will now have access to read the variable as
string myString = Variables.MyVariableName.ToString();
In JavaScript, an object is a standalone entity, with properties and type.
For fetching values from Object in form of array: Object.values(obj) // obj is object name that you used Result -> ["value1", "value2", "value3", "value4"]
For fetching keys from Object in form of array: Object.keys(obj) // obj is object name that you used Result -> ["key1", "key2", "key3", "key4"]
As both functions are returning array you can get the length of keys or value by using length property. For instance - Object.values(obj).length or Object.keys(obj).length
NPlot is a pretty good simple open source 2D plotting API. Unfortunately, the web site is down. I don't know if this is just temporary or not. I haven't heard of any bad news. It may come back up.
Here is an article describing it:
http://aspnet.4guysfromrolla.com/articles/072507-1.aspx
The previous article uses VB.NET, but obviously this will work with C#.
Again, not sure why nplot's site is not currently working but it is a somewhat popular plotting API that I've used in the past. I post it for your information and in case of the likely event nplot will be back up soon. :)
Edit:
Thanks to a Hosam Aly, it looks like the SourceForge project can still be accessed here:
Swift 3: Easiest way to dismiss keyboard:
//Dismiss keyboard method
func keyboardDismiss() {
textField.resignFirstResponder()
}
//ADD Gesture Recignizer to Dismiss keyboard then view tapped
@IBAction func viewTapped(_ sender: AnyObject) {
keyboardDismiss()
}
//Dismiss keyboard using Return Key (Done) Button
//Do not forgot to add protocol UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
keyboardDismiss()
return true
}
After coming up with some good thoughts on making generic types in python, I started looking for others who had the same idea, but I couldn't find any. So, here it is. I tried this out and it works well. It allows us to parameterize our types in python.
class List( type ):
def __new__(type_ref, member_type):
class List(list):
def append(self, member):
if not isinstance(member, member_type):
raise TypeError('Attempted to append a "{0}" to a "{1}" which only takes a "{2}"'.format(
type(member).__name__,
type(self).__name__,
member_type.__name__
))
list.append(self, member)
return List
You can now derive types from this generic type.
class TestMember:
pass
class TestList(List(TestMember)):
def __init__(self):
super().__init__()
test_list = TestList()
test_list.append(TestMember())
test_list.append('test') # This line will raise an exception
This solution is simplistic, and it does have it's limitations. Each time you create a generic type, it will create a new type. Thus, multiple classes inheriting List( str )
as a parent would be inheriting from two separate classes. To overcome this, you need to create a dict to store the various forms of the inner class and return the previous created inner class, rather than creating a new one. This would prevent duplicate types with the same parameters from being created. If interested, a more elegant solution can be made with decorators and/or metaclasses.
I've searched a lot and the best way I've found so far is on this article:
Class to serialize
package net.sghill.example;
import net.sghill.example.UserDeserializer
import net.sghill.example.UserSerializer
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;
@JsonDeserialize(using = UserDeserializer.class)
public class User {
private ObjectId id;
private String username;
private String password;
public User(ObjectId id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public ObjectId getId() { return id; }
public String getUsername() { return username; }
public String getPassword() { return password; }
}
Deserializer class
package net.sghill.example;
import net.sghill.example.User;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.ObjectCodec;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;
import java.io.IOException;
public class UserDeserializer extends JsonDeserializer<User> {
@Override
public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
return new User(null, node.get("username").getTextValue(), node.get("password").getTextValue());
}
}
Edit: Alternatively you can look at this article which uses new versions of com.fasterxml.jackson.databind.JsonDeserializer.
The size_t
type is defined as the unsigned integral type of the sizeof
operator. In the real world, you will often see int
defined as 32 bits (for backward compatibility) but size_t
defined as 64 bits (so you can declare arrays and structures more than 4 GiB in size) on 64-bit platforms. If a long int
is also 64-bits, this is called the LP64 convention; if long int
is 32 bits but long long int
and pointers are 64 bits, that’s LLP64. You also might get the reverse, a program that uses 64-bit instructions for speed, but 32-bit pointers to save memory. Also, int
is signed and size_t
is unsigned.
There were historically a number of other platforms where addresses were wider or shorter than the native size of int
. In fact, in the ’70s and early ’80s, this was more common than not: all the popular 8-bit microcomputers had 8-bit registers and 16-bit addresses, and the transition between 16 and 32 bits also produced many machines that had addresses wider than their registers. I occasionally still see questions here about Borland Turbo C for MS-DOS, whose Huge memory mode had 20-bit addresses stored in 32 bits on a 16-bit CPU (but which could support the 32-bit instruction set of the 80386); the Motorola 68000 had a 16-bit ALU with 32-bit registers and addresses; there were IBM mainframes with 15-bit, 24-bit or 31-bit addresses. You also still see different ALU and address-bus sizes in embedded systems.
Any time int
is smaller than size_t
, and you try to store the size or offset of a very large file or object in an unsigned int
, there is the possibility that it could overflow and cause a bug. With an int
, there is also the possibility of getting a negative number. If an int
or unsigned int
is wider, the program will run correctly but waste memory.
You should generally use the correct type for the purpose if you want portability. A lot of people will recommend that you use signed math instead of unsigned (to avoid nasty, subtle bugs like 1U < -3
). For that purpose, the standard library defines ptrdiff_t
in <stddef.h>
as the signed type of the result of subtracting a pointer from another.
That said, a workaround might be to bounds-check all addresses and offsets against INT_MAX
and either 0
or INT_MIN
as appropriate, and turn on the compiler warnings about comparing signed and unsigned quantities in case you miss any. You should always, always, always be checking your array accesses for overflow in C anyway.
DECLARE @isAvailable BIT = 0;
IF EXISTS(SELECT 1 FROM [User] WHERE (UserID = 20070022))
BEGIN
SET @isAvailable = 1
END
initially isAvailable boolean value is set to 0
Use
.title{
display: inline-block;
height: 25px;
}
The only trick is browser support. Check if your list of supported browsers handles inline-block here.
l = Location.find(:id => id, :select => "name, website, city", :limit => 1)
...or...
l = Location.find_by_sql(:conditions => ["SELECT name, website, city FROM locations WHERE id = ? LIMIT 1", id])
This reference doc gives you the entire list of options you can use with .find
, including how to limit by number, id, or any other arbitrary column/constraint.
l = Location.where(["id = ?", id]).select("name, website, city").first
Ref: Active Record Query Interface
You can also swap the order of these chained calls, doing .select(...).where(...).first
- all these calls do is construct the SQL query and then send it off.
You would need to create a generic class named MyProp. Then, you will need to add implicit or explicit cast operators so you can get and set the value as if it were the type specified in the generic type parameter. These cast operators can do the extra work that you need.
You can display an image in your own window using Tkinter, w/o depending on image viewers installed in your system:
import Tkinter as tk
from PIL import Image, ImageTk # Place this at the end (to avoid any conflicts/errors)
window = tk.Tk()
#window.geometry("500x500") # (optional)
imagefile = {path_to_your_image_file}
img = ImageTk.PhotoImage(Image.open(imagefile))
lbl = tk.Label(window, image = img).pack()
window.mainloop()
For Python 3, replace import Tkinter as tk
with import tkinter as tk
.
` Adding the following to pom.xml will resolve the issue. <pluginRepositories>
<pluginRepository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<updatePolicy>never</updatePolicy>
</releases>
</pluginRepository>
</pluginRepositories>
<repositories>
<repository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories> `
function sameDay( d1, d2 ){
return d1.getUTCFullYear() == d2.getUTCFullYear() &&
d1.getUTCMonth() == d2.getUTCMonth() &&
d1.getUTCDate() == d2.getUTCDate();
}
if (sameDay( new Date(userString), new Date)){
// ...
}
Using the UTC* methods ensures that two equivalent days in different timezones matching the same global day are the same. (Not necessary if you're parsing both dates directly, but a good thing to think about.)
You can use System.IO.Path.GetDirectoryName(fileName)
, or turn the path into a FileInfo
using FileInfo.Directory
.
If you're doing other things with the path, the FileInfo
class may have advantages.
On a 32-bit JVM, the largest heap size you can theoretically set is 4gb. To use a larger heap size, you need to use a 64-bit JVM. Try the following:
java -Xmx6144M -d64
The -d64 flag is important as this tells the JVM to run in 64-bit mode.
You can get columns number from ResultSetMetaData:
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
You can try this
public string ToString(this object value)
{
// this will throw an exception if value is null
string val = Convert.ToString (value);
// it can be a space
If (string.IsNullOrEmpty(val.Trim())
return string.Empty:
}
// to avoid not all code paths return a value
return val;
}
SQLDataReaders are forward-only. You're essentially doing this:
count++; // initially 1
.DataBind(); //consuming all the records
//next iteration on
.Read()
//we've now come to end of resultset, thanks to the DataBind()
//count is still 1
You could do this instead:
if (reader.HasRows)
{
rep.DataSource = reader;
rep.DataBind();
}
int count = rep.Items.Count; //somehow count the num rows/items `rep` has.
var student = [];
var obj = {
'first_name': name,
'last_name': name,
'age': age,
}
student.push(obj);
For Typescript users, the "atom-typescript" package adds a typescript aware symbols view, you can trigger it with Cmd+R, and it works great to jump to methods-
https://atom.io/packages/atom-typescript#alternative-to-symbols-view
Better make the google object convert as a javascript readable object first.
Create two functions like below and call it passing google map return object.
function getShortAddressObject(object) {
let address = {};
const address_components = object[0].address_components;
address_components.forEach(element => {
address[element.types[0]] = element.short_name;
});
return address;
}
function getLongAddressObject(object) {
let address = {};
const address_components = object[0].address_components;
address_components.forEach(element => {
address[element.types[0]] = element.long_name;
});
return address;
}
Then user can access names like below.
var addressObj = getLongAddressObject(object);
var country = addressObj.country; //Sri Lanka
All address parts are like below.
administrative_area_level_1: "Western Province"
administrative_area_level_2: "Colombo"
country: "Sri Lanka"
locality: "xxxx xxxxx"
political: "xxxxx"
route: "xxxxx - xxxxx Road"
street_number: "No:00000"
The easiest way is to not store the count, relying on the COUNT aggregate function to reflect the value as it is in the database:
SELECT c.category_name,
COUNT(p.post_id) AS num_posts
FROM CATEGORY c
LEFT JOIN POSTS p ON p.category_id = c.category_id
You can create a view to house the query mentioned above, so you can query the view just like you would a table...
But if you're set on storing the number, use:
UPDATE CATEGORY
SET count = count + 1
WHERE category_id = ?
..replacing "?" with the appropriate value.
Message Edit ( complete rewrite ) When order does not matter, that's when. Both should give Log(n) - it would be of utility to see if either is over five percent faster than the other. HashSet can give O(1) testing in a loop should reveal whether it is.
I liked the solution provided by @madhead
However the problem I had is that it wouldn't work for a sorted list so instead of passing the index to the delete function I passed the item and then got the index via indexof
e.g.:
var index = $scope.items.indexOf(item);
$scope.items.splice(index, 1);
An updated version of madheads example is below: link to example
HTML
<!DOCTYPE html>
<html data-ng-app="demo">
<head>
<script data-require="[email protected]" data-semver="1.1.5" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div data-ng-controller="DemoController">
<ul>
<li data-ng-repeat="item in items|orderBy:'toString()'">
{{item}}
<button data-ng-click="removeItem(item)">Remove</button>
</li>
</ul>
<input data-ng-model="newItem"><button data-ng-click="addItem(newItem)">Add</button>
</div>
</body>
</html>
JavaScript
"use strict";
var demo = angular.module("demo", []);
function DemoController($scope){
$scope.items = [
"potatoes",
"tomatoes",
"flour",
"sugar",
"salt"
];
$scope.addItem = function(item){
$scope.items.push(item);
$scope.newItem = null;
}
$scope.removeItem = function(item){
var index = $scope.items.indexOf(item);
$scope.items.splice(index, 1);
}
}
Easiest way is to open CMD or powershell as administrator and type
set PATH=%PATH%;C:\Python27
just use printf
instead of
repo forall -c '....$variable'
use printf to replace the variable token with the expanded variable.
For example:
template='.... %s'
repo forall -c $(printf "${template}" "${variable}")
If we encapsulate that in a function we could use recursion and state clearly the purpose by naming the function properly (not sure if getAny
is actually a good name):
def getAny(dic, keys, default=None):
return (keys or default) and dic.get(keys[0],
getAny( dic, keys[1:], default=default))
or even better, without recursion and more clear:
def getAny(dic, keys, default=None):
for k in keys:
if k in dic:
return dic[k]
return default
Then that could be used in a way similar to the dict.get method, like:
getAny(myDict, keySet)
and even have a default result in case of no keys found at all:
getAny(myDict, keySet, "not found")
You can use the Windows ? New Window option to duplicate the current window. See more at: Why I like Visual Studio 2010? Undock Windows
You should not care. If size is a concern I would use byte, short, int, then long. The only reason you would use an int larger than int32 is if you need a number higher than 2147483647 or lower than -2147483648.
Other than that I wouldn't care, there are plenty of other items to be concerned with.
Use WITH ORDINALITY
for set-returning functions:
When a function in the
FROM
clause is suffixed byWITH ORDINALITY
, abigint
column is appended to the output which starts from 1 and increments by 1 for each row of the function's output. This is most useful in the case of set returning functions such asunnest()
.
In combination with the LATERAL
feature in pg 9.3+, and according to this thread on pgsql-hackers, the above query can now be written as:
SELECT t.id, a.elem, a.nr
FROM tbl AS t
LEFT JOIN LATERAL unnest(string_to_array(t.elements, ','))
WITH ORDINALITY AS a(elem, nr) ON TRUE;
LEFT JOIN ... ON TRUE
preserves all rows in the left table, even if the table expression to the right returns no rows. If that's of no concern you can use this otherwise equivalent, less verbose form with an implicit CROSS JOIN LATERAL
:
SELECT t.id, a.elem, a.nr
FROM tbl t, unnest(string_to_array(t.elements, ',')) WITH ORDINALITY a(elem, nr);
Or simpler if based off an actual array (arr
being an array column):
SELECT t.id, a.elem, a.nr
FROM tbl t, unnest(t.arr) WITH ORDINALITY a(elem, nr);
Or even, with minimal syntax:
SELECT id, a, ordinality
FROM tbl, unnest(arr) WITH ORDINALITY a;
a
is automatically table and column alias. The default name of the added ordinality column is ordinality
. But it's better (safer, cleaner) to add explicit column aliases and table-qualify columns.
With row_number() OVER (PARTITION BY id ORDER BY elem)
you get numbers according to the sort order, not the ordinal number of the original ordinal position in the string.
You can simply omit ORDER BY
:
SELECT *, row_number() OVER (PARTITION by id) AS nr
FROM (SELECT id, regexp_split_to_table(elements, ',') AS elem FROM tbl) t;
While this normally works and I have never seen it fail in simple queries, PostgreSQL asserts nothing concerning the order of rows without ORDER BY
. It happens to work due to an implementation detail.
To guarantee ordinal numbers of elements in the blank-separated string:
SELECT id, arr[nr] AS elem, nr
FROM (
SELECT *, generate_subscripts(arr, 1) AS nr
FROM (SELECT id, string_to_array(elements, ' ') AS arr FROM tbl) t
) sub;
Or simpler if based off an actual array:
SELECT id, arr[nr] AS elem, nr
FROM (SELECT *, generate_subscripts(arr, 1) AS nr FROM tbl) t;
Related answer on dba.SE:
None of these features are available, yet: RETURNS TABLE
, generate_subscripts()
, unnest()
, array_length()
. But this works:
CREATE FUNCTION f_unnest_ord(anyarray, OUT val anyelement, OUT ordinality integer)
RETURNS SETOF record
LANGUAGE sql IMMUTABLE AS
'SELECT $1[i], i - array_lower($1,1) + 1
FROM generate_series(array_lower($1,1), array_upper($1,1)) i';
Note in particular, that the array index can differ from ordinal positions of elements. Consider this demo with an extended function:
CREATE FUNCTION f_unnest_ord_idx(anyarray, OUT val anyelement, OUT ordinality int, OUT idx int)
RETURNS SETOF record
LANGUAGE sql IMMUTABLE AS
'SELECT $1[i], i - array_lower($1,1) + 1, i
FROM generate_series(array_lower($1,1), array_upper($1,1)) i';
SELECT id, arr, (rec).*
FROM (
SELECT *, f_unnest_ord_idx(arr) AS rec
FROM (VALUES (1, '{a,b,c}'::text[]) -- short for: '[1:3]={a,b,c}'
, (2, '[5:7]={a,b,c}')
, (3, '[-9:-7]={a,b,c}')
) t(id, arr)
) sub;
id | arr | val | ordinality | idx
----+-----------------+-----+------------+-----
1 | {a,b,c} | a | 1 | 1
1 | {a,b,c} | b | 2 | 2
1 | {a,b,c} | c | 3 | 3
2 | [5:7]={a,b,c} | a | 1 | 5
2 | [5:7]={a,b,c} | b | 2 | 6
2 | [5:7]={a,b,c} | c | 3 | 7
3 | [-9:-7]={a,b,c} | a | 1 | -9
3 | [-9:-7]={a,b,c} | b | 2 | -8
3 | [-9:-7]={a,b,c} | c | 3 | -7
Compare:
Generally, the system displays an ANR if an application cannot respond to user input.
In any situation in which your app performs a potentially lengthy operation, you should not perform the work on the UI thread, but instead create a worker thread and do most of the work there. This keeps the UI thread (which drives the user interface event loop) running and prevents the system from concluding that your code has frozen.
Android applications normally run entirely on a single thread by default the "UI thread" or "main thread"). This means anything your application is doing in the UI thread that takes a long time to complete can trigger the ANR dialog because your application is not giving itself a chance to handle the input event or intent broadcasts.
Therefore, any method that runs in the UI thread should do as little work as possible on that thread. In particular, activities should do as little as possible to set up in key life-cycle methods such as onCreate() and onResume(). Potentially long running operations such as network or database operations, or computationally expensive calculations such as resizing bitmaps should be done in a worker thread (or in the case of databases operations, via an asynchronous request).
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
// Do the long-running work in here
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
// This is called each time you call publishProgress()
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
// This is called when doInBackground() is finished
protected void onPostExecute(Long result) {
showNotification("Downloaded " + result + " bytes");
}
}
To execute this worker thread, simply create an instance and call execute():
new DownloadFilesTask().execute(url1, url2, url3);
http://developer.android.com/training/articles/perf-anr.html
If your are come from react-native
and facing this error just do this
Podfile
(your project > ios>Podfile)#use_flipper!
#post_install do |installer|
#flipper_post_install(installer)
#end
IOS
folder enter this command pod install
yep, that is it hope it works to you
For me cleaning the project (Command + Shift + K) and restarting xCode worked for me
Here's a suggestion: use two indices into the string, say start
and end
. start
points to the first character of the next string to extract, end
points to the character after the last one belonging to the next string to extract. start
starts at zero, end
gets the position of the first char after start
. Then you take the string between [start..end)
and add that to your array. You keep going until you hit the end of the string.
shopList = []
maxLengthList = 6
while len(shopList) < maxLengthList:
item = input("Enter your Item to the List: ")
shopList.append(item)
print shopList
print "That's your Shopping List"
print shopList
Because the Method2
is static, all you have to do is call like this:
public class AllMethods
{
public static void Method2()
{
// code here
}
}
class Caller
{
public static void Main(string[] args)
{
AllMethods.Method2();
}
}
If they are in different namespaces you will also need to add the namespace of AllMethods
to caller.cs in a using
statement.
If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:
public class MyClass
{
public void InstanceMethod()
{
// ...
}
}
public static void Main(string[] args)
{
var instance = new MyClass();
instance.InstanceMethod();
}
Update
As of C# 6, you can now also achieve this with using static
directive to call static methods somewhat more gracefully, for example:
// AllMethods.cs
namespace Some.Namespace
{
public class AllMethods
{
public static void Method2()
{
// code here
}
}
}
// Caller.cs
using static Some.Namespace.AllMethods;
namespace Other.Namespace
{
class Caller
{
public static void Main(string[] args)
{
Method2(); // No need to mention AllMethods here
}
}
}
Further Reading
Running
npm run scss
npm run start
in that order in terminal solved the issue for me.
If there is any chance that you will need to search for empty strings,
a['Names'].str.contains('')
will NOT work, as it will always return True.
Instead, use
if '' in a["Names"].values
to accurately reflect whether or not a string is in a Series, including the edge case of searching for an empty string.
I try to explain it more understandably than the referred PostgreSQL documentation.
Neither TIMESTAMP
variants store a time zone (or an offset), despite what the names suggest. The difference is in the interpretation of the stored data (and in the intended application), not in the storage format itself:
TIMESTAMP WITHOUT TIME ZONE
stores local date-time (aka. wall calendar date and wall clock time). Its time zone is unspecified as far as PostgreSQL can tell (though your application may knows what it is). Hence, PostgreSQL does no time zone related conversion on input or output. If the value was entered into the database as '2011-07-01 06:30:30'
, then no mater in what time zone you display it later, it will still say year 2011, month 07, day 01, 06 hours, 30 minutes, and 30 seconds (in some format). Also, any offset or time zone you specify in the input is ignored by PostgreSQL, so '2011-07-01 06:30:30+00'
and '2011-07-01 06:30:30+05'
are the same as just '2011-07-01 06:30:30'
.
For Java developers: it's analogous to java.time.LocalDateTime
.
TIMESTAMP WITH TIME ZONE
stores a point on the UTC time line. How it looks (how many hours, minutes, etc.) depends on your time zone, but it always refers to the same "physical" instant (like the moment of an actual physical event). The
input is internally converted to UTC, and that's how it's stored. For that, the offset of the input must be known, so when the input contains no explicit offset or time zone (like '2011-07-01 06:30:30'
) it's assumed to be in the current time zone of the PostgreSQL session, otherwise the explicitly specified offset or time zone is used (as in '2011-07-01 06:30:30+05'
). The output is displayed converted to the current time zone of the PostgreSQL session.
For Java developers: It's analogous to java.time.Instant
(with lower resolution though), but with JDBC and JPA 2.2 you are supposed to map it to java.time.OffsetDateTime
(or to java.util.Date
or java.sql.Timestamp
of course).
Some say that both TIMESTAMP
variations store UTC date-time. Kind of, but it's confusing to put it that way in my opinion. TIMESTAMP WITHOUT TIME ZONE
is stored like a TIMESTAMP WITH TIME ZONE
, which rendered with UTC time zone happens to give the same year, month, day, hours, minutes, seconds, and microseconds as they are in the local date-time. But it's not meant to represent the point on the time line that the UTC interpretation says, it's just the way the local date-time fields are encoded. (It's some cluster of dots on the time line, as the real time zone is not UTC; we don't know what it is.)
another solution is to build a new list
List<Dog> dogs = new ArrayList<Dog>();
List<Animal> animals = new ArrayList<Animal>(dogs);
animals.add(new Cat());
The .forEach function can have a callback function(eachelement, elementIndex) So basically what you need to do is :
arr.forEach(function(element,index){
arr[index] = "four"; //set the value
});
console.log(arr); //the array has been overwritten.
Or if you want to keep the original array, you can make a copy of it before doing the above process. To make a copy, you can use:
var copy = arr.slice();
There is an option in Postman if you download it from https://www.getpostman.com instead of the chrome store (most probably it has been introduced in the new versions and the chrome one will be updated later) not sure about the old ones.
In the settings, turn off the SSL certificate verification option
Be sure to remember to reactivate it afterwards, this is a security feature.
If you really want to use the chrome app, you could always add an exception to chrome for the url: Enter the url you would like to open in the chrome browser, you'll get a warning with a link at the bottom of the page to add an exception, which if you do, it will also allow postman to access your url. But the first option of using the postman stand-alone app is much better.
I hope this can help.
change your String to String phno="tel:10digits";
and try again.
One danger with params
Keyword is, if after Calls to the Method have been coded,
params
Parameter prior to the Signature change were Type-Compatible with the params
Parameter,those Calls will continue to compile with one/more Expressions previously intended for required Parameters being treated as the optional params
Parameter. I just ran into the worst possible case of this: the params
Parameter was of Type object[]
.
This is noteworthy because developers are used to the compiler slapping their wrists with the much, much more common scenario where Parameters are removed from a Method with all required Parameters (because the # of Parameters expected would change).
For me, it's not worth the shortcut. (Type)[]
without params
will work with 0 to infinity # of Parameters without needing Overrides. Worst case is you'll have to add a , new (Type) [] {}
to Calls where it doesn't apply.
Btw, imho, the safest (and most readable practice) is to:
pass via Named Parameters (which we can now do even in C# ~2 decades after we could in VB ;P) (because:
1.1. it's the only way that guarantees prevention of unintended values passed to Parameters after Parameter order, Compatible-Type and/or count change after Calls have been coded,
1.2. it reduces those chances after a Parameter meaning change, because the likely new identifier name reflecting the new meaning is right next to the value being passed to it,
1.3. it avoids having to count commas and jump back & forth from Call to Signature to see what Expression is being passed for what Parameter, and
1.3.1. By the way, this reason alone should be plenty (in terms of avoiding frequent error-prone violations of the DRY Principle just to read the code not to mention also modify it), but this reason can be exponentially more important if there are one/more Expressions being Passed that themselves contain commas, i.e. Multi-Dimensional Array Refs or Multi-Parameter Function Calls. In that case, you couldn't even use (which even if you could, would still be adding an extra step per Parameter per Method Call) a Find All Occurrences in a Selection feature in your editor to automate the comma-counting for you.
1.4. if you must use Optional Parameters (params
or not), it allows you to search for Calls where a particular Optional Parameter is Passed (and therefore, most likely is not or at least has the possibility of being not the Default Value),
(NOTE: Reasons 1.2. and 1.3. can ease and reduce chances of error even on coding the initial Calls not to mention when Calls have to be read and/or changed.))
and
do so ONE - PARAMETER - PER - LINE for better readability (because:
2.1. it's less cluttered, and
2.2. it avoids having to scroll right & back left (and having to do so PER - LINE, since most mortals can't read the left part of multiple lines, scroll right and read the right part)).
2.3. it's consistent with the "Best Practice" we've already evolved into for Assignment Statements, because every Parameter Passed is in essence an Assignment Statement (assigning a Value or Reference to a Local Variable). Just like those who follow the latest "Best Practice" in Coding Style wouldn't dream of coding multiple Assignment Statements per line, we probably shouldn't (and won't once "Best Practice" catches up to my "genius" ;P ) do so when Passing Parameters.
NOTES:
Passing in Variables whose names mirror the Parameters' doesn't help when:
1.1. you're passing in Literal Constants (i.e. a simple 0/1, false/true or null that even "'Best Practices'" may not require you use a Named Constant for and their purpose can't be easily inferred from the Method name),
1.2. the Method is significantly lower-level / more generic than the Caller such that you would not want / be able to name your Variables the same/similar to the Parameters (or vice versa), or
1.3. you're re-ordering / replacing Parameters in the Signature that may result in prior Calls still Compiling because the Types happen to still be compatible.
Having an auto-wrap feature like VS does only eliminates ONE (#2.2) of the 8 reasons I gave above. Prior to as late as VS 2015, it did NOT auto-indent (!?! Really, MS?!?) which increases severity of reason #2.1.
VS should have an option that generates Method Call snippets with Named Parameters (one per line of course ;P) and a compiler option that requires Named Parameters (similar in concept to Option Explicit in VB which, btw, the requirement of was prolly once thought equally as outrageous but now is prolly required by "'Best Practices'"). In fact, "back in my day" ;), in 1991 just months into my career, even before I was using (or had even seen) a language with Named Parameters, I had the anti-sheeple / "just cuz you can, don't mean you should" / don't blindly "cut the ends of the roast" sense enough to simulate it (using in-line comments) without having seen anyone do so. Not having to use Named Parameters (as well other syntax that save "'precious'" source code keystrokes) is a relic of the Punch Card era when most of these syntaxes started. There's no excuse for that with modern hardware and IDE's and much more complex software where readability is much, Much, MUCH more important. "Code is read much more often than is written". As long as you're not duplicating non-auto-updated code, every keystroke saved is likely to cost exponentially more when someone (even yourself) is trying to read it later.
Though I consider myself a .NET developer, I don't prefer calling it that way. c# developer sounds much better and is a much clearer message: it says that I understand both C# and .NET (because C# and .NET are tied together). I could call myself a VB.NET developer, same story there.
What is a .NET developer? I don't know, because you cannot develop with .NET, if develop is a synonym for programming. .NET is the environment, the libraries, the languages, the CLR, the CLI, JIT, the LR, the BCL, the IDE and the IL. I find it a poor job description, but it may also mean that they don't really care: either you are an F#, a C#, an IronPython or a VB.NET developer, they're all implicitly and secretly .NET developers.
What do you need? A solid understanding why ".NET" is a poor job description and ask for a more precise one. Nobody can know everything of .NET, it is simply too wide. Orientate yourself to all sides of it and do both ASP.NET and WinForms. Don't forget Silverlight, WPF etc and two or three .NET languages.
In other words: know the forest by knowing what trees and flowers it habitats and specialize in knowing a few beautiful and common ones well.
Download jquery.multiselect
Include the jquery.multiselect.js and jquery.multiselect.css files
<script src="jquery-ui-multiselect-widget-master/src/jquery.multiselect.js" type="text/javascript"></script>
<link rel="stylesheet" href="jquery-ui-multiselect-widget-master/jquery.multiselect.css" />
Populate your select input
Add the multiselect
$('#' + Field).multiselect({
checkAllText: "Your text for CheckAll",
uncheckAllText: "Your text for UncheckCheckAll",
noneSelectedText: "Your text for NoOptionHasBeenSelected",
selectedText: "You selected # of #" //The multiselect knows to display the second # as the total
});
You may change the style
ui-multiselect { //The button
background:#fff !important; //background-color wouldn't work here
text-align: right !important;
}
ui-multiselect-header { //The CheckAll/ UncheckAll line)
background: lightgray !important;
text-align: right !important;
}
ui-multiselect-menu { //The options
text-align: right !important;
}
If you want to repopulate the select, you must refresh it:
$('#' + Field).multiselect('refresh');
To get the selected values (comma separated):
var SelectedOptions = $('#' + Field).multiselect("getChecked").map(function () {
return this.value;
}).get();
To clear all selected values:
$('#' + Field).multiselect("uncheckAll");
I usually use this method
public static SelectList SetSelectedValue(SelectList list, string value)
{
if (value != null)
{
var selected = list.Where(x => x.Value == value).First();
selected.Selected = true;
return list;
}
return list;
}
I was looking for an solution to make an XHR request to a server from a local html file and found a solution using Chrome and PHP. (no Jquery)
Javascripts:
var x = new XMLHttpRequest();
if(x) x.onreadystatechange=function(){
if (x.readyState === 4 && x.status===200){
console.log(x.responseText); //Success
}else{
console.log(x); //Failed
}
};
x.open(GET, 'http://example.com/', true);
x.withCredentials = true;
x.send();
My Chrome's request header Origin: null
My PHP response header (Note that 'null' is a string). HTTP_REFERER allow cross-origin from a remote server to another.
header('Access-Control-Allow-Origin: '.(trim($_SERVER['HTTP_REFERER'],'/')?:'null'),true);
header('Access-Control-Allow-Credentials:true',true);
I was able to successfully connect to my server.
You can disregards the Credentials headers, but this works for me with Apache's AuthType Basic
enabled
I tested compatibility with FF and Opera, It works in many cases such as:
From a VM LAN IP (192.168.0.x) back to the VM'S WAN (public) IP:port
From a VM LAN IP back to a remote server domain name.
From a local .HTML file to the VM LAN IP and/or VM WAN IP:port,
From a local .HTML file to a remote server domain name.
And so on.
You can use DateTime.ParseExact()
method.
Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
DateTime date = DateTime.ParseExact("04/30/2013 23:00",
"MM/dd/yyyy HH:mm",
CultureInfo.InvariantCulture);
Here is a DEMO
.
hh
is for 12-hour clock from 01 to 12, HH
is for 24-hour clock from 00 to 23.
For more information, check Custom Date and Time Format Strings
Smart pointers will clean themselves up after they go out of scope (thereby removing fear of most memory leaks). Shared pointers are smart pointers that keep a count of how many instances of the pointer exist, and only clean up the memory when the count reaches zero. In general, only use shared pointers (but be sure to use the correct kind--there is a different one for arrays). They have a lot to do with RAII.