Because async/await uses promises under the hood, you can write a little utility function like this:
export function catchEm(promise) {
return promise.then(data => [null, data])
.catch(err => [err]);
}
Then import it whenever you need to catch some errors, and wrap your async function which returns a promise with it.
import catchEm from 'utility';
async performAsyncWork() {
const [err, data] = await catchEm(asyncFunction(arg1, arg2));
if (err) {
// handle errors
} else {
// use data
}
}
So, you may download it from:
https://go.microsoft.com/fwlink/?LinkId=708984
And I got this from: http://blogs.bukutamudigital.com/2016/06/28/visual-studio-2015-update-3-offline-installer/
It's around 6GB
For IntelliJ IDEA 2019.3.4 (Ultimate Edition), the following worked for me:
In my case issue was with wrong path to NDK
.
If your project requires it please check it in menu File -> Project Structure -> SDK Location
:
There is a much easier way to compile and run C code using GCC, no configuration needed:
Ctrl+Alt+N
, or press F1
and then select/type Run Code
, or right click the Text Editor and then click Run Code
in context menu, the code will be compiled and run, and the output will be shown in the Output Window.Moreover you could update the config in settings.json using different C compilers as you want, the default config for C is as below:
"code-runner.executorMap": {
"c": "gcc $fullFileName && ./a.out"
}
yum update
helped me out. After I had
wget: symbol lookup error: wget: undefined symbol: psl_latest
I faced this problem and this is how I solved it.
1) Delete all the migration records from your app's migration directory. These are files named 0001_,0002_,0003_ etc. Be careful as to not delete the _init__.py file.
2) Delete the db.sqlite3 file. It will be regenerated later.
Now, run the following commands:
python manage.py makemigrations appname
python manage.py migrate
Be sure to write the name of your app after makemigrations. You might have to create a superuser to access your database again. Do so by the following
python manage.py createsuperuser
Swift 4.1 introduces new -Osize
optimization mode.
In Swift 4.1 the compiler now supports a new optimization mode which enables dedicated optimizations to reduce code size.
The Swift compiler comes with powerful optimizations. When compiling with -O the compiler tries to transform the code so that it executes with maximum performance. However, this improvement in runtime performance can sometimes come with a tradeoff of increased code size. With the new -Osize optimization mode the user has the choice to compile for minimal code size rather than for maximum speed.
To enable the size optimization mode on the command line, use -Osize instead of -O.
Further reading : https://swift.org/blog/osize/
I think I figured out the questions after reading the log. Thanks to Will's reminder, I checked the log and found out the some program else is listening to that port. Before I can start to figure out which program, my computer was restarted and localhost:8080 works and showing tomcat page. Whooh
mongod --port portnumber --dbpath /path_to_your_folder
By default portnumber is 27017 and path is /var/lib/mongodb
You can set your own port number and path where you want to keep all your database.
Remove the line that says
Require all granted
it's only needed on Apache >=2.4
I had the same problem and in order to execute pip install inside virtualenv I had to use this command:
RUN pip install virtualenv virtualenvwrapper
RUN mkdir -p /opt/virtualenvs
ENV WORKON_HOME /opt/virtualenvs
RUN /bin/bash -c "source /usr/local/bin/virtualenvwrapper.sh \
&& mkvirtualenv myapp \
&& workon myapp \
&& pip install -r /mycode/myapp/requirements.txt"
I hope it helps.
Within the package there is a class called JwtSecurityTokenHandler
which derives from System.IdentityModel.Tokens.SecurityTokenHandler
. In WIF this is the core class for deserialising and serialising security tokens.
The class has a ReadToken(String)
method that will take your base64 encoded JWT string and returns a SecurityToken
which represents the JWT.
The SecurityTokenHandler
also has a ValidateToken(SecurityToken)
method which takes your SecurityToken
and creates a ReadOnlyCollection<ClaimsIdentity>
. Usually for JWT, this will contain a single ClaimsIdentity
object that has a set of claims representing the properties of the original JWT.
JwtSecurityTokenHandler
defines some additional overloads for ValidateToken
, in particular, it has a ClaimsPrincipal ValidateToken(JwtSecurityToken, TokenValidationParameters)
overload. The TokenValidationParameters
argument allows you to specify the token signing certificate (as a list of X509SecurityTokens
). It also has an overload that takes the JWT as a string
rather than a SecurityToken
.
The code to do this is rather complicated, but can be found in the Global.asax.cx code (TokenValidationHandler
class) in the developer sample called "ADAL - Native App to REST service - Authentication with ACS via Browser Dialog", located at
http://code.msdn.microsoft.com/AAL-Native-App-to-REST-de57f2cc
Alternatively, the JwtSecurityToken
class has additional methods that are not on the base SecurityToken
class, such as a Claims
property that gets the contained claims without going via the ClaimsIdentity
collection. It also has a Payload
property that returns a JwtPayload
object that lets you get at the raw JSON of the token. It depends on your scenario which approach it most appropriate.
The general (i.e. non JWT specific) documentation for the SecurityTokenHandler
class is at
http://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.securitytokenhandler.aspx
Depending on your application, you can configure the JWT handler into the WIF pipeline exactly like any other handler.
There are 3 samples of it in use in different types of application at
Probably, one will suite your needs or at least be adaptable to them.
Be careful with invalid values for keys "directories" and "files" in package.json
If you start with a new application, and you want to start completely blank, you have to either start in a complete empty folder or have a valid package.json file in it.
If you do not want to create a package.json file first, just type: npm i some_package
Package with name "some_package" should be installed correctly in a new sub folder "node_modules".
If you create a package.json file first, type: npm init
Keep all the defaults (by just clicking ENTER), you should end up with a valid file.
It should look like this:
{
"name": "yourfoldername",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Note that the following keys are missing: "directories", "repository" and "files". It looks like if you use incorrect values for "directories" and/or "files", you are not able to install the package. Leaving these keys out, solved the issue for me.
Also note key "main". This one is present, but it does contain an invalid value. No file "index.js" exists (yet). You can safely remove it.
Now type: npm i some_package
and package with name "some_package" should be installed correctly in a new sub folder "node_modules".
I think all you need to do for your function is just add PtrSafe: i.e. the first line of your first function should look like this:
Private Declare PtrSafe Function swe_azalt Lib "swedll32.dll" ......
This is an old post but maybe this could help people to complete the CORS problem. To complete the basic authorization problem you should avoid authorization for OPTIONS requests in your server. This is an Apache configuration example. Just add something like this in your VirtualHost or Location.
<LimitExcept OPTIONS>
AuthType Basic
AuthName <AUTH_NAME>
Require valid-user
AuthUserFile <FILE_PATH>
</LimitExcept>
Another option if using drupal is simply to add the css style that you want to use. that way it does not strip out the style or class name.
so in my case under the css tab in drupal 7 simply add something like
facebook=span.icon-facebook2
also check that font-styles button is enabled
To solve the issue you must assign the proper ownership permissions. Try the below which should resolve all permission related issues for specific users but as stated in the comments this should not be used in production:
root@server:/var/log/postgresql# sudo -u postgres psql
psql (8.4.4)
Type "help" for help.
postgres=# \du
List of roles
Role name | Attributes | Member of
-----------------+-------------+-----------
<user-name> | Superuser | {}
: Create DB
postgres | Superuser | {}
: Create role
: Create DB
postgres=# alter role <user-name> superuser;
ALTER ROLE
postgres=#
So connect to the database under a Superuser account sudo -u postgres psql
and execute a ALTER ROLE <user-name> Superuser;
statement.
Keep in mind this is not the best solution on multi-site hosting server so take a look at assigning individual roles instead: https://www.postgresql.org/docs/current/static/sql-set-role.html and https://www.postgresql.org/docs/current/static/sql-alterrole.html.
As others have said, use ArrayList
. Here's how:
public class t
{
private List<Integer> x = new ArrayList<Integer>();
public void add(int num)
{
this.x.add(num);
}
}
As you can see, your add
method just calls the ArrayList
's add method. This is only useful if your variable is private (which it is).
Something like this should work
var yesterday = DateTime.Now.Date.AddDays(-1);
DateTime.Now
gives you the current date and time.
If your looking to remove the the time element then adding .Date
constrains it to the date only ie time is 00:00:00
.
Finally .AddDays(-1)
removes 1 day to give you yesterday.
An approach that worked for me on IE (I couldn't use the display technique because there was an input that must not loose focus)
It works if you have 0 margin (changing the padding works as well)
if(div.style.marginLeft == '0px'){
div.style.marginLeft = '';
div.style.marginRight = '0px';
} else {
div.style.marginLeft = '0px';
div.style.marginRight = '';
}
JSON is "JavaScript Object Notation". JavaScript specifies its keys must be strings or symbols.
The following quotation from MDN Docs uses the terms "key/property" to refer to what I more often hear termed as "key/value".
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Objects
In JavaScript, objects can be seen as a collection of properties. With the object literal syntax, a limited set of properties are initialized; then properties can be added and removed. Property values can be values of any type, including other objects, which enables building complex data structures. Properties are identified using key values. A key value is either a String or a Symbol value.
You can get the best of both worlds. It is possible to use ExternalProject
to download the gtest source and then use add_subdirectory()
to add it to your build. This has the following advantages:
Used in the normal way, ExternalProject won't do the download and unpacking at configure time (i.e. when CMake is run), but you can get it to do so with just a little bit of work. I've written a blog post on how to do this which also includes a generalised implementation which works for any external project which uses CMake as its build system, not just gtest. You can find them here:
Update: This approach is now also part of the googletest documentation.
Its actually formulated more like:
https://<bucket-name>.s3.amazonaws.com/<key>
See here
Here is something I did which open Facebook App with Link
shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setComponent(new ComponentName("com.facebook.katana",
"com.facebook.katana.activity.composer.ImplicitShareIntentHandler"));
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, videoUrl);
The key checks for FAST REFRESH includes the following:
1) An Oracle materialized view log must be present for each base table.
2) The RowIDs of all the base tables must appear in the SELECT list of the MVIEW query definition.
3) If there are outer joins, unique constraints must be placed on the join columns of the inner table.
No 3 is easy to miss and worth highlighting here
How do they achieve internally that you are able to pass something like x > 5 into a method?
The short answer is that they don't.
Any sort of logical operation on a numpy array returns a boolean array. (i.e. __gt__
, __lt__
, etc all return boolean arrays where the given condition is true).
E.g.
x = np.arange(9).reshape(3,3)
print x > 5
yields:
array([[False, False, False],
[False, False, False],
[ True, True, True]], dtype=bool)
This is the same reason why something like if x > 5:
raises a ValueError if x
is a numpy array. It's an array of True/False values, not a single value.
Furthermore, numpy arrays can be indexed by boolean arrays. E.g. x[x>5]
yields [6 7 8]
, in this case.
Honestly, it's fairly rare that you actually need numpy.where
but it just returns the indicies where a boolean array is True
. Usually you can do what you need with simple boolean indexing.
This is a security and maintainability question.
Whenever possible, you should use 'safe' (unidirectional) methods such as GET and HEAD in order to limit potential vulnerability.
Whenever possible, you should use 'idempotent' methods such as GET, HEAD, PUT and DELETE, which can't have side effects and are therefore less error prone/easier to control.
Here's a zsh-only function that I like for its compactness. It uses the ‘A’ expansion modifier — see zshexpn(1).
realpath() { for f in "$@"; do echo ${f}(:A); done }
SLF4J 1.5.11 and 1.6.0 versions are not compatible (see compatibility report) because the argument list of org.slf4j.spi.LocationAwareLogger.log
method has been changed (added Object[] p5):
SLF4J 1.5.11:
LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
String p4, Throwable p5 )
SLF4J 1.6.0:
LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
String p4, Object[] p5, Throwable p6 )
See compatibility reports for other SLF4J versions on this page.
You can generate such reports by the japi-compliance-checker tool.
I know this is an old post but having read this I think this solution is much simpler (though technically it solves the problem with Javascript not PHP).
<html>
<head>
<title>Ultan.me - Unset</title>
<script type="text/javascript">
function setTitle( text ) {
document.title = text;
}
</script>
<!-- other head info -->
</head>
<?php
// Make the call to the DB to get the title text. See OP post for example
$title_text = "Ultan.me - DB Title";
// Use body onload to set the title of the page
print "<body onload=\"setTitle( '$title_text' )\" >";
// Rest of your code here
print "<p>Either use php to print stuff</p>";
?>
<p>or just drop in and out of php</p>
<?php
// close the html page
print "</body></html>";
?>
A slight variation on Jack's answer to add support for PHP < 7:
// Get an RFC-4122 compliant globaly unique identifier
function get_guid() {
$data = PHP_MAJOR_VERSION < 7 ? openssl_random_pseudo_bytes(16) : random_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // Set version to 0100
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // Set bits 6-7 to 10
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
Something like this:
// interface implementation publisher
public delegate void eiSubjectEventHandler(eiSubject subject);
public interface eiSubject
{
event eiSubjectEventHandler OnUpdate;
void GenereteEventUpdate();
}
// class implementation publisher
class ecSubject : eiSubject
{
private event eiSubjectEventHandler _OnUpdate = null;
public event eiSubjectEventHandler OnUpdate
{
add
{
lock (this)
{
_OnUpdate -= value;
_OnUpdate += value;
}
}
remove { lock (this) { _OnUpdate -= value; } }
}
public void GenereteEventUpdate()
{
eiSubjectEventHandler handler = _OnUpdate;
if (handler != null)
{
handler(this);
}
}
}
// interface implementation subscriber
public interface eiObserver
{
void DoOnUpdate(eiSubject subject);
}
// class implementation subscriber
class ecObserver : eiObserver
{
public virtual void DoOnUpdate(eiSubject subject)
{
}
}
I use this function for debugging:
function pre($pre=true) {
if($pre) {
echo "<pre>";
}
foreach(func_get_args as $arg) {
print_r($arg);
# or, if it pleases you more:
# var_dump(arg);
}
if($pre) {
echo "<pre>";
}
}
This way you don't have to
pre($arrayOne);
pre($arrayTwo);
But in one go:
pre($arrayOne, $arrayTwo);
Or as many arguments you give it.
SharePoint uses a lot of different logging mechanisms. Most importantly you can configure the location of the logs through Central Admin. To give you an understanding of the logs involved, here is a quote from http://raiumair.wordpress.com/2007/06/19/quick-a-to-z-of-sharepoint-logs/
All file based logs can be read by text editors and can be parsed by using popular log parsing tools (Log Parser 2.2 from Microsoft or Funnel Web). It will also be a good idea to read the IIS Logs which are generally saved at (System Drive):\WINDOWS\system32\LogFiles
a) Diagnostics Logs
· Event Throttling Logs – These end up going to the Windows Event Log and can be viewed in the Event Viewer. They show Errors and Warnings.
· Trace Logs – These show detailed line by line tracing infomration emitted during a web request or service execution. They end up being stored at a known location on the front-end server. Default Location: (System Drive):\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\LOGS\
b) Audit Logs - They end up in the associated Content Database tables and can be viewed at Site Collection Level as well as Site Level using the web browser. WSS 3.0 and MOSS 2007 use different pages to show Audit Log Reports.
c) Usage Logs – They get stored locally on the front-end servers and get processed both locally and at farm level via SSP (this is based on the setup as I understand the results from the local processing are merged by SSP) and can be viewed at both the Site Level and Site Collection Level. Default Location: (System Drive):\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\Logs
d) Search\Query Logs – These are saved in the associated SSP database but can be viewed at SSP level via the Web Browser and in MOSS at Site Collection Level by going to the settings page.
e) Information Management Logs – Stored in the associated Content Database and can be can be viewed at the Site Collection Level.
f) Content and Structure Logs – This option is only available after one enables the publication feature. This store is saved in the Content Database associated with the Site Collection and can be viewed at Site Collection level by going to the settings page.
This is how I solved it
if recursive:
items = os.walk(target_directory)
else:
items = [next(os.walk(target_directory))]
...
Matt's solution didn't work for me on OS X, but Paul's did.
The short version from Paul's link is:
Created /usr/local/bin/ssh_session
with the following text:
#!/bin/bash
export SSH_SESSION=1
if [ -z "$SSH_ORIGINAL_COMMAND" ] ; then
export SSH_LOGIN=1
exec login -fp "$USER"
else
export SSH_LOGIN=
[ -r /etc/profile ] && source /etc/profile
[ -r ~/.profile ] && source ~/.profile
eval exec "$SSH_ORIGINAL_COMMAND"
fi
Execute:
chmod +x /usr/local/bin/ssh_session
Add the following to /etc/sshd_config
:
ForceCommand /usr/local/bin/ssh_session
I had got this error after changing the web service return type and SoapDocumentMethod.
Initially it was:
[WebMethod]
public int Foo()
{
return 0;
}
I decided to make it fire and forget type like this:
[SoapDocumentMethod(OneWay = true)]
[WebMethod]
public void Foo()
{
return;
}
In such cases, updating the web reference helped.
To update a web service reference:
In many linux release, you can find complier.h in /usr/linux/ , you can include it for use simply. And another opinion, unlikely() is more useful rather than likely(), because
if ( likely( ... ) ) {
doSomething();
}
it can be optimized as well in many compiler.
And by the way, if you want to observe the detail behavior of the code, you can do simply as follow:
gcc -c test.c objdump -d test.o > obj.s
Then, open obj.s, you can find the answer.
If you want to try to do it by using interface, you can view my video for this. This way, you no need to write any code to show Activity Indicator in the middle of the iPhone screen.
You have to create custom pipe.
import { Injectable, Pipe } from '@angular/core';
@Pipe({
name: 'keyobject'
})
@Injectable()
export class Keyobject {
transform(value, args:string[]):any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]});
}
return keys;
}}
And then use it in your *ngFor
*ngFor="let item of data | keyobject"
This is built from Álvaro González's answer and How to increase IDE memory limit in IntelliJ IDEA on Mac?
Go to Help > Edit Custom Properties
Add:
idea.max.intellisense.filesize=999999
Restart the IDE.
In views with {{}}
and/or ng-model, Angular is setting up $watch()
es for you behind the scenes.
By default $watch
compares by reference. If you set the third parameter to $watch
to true
, Angular will instead "shallow" watch the object for changes. For arrays this means comparing the array items, for object maps this means watching the properties. So this should do what you want:
$scope.$watch('myModel', function() { ... }, true);
Update: Angular v1.2 added a new method for this, `$watchCollection():
$scope.$watchCollection('myModel', function() { ... });
Note that the word "shallow" is used to describe the comparison rather than "deep" because references are not followed -- e.g., if the watched object contains a property value that is a reference to another object, that reference is not followed to compare the other object.
I also found that in some cases the reason for 502/400 in case of many headers could be because of a large number of headers without regard to size. from the docs
tune.http.maxhdr Sets the maximum number of headers in a request. When a request comes with a number of headers greater than this value (including the first line), it is rejected with a "400 Bad Request" status code. Similarly, too large responses are blocked with "502 Bad Gateway". The default value is 101, which is enough for all usages, considering that the widely deployed Apache server uses the same limit. It can be useful to push this limit further to temporarily allow a buggy application to work by the time it gets fixed. Keep in mind that each new header consumes 32bits of memory for each session, so don't push this limit too high.
https://cbonte.github.io/haproxy-dconv/configuration-1.5.html#3.2-tune.http.maxhdr
Two options:
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
Or
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
String enums look different than regular ones, for example:
enum MyEnum {
A = "a",
B = "b",
C = "c"
}
Compiles into:
var MyEnum;
(function (MyEnum) {
MyEnum["A"] = "a";
MyEnum["B"] = "b";
MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));
Which just gives you this object:
{
A: "a",
B: "b",
C: "c"
}
You can get all the keys (["A", "B", "C"]
) like this:
Object.keys(MyEnum);
And the values (["a", "b", "c"]
):
Object.keys(MyEnum).map(key => MyEnum[key])
Or using Object.values():
Object.values(MyEnum)
In bash, we use
declare -A name_of_dictonary_variable
so that Bash understands it is a dictionary.
For e.g. you want to create sounds
dictionary then,
declare -A sounds
sounds[dog]="Bark"
sounds[wolf]="Howl"
where dog
and wolf
are "keys"
, and Bark
and Howl
are "values"
.
You can access all values using : echo ${sounds[@]}
OR echo ${sounds[*]}
You can access all keys only using: echo ${!sounds[@]}
And if you want any value for a particular key, you can use:
${sounds[dog]}
this will give you value (Bark
) for key (Dog
).
You don't need to wait. Protractor automatically waits for angular to be ready and then it executes the next step in the control flow.
Maybe:
crimefile = open(fileName, 'r')
yourResult = [line.split(',') for line in crimefile.readlines()]
Is this perhaps what you are looking for?
select NEWID() * from TABLE
There is no reliable way. You can perhaps look at the user-agent string, but this can be spoofed, or omitted. Alternatively, you could use a GeoIP service to lookup the client's IP address, but again, this can be easily circumvented.
I guess it's just because the onblur event is called as a result of the input losing focus, there isn't a blur action associated with an input, like there is a click action associated with a button
@echo off & setlocal EnableDelayedExpansion
set Var=finding the length of strings
for /l %%A in (0,1,10000) do if not "%Var%"=="!Var:~0,%%A!" (set /a Length+=1) else (echo !Length! & pause & exit /b)
set the var to whatever you want to find the length of it or change it to set /p var= so that the user inputs it. Putting this here for future reference.
MacOSX: cd /Users/USER_NAME/anaconda3/bin && ./activate
The app is trying to create a COM Object and even if that COM DLL exists, it may depend on another DLL which isn't installed. You can use DependencyWalker to find out if this is the case.
Quite simply, both lines create the object on the stack, rather than on the heap as 'new' does. The second line actually involves a second call to a copy constructor, so it should be avoided (it also needs to be corrected as indicated in the comments). You should use the stack for small objects as much as possible since it is faster, however if your objects are going to survive for longer than the stack frame, then it's clearly the wrong choice.
I needed something similar, and came up with using the :before (or :after) pseudoclasses:
#mydiv {
background-color: #fbb;
margin-top: 100px;
position: relative;
}
#mydiv:before {
content: "";
background-color: #bfb;
top: -100px;
height: 100px;
width: 100%;
position: absolute;
}
Put the "hibernate-entitymanager.jar"
in the classpath of application.
For newer versions, you should use "hibernate-core.jar"
instead of the deprecated hibernate-entitymanager
If you are running through some IDE, like Eclipse: Project Properties -> Java Build Path -> Libraries.
Otherwise put it in the /lib
of your application.
I would use a StringBuilder class for doing string manipulation as it will more efficient (being mutable)
string flights = "Flight A, B,C,D";
StringBuilder message = new StringBuilder();
message.Append("Hi We have these flights for you: ");
message.Append(flights);
message.Append(" . Which one do you want?");
Ruby does have a method for this:
File.readlines('foo').each do |line|
Starting the OracleServiceXXX from the services.msc worked for me in Windows.
Possible solutions:
Use nginx on the server as a proxy that will listen to port A and multiplex to port B or C.
If you use AWS you can use the load balancer to redirect the request to specific port based on the host.
Pending Intent is an intent who provides all permission to other application to do a particular works. When the main activity is destroyed, Android OS takes back the permission from it.
If you happen to be working in Active Directory on an intranet, here are some tips:
(Windows Server 2012)
Running anything that talks to AD on a web server requires a bunch of changes and patience. Since when running on a web server vs. local IIS/IIS Express it runs in the AppPool's identity so, you have to set it up to impersonate whoever hits the site.
How to get the current logged-in user in an active directory when your ASP.NET MVC application is running on a web server inside the network:
// Find currently logged in user
UserPrincipal adUser = null;
using (HostingEnvironment.Impersonate())
{
var userContext = System.Web.HttpContext.Current.User.Identity;
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings["AllowedDomain"], null,
ContextOptions.Negotiate | ContextOptions.SecureSocketLayer);
adUser = UserPrincipal.FindByIdentity(ctx, userContext.Name);
}
//Then work with 'adUser' from here...
You must wrap any calls having to do with 'active directory context' in the following so it's acting as the hosting environment to get the AD information:
using (HostingEnvironment.Impersonate()){ ... }
You must also have impersonate
set to true in your web.config:
<system.web>
<identity impersonate="true" />
You must have Windows authentication on in web.config:
<authentication mode="Windows" />
I believe (and I am hardly well-versed in Python) that the main difference is that a tuple is immutable (it can't be changed in place after assignment) and a list is mutable (you can append, change, subtract, etc).
So, I tend to make my tuples things that shouldn't change after assignment and my lists things that can.
I had the same problem. The reason was that I had two JAR files were not added through the Maven dependency, so when I ran mvn compile
, the console display the error error:
Symbol cannot be found,Class...".
To fix it:
mvn compile
The accepted answer is good and fast:
i.ToString("00")
or
i.ToString("000")
If you need more complexity, String.Format is worth a try:
var str1 = "";
var str2 = "";
for (int i = 1; i < 100; i++)
{
str1 = String.Format("{0:00}", i);
str2 = String.Format("{0:000}", i);
}
For the i = 10
case:
str1: "10"
str2: "010"
I use this, for example, to clear the text on particular Label Controls on my form by name:
private void EmptyLabelArray()
{
var fmt = "Label_Row{0:00}_Col{0:00}";
for (var rowIndex = 0; rowIndex < 100; rowIndex++)
{
for (var colIndex = 0; colIndex < 100; colIndex++)
{
var lblName = String.Format(fmt, rowIndex, colIndex);
foreach (var ctrl in this.Controls)
{
var lbl = ctrl as Label;
if ((lbl != null) && (lbl.Name == lblName))
{
lbl.Text = null;
}
}
}
}
}
Use this
<input type="checkbox" onclick="onClickHandler()" id="box" />
<script>
function onClickHandler(){
var chk=document.getElementById("box").value;
//use this value
}
</script>
Yes, it's possible, e.g. using the implicit conversion from RAW to BLOB:
insert into blob_fun values(1, hextoraw('453d7a34'));
453d7a34
is a string of hexadecimal values, which is first explicitly converted to the RAW data type and then inserted into the BLOB column. The result is a BLOB value of 4 bytes.
Best way is running Particular migration again by using down or up(in rails 4. It's change)
rails db:migrate:up VERSION=timestamp
Now how you get the timestamp. Go to this path
/db/migrate
Identify migration file you want to revert.pick the timestamp from that file name.
A comment about Will's answer, you might want to replace HttpContext.Current.Response.End();
with HttpContext.Current.ApplicationInstance.CompleteRequest();
The reason is that Response.End()
throws a System.Threading.ThreadAbortException
. It aborts a thread. If you have an exception logger, it will be littered with ThreadAbortExceptions, which in this case is expected behavior.
Intuitively, sending a CSV file to the browser should not raise an exception.
See here for more Is Response.End() considered harmful?
case_when
is now a pretty clean implementation of the SQL-style case when:
structure(list(a = c(1, 3, 4, 6, 3, 2, 5, 1), b = c(1, 3, 4,
2, 6, 7, 2, 6), c = c(6, 3, 6, 5, 3, 6, 5, 3), d = c(6, 2, 4,
5, 3, 7, 2, 6), e = c(1, 2, 4, 5, 6, 7, 6, 3), f = c(2, 3, 4,
2, 2, 7, 5, 2)), .Names = c("a", "b", "c", "d", "e", "f"), row.names = c(NA,
8L), class = "data.frame") -> df
df %>%
mutate( g = case_when(
a == 2 | a == 5 | a == 7 | (a == 1 & b == 4 ) ~ 2,
a == 0 | a == 1 | a == 4 | a == 3 | c == 4 ~ 3
))
Using dplyr 0.7.4
The manual: http://dplyr.tidyverse.org/reference/case_when.html
Right Click on Project > Properties > Java Build Path > Libraries > select classpath -> add Library -> Junit -> select junit version -> finish -> applay
I know the OP says Recycle Bin. What I do though is recreate the file, especially if it's a single file. And when in the file, I just press CMD+Z (I'm on a Mac) and I get my file back.
I developed a multithreaded swing based simulation of robot navigation through a set of randomized grid terrain of food sources and mines and developed a genetic algorithm based strategy of exploring the optimization of robotic behavior and survival of fittest genes for a robotic chromosome. This was done using charting and mapping of each iteration cycle.
Since, then I have developed even more game behavior. An example application I built recently for myself was a genetic algorithm for solving the traveling sales man problem in route finding in UK taking into account start and goal states as well as one/multiple connection points, delays, cancellations, construction works, rush hour, public strikes, consideration between fastest vs cheapest routes. Then providing a balanced recommendation for the route to take on a given day.
Generally, my strategy is to use POJO based representaton of genes then I apply specific interface implementations for selection, mutation, crossover strategies, and the criteria point. My fitness function then basically becomes a quite complex based on the strategy and criteria I need to apply as a heuristic measure.
I have also looked into applying genetic algorithm into automated testing within code using systematic mutation cycles where the algorithm understands the logic and tries to ascertain a bug report with recommendations for code fixes. Basically, a way to optimize my code and provide recommendations for improvement as well as a way of automating the discovery of new programmatic code. I have also tried to apply genetic algorithms to music production amongst other applications.
Generally, I find evolutionary strategies like most metaheuristic/global optimization strategies, they are slow to learn at first but start to pick up as the solutions become closer and closer to goal state and as long as your fitness function and heuristics are well aligned to produce that convergence within your search space.
You need to override the color:
a { color:red } /* Globally */
/* Each state */
a:visited { text-decoration: none; color:red; }
a:hover { text-decoration: none; color:blue; }
a:focus { text-decoration: none; color:yellow; }
a:hover, a:active { text-decoration: none; color:black }
For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:
"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets>
<sheet name="MySheet1" sheetId="1" r:id="rId1" />
<sheet name="MySheet2" sheetId="2" r:id="rId2" />
</sheets>
</workbook>
The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" ?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData>
<row r="1">
<c r="A1">
<v>100</v>
</c>
</row>
</sheetData>
</worksheet>
"
Detection of cell encodings:
Due to my reputation points being less than 50 I could not comment on or vote for E Coder's answer above. This is the best way to do it so you don't have to use the group by as I had a similar issue.
By doing SUM((coalesce(VALUE1 ,0)) + (coalesce(VALUE2 ,0)))
as Total this will get you the number you want but also rid you of any error for not performing a Group By.
This was my query and gave me a total count and total amount for the each dealer and then gave me a subtotal for Quality and Risky dealer loans.
SELECT
DISTINCT STEP1.DEALER_NBR
,COUNT(*) AS DLR_TOT_CNT
,SUM((COALESCE(DLR_QLTY,0))+(COALESCE(DLR_RISKY,0))) AS DLR_TOT_AMT
,COUNT(STEP1.DLR_QLTY) AS DLR_QLTY_CNT
,SUM(STEP1.DLR_QLTY) AS DLR_QLTY_AMT
,COUNT(STEP1.DLR_RISKY) AS DLR_RISKY_CNT
,SUM(STEP1.DLR_RISKY) AS DLR_RISKY_AMT
FROM STEP1
WHERE DLR_QLTY IS NOT NULL OR DLR_RISKY IS NOT NULL
GROUP BY STEP1.DEALER_NBR
add this to your css:
.carousel-inner > .item > img, .carousel-inner > .item > a > img {
width: 100%;
}
Stuff(someColumn, 1, 4, '')
This says, starting with the first 1
character position, replace 4
characters with nothing ''
another alternative is my EditV32 (x86) or EditV64 (x64) command-line tools. For example:
editv32 -m -p "Password: " PWD
-m means "masked input" and -p is the prompt. The user's input is stored in the PWD environment variable. You can get it here:
If I understood correctly you are trying to use a single query, i think you can just merge your date search toghter in WHERE
clauses
SELECT id
FROM events
WHERE start BETWEEN '2013-06-13' AND '2013-07-22'
AND end BETWEEN '2013-06-13' AND '2013-07-22'
or even more simply you can just use both column to set search time filter
SELECT id
FROM events
WHERE start >= '2013-07-22' AND end <= '2013-06-13'
i use "Versions", quite easy, but not free .
Sorry you're not using PostgreSQL...
SELECT DISTINCT ON contract, activity * FROM thetable ORDER BY contract, activity
http://www.postgresql.org/docs/8.3/static/sql-select.html#SQL-DISTINCT
Oh wait. You only want values with exactly one...
SELECT contract, activity, count() FROM thetable GROUP BY contract, activity HAVING count() = 1
There are two pages: Pageone.html :
<script>
var hello = "hi"
location.replace("http://example.com/PageTwo.html?" + hi + "");
</script>
PageTwo.html :
<script>
var link = window.location.href;
link = link.replace("http://example.com/PageTwo.html?","");
document.write("The variable contained this content:" + link + "");
</script>
Hope it helps!
What about casting to Number in Javascript using the Unary (+) Operator
lat: 12.23
lat: +12.23
Depends on the use case. Here is a fullchart what works and what not: parseInt vs unary plus - when to use which
If SSH port number is not 22(default), add Port xx
in ~/.ssh/config
In my case (synology),
Host my_synology
Hostname xxxx.synology.me
IdentityFile ~/.ssh/id_rsa_xxxx
User myname
Port xx
Then clone using Host title in config. ("my_synology". to avoid @chopstik 's "*")
git clone my_synology:path/to/repo.git
I used Robert Lee`s answer and it works great! Just writing down the complete function i'm using:
function isMobileDevice(){
$aMobileUA = array(
'/iphone/i' => 'iPhone',
'/ipod/i' => 'iPod',
'/ipad/i' => 'iPad',
'/android/i' => 'Android',
'/blackberry/i' => 'BlackBerry',
'/webos/i' => 'Mobile'
);
//Return true if Mobile User Agent is detected
foreach($aMobileUA as $sMobileKey => $sMobileOS){
if(preg_match($sMobileKey, $_SERVER['HTTP_USER_AGENT'])){
return true;
}
}
//Otherwise return false..
return false;
}
Most pure lua print table functions I've seen have a problem with deep recursion and tend to cause a stack overflow when going too deep. This print table function that I've written does not have this problem. It should also be capable of handling really large tables due to the way it handles concatenation. In my personal usage of this function, it outputted 63k lines to file in about a second.
The output also keeps lua syntax and the script can easily be modified for simple persistent storage by writing the output to file if modified to allow only number, boolean, string and table data types to be formatted.
function print_table(node)
local cache, stack, output = {},{},{}
local depth = 1
local output_str = "{\n"
while true do
local size = 0
for k,v in pairs(node) do
size = size + 1
end
local cur_index = 1
for k,v in pairs(node) do
if (cache[node] == nil) or (cur_index >= cache[node]) then
if (string.find(output_str,"}",output_str:len())) then
output_str = output_str .. ",\n"
elseif not (string.find(output_str,"\n",output_str:len())) then
output_str = output_str .. "\n"
end
-- This is necessary for working with HUGE tables otherwise we run out of memory using concat on huge strings
table.insert(output,output_str)
output_str = ""
local key
if (type(k) == "number" or type(k) == "boolean") then
key = "["..tostring(k).."]"
else
key = "['"..tostring(k).."']"
end
if (type(v) == "number" or type(v) == "boolean") then
output_str = output_str .. string.rep('\t',depth) .. key .. " = "..tostring(v)
elseif (type(v) == "table") then
output_str = output_str .. string.rep('\t',depth) .. key .. " = {\n"
table.insert(stack,node)
table.insert(stack,v)
cache[node] = cur_index+1
break
else
output_str = output_str .. string.rep('\t',depth) .. key .. " = '"..tostring(v).."'"
end
if (cur_index == size) then
output_str = output_str .. "\n" .. string.rep('\t',depth-1) .. "}"
else
output_str = output_str .. ","
end
else
-- close the table
if (cur_index == size) then
output_str = output_str .. "\n" .. string.rep('\t',depth-1) .. "}"
end
end
cur_index = cur_index + 1
end
if (size == 0) then
output_str = output_str .. "\n" .. string.rep('\t',depth-1) .. "}"
end
if (#stack > 0) then
node = stack[#stack]
stack[#stack] = nil
depth = cache[node] == nil and depth + 1 or depth - 1
else
break
end
end
-- This is necessary for working with HUGE tables otherwise we run out of memory using concat on huge strings
table.insert(output,output_str)
output_str = table.concat(output)
print(output_str)
end
Here is an example:
local t = {
["abe"] = {1,2,3,4,5},
"string1",
50,
["depth1"] = { ["depth2"] = { ["depth3"] = { ["depth4"] = { ["depth5"] = { ["depth6"] = { ["depth7"]= { ["depth8"] = { ["depth9"] = { ["depth10"] = {1000}, 900}, 800},700},600},500}, 400 }, 300}, 200}, 100},
["ted"] = {true,false,"some text"},
"string2",
[function() return end] = function() return end,
75
}
print_table(t)
Output:
{
[1] = 'string1',
[2] = 50,
[3] = 'string2',
[4] = 75,
['abe'] = {
[1] = 1,
[2] = 2,
[3] = 3,
[4] = 4,
[5] = 5
},
['function: 06472B70'] = 'function: 06472A98',
['depth1'] = {
[1] = 100,
['depth2'] = {
[1] = 200,
['depth3'] = {
[1] = 300,
['depth4'] = {
[1] = 400,
['depth5'] = {
[1] = 500,
['depth6'] = {
[1] = 600,
['depth7'] = {
[1] = 700,
['depth8'] = {
[1] = 800,
['depth9'] = {
[1] = 900,
['depth10'] = {
[1] = 1000
}
}
}
}
}
}
}
}
}
},
['ted'] = {
[1] = true,
[2] = false,
[3] = 'some text'
}
}
It may be useful for someone, so I'll post it here.
I was missing this dependency on my pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
Something like
SELECT * FROM tablename where visible=1 ORDER BY COALESCE(position, 999999999) ASC, id DESC
Replace 999999999 with what ever the max value for the field is
GUI Option:
Open System Properties
a. Type it in the Start Menu
b. Use the keyboard shortcut Win+Pause)
c. From Windows Explorer
address bar go to
%windir%\System32\SystemPropertiesProtection.exe
d. Write SystemPropertiesProtection
in run window and press Enter
Switch to the Advanced
tab
Environment Variables
PATH
in the System variables
sectionEdit
For example:
C:\Windows;C:\Windows\System32;C:\Python27
Command Line Option:
Check existing paths under PATH
variable (the paths are separated by semicolons). If your python folder already listed then no need to add again. Default python folder is C:\Python27
C:\Windows\system32>path
or C:\Windows\system32>echo %PATH%
Append python path using setx
command. The /M
option sets the variable at SYSTEM
scope.
The default behavior is to set it for the USER
.
C:\Windows\system32>setx /M PATH "%PATH%;C:\Python27"
I don't see it mentioned here, but splatting your arguments is a useful alternative and becomes especially useful if you are building out the arguments to a command dynamically (as opposed to using Invoke-Expression
). You can splat with arrays for positional arguments and hashtables for named arguments. Here are some examples:
Test-Connection www.google.com localhost
$argumentArray = 'www.google.com', 'localhost'
Test-Connection @argumentArray
Note that when splatting, we reference the splatted variable with an
@
instead of a$
. It is the same when using a Hashtable to splat as well.
Test-Connection -ComputerName www.google.com -Source localhost
$argumentHash = @{
ComputerName = 'www.google.com'
Source = 'localhost'
}
Test-Connection @argumentHash
Test-Connection www.google.com localhost -Count 1
$argumentHash = @{
Count = 1
}
$argumentArray = 'www.google.com', 'localhost'
Test-Connection @argumentHash @argumentArray
Using
Dim myarray As Variant
works but
Dim myarray As String
doesn't so I sitck to Variant
I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=D:\test.xls " & _
";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
For i = 0 To rs.Fields.Count - 1
Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
strNaam = rs.Fields(0).Value
Next
rs.MoveNext
Loop
rs.Close
There are other ways, depending on what you want to do, such as GetString (GetString Method Description).
private bool IsValidPath(string path)
{
Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
if (string.IsNullOrWhiteSpace(path) || path.Length < 3)
{
return false;
}
if (!driveCheck.IsMatch(path.Substring(0, 3)))
{
return false;
}
var x1 = (path.Substring(3, path.Length - 3));
string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
strTheseAreInvalidFileNameChars += @":?*";
Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");
if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
{
return false;
}
var driveLetterWithColonAndSlash = Path.GetPathRoot(path);
if (!DriveInfo.GetDrives().Any(x => x.Name == driveLetterWithColonAndSlash))
{
return false;
}
return true;
}
You can attach a SLOT to the
void aboutToQuit();
signal of your QApplication. This signal should be raised just before app closes.
An old post, but I love to share as I have the same case but I finally knew the problem :
Problem is : We make a function to work with specified an HTML element, but the HTML element related to this function is not yet created (because the element was dynamically generated). To make it works, we should make the function at the same time we create the element. Element first than make function related to it.
Simply word, a function will only works to the element that created before it (him). Any elements that created dynamically means after him.
But please inspect this sample that did not heed the above case :
<div class="btn-list" id="selected-country"></div>
Dynamically appended :
<button class="btn-map" data-country="'+country+'">'+ country+' </button>
This function is working good by clicking the button :
$(document).ready(function() {
$('#selected-country').on('click','.btn-map', function(){
var datacountry = $(this).data('country'); console.log(datacountry);
});
})
or you can use body like :
$('body').on('click','.btn-map', function(){
var datacountry = $(this).data('country'); console.log(datacountry);
});
compare to this that not working :
$(document).ready(function() {
$('.btn-map').on("click", function() {
var datacountry = $(this).data('country'); alert(datacountry);
});
});
hope it will help
For all your Swift-ers out there, this worked perfectly for me. It's notably one of the shorter ways to accomplish setting the title, as well:
override public func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "presentLineItem" {
print("Setting Title")
var vc = segue.destinationViewController as! LineItemsTableViewController
vc.navigationItem.title = "Line Item"
}
}
This solution worked for me
var str = "good_luck_buddy";
var index = str.indexOf('_');
var arr = [str.slice(0, index), str.slice(index + 1)];
//arr[0] = "good"
//arr[1] = "luck_buddy"
OR
var str = "good_luck_buddy";
var index = str.indexOf('_');
var [first, second] = [str.slice(0, index), str.slice(index + 1)];
//first = "good"
//second = "luck_buddy"
You can use exceptional handling as str.digit
will only work for integers and can fail for something like this too:
>>> str.isdigit(' 1')
False
Using a generator function:
def solve(lis):
for x in lis:
try:
yield float(x)
except ValueError:
pass
>>> mylist = ['1','orange','2','3','4','apple', '1.5', '2.6']
>>> list(solve(mylist))
[1.0, 2.0, 3.0, 4.0, 1.5, 2.6] #returns converted values
or may be you wanted this:
def solve(lis):
for x in lis:
try:
float(x)
return True
except:
return False
...
>>> mylist = ['1','orange','2','3','4','apple', '1.5', '2.6']
>>> [x for x in mylist if solve(x)]
['1', '2', '3', '4', '1.5', '2.6']
or using ast.literal_eval
, this will work for all types of numbers:
>>> from ast import literal_eval
>>> def solve(lis):
for x in lis:
try:
literal_eval(x)
return True
except ValueError:
return False
...
>>> mylist=['1','orange','2','3','4','apple', '1.5', '2.6', '1+0j']
>>> [x for x in mylist if solve(x)]
['1', '2', '3', '4', '1.5', '2.6', '1+0j']
Why use regex for that. String
implements IEnumerable<char>
, so you can just use LINQ.
test.Count(c => c == '&')
Part A: Configuring your Application Pool
Suppose the Application Pool is named 'MyPool' Go to 'Advanced Settings' of the Application Pool from the IIS Manager
Scroll down to 'Identity'. Trying to edit the value will bring up a dialog box. Select 'Built-In account' and under it, select 'ApplicationPoolIdentity'.
A few lines below 'Identity', you should find 'Load User Profile'. This value should be set to 'True'.
Part B: Configuring your website
Part C: Configuring your folder
The folder in question is C:\Whatever
You should now be able to use the browse the website
on my C drive I first create a txt file to create a new table. You can use what ever you want in this text file
in this case the text file is called "Bedrijf.txt"
the content:
Print 'START(A) create table'
GO 1
If not EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'Bedrijf'
)
BEGIN
CREATE TABLE [dbo].[Bedrijf] (
[IDBedrijf] [varchar] (38) NOT NULL ,
[logo] [varbinary] (max) NULL ,
[VolledigeHandelsnaam] [varchar] (100) NULL
) ON [PRIMARY]
save it
then I create an other txt file with the name "Bedrijf.bat" and the extension bat. It's content:
OSQL.EXE -U Username -P Password -S IPaddress -i C:Bedrijf.txt -o C:Bedrijf.out -d myDatabaseName
save it and from explorer double click to execute
The results will be saved in a txt file on your C drive with the name "Bedrijf.out"
it shows
1> 2> 3> START(A) create table
if all goes well
That's it
This is cleaner and will put in a csv.
Import-Module ActiveDirectory
$Groups = (Get-AdGroup -filter * | Where {$_.name -like "**"} | select name -expandproperty name)
$Table = @()
$Record = [ordered]@{
"Group Name" = ""
"Name" = ""
"Username" = ""
}
Foreach ($Group in $Groups)
{
$Arrayofmembers = Get-ADGroupMember -identity $Group | select name,samaccountname
foreach ($Member in $Arrayofmembers)
{
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
}
}
$Table | export-csv "C:\temp\SecurityGroups.csv" -NoTypeInformation
If you merge a commit into your branch, you should get all the history between.
Observe:
$ git init ./ Initialized empty Git repository in /Users/dfarrell/git/demo/.git/ $ echo 'a' > letter $ git add letter $ git commit -m 'Initial Letter' [master (root-commit) 6e59e76] Initial Letter 1 file changed, 1 insertion(+) create mode 100644 letter $ echo 'b' >> letter $ git add letter && git commit -m 'Adding letter' [master 7126e6d] Adding letter 1 file changed, 1 insertion(+) $ echo 'c' >> letter; git add letter && git commit -m 'Adding letter' [master f2458be] Adding letter 1 file changed, 1 insertion(+) $ echo 'd' >> letter; git add letter && git commit -m 'Adding letter' [master 7f77979] Adding letter 1 file changed, 1 insertion(+) $ echo 'e' >> letter; git add letter && git commit -m 'Adding letter' [master 790eade] Adding letter 1 file changed, 1 insertion(+) $ git log commit 790eade367b0d8ab8146596cd717c25fd895302a Author: Dan Farrell Date: Thu Jul 16 14:21:26 2015 -0500 Adding letter commit 7f77979efd17f277b4be695c559c1383d2fc2f27 Author: Dan Farrell Date: Thu Jul 16 14:21:24 2015 -0500 Adding letter commit f2458bea7780bf09fe643095dbae95cf97357ccc Author: Dan Farrell Date: Thu Jul 16 14:21:19 2015 -0500 Adding letter commit 7126e6dcb9c28ac60cb86ae40fb358350d0c5fad Author: Dan Farrell Date: Thu Jul 16 14:20:52 2015 -0500 Adding letter commit 6e59e7650314112fb80097d7d3803c964b3656f0 Author: Dan Farrell Date: Thu Jul 16 14:20:33 2015 -0500 Initial Letter $ git checkout 6e59e7650314112fb80097d7d3803c964b3656f $ git checkout 7126e6dcb9c28ac60cb86ae40fb358350d0c5fad Note: checking out '7126e6dcb9c28ac60cb86ae40fb358350d0c5fad'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -b with the checkout command again. Example: git checkout -b new_branch_name HEAD is now at 7126e6d... Adding letter $ git checkout -b B 7126e6dcb9c28ac60cb86ae40fb358350d0c5fad Switched to a new branch 'B' $ git pull 790eade367b0d8ab8146596cd717c25fd895302a fatal: '790eade367b0d8ab8146596cd717c25fd895302a' does not appear to be a git repository fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. $ git merge 7f77979efd17f277b4be695c559c1383d2fc2f27 Updating 7126e6d..7f77979 Fast-forward letter | 2 ++ 1 file changed, 2 insertions(+) $ cat letter a b c d
First, close all instances of Google Chrome. There should be no instances of chrome.exe
running in the Windows Task Manager. Then
%LOCALAPPDATA%\Google\Chrome\User Data\Default\
..txt
). This will serve as a backup, should something go wrong.window_placement
. Under window_placement
you will see things like "bottom", "left", "right", etc. with numbers after them.You will need to play around with these numbers to get your desired window size and placement. When finished, save this file with the name "Preferences" again with no extension. This will overwrite the existing Preferences file. Open Chrome and see how you did. If you're not satisfied with the size and placement, close Chrome and change the numbers in the Preferences file until you get what you want.
Lots of reasons for this warning. Mine is because I have a segue connected from a ViewController to another that will be presented modally. But, the ViewController I am presenting from is being dynamically generated by a PageViewController. Which is why it is detached in the Storyboard. My app isn't going to crash because of it; but I would like to silence the warning.
There's no Console.writeline
in Java. Its in .NET.
Console and standard out are not same. If you read the Javadoc page you mentioned, you will see that an application can have access to a console only if it is invoked from the command line and the output is not redirected like this
java -jar MyApp.jar > MyApp.log
Other such cases are covered in SimonJ's answer, though he missed out on the point that there's no Console.writeline
.
I've got this error just on devices with API lower that 21. In my case, I have had to work with a project where multiDexEnabled
option in build.gradle
was already set to true
. I checked dex file from APK and referenced methods number was less than 64k, so project doesn't need to be a multidex one, therefore I set multiDexEnabled
to false
. This solution worked for me.
It is worth mentioning that there is also: database scoped global temporary tables(currently supported only by Azure SQL Database).
Global temporary tables for SQL Server (initiated with ## table name) are stored in tempdb and shared among all users’ sessions across the whole SQL Server instance.
Azure SQL Database supports global temporary tables that are also stored in tempdb and scoped to the database level. This means that global temporary tables are shared for all users’ sessions within the same Azure SQL Database. User sessions from other databases cannot access global temporary tables.
-- Session A creates a global temp table ##test in Azure SQL Database testdb1 -- and adds 1 row CREATE TABLE ##test ( a int, b int); INSERT INTO ##test values (1,1); -- Session B connects to Azure SQL Database testdb1 -- and can access table ##test created by session A SELECT * FROM ##test ---Results 1,1 -- Session C connects to another database in Azure SQL Database testdb2 -- and wants to access ##test created in testdb1. -- This select fails due to the database scope for the global temp tables SELECT * FROM ##test ---Results Msg 208, Level 16, State 0, Line 1 Invalid object name '##test'
ALTER DATABASE SCOPED CONFIGURATION
GLOBAL_TEMPORARY_TABLE_AUTODROP = { ON | OFF }
APPLIES TO: Azure SQL Database (feature is in public preview)
Allows setting the auto-drop functionality for global temporary tables. The default is ON, which means that the global temporary tables are automatically dropped when not in use by any session. When set to OFF, global temporary tables need to be explicitly dropped using a DROP TABLE statement or will be automatically dropped on server restart.
With Azure SQL Database single databases and elastic pools, this option can be set in the individual user databases of the SQL Database server. In SQL Server and Azure SQL Database managed instance, this option is set in TempDB and the setting of the individual user databases has no effect.
Here's an extension method using @ata answer as inspiration.
"hello-world123, 456".MakeAlphaNumeric(new char[]{'-'});// yields "hello-world123456"
or if you require additional characters other than hyphen...
"hello-world123, 456!?".MakeAlphaNumeric(new char[]{'-','!'});// yields "hello-world123456!"
public static class StringExtensions
{
public static string MakeAlphaNumeric(this string input, params char[] exceptions)
{
var charArray = input.ToCharArray();
var alphaNumeric = Array.FindAll<char>(charArray, (c => char.IsLetterOrDigit(c)|| exceptions?.Contains(c) == true));
return new string(alphaNumeric);
}
}
Given that you wish to wait for the print dialog to go away I would use focus binding on the window.
print();
var handler = function(){
//unbind task();
$(window).unbind("focus",handler);
}
$(window).bind("focus",handler);
By putting in the unbind in the handler function we prevent the focus event staying bond to the window.
Here is a script that deploys an executable jar as a systemd service.
It creates a user for the service and the .service file, and place the jar file under /var, and makes some basic lock down of privileges.
#!/bin/bash
# Argument: The jar file to deploy
APPSRCPATH=$1
# Argument: application name, no spaces please, used as folder name under /var
APPNAME=$2
# Argument: the user to use when running the application, may exist, created if not exists
APPUSER=$3
# Help text
USAGE="
Usage: sudo $0 <jar-file> <app-name> <runtime-user>
If an app with the name <app-name> already exist, it is stopped and deleted.
If the <runtime-user> does not already exist, it is created.
"
# Check that we are root
if [ ! "root" = "$(whoami)" ]; then
echo "Must be root. Please use e.g. sudo"
echo "$USAGE"
exit
fi
# Check arguments
if [ "$#" -ne 3 -o ${#APPSRCPATH} = 0 -o ${#APPNAME} = 0 -o ${#APPUSER} = 0 ]; then
echo "Incorrect number of parameters."
echo "$USAGE"
exit
fi
if [ ! -f $APPSRCPATH ]; then
echo "Can't find jar file $APPSRCPATH"
echo "$USAGE"
exit
fi
# Infered values
APPFILENAME=$(basename $APPSRCPATH)
APPFOLDER=/var/javaapps/$APPNAME
APPDESTPATH=$APPFOLDER/$APPFILENAME
# Stop the service if it already exist and is running
systemctl stop $APPNAME >/dev/null 2>&1
# Create the app folder, deleting any previous content
rm -fr $APPFOLDER
mkdir -p $APPFOLDER
# Create the user if it does not exist
if id "$APPUSER" >/dev/null 2>&1; then
echo "Using existing user $APPUSER"
else
adduser --disabled-password --gecos "" $APPUSER
echo "Created user $APPUSER"
fi
# Place app in app folder, setting owner and rights
cp $APPSRCPATH $APPDESTPATH
chown $APPUSER $APPDESTPATH
chmod 500 $APPDESTPATH
echo "Added or updated the $APPDESTPATH file"
# Create the .service file used by systemd
echo "
[Unit]
Description=$APPNAME
After=syslog.target
[Service]
User=$APPUSER
ExecStart=/usr/bin/java -jar $APPDESTPATH
SuccessExitStatus=143
[Install]
WantedBy=multi-user.target
" > /etc/systemd/system/$APPNAME.service
echo "Created the /etc/systemd/system/$APPNAME.service file"
# Reload the daemon
systemctl daemon-reload
# Start the deployed app
systemctl start $APPNAME
systemctl status $APPNAME
To go one step further, you could declare a type pointer to a function signature like:
interface myCallbackType { (myArgument: string): void }
and use it like this:
public myCallback : myCallbackType;
This question should be on Server Fault. Nevertheless, the following should do the trick, assuming you're talking about TCP and the IP you want to allow is 1.2.3.4:
iptables -A INPUT -p tcp --dport 8000 -s 1.2.3.4 -j ACCEPT
iptables -A INPUT -p tcp --dport 8000 -j DROP
If you're experimenting with Metal rendering & you're extracting the CGImage generated by imageByApplyingAlpha in the first reply, you may end up with a Metal rendering that's larger than you expect. While experimenting with Metal, you may want to change one line of code in imageByApplyingAlpha:
UIGraphicsBeginImageContextWithOptions (self.size, NO, 1.0f);
// UIGraphicsBeginImageContextWithOptions (self.size, NO, 0.0f);
If you're using a device with a scale factor of 3.0, like the iPhone 11 Pro Max, the 0.0 scale factor shown above will give you an CGImage that's three times larger than you're expecting. Changing the scale factor to 1.0 should avoid any scaling.
Hopefully, this reply will save beginners a lot of aggravation.
I've solved this error by this way.
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, 'http://www.someurl/' );
curl_setopt ( $ch, CURLOPT_TIMEOUT, 30);
ob_start();
$response = curl_exec ( $ch );
$data = ob_get_clean();
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200 ) success;
Error still occurs, but I can handle response data in variable.
By default, MomentJS parses in local time. If only a date string (with no time) is provided, the time defaults to midnight.
In your code, you create a local date and then convert it to the UTC timezone (in fact, it makes the moment instance switch to UTC mode), so when it is formatted, it is shifted (depending on your local time) forward or backwards.
If the local timezone is UTC+N (N being a positive number), and you parse a date-only string, you will get the previous date.
Here are some examples to illustrate it (my local time offset is UTC+3 during DST):
>>> moment('07-18-2013', 'MM-DD-YYYY').utc().format("YYYY-MM-DD HH:mm")
"2013-07-17 21:00"
>>> moment('07-18-2013 12:00', 'MM-DD-YYYY HH:mm').utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 09:00"
>>> Date()
"Thu Jul 25 2013 14:28:45 GMT+0300 (Jerusalem Daylight Time)"
If you want the date-time string interpreted as UTC, you should be explicit about it:
>>> moment(new Date('07-18-2013 UTC')).utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"
or, as Matt Johnson mentions in his answer, you can (and probably should) parse it as a UTC date in the first place using moment.utc()
and include the format string as a second argument to prevent ambiguity.
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"
To go the other way around and convert a UTC date to a local date, you can use the local()
method, as follows:
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').local().format("YYYY-MM-DD HH:mm")
"2013-07-18 03:00"
you can use
android.R.drawable.xxx
(use autocomplete to see whats in there)
Or download the stuff from http://developer.android.com/design/downloads/index.html
With JavaScript version 1.6 it's as easy as this:
Array.prototype.equals = function( array ) {
return this.length == array.length &&
this.every( function(this_i,i) { return this_i == array[i] } )
}
For example, [].equals([])
gives true
, while [1,2,3].equals( [1,3,2] )
yields false
.
var
variables still have a type - and the compiler error message says this type must be established during the declaration.
The specific request (assigning an initial null value) can be done, but I don't recommend it. It doesn't provide an advantage here (as the type must still be specified) and it could be viewed as making the code less readable:
var x = (String)null;
Which is still "type inferred" and equivalent to:
String x = null;
The compiler will not accept var x = null
because it doesn't associate the null with any type - not even Object. Using the above approach, var x = (Object)null
would "work" although it is of questionable usefulness.
Generally, when I can't use var
's type inference correctly then
The second approach can be done by moving code into methods or functions.
I'm on Visual Studio 2013 and just updated to the Windows 10 May 2019 update and compiling suddenly had to be redone every time, regardless of changes. Tried renaming the pch to ProjectName instead of TargetName, looked for missing files with the detailed log and that Python script, but in the end it was my time was not synced with MS's servers (by like milliseconds).
What resolved this for me was
Now my projects don't need to be recompiled for no reason.
I prefer this as an extension method:
public static async Task<IEnumerable<T>> WhenAll<T>(this IEnumerable<Task<T>> tasks)
{
return await Task.WhenAll(tasks);
}
So that it is usable with method chaining:
var inputs = await events
.Select(async ev => await ProcessEventAsync(ev))
.WhenAll()
It seems the docs/tool have been updated and you can now add the image
tag to your script. This was successful for me.
Example:
version: '2'
services:
baggins.api.rest:
image: my.image.name:rc2
build:
context: ../..
dockerfile: app/Docker/Dockerfile.release
ports:
...
If you want to use them as in swift 2, you can use these funcs:
For CGRectMake:
func CGRectMake(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -> CGRect {
return CGRect(x: x, y: y, width: width, height: height)
}
For CGPointMake:
func CGPointMake(_ x: CGFloat, _ y: CGFloat) -> CGPoint {
return CGPoint(x: x, y: y)
}
For CGSizeMake:
func CGSizeMake(_ width: CGFloat, _ height: CGFloat) -> CGSize {
return CGSize(width: width, height: height)
}
Just put them outside any class and it should work. (Works for me at least)
Many integrated products (especially by Apple) such as iPods, iPads are a good example of tight coupling: once the battery dies you might as well buy a new device because the battery is soldered fixed and won't come loose, thus making replacing very expensive. A loosely coupled player would allow effortlessly changing the battery.
The same goes for software development: it is generally (much) better to have loosely coupled code to facilitate extension and replacement (and to make individual parts easier to understand). But, very rarely, under special circumstances tight coupling can be advantageous because the tight integration of several modules allows for better optimisation.
HttpCookie cook = new HttpCookie("testcook");
cook = Request.Cookies["CookName"];
if (cook != null)
{
lbl_cookie_value.Text = cook.Value;
}
else
{
lbl_cookie_value.Text = "Empty value";
}
Reference Click here
If you need to perform in Microsoft Windows the equivalent of a symlink to /dev/null
in Linux you would open and administrator's cmd
and type:
For files:
mklink c:\path\to\file.ext NUL:
Or, for directories:
mklink /D c:\path\to\dir NUL:
This will keep the file/direcotry always at 0 byte, and still return success to every write attempt.
here is the sample code to draw image on canvas-
$("#selectedImage").change(function(e) {
var URL = window.URL;
var url = URL.createObjectURL(e.target.files[0]);
img.src = url;
img.onload = function() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, 500, 500);
}});
In the above code selectedImage is an input control which can be used to browse image on system. For more details of sample code to draw image on canvas while maintaining the aspect ratio:
http://newapputil.blogspot.in/2016/09/show-image-on-canvas-html5.html
Use Bash and the date command to convert from an ISO-like format to the one you want. I wanted an org-mode date format (and list item), so I did this:
echo + [$(date -d "$(git log --pretty=format:%ai -1)" +"%Y-%m-%d %a %H:%M")] \
$(git log --pretty=format:"%h %s" --abbrev=12 -1)
And the result is for example:
+ [2015-09-13 Sun 22:44] 2b0ad02e6cec Merge pull request #72 from 3b/bug-1474631
Use the insert method of the combobox to insert the "Please select item" in to 0 index,
comboBox1.Items.Insert(0, "Please select any value");
and add all the items to the combobox after the first index. In the form load set
comboBox1.SelectedIndex = 0;
EDIT:
In form load write the text in to the comboBox1.Text
by hardcoding
comboBox1.Text = "Please, select any value";
and in the TextChanged event of the comboBox1 write the following code
private void comboBox1_TextChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex < 0)
{
comboBox1.Text = "Please, select any value";
}
else
{
comboBox1.Text = comboBox1.SelectedText;
}
}
dbsize()
returns the total number of keys.
You can quickly estimate the number of keys matching a given pattern by sampling keys at random, then checking what fraction of them matches the pattern.
Example in python; counting all keys starting with prefix_
:
import redis
r = redis.StrictRedis(host = 'localhost', port=6379)
iter=1000
print 'Approximately', r.dbsize() * float(sum([r.randomkey().startswith('prefix_') for i in xrange(iter)])) / iter
Even iter=100
gives a decent estimate in my case, yet is very fast, compared to keys prefix_
.
An improvement is to sample 1000 keys on every request, but keep the total count, so that after two requests you'll divide by 2000, after three requests you'll divide by 3000. Thus, if your application is interested in the total number of matching keys fairly often, then every time it will get closer and closer to the true value.
The file .pgpass in a user's home directory or the file referenced by PGPASSFILE can contain passwords to be used if the connection requires a password (and no password has been specified otherwise). On Microsoft Windows the file is named %APPDATA%\postgresql\pgpass.conf (where %APPDATA% refers to the Application Data subdirectory in the user's profile).
This file should contain lines of the following format:
hostname:port:database:username:password
(You can add a reminder comment to the file by copying the line above and preceding it with #.) Each of the first four fields can be a literal value, or *, which matches anything. The password field from the first line that matches the current connection parameters will be used. (Therefore, put more-specific entries first when you are using wildcards.) If an entry needs to contain : or \, escape this character with . A host name of localhost matches both TCP (host name localhost) and Unix domain socket (pghost empty or the default socket directory) connections coming from the local machine. In a standby server, a database name of replication matches streaming replication connections made to the master server. The database field is of limited usefulness because users have the same password for all databases in the same cluster.
On Unix systems, the permissions on .pgpass must disallow any access to world or group; achieve this by the command chmod 0600 ~/.pgpass. If the permissions are less strict than this, the file will be ignored. On Microsoft Windows, it is assumed that the file is stored in a directory that is secure, so no special permissions check is made.
Definitely possible with any number of libraries and/or HTML5 technologies. You could possible hack something together in pure CSS by using something like the border-bottom property, but it would probably be horribly hacky.
If you're serious about this, you should take a look at a JS library for canvas drawing or SVG. For example, something like http://www.graphjs.org/ or http://jsdraw2dx.jsfiction.com/
In the .service file under the [Unit] section:
[Unit]
Description=My Website
After=syslog.target network.target mongodb.service
The important part is the mongodb.service
The manpage describes it however due to formatting it's not as clear on first sight
For ExpressJs router:
router.post('/login', async(req, res) => {
return res.send({redirect: '/yoururl'});
})
Client-side:
success: function (response) {
if (response.redirect) {
window.location = response.redirect
}
},
You just need to put a small timeout event before doing .click()
like this :
setTimeout(function(){ $('#btn').click()}, 100);
Float the #list
and #similar
the right and add clear: right;
to #similar
Like so:
#map { float:left; width:700px; height:500px; }
#list { float:right; width:200px; background:#eee; list-style:none; padding:0; }
#similar { float:right; width:200px; background:#000; clear:right; }
<div id="map"></div>
<ul id="list"></ul>
<div id="similar">this text should be below, not next to ul.</div>
You might need a wrapper(div) around all of them though that's the same width of the left and right element.
The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:
ffmpeg -i input.mov -qscale 0 output.mp4
Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0
):
ffmpeg -i input.mov -q:v 0 output.mp4
Another Apache ObjectUtils example. Able to sort other types of objects.
@Override
public int compare(Object o1, Object o2) {
String s1 = ObjectUtils.toString(o1);
String s2 = ObjectUtils.toString(o2);
return s1.toLowerCase().compareTo(s2.toLowerCase());
}
Following are some things I found in my collection of obscure Ruby.
So, in Ruby, a simple no-bells implementation of the Unix command cat
would be:
#!/usr/bin/env ruby
puts ARGF.read
ARGF
is your friend when it comes to input; it is a virtual file that gets all input from named files or all from STDIN.
ARGF.each_with_index do |line, idx|
print ARGF.filename, ":", idx, ";", line
end
# print all the lines in every file passed via command line that contains login
ARGF.each do |line|
puts line if line =~ /login/
end
Thank goodness we didn’t get the diamond operator in Ruby, but we did get ARGF
as a replacement. Though obscure, it actually turns out to be useful. Consider this program, which prepends copyright headers in-place (thanks to another Perlism, -i
) to every file mentioned on the command-line:
#!/usr/bin/env ruby -i
Header = DATA.read
ARGF.each_line do |e|
puts Header if ARGF.pos - e.length == 0
puts e
end
__END__
#--
# Copyright (C) 2007 Fancypants, Inc.
#++
Credit to:
Create a diagram for existing database schema or its subset as follows:
The ERD is displayed.
Export the diagram as follows:
The diagram is exported. To export in a vector format, use To PDF File, instead. This allows for simplified editing using Inkscape (or other vector image editor).
These instructions may work for SQL Developer 3.2.09.23 to 4.1.3.20.
One possible simplification would be to subclass AuthorizeAttribute
:
public class RolesAttribute : AuthorizeAttribute
{
public RolesAttribute(params string[] roles)
{
Roles = String.Join(",", roles);
}
}
Usage:
[Roles("members", "admin")]
Semantically it is the same as Jim Schmehil's answer.
For SMTP hosts and Gmail I like to use Swaks -> https://easyengine.io/tutorials/mail/swaks-smtp-test-tool/
On a Mac:
brew install swaks
swaks --to [email protected] --server smtp.example.com
I'm using ReactJs and used import 'core-js/es6/string';
at the start of index.js
to solve my problem.
I'm also using import 'react-app-polyfill/ie11';
to support running React in IE11.
react-app-polyfill
This package includes polyfills for various browsers. It includes minimum requirements and commonly used language features used by Create React App projects.
https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md
TLDR - In addition to the previous responses. There might be a problem with the version of the fastboot
command. Try to download the newest one via Android SDK Manager instead of default one available in the OS repository.
There is one more thing you can do to fix this issue. I had the similar problem when trying to flash Nexus Player. All the adb commands we working fine while in normal boot mode. However, after switching to fastboot mode I wasn't able to execute fastboot commands. My device was not visible in the output of the fastboot devices
command. I've set the right rules in /etc/udev/rules.d/11-android.rules file. The lsusb
command showed that the device has been pluged in.
The soultion was quite simple. I've downloaded the the fastboot
via Android Studio's SDK Manager instead of using the default one available in Ubuntu packages.
All you need is sdkmanager. Download the Android SDK Platform Tools and replace the default /usr/bin/fastboot with the new one.
Fusion charts has a new javascript/jquery library that looks promising.
You can also use info files
to list all the sections of all the binaries loaded in process binary.
1) Are you sure mod_rewrite module is enabled? Check phpinfo()
2) Your above rule assumes the URL starts with "folder". Is this correct? Did you acutally want to have folder in the URL? This would match a URL like:
/folder/thing -> /folder/thing.php
If you actually want
/thing -> /folder/thing.php
You need to drop the folder from the match expression.
I usually use this to route request to page without php (but yours should work which leads me to think that mod_rewrite may not be enabled):
RewriteRule ^([^/\.]+)/?$ $1.php [L,QSA]
3) Assuming you are declaring your rules in an .htaccess file, does your installation allow for setting Options (AllowOverride) overrides in .htaccess files? Some shared hosts do not.
When the server finds an .htaccess file (as specified by AccessFileName) it needs to know which directives declared in that file can override earlier access information.
If you include the library System.Data.Entity
you can use an overload of the Include()
method which takes a lambda expression instead of a string. You can then Select()
over children with Linq expressions rather than string
paths.
return DatabaseContext.Applications
.Include(a => a.Children.Select(c => c.ChildRelationshipType));
As setup in the terminal using vi
:
The Home
button on a Macbook Pro keyboard: Fn + Left Arrow
.
The End
button on a Macbook Pro keyboard: Fn + Right Arrow
.
pd.date_range('2019-01-01', '2019-02-01').shape[0]
You can null/blank/space Etc value using LinQ Use Following Query
var BlankValueRows = (from dr1 in Dt.AsEnumerable()
where dr1["Columnname"].ToString() == ""
|| dr1["Columnname"].ToString() == ""
|| dr1["Columnname"].ToString() == ""
select Columnname);
Here Replace Columnname with table column name and "" your search item in above code we looking null value.
I found a solution to solve this problem in Python.
go to c:\python27\ directory and rigtlcick python.exe and tab to compaitbility and select the admin privilege option and apply the changes. Now you issue the command it allows to create the socket connection.
I have build a small demo project on this you could have a look to it Link to project
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;
public class ImplementationOfStackUsingTwoQueue {
private static Deque<Integer> inboxQueue = new LinkedList<>();
private static Queue<Integer> outboxQueue = new LinkedList<>();
public void pushInStack(Integer val){
inboxQueue.add(val);
}
public void popFromStack(){
if(outboxQueue.isEmpty()){
while(!inboxQueue.isEmpty()){
outboxQueue.add(inboxQueue.pollLast());
}
}
}
public static void main(String[] args) {
ImplementationOfStackUsingTwoQueue obj = new ImplementationOfStackUsingTwoQueue();
obj.pushInStack(1);
obj.pushInStack(2);
obj.pushInStack(3);
obj.pushInStack(4);
obj.pushInStack(5);
System.out.println("After pushing the values in Queue" + inboxQueue);
obj.popFromStack();
System.out.println("After popping the values from Queue" + outboxQueue);
}
}
Using PNG is not such a good idea. Actually it's costly as far as performance is concerned. You can use drawable XML files, for example, Facebook's background.
This will help you to smooth and speed up your performance, and for the logo use .9 patch images.
Try this, it’ll sort the list in-place in descending order (there’s no need to specify a key in this case):
Process
listB = [24, 13, -15, -36, 8, 22, 48, 25, 46, -9]
listC = sorted(listB, reverse=True) # listB remains untouched
print listC
output:
[48, 46, 25, 24, 22, 13, 8, -9, -15, -36]
Use the std::getline()
from <string>
.
istream & getline(istream & is,std::string& str)
So, for your case it would be:
std::getline(read,x);
Current css version still doesn't support selector find by content. But there is a way, by using css selector find by attribute, but you have to put some identifier on all of the <td>
that have $
inside. Example:
using nth-child in tables tr td
html
<tr>
<td> </td>
<td data-rel='$'>$</td>
<td> </td>
</tr>
css
table tr td[data-rel='$'] {
background-color: #333;
color: white;
}
Please try these example.
table tr td[data-content='$'] {_x000D_
background-color: #333;_x000D_
color: white;_x000D_
}
_x000D_
<table border="1">_x000D_
<tr>_x000D_
<td>A</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>B</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>C</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>D</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Date functions are available natively, such as:
<xsl:value-of select="current-dateTime()"/>
There is also current-date()
and current-time()
.
Use the EXSLT date and times extension package.
date.xsl
to the location of your XSL files.date.xsl
.For example:
<xsl:stylesheet version="1.0"
xmlns:date="http://exslt.org/dates-and-times"
extension-element-prefixes="date"
...>
<xsl:import href="date.xsl" />
<xsl:template match="//root">
<xsl:value-of select="date:date-time()"/>
</xsl:template>
</xsl:stylesheet>
Use putty. Put install directory path in environment values (PATH), and restart your PC if required.
Open cmd (command prompt) and type
C:/> pscp "C:\Users/gsjha/Desktop/example.txt" user@host:/home/
It'll be copied to the system.
IN this answer when i say a file i mean the location in memory
All the data that is saved is stored in memory using a data structure called inodes Every inode has a inodenumber.The inode number is used to access the inode.All the hard links to a file may have different names but share the same inode number.Since all the hard links have the same inodenumber(which inturn access the same inode),all of them point to the same physical memory.
A symbolic link is a special kind of file.Since it is also a file it will have a file name and an inode number.As said above the inode number acceses an inode which points to data.Now what makes a symbolic link special is that the inodenumbers in symbolic links access those inodes which point to "a path" to another file.More specifically the inode number in symbolic link acceses those inodes who point to another hard link.
when we are moving,copying,deleting a file in GUI we are playing with the hardlinks of the file not the physical memory.when we delete a file we are deleting the hardlink of the file. we are not wiping out the physical memory.If all the hardlinks to file are deleted then it will not be possible to access the data stored although it may still be present in memory
Yes, that's possible, albeit not literally the <td>
, but what's in it. The simple trick is, to make sure that the content extends to the borders of the cell (it won't include the borders itself though).
As already explained, this isn't semantically correct. An a
element is an inline element and should not be used as block-level element. However, here's an example (but JavaScript plus a td:hover CSS style will be much neater) that works in most browsers:
<td>
<a href="http://example.com">
<div style="height:100%;width:100%">
hello world
</div>
</a>
</td>
PS: it's actually neater to change a
in a block-level element using CSS as explained in another solution in this thread. it won't work well in IE6 though, but that's no news ;)
If your world is only Internet Explorer (rare, nowadays), you can violate the HTML standard and write this, it will work as expected, but will be highly frowned upon and be considered ill-advised (you haven't heard this from me). Any other browser than IE will not render the link, but will show the table correctly.
<table>
<tr>
<a href="http://example.com"><td width="200">hello world</td></a>
</tr>
</table>
When you use a function ...
<p onclick="update_url('/en/step2');">Link</p>
<script>
function update_url(url) {
history.pushState(null, null, url);
}
</script>
There are more than a few gateways out there, but I am not aware of a reliable gateway that is free. Most gateways like PayPal will provide you APIs that will allow you to process credit cards, as well as do things like void, charge, or refund.
The other thing you need to worry about is the coming of PCI compliance which basically says if you are not compliant, you (or the company you work for) will be liable by your Merchant Bank and/or Card Vendor for not being compliant by July of 2010. This will impose large fines on you and possibly revoke the ability for you to process credit cards.
All that being said companies like PayPal have a PHP SDK:
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/library_download_sdks
Authorize.Net:
http://developer.authorize.net/samplecode/
Those are two of the more popular ones for the United States.
For PCI Info see:
I have done the same issue using following code:
@using (Html.BeginForm("Delete", "Admin"))
{
@Html.Hidden("ProductID", item.ProductID)
<input type="submit" value="Delete" />
}
if (!a) {
// is emtpy
}
To ignore white space for strings:
if (!a.trim()) {
// is empty or whitespace
}
If you need legacy support (IE8-) for trim()
, use $.trim
or a polyfill.
The execmgr.log
will show the commandline and ccmcache folder used for installation. Typically, required apps don't show on appenforce.log
and some clients will have outdated appenforce
or no ppenforce.log
files.
execmgr.log
also shows required hidden uninstall actions as well.
You may want to save the blog link. I still reference it from time to time.
Another thing that people may find useful...make sure to leave off ".py" from your module name. For example, if you are trying to generate documentation for 'original' in 'original.py':
yourcode_dir$ pydoc -w original.py no Python documentation found for 'original.py' yourcode_dir$ pydoc -w original wrote original.html
Use IGNORE_DUP_KEY = OFF
during primary key definition to ignore the duplicates while insert.
for example
create table X( col1.....)
CONSTRAINT [pk_X] PRIMARY KEY CLUSTERED
(
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 70) ON [PRIMARY]
) ON [PRIMARY]
There will be an option in configure under Build Triggers
Check the GitHub Branches
A hook will be created and then you can build any branch you like from Jenkins when you select github Branches
Hope it helps :)
I figured out the method I have written below, and it works perfectly for me
in eclipse, follow these simple steps: File -> Import -> type svn -> project from svn -> next -> Create a new repository location -> Next - > You would see "Secure Storage" below the Authentication Menu. Click on this button "Secure Storage" . This is the place where we can delete all the password caches. Now once you are here, follow these:
All the stored passwords are now gone, and you can use your new svn password to sync
To add to what joshb has stated already - this works just fine for me. Make sure to add references to Microsoft.Expression.Interactions.dll and System.Windows.Interactivity.dll and in your xaml do:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
I ended up using something like this for my needs. This shows that you can also pass a custom parameter:
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding Path=DataContext.RowSelectedItem, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
CommandParameter="{Binding Path=SelectedItem, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}}" />
</i:EventTrigger>
</i:Interaction.Triggers>
You can draw multiple straight lines on view using Finger paint example which is in Developer android. example link
Just comment: mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
You will be able to draw straight lines.
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
public class JoinPointsActivity extends Activity {
/** Called when the activity is first created. */
Paint mPaint;
float Mx1,My1;
float x,y;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
MyView view1 =new MyView(this);
view1.setBackgroundResource(R.drawable.image_0031_layer_1);
setContentView(view1);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(0xFFFF0000);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
// mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(10);
}
public class MyView extends View {
private static final float MINP = 0.25f;
private static final float MAXP = 0.75f;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
public MyView(Context c) {
super(c);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(0xFFAAAAAA);
// canvas.drawLine(mX, mY, Mx1, My1, mPaint);
// canvas.drawLine(mX, mY, x, y, mPaint);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private void touch_start(float x, float y) {
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
// mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
mX = x;
mY = y;
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
// commit the path to our offscreen
mCanvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
mPath.reset();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
// Mx1=(int) event.getX();
// My1= (int) event.getY();
invalidate();
break;
}
return true;
}
}
}
In C++ the stack memory is where local variables get stored/constructed. The stack is also used to hold parameters passed to functions.
The stack is very much like the std::stack class: you push parameters onto it and then call a function. The function then knows that the parameters it expects can be found on the end of the stack. Likewise, the function can push locals onto the stack and pop them off it before returning from the function. (caveat - compiler optimizations and calling conventions all mean things aren't this simple)
The stack is really best understood from a low level and I'd recommend Art of Assembly - Passing Parameters on the Stack. Rarely, if ever, would you consider any sort of manual stack manipulation from C++.
Generally speaking, the stack is preferred as it is usually in the CPU cache, so operations involving objects stored on it tend to be faster. However the stack is a limited resource, and shouldn't be used for anything large. Running out of stack memory is called a Stack buffer overflow. It's a serious thing to encounter, but you really shouldn't come across one unless you have a crazy recursive function or something similar.
Heap memory is much as rskar says. In general, C++ objects allocated with new, or blocks of memory allocated with the likes of malloc end up on the heap. Heap memory almost always must be manually freed, though you should really use a smart pointer class or similar to avoid needing to remember to do so. Running out of heap memory can (will?) result in a std::bad_alloc.
Continuing this answer, There is another difference that if you want your method to return different values for example when it is first time called, second time called etc then you can pass values so for example...
PowerMockito.doReturn(false, false, true).when(SomeClass.class, "SomeMethod", Matchers.any(SomeClass.class));
So it will return false when the method is called in same test case and then it will return false again and lastly true.
Note that the "if ($str)"
and "IsNullOrEmpty"
tests don't work comparably in all instances: an assignment of $str=0
produces false for both, and depending on intended program semantics, this could yield a surprise.
Might be it will help someone, 4 level and 2 child's on each level
Library.Include(a => a.Library.Select(b => b.Library.Select(c => c.Library)))
.Include(d=>d.Book.)
.Include(g => g.Library.Select(h=>g.Book))
.Include(j => j.Library.Select(k => k.Library.Select(l=>l.Book)))
For Single valued associations, i.e.-One-to-One and Many-to-One:-
Default Lazy=proxy
Proxy lazy loading:- This implies a proxy object of your associated entity is loaded. This means that only the id connecting the two entities is loaded for the proxy object of associated entity.
Eg: A and B are two entities with Many to one association. ie: There may be multiple A's for every B. Every object of A will contain a reference of B.
`
public class A{
int aid;
//some other A parameters;
B b;
}
public class B{
int bid;
//some other B parameters;
}
`
The relation A will contain columns(aid,bid,...other columns of entity A).
The relation B will contain columns(bid,...other columns of entity B)
Proxy implies when A is fetched, only id is fetched for B and stored into a proxy object of B which contains only id.
Proxy object of B is a an object of a proxy-class which is a subclass of B with only minimal fields.
Since bid is already part of relation A, it is not necessary to fire a query to get bid from the relation B.
Other attributes of entity B are lazily loaded only when a field other than bid is accessed.
For Collections, i.e.-Many-to-Many and One-to-Many:-
Default Lazy=true
Please also note that the fetch strategy(select,join etc) can override lazy.
ie: If lazy='true' and fetch='join', fetching of A will also fetch B or Bs(In case of collections). You can get the reason if you think about it.
Default fetch for single valued association is "join".
Default fetch for collections is "select".
Please verify the last two lines. I have deduced that logically.
You can also drop the column and its constraint(s) in a single statement rather than individually.
CREATE TABLE #T
(
Col1 INT CONSTRAINT UQ UNIQUE CONSTRAINT CK CHECK (Col1 > 5),
Col2 INT
)
ALTER TABLE #T DROP CONSTRAINT UQ ,
CONSTRAINT CK,
COLUMN Col1
DROP TABLE #T
(but not other possible column dependencies such as foreign keys, unique and primary key constraints, computed columns, indexes)
CREATE TABLE [dbo].[TestTable]
(
A INT DEFAULT '1' CHECK (A=1),
B INT,
CHECK (A > B)
)
GO
DECLARE @TwoPartTableNameQuoted nvarchar(500) = '[dbo].[TestTable]',
@ColumnNameUnQuoted sysname = 'A',
@DynSQL NVARCHAR(MAX);
SELECT @DynSQL =
'ALTER TABLE ' + @TwoPartTableNameQuoted + ' DROP' +
ISNULL(' CONSTRAINT ' + QUOTENAME(OBJECT_NAME(c.default_object_id)) + ',','') +
ISNULL(check_constraints,'') +
' COLUMN ' + QUOTENAME(@ColumnNameUnQuoted)
FROM sys.columns c
CROSS APPLY (SELECT ' CONSTRAINT ' + QUOTENAME(OBJECT_NAME(referencing_id)) + ','
FROM sys.sql_expression_dependencies
WHERE referenced_id = c.object_id
AND referenced_minor_id = c.column_id
AND OBJECTPROPERTYEX(referencing_id, 'BaseType') = 'C'
FOR XML PATH('')) ck(check_constraints)
WHERE c.object_id = object_id(@TwoPartTableNameQuoted)
AND c.name = @ColumnNameUnQuoted;
PRINT @DynSQL;
EXEC (@DynSQL);
I don't think there is any difference, one is a shortcut for the other. Although your exact implementation might deal with them differently.
The combined parallel worksharing constructs are a shortcut for specifying a parallel construct containing one worksharing construct and no other statements. Permitted clauses are the union of the clauses allowed for the parallel and worksharing contructs.
Taken from http://www.openmp.org/mp-documents/OpenMP3.0-SummarySpec.pdf
The specs for OpenMP are here:
A separator can be a bad idea for some languages like Hebrew or Japanese. Try this:
// Array of Strings
let array: [String] = ["red", "green", "blue"]
let arrayAsString: String = array.description
let stringAsData = arrayAsString.data(using: String.Encoding.utf16)
let arrayBack: [String] = try! JSONDecoder().decode([String].self, from: stringAsData!)
For other data types respectively:
// Set of Doubles
let set: Set<Double> = [1, 2.0, 3]
let setAsString: String = set.description
let setStringAsData = setAsString.data(using: String.Encoding.utf16)
let setBack: Set<Double> = try! JSONDecoder().decode(Set<Double>.self, from: setStringAsData!)
ES6 modules support in Node.js is fairly recent; even in the bleeding-edge versions, it is still experimental. With Node.js 10, you can start Node.js with the --experimental-modules
flag, and it will likely work.
To import on older Node.js versions - or standard Node.js 10 - use CommonJS syntax:
const fs = require('fs');
Find existing sessions to DB using this query:
SELECT s.inst_id,
s.sid,
s.serial#,
p.spid,
s.username,
s.program
FROM gv$session s
JOIN gv$process p ON p.addr = s.paddr AND p.inst_id = s.inst_id
WHERE s.type != 'BACKGROUND';
you'll see something like below.
Then, run below query with values extracted from above results.
ALTER SYSTEM KILL SESSION '<put above s.sid here>,<put above s.serial# here>';
Ex: ALTER SYSTEM KILL SESSION '93,943';
Verify user account, you are working on. If any system user has no permissions for installation packages, npm particulary also is showing this message.
Surely typing /usr/sbin/apache2 -v into the shell is the best and quickest way to go, by the way here's another option, just in case there's PHP too in your server and you're interested into gathering Apache version (and much more infos) in quick programmatical steps.
Just make an info.php file in your Apache web root folder (or whatever you like) and write these inside it:
<?php
phpinfo();
?>
Now go to yoursite.com/info.php (or localhost/info.php for local machines).
You'll see your Apache version in PHP Variables section, here's an example:
Also, please notice that these steps obviously apply to any web server with PHP integration, so it's not limited to Apache and once created that page could be handy while developing (just don't forget to remove it on production environments!!)
if you want infos from the actual running batchfile, try this :
@echo off
set myNameFull=%0
echo myNameFull %myNameFull%
set myNameShort=%~n0
echo myNameShort %myNameShort%
set myNameLong=%~nx0
echo myNameLong %myNameLong%
set myPath=%~dp0
echo myPath %myPath%
set myLogfileWpath=%myPath%%myNameShort%.log
echo myLogfileWpath %myLogfileWpath%
more samples? C:> HELP CALL
%0 = parameter 0 = batchfile %1 = parameter 1 - 1st par. passed to batchfile... so you can try that stuff (e.g. "~dp") between 1st (e.g. "%") and last (e.g. "1") also for parameters
Here is some code which extends Object with rad(deg)
, deg(rad)
and also two more useful functions: getAngle(point1,point2)
and getDistance(point1,point2)
where a point needs to have a x
and y
property.
Object.prototype.rad = (deg) => Math.PI/180 * deg;
Object.prototype.deg = (rad) => 180/Math.PI * rad;
Object.prototype.getAngle = (point1, point2) => Math.atan2(point1.y - point2.y, point1.x - point2.x);
Object.prototype.getDistance = (point1, point2) => Math.sqrt(Math.pow(point1.x-point2.x, 2) + Math.pow(point1.y-point2.y, 2));
Best description is on: http://inthecheesefactory.com/blog/things-you-need-to-know-about-android-m-permission-developer-edition/en
For simple use permissions you can use this lib: http://hotchemi.github.io/PermissionsDispatcher/
For example your directory is like this:
Desktop >
ProjectFolder >
index.html
css >
style.css
images >
img.png
You are at your style.css and you want to use img.png as a background-image, use this:
url("../images/img.png")
Works for me!
For my case handling UIDeviceOrientationDidChangeNotification
was not good solution as it is called more frequent and UIDeviceOrientation
is not always equal to UIInterfaceOrientation
because of (FaceDown, FaceUp).
I handle it using UIApplicationDidChangeStatusBarOrientationNotification
:
//To add the notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChangeOrientation:)
//to remove the
[[NSNotificationCenter defaultCenter]removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
...
- (void)didChangeOrientation:(NSNotification *)notification
{
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (UIInterfaceOrientationIsLandscape(orientation)) {
NSLog(@"Landscape");
}
else {
NSLog(@"Portrait");
}
}
double amount = 25.00;
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(amount));
How the value attributes gets its value:
So in your case it should be:
obj = { '1': '1st', '2': '2nd' };
<select ng-options="k as v for (k,v) in obj"></select>
Expanding Rentering.com's answer, in scenarios where a whole graph of many types is to be taken care of, and you're looking for a strongly typed solution, this class can help, see usage (fluent) below. It operates as either a black-list or white-list per type. A type cannot be both (Gist - also contains global ignore list).
public class PropertyFilterResolver : DefaultContractResolver
{
const string _Err = "A type can be either in the include list or the ignore list.";
Dictionary<Type, IEnumerable<string>> _IgnorePropertiesMap = new Dictionary<Type, IEnumerable<string>>();
Dictionary<Type, IEnumerable<string>> _IncludePropertiesMap = new Dictionary<Type, IEnumerable<string>>();
public PropertyFilterResolver SetIgnoredProperties<T>(params Expression<Func<T, object>>[] propertyAccessors)
{
if (propertyAccessors == null) return this;
if (_IncludePropertiesMap.ContainsKey(typeof(T))) throw new ArgumentException(_Err);
var properties = propertyAccessors.Select(GetPropertyName);
_IgnorePropertiesMap[typeof(T)] = properties.ToArray();
return this;
}
public PropertyFilterResolver SetIncludedProperties<T>(params Expression<Func<T, object>>[] propertyAccessors)
{
if (propertyAccessors == null)
return this;
if (_IgnorePropertiesMap.ContainsKey(typeof(T))) throw new ArgumentException(_Err);
var properties = propertyAccessors.Select(GetPropertyName);
_IncludePropertiesMap[typeof(T)] = properties.ToArray();
return this;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var properties = base.CreateProperties(type, memberSerialization);
var isIgnoreList = _IgnorePropertiesMap.TryGetValue(type, out IEnumerable<string> map);
if (!isIgnoreList && !_IncludePropertiesMap.TryGetValue(type, out map))
return properties;
Func<JsonProperty, bool> predicate = jp => map.Contains(jp.PropertyName) == !isIgnoreList;
return properties.Where(predicate).ToArray();
}
string GetPropertyName<TSource, TProperty>(
Expression<Func<TSource, TProperty>> propertyLambda)
{
if (!(propertyLambda.Body is MemberExpression member))
throw new ArgumentException($"Expression '{propertyLambda}' refers to a method, not a property.");
if (!(member.Member is PropertyInfo propInfo))
throw new ArgumentException($"Expression '{propertyLambda}' refers to a field, not a property.");
var type = typeof(TSource);
if (!type.GetTypeInfo().IsAssignableFrom(propInfo.DeclaringType.GetTypeInfo()))
throw new ArgumentException($"Expresion '{propertyLambda}' refers to a property that is not from type '{type}'.");
return propInfo.Name;
}
}
Usage:
var resolver = new PropertyFilterResolver()
.SetIncludedProperties<User>(
u => u.Id,
u => u.UnitId)
.SetIgnoredProperties<Person>(
r => r.Responders)
.SetIncludedProperties<Blog>(
b => b.Id)
.Ignore(nameof(IChangeTracking.IsChanged)); //see gist
Section 3 of RFC4122 provides the formal definition of UUID string representations. It's 36 characters (32 hex digits + 4 dashes).
Sounds like you need to figure out where the invalid 60-char IDs are coming from and decide 1) if you want to accept them, and 2) what the max length of those IDs might be based on whatever API is used to generate them.
Update to the answer
// Get stack trace for the exception with source file information
var st = new StackTrace(ex, true);
// Get the top stack frame
var frame = st.GetFrame(st.FrameCount-1);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
The following worked for me:
var form_enabled = true;
$().ready(function(){
// allow the user to submit the form only once each time the page loads
$('#form_id').on('submit', function(){
if (form_enabled) {
form_enabled = false;
return true;
}
return false;
});
});
This cancels the submit event if the user tries to submit the form multiple times (by clicking a submit button, pressing Enter, etc.)
After a lot of search and tests i found the solution : if you are in windows :
1 - first you must found the PG databases directory execute the command as sql command in pgAdmin query tools
$ show data_directory;
result :
------------------------ - D:/PG_DATA/data - ------------------------
2 - go to the bin directory of postgres in my case it's located "c:/programms/postgresSql/bin"
and open a command prompt (CMD) and execute this command :
pg_ctl -D "D:\PSG_SQL\data" restart
This should do it.
If you are using PostgreSQL, this is the right way to get it. This is just an assumption where as you have a book table TITLE and PRICE column with populated data. Here's the query
SELECT xpath('/bookstore/book/title/@lang', xmlforest(book.title AS title, book.price AS price), ARRAY[ARRAY[]::TEXT[]]) FROM book LIMIT 1;
There are multiple problems here
Ex
$(document).ready(function(){
$("#addCF").click(function(){
$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> <a href="javascript:void(0);" id="remCF">Remove</a></td></tr>');
});
$("#customFields").on('click', '#remCF', function(){
$(this).parent().parent().remove();
});
});
Demo: Fiddle
See this demo where id properties are removed.
$(document).ready(function(){
$("#addCF").click(function(){
$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" name="customFieldName[]" value="" placeholder="Input Name" /> <input type="text" class="code" name="customFieldValue[]" value="" placeholder="Input Value" /> <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');
});
$("#customFields").on('click', '.remCF', function(){
$(this).parent().parent().remove();
});
});
You can use Series.isin
:
df = df[~df.datecolumn.isin(a)]
While the error message suggests that all()
or any()
can be used, they are useful only when you want to reduce the result into a single Boolean value. That is however not what you are trying to do now, which is to test the membership of every values in the Series against the external list, and keep the results intact (i.e., a Boolean Series which will then be used to slice the original DataFrame).
You can read more about this in the Gotchas.
It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.
Edit: This is what the forums say:
By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.
To disable:
/system/bin/bugmailer.sh must be deleted/renamed.
There should be a folder on your SD card called "bug reports".
Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948
And this one: http://forum.xda-developers.com/showthread.php?t=1405639
There are some good solutions above, and mine is just a combination of two (I came here looking for a solution).
@Sarvar Nishonboyev's solution is good because it maintains the creation of the form input label and help-block for error messages.
I went with:
<?php
use yii\helpers\ArrayHelper;
use app\models\Product;
?>
<?=
$form->field($model, 'parent_id')
->dropDownList(
ArrayHelper::map(Product::find()->asArray()->all(), 'parent_id', 'name')
)
?>
Again, full credit to: @Sarvar Nishonboyev's and @ippi
Use a reverse dict.
fun_dict = {'fun1': fun1,
'fun2': fun2,
'fun3': fun3}
r_dict = dict(zip(fun_dict.values(), fun_dict.keys()))
The reverse dict will map each function reference to the exact name you gave it in fun_dict, which may or may not be the name you used when you defined the function. And, this technique generalizes to other objects, including integers.
For extra fun and insanity, you can store the forward and reverse values in the same dict. I wouldn't do that if you were mapping strings to strings, but if you are doing something like function references and strings, it's not too crazy.
how about simply:
import os
os.system('dir c:\\')
You can use the stringr
library:
library('stringr')
a <- runif(10)
b <- letters[1:10]
c <- c(rep('A-B', 4), rep('A_B', 6))
data <- data.frame(a, b, c)
data
# a b c
# 1 0.19426707 a A-B
# 2 0.12902673 b A-B
# 3 0.78324955 c A-B
# 4 0.06469028 d A-B
# 5 0.34752264 e A_C
# 6 0.55313288 f A_C
# 7 0.31264280 g A_C
# 8 0.33759921 h A_C
# 9 0.72322599 i A_C
# 10 0.25223075 j A_C
data$c <- str_replace_all(data$c, '_', '-')
data
# a b c
# 1 0.19426707 a A-B
# 2 0.12902673 b A-B
# 3 0.78324955 c A-B
# 4 0.06469028 d A-B
# 5 0.34752264 e A-C
# 6 0.55313288 f A-C
# 7 0.31264280 g A-C
# 8 0.33759921 h A-C
# 9 0.72322599 i A-C
# 10 0.25223075 j A-C
Note that this does change factored variables into character.
Jonathan is correct. PHP arrays act as a map table mapping keys to values. in some cases you can get an index if your array is defined, such as
$var = array(2,5);
for ($i = 0; $i < count($var); $i++) {
echo $var[$i]."\n";
}
your output will be
2
5
in which case each element in the array has a knowable index, but if you then do something like the following
$var = array_push($var,10);
for ($i = 0; $i < count($var); $i++) {
echo $var[$i]."\n";
}
you get no output. This happens because arrays in PHP are not linear structures like they are in most languages. They are more like hash tables that may or may not have keys for all stored values. Hence foreach doesn't use indexes to crawl over them because they only have an index if the array is defined. If you need to have an index, make sure your arrays are fully defined before crawling over them, and use a for loop.
As others have mentioned, try stopPropagation()
.
And there is a second handler to try: event.cancelBubble = true;
It's a IE specific handler, but it is supported in at least FF. Don't really know much about it, as I haven't used it myself, but it might be worth a shot, if all else fails.
aiohttp can be used with HTTP proxy already:
import asyncio
import aiohttp
@asyncio.coroutine
def do_request():
proxy_url = 'http://localhost:8118' # your proxy address
response = yield from aiohttp.request(
'GET', 'http://google.com',
proxy=proxy_url,
)
return response
loop = asyncio.get_event_loop()
loop.run_until_complete(do_request())
import re
abc = "askhnl#$%askdjalsdk"
ddd = abc.replace("#$%","")
print (ddd)
and you shall see your result as
'askhnlaskdjalsdk
You can do this with css transforms, though be careful with container height/width. Also you may need to position it lower:
input[type="range"] {_x000D_
position: absolute;_x000D_
top: 40%;_x000D_
transform: rotate(270deg);_x000D_
}
_x000D_
<input type="range"/>
_x000D_
or the 3d transform equivalent:
input[type="range"] {
transform: rotateZ(270deg);
}
You can also use this to switch the direction of the slide by setting it to 180deg or 90deg for horizontal or vertical respectively.
Simplest way for me:
from urlextract import URLExtract
from requests import get
url = "sample.com/samplepage/"
req = requests.get(url)
text = req.text
# or if you already have the html source:
# text = "This is html for ex <a href='http://google.com/'>Google</a> <a href='http://yahoo.com/'>Yahoo</a>"
text = text.replace(' ', '').replace('=','')
extractor = URLExtract()
print(extractor.find_urls(text))
output:
['http://google.com/', 'http://yahoo.com/']
grep -nr search_string search_dir
will do a RECURSIVE (meaning the directory and all it's sub-directories) search for the search_string. (as correctly answered by usta).
The reason you were not getting any anwers with your friend's suggestion of:
grep -nr string
is because no directory was specified. If you are in the directory that you want to do the search in, you have to do the following:
grep -nr string .
It is important to include the '.' character, as this tells grep to search THIS directory.
It's just the wrong order
var e = $('<div style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
$('#box').append(e);
e.attr('id', 'myid');
Append first and then access/set attr.
Well, std::string
is a class, const char *
is a pointer. Those are two different things. It's easy to get from string
to a pointer (since it typically contains one that it can just return), but for the other way, you need to create an object of type std::string
.
My recommendation: Functions that take constant strings and don't modify them should always take const char *
as an argument. That way, they will always work - with string literals as well as with std::string
(via an implicit c_str()
).
To make this work on Ubuntu Linux:
I installed the Ubuntu package ruby-json:
apt-get install ruby-json
I wrote the script in ${HOME}/rubybin/jsonDEMO
$HOME/.bashrc
included:
${HOME}/rubybin:${PATH}
(On this occasion I also typed the above on the bash command line.)
Then it worked when I entered on the command line:
jsonDemo
A link with 1 function defined
<a href="#" onclick="someFunc()">Click me To fire some functions</a>
Firing multiple functions from someFunc()
function someFunc() {
showAlert();
validate();
anotherFunction();
YetAnotherFunction();
}
In addition to the answers here you might want to make sure that the documentation is downloaded. To do that go to SDK Manager
and then the SDK Tools tab and make sure Documentation for Android SDK is installed.
If it isn't check the box and click Apply.
Try this (subquery):
SELECT * FROM terms WHERE id IN
(SELECT term_id FROM terms_relation WHERE taxonomy = "categ")
Or you can try this (JOIN):
SELECT t.* FROM terms AS t
INNER JOIN terms_relation AS tr
ON t.id = tr.term_id AND tr.taxonomy = "categ"
If you want to receive all fields from two tables:
SELECT t.id, t.name, t.slug, tr.description, tr.created_at, tr.updated_at
FROM terms AS t
INNER JOIN terms_relation AS tr
ON t.id = tr.term_id AND tr.taxonomy = "categ"
Logically OLAP functions are calculated after GROUP BY/HAVING, so you can only access columns in GROUP BY or columns with an aggregate function. Following looks strange, but is Standard SQL:
SELECT employee_number,
MAX(MAX(course_completion_date))
OVER (PARTITION BY course_code) AS max_course_date,
MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code
And as Teradata allows re-using an alias this also works:
SELECT employee_number,
MAX(max_date)
OVER (PARTITION BY course_code) AS max_course_date,
MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code
Surround what you want to be bold with:
<span style="font-weight:bold">Your bold text</span>
This would go inside your <td>
tag.
Please try using following way.
@Html.Hidden("hdnFlag",(object) Convert.ToInt32(ViewBag.page_Count))
I had a similar issue, in that I only wanted return elements that were visible in a page object. I found that I'm able to use the css :not
. In the case of this issue, this should do you...
expect($('i.icon-spinner:not(.ng-hide)').isDisplayed()).toBeTruthy();
In the context of a page object, you can get ONLY those elements that are visible in this way as well. Eg. given a page with multiple items, where only some are visible, you can use:
this.visibileIcons = $$('i.icon:not(.ng-hide)');
This will return you all visible i.icon
s
The sessions parameter is derived from the processes parameter and changes accordingly when you change the number of max processes. See the Oracle docs for further info.
To get only the info about the sessions:
select current_utilization, limit_value
from v$resource_limit
where resource_name='sessions';
CURRENT_UTILIZATION LIMIT_VALUE ------------------- ----------- 110 792
Try this to show info about both:
select resource_name, current_utilization, max_utilization, limit_value
from v$resource_limit
where resource_name in ('sessions', 'processes');
RESOURCE_NAME CURRENT_UTILIZATION MAX_UTILIZATION LIMIT_VALUE ------------- ------------------- --------------- ----------- processes 96 309 500 sessions 104 323 792
Chrome Devtool is the best and easiest way for logging and debugging.
A useful explanation to how braces are used (in addition to Filip Ekberg's useful answer, above) can be found in the short paper Parenthesis in Programming Languages.
You can use Configuration to resolve this.
Ex (Startup.cs):
You can pass by DI to the controllers after this implementation.
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var microserviceName = Configuration["microserviceName"];
services.AddSingleton(Configuration);
...
}
For me this problem occurred because I had a some invalid character in my Groovy script. In our case this was an extra blank line after the closing bracket of the script.
I've just managed to setup new TabLayout, so here are the quick steps to do this (????)?*:???
Add dependencies inside your build.gradle file:
dependencies {
compile 'com.android.support:design:23.1.1'
}
Add TabLayout inside your layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"/>
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Setup your Activity like this:
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class TabLayoutActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pull_to_refresh);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
viewPager.setAdapter(new SectionPagerAdapter(getSupportFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
}
public class SectionPagerAdapter extends FragmentPagerAdapter {
public SectionPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FirstTabFragment();
case 1:
default:
return new SecondTabFragment();
}
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "First Tab";
case 1:
default:
return "Second Tab";
}
}
}
}
As others have said, any compiler worth its salt will generate practically identical code. Any difference in performance is negligible - you are micro-optimizing.
The real question is, what is more readable? And that's the for
loop (at least IMHO).
insert into EXCEPTION_CODES (CODE, MESSAGE)
select CODE, MESSAGE from Exception_code_tmp
This is how you can do using Colab on Google Drive
import pandas as pd
import glob
path = r'/content/drive/My Drive/data/actual/comments_only' # use your path
all_files = glob.glob(path + "/*.csv")
li = []
for filename in all_files:
df = pd.read_csv(filename, index_col=None, header=0)
li.append(df)
frame = pd.concat(li, axis=0, ignore_index=True,sort=True)
frame.to_csv('/content/drive/onefile.csv')
Here is a tightened up version of Sniper's post. It presumes well formed base64 string with no carriage returns. This version eliminates a couple of loops, adds the &0xff
fix from Yaroslav, eliminates trailing nulls, plus a bit of code golf.
decodeBase64 = function(s) {
var e={},i,b=0,c,x,l=0,a,r='',w=String.fromCharCode,L=s.length;
var A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
for(i=0;i<64;i++){e[A.charAt(i)]=i;}
for(x=0;x<L;x++){
c=e[s.charAt(x)];b=(b<<6)+c;l+=6;
while(l>=8){((a=(b>>>(l-=8))&0xff)||(x<(L-2)))&&(r+=w(a));}
}
return r;
};
"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."
http://www.sightspecific.com/~mosh/www_faq/multrec.html
For a quick fix to your problem, change your ;
to a comma ,
and eliminate the spaces between email addresses
<a href='mailto:[email protected],[email protected]'>Email Us</a>
First, I see you're using an explicit $.parseJSON()
. If that's because you're manually serializing JSON on the server-side, don't. ASP.NET will automatically JSON-serialize your method's return value and jQuery will automatically deserialize it for you too.
To iterate through the first item in the array you've got there, use code like this:
var firstItem = response.d[0];
for(key in firstItem) {
console.log(key + ':' + firstItem[key]);
}
If there's more than one item (it's hard to tell from that screenshot), then you can loop over response.d
and then use this code inside that outer loop.
Mine application's apk was at this location
C:\Users\haseeb_mir\AndroidStudioProjects\MyTestApp\app\build\outputs\apk\debug
pt_kill
has an option for such. But it is on-demand, not continually monitoring. It does what @Rafa suggested. However see --sentinel
for a hint of how to come close with cron
.