I am trying to obtain a handle on one of the views in the Action Bar
I will assume that you mean something established via android:actionLayout
in your <item>
element of your <menu>
resource.
I have tried calling findViewById(R.id.menu_item)
To retrieve the View
associated with your android:actionLayout
, call findItem()
on the Menu
to retrieve the MenuItem
, then call getActionView()
on the MenuItem
. This can be done any time after you have inflated the menu resource.
To those would prefer to keep it simple, stupid; If you rather get rid of the notices instead of installing a helper or downgrading, simply disable the error in your settings.json
by adding this:
"intelephense.diagnostics.undefinedTypes": false
Remove ng.ps1
from the directory C:\Users\%username%\AppData\Roaming\npm\
then try clearing the npm cache at C:\Users\%username%\AppData\Roaming\npm-cache\
Adding the Local Python Path before the WindowsApps resolved the problem.
According to the release-notes, Java 11 removed the Java EE modules:
java.xml.bind (JAXB) - REMOVED
See JEP 320 for more info.
You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.3</version>
<scope>runtime</scope>
</dependency>
Use latest release of Eclipse Implementation of JAXB 3.0.0:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>3.0.0</version>
<scope>runtime</scope>
</dependency>
Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*
, so update import statements:
javax.xml.bind -> jakarta.xml.bind
I solved the problem by changing the StartupType of the ssh-agent to Manual
via Set-Service ssh-agent -StartupType Manual
.
Then I was able to start the service via Start-Service ssh-agent
or just ssh-agent.exe
.
Go to > Control Panel\User Accounts\Credential Manager
> Manage Windows Credentials
and remove all generic credentials involving Git. This way you're resetting all the credentials; After this, when you clone, you'll be newly and securely asked your username and password instead of Authentication error. Similar logic can be applied for Mac users.
Hope it helps.
The provider is bundled with PowerShell>=6.0.
If all you need is a way to install a package from a file, just grab the .msi installer for the latest version from the github releases page, copy it over to the machine, install it and use it.
Gulp 4.0 has changed the way that tasks should be defined if the task depends on another task to execute. The list parameter has been deprecated.
An example from your gulpfile.js would be:
// Starts a BrowerSync instance
gulp.task('server', ['build'], function(){
browser.init({server: './_site', port: port});
});
Instead of the list parameter they have introduced gulp.series()
and gulp.parallel()
.
This task should be changed to something like this:
// Starts a BrowerSync instance
gulp.task('server', gulp.series('build', function(){
browser.init({server: './_site', port: port});
}));
I'm not an expert in this. You can see a more robust example in the gulp documentation for running tasks in series or these following excellent blog posts by Jhey Thompkins and Stefan Baumgartner
Prefix the variable name with env
:
$env:path
For example, if you want to print the value of environment value "MINISHIFT_USERNAME", then command will be:
$env:MINISHIFT_USERNAME
You can also enumerate all variables via the env
drive:
Get-ChildItem env:
It is a conflict (bug) between Themes inside style.xml file in android versions 7 (Api levels 24,25) & 8 (api levels 26,27), when you have
android:screenOrientation="portrait"
:inside specific activity (that crashes) in AndroidManifest.xml
&
<item name="android:windowIsTranslucent">true</item>
in the theme that applied to that activity inside style.xml
It can be solve by these ways according to your need :
1- Remove on of the above mentioned properties that make conflict
2- Change Activity orientation to one of these values as you need : unspecified
or behind
and so on that can be found here : Google reference for android:screenOrientation
`
3- Set the orientation programmatically in run time
For VSCode Terminal
First open cmd
and install angular-cli
as global
npm install -g @angular/cli
Then update your Environment Variables following this step
win + s
// this will open search box%AppData%\npm
inside PATH
OK
and close.Now you can restart your VSCode
and it will work as it will normally do.
If you want to select the type of console, you can write this in the file "keybinding.json" (this file can be found in the following path "File-> Preferences-> Keyboard Shortcuts") `
//with this you can select what type of console you want
{
"key": "ctrl+shift+t",
"command": "shellLauncher.launch"
},
//and this will help you quickly change console
{
"key": "ctrl+shift+j",
"command": "workbench.action.terminal.focusNext"
},
{
"key": "ctrl+shift+k",
"command": "workbench.action.terminal.focusPrevious"
}`
Following worked for me:
If you get the following error In order to install Windows Azure Active Directory Module for Windows PowerShell, you must have Microsoft Online Services Sign-In Assistant version 7.0 or greater installed on this computer, then install the Microsoft Online Services Sign-In Assistant for IT Professionals BETA: http://www.microsoft.com/en-us/download/details.aspx?id=39267
C:\Windows\System32\WindowsPowerShell\v1.0\Modules\
to the folder
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\
https://stackoverflow.com/a/16018733/5810078.
(But I have actually copied all the possible files from
C:\Windows\System32\WindowsPowerShell\v1.0\
to
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\
(For copying you need to alter the security permissions of that folder))
This, at least for me, will make Visual Studio Code open a new Bash window as an external terminal.
If you want the integrated environment you need to point to the sh.exe
file inside the bin
folder of your Git installation.
So the configuration should say C:\\<my-git-install>\\bin\\sh.exe
.
It works for me...
if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type)
{
$certCallback = @"
using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public class ServerCertificateValidationCallback
{
public static void Ignore()
{
if(ServicePointManager.ServerCertificateValidationCallback ==null)
{
ServicePointManager.ServerCertificateValidationCallback +=
delegate
(
Object obj,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors errors
)
{
return true;
};
}
}
}
"@
Add-Type $certCallback
}
[ServerCertificateValidationCallback]::Ignore()
Invoke-WebRequest -Uri https://apod.nasa.gov/apod/
You should install the latest version of PowerShell, then use this command Install-Module Azure
to install azure module. Because from Powershell 5.0 onwards you , you will be able to use the cmdlet to Install-Module, Save-Module
PS > $psversiontable
Name Value
---- -----
PSVersion 5.1.14393.576
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.14393.576
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
More information about install Azure PowerShell, refer to the link.
This works for me in PowerShell:
docker run --rm -v ${PWD}:/data alpine ls /data
You can simply type Q:
and that should solve your problem.
I think you can use the powershell in administrative mode or command prompt.
Finally, I got the answer.
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.tv1.setText(android_versionnames[position]);
holder.row_linearlayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
row_index=position;
notifyDataSetChanged();
}
});
if(row_index==position){
holder.row_linearlayout.setBackgroundColor(Color.parseColor("#567845"));
holder.tv1.setTextColor(Color.parseColor("#ffffff"));
}
else
{
holder.row_linearlayout.setBackgroundColor(Color.parseColor("#ffffff"));
holder.tv1.setTextColor(Color.parseColor("#000000"));
}
}
here 'row_index' is set as '-1' initially
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView tv1;
LinearLayout row_linearlayout;
RecyclerView rv2;
public ViewHolder(final View itemView) {
super(itemView);
tv1=(TextView)itemView.findViewById(R.id.txtView1);
row_linearlayout=(LinearLayout)itemView.findViewById(R.id.row_linrLayout);
rv2=(RecyclerView)itemView.findViewById(R.id.recyclerView1);
}
}
Another way to solve this is like this:
tensor_shape[0].value
This will return the int value of the Dimension object.
I know is late but you can quickly accomplish that by just typing Ctrl + Shift + p and then type default, it will show an option that says
Terminal: Select Default Shell
, it will then display all the terminals available to you.
You really just need a single struct, and as mentioned in the comments the correct annotations on the field will yield the desired results. JSON is not some extremely variant data format, it is well defined and any piece of json, no matter how complicated and confusing it might be to you can be represented fairly easily and with 100% accuracy both by a schema and in objects in Go and most other OO programming languages. Here's an example;
package main
import (
"fmt"
"encoding/json"
)
type Data struct {
Votes *Votes `json:"votes"`
Count string `json:"count,omitempty"`
}
type Votes struct {
OptionA string `json:"option_A"`
}
func main() {
s := `{ "votes": { "option_A": "3" } }`
data := &Data{
Votes: &Votes{},
}
err := json.Unmarshal([]byte(s), data)
fmt.Println(err)
fmt.Println(data.Votes)
s2, _ := json.Marshal(data)
fmt.Println(string(s2))
data.Count = "2"
s3, _ := json.Marshal(data)
fmt.Println(string(s3))
}
https://play.golang.org/p/ScuxESTW5i
Based on your most recent comment you could address that by using an interface{}
to represent data besides the count, making the count a string and having the rest of the blob shoved into the interface{}
which will accept essentially anything. That being said, Go is a statically typed language with a fairly strict type system and to reiterate, your comments stating 'it can be anything' are not true. JSON cannot be anything. For any piece of JSON there is schema and a single schema can define many many variations of JSON. I advise you take the time to understand the structure of your data rather than hacking something together under the notion that it cannot be defined when it absolutely can and is probably quite easy for someone who knows what they're doing.
For more performance: A simple change is observing that after n = 3n+1, n will be even, so you can divide by 2 immediately. And n won't be 1, so you don't need to test for it. So you could save a few if statements and write:
while (n % 2 == 0) n /= 2;
if (n > 1) for (;;) {
n = (3*n + 1) / 2;
if (n % 2 == 0) {
do n /= 2; while (n % 2 == 0);
if (n == 1) break;
}
}
Here's a big win: If you look at the lowest 8 bits of n, all the steps until you divided by 2 eight times are completely determined by those eight bits. For example, if the last eight bits are 0x01, that is in binary your number is ???? 0000 0001 then the next steps are:
3n+1 -> ???? 0000 0100
/ 2 -> ???? ?000 0010
/ 2 -> ???? ??00 0001
3n+1 -> ???? ??00 0100
/ 2 -> ???? ???0 0010
/ 2 -> ???? ???? 0001
3n+1 -> ???? ???? 0100
/ 2 -> ???? ???? ?010
/ 2 -> ???? ???? ??01
3n+1 -> ???? ???? ??00
/ 2 -> ???? ???? ???0
/ 2 -> ???? ???? ????
So all these steps can be predicted, and 256k + 1 is replaced with 81k + 1. Something similar will happen for all combinations. So you can make a loop with a big switch statement:
k = n / 256;
m = n % 256;
switch (m) {
case 0: n = 1 * k + 0; break;
case 1: n = 81 * k + 1; break;
case 2: n = 81 * k + 1; break;
...
case 155: n = 729 * k + 425; break;
...
}
Run the loop until n = 128, because at that point n could become 1 with fewer than eight divisions by 2, and doing eight or more steps at a time would make you miss the point where you reach 1 for the first time. Then continue the "normal" loop - or have a table prepared that tells you how many more steps are need to reach 1.
PS. I strongly suspect Peter Cordes' suggestion would make it even faster. There will be no conditional branches at all except one, and that one will be predicted correctly except when the loop actually ends. So the code would be something like
static const unsigned int multipliers [256] = { ... }
static const unsigned int adders [256] = { ... }
while (n > 128) {
size_t lastBits = n % 256;
n = (n >> 8) * multipliers [lastBits] + adders [lastBits];
}
In practice, you would measure whether processing the last 9, 10, 11, 12 bits of n at a time would be faster. For each bit, the number of entries in the table would double, and I excect a slowdown when the tables don't fit into L1 cache anymore.
PPS. If you need the number of operations: In each iteration we do exactly eight divisions by two, and a variable number of (3n + 1) operations, so an obvious method to count the operations would be another array. But we can actually calculate the number of steps (based on number of iterations of the loop).
We could redefine the problem slightly: Replace n with (3n + 1) / 2 if odd, and replace n with n / 2 if even. Then every iteration will do exactly 8 steps, but you could consider that cheating :-) So assume there were r operations n <- 3n+1 and s operations n <- n/2. The result will be quite exactly n' = n * 3^r / 2^s, because n <- 3n+1 means n <- 3n * (1 + 1/3n). Taking the logarithm we find r = (s + log2 (n' / n)) / log2 (3).
If we do the loop until n = 1,000,000 and have a precomputed table how many iterations are needed from any start point n = 1,000,000 then calculating r as above, rounded to the nearest integer, will give the right result unless s is truly large.
The issue is with
At the time of writing this, no environment supports ES6 modules natively. When using them in Node.js you need to use something like Babel to convert the modules to CommonJS. But how exactly does that happen?
Many people consider module.exports = ...
to be equivalent to export default ...
and exports.foo ...
to be equivalent to export const foo = ...
. That's not quite true though, or at least not how Babel does it.
ES6 default
exports are actually also named exports, except that default
is a "reserved" name and there is special syntax support for it. Lets have a look how Babel compiles named and default exports:
// input
export const foo = 42;
export default 21;
// output
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var foo = exports.foo = 42;
exports.default = 21;
Here we can see that the default export becomes a property on the exports
object, just like foo
.
We can import the module in two ways: Either using CommonJS or using ES6 import
syntax.
Your issue: I believe you are doing something like:
var bar = require('./input');
new bar();
expecting that bar
is assigned the value of the default export. But as we can see in the example above, the default export is assigned to the default
property!
So in order to access the default export we actually have to do
var bar = require('./input').default;
If we use ES6 module syntax, namely
import bar from './input';
console.log(bar);
Babel will transform it to
'use strict';
var _input = require('./input');
var _input2 = _interopRequireDefault(_input);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
console.log(_input2.default);
You can see that every access to bar
is converted to access .default
.
In Powershell 3.0 and above there is both a Invoke-WebRequest and Invoke-RestMethod. Curl is actually an alias of Invoke-WebRequest in PoSH. I think using native Powershell would be much more appropriate than curl, but it's up to you :).
Invoke-WebRequest MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849901.aspx?f=255&MSPPError=-2147217396
Invoke-RestMethod MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849971.aspx?f=255&MSPPError=-2147217396
Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.
On PSv5.1 or higher, where >
and >>
are effectively aliases of Out-File
, you can set the default encoding for >
/ >>
/ Out-File
via the $PSDefaultParameterValues
preference variable:
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
On PSv5.0 or below, you cannot change the encoding for >
/ >>
, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File
.
(The $PSDefaultParameterValues
preference variable was introduced in PSv3.0).
On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
an -Encoding
parameter (which in PSv5.1+ includes >
and >>
), use:
$PSDefaultParameterValues['*:Encoding'] = 'utf8'
If you place this command in your $PROFILE
, cmdlets such as Out-File
and Set-Content
will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding
parameter.
Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues
:
$PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }
Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.
For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.
The automatic $OutputEncoding
variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.
PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.
This means that source-code files without a BOM are assumed to be UTF-8, and using >
/ Out-File
/ Set-Content
defaults to BOM-less UTF-8; explicit use of the utf8
-Encoding
argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom
value.
If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1
file will typically not have a UTF-8 pseudo-BOM:
Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat
, sed
, and awk
- and even some editors such as gedit
- to pass the pseudo-BOM through, i.e., to treat it as data.
bash
with, say, text=$(cat file)
or text=$(<file)
- the resulting variable will contain the pseudo-BOM as the first 3 bytes.Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.
Note:
The following doesn't aspire to cover all standard cmdlets.
Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.
As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.
Cmdlets that write:
Out-File
and >
/ >>
create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content
/ Add-Content
(see next point); New-ModuleManifest
and Export-CliXml
also create UTF-16LE files.
Set-Content
(and Add-Content
if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default
).
Export-Csv
indeed creates ASCII files, as documented, but see the notes re -Append
below.
Export-PSSession
creates UTF-8 files with BOM by default.
New-Item -Type File -Value
currently creates BOM-less(!) UTF-8.
The Send-MailMessage
help topic also claims that ASCII encoding is the default - I have not personally verified that claim.
Start-Transcript
invariably creates UTF-8 files with BOM, but see the notes re -Append
below.
Re commands that append to an existing file:
>>
/ Out-File -Append
make no attempt to match the encoding of a file's existing content.
That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding
, which is not an option with >>
(except indirectly in PSv5.1+, via $PSDefaultParameterValues
, as shown above).
In short: you must know the encoding of an existing file's content and append using that same encoding.
Add-Content
is the laudable exception: in the absence of an explicit -Encoding
argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.
This inconsistency between Out-File -Append
/ >>
and Add-Content
, which also affects PowerShell Core, is discussed in this GitHub issue.
Export-Csv -Append
partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append
assumes UTF-8 is, whereas Add-Content
assumes ANSI.
Start-Transcript -Append
partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.
Cmdlets that read (that is, the encoding used in the absence of a BOM):
Get-Content
and Import-PowerShellDataFile
default to ANSI (Default
), which is consistent with Set-Content
.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.
By contrast, Import-Csv
, Import-CliXml
and Select-String
assume UTF-8 in the absence of a BOM.
You didn't tell us what particular problem do you have with the WinSCP, so I can really only repeat what's in WinSCP documentation.
Download WinSCP .NET assembly.
The latest package as of now is WinSCP-5.17.10-Automation.zip
;
Extract the .zip
archive along your script;
Use a code like this (based on the official PowerShell upload example):
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "example.com"
UserName = "user"
Password = "mypassword"
SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
}
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Upload
$session.PutFiles("C:\FileDump\export.txt", "/Outbox/").Check()
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
You can have WinSCP generate the PowerShell script for the upload for you:
You will get a code like above with all session and transfer settings filled in.
(I'm the author of WinSCP)
Hope below helps!
PS C:\Users\aameer>$invoice = $object.'Invoice Month'
$invoice = "01-" + $invoice
[datetime]$Format_date =$invoice
Now type is converted. You can use method or can access any property.
Example :$Format_date.AddDays(5)
With a simple for
loop:
for _, v := range myconfig {
if v.Key == "key1" {
// Found!
}
}
Note that since element type of the slice is a struct
(not a pointer), this may be inefficient if the struct type is "big" as the loop will copy each visited element into the loop variable.
It would be faster to use a range
loop just on the index, this avoids copying the elements:
for i := range myconfig {
if myconfig[i].Key == "key1" {
// Found!
}
}
Notes:
It depends on your case whether multiple configs may exist with the same key
, but if not, you should break
out of the loop if a match is found (to avoid searching for others).
for i := range myconfig {
if myconfig[i].Key == "key1" {
// Found!
break
}
}
Also if this is a frequent operation, you should consider building a map
from it which you can simply index, e.g.
// Build a config map:
confMap := map[string]string{}
for _, v := range myconfig {
confMap[v.Key] = v.Value
}
// And then to find values by key:
if v, ok := confMap["key1"]; ok {
// Found
}
Requesting Permissions In the following code, we will ask for camera permission:
in java
EasyPermissions is a wrapper library to simplify basic system permissions logic when targeting Android M or higher.
Installation EasyPermissions is installed by adding the following dependency to your build.gradle file:
dependencies {
// For developers using AndroidX in their applications
implementation 'pub.devrel:easypermissions:3.0.0'
// For developers using the Android Support Library
implementation 'pub.devrel:easypermissions:2.0.1'
}
private void askAboutCamera(){
EasyPermissions.requestPermissions(
this,
"A partir deste ponto a permissão de câmera é necessária.",
CAMERA_REQUEST_CODE,
Manifest.permission.CAMERA );
}
It is sure because the Invoke-WebRequest command has a dependency on the Internet Explorer assemblies and are invoking it to parse the result as per default behaviour. As Matt suggest, you can simply launch IE and make your selection in the settings prompt which is popping up at first launch. And the error you experience will disappear.
But this is only possible if you run your powershell scripts as the same windows user as whom you launched the IE with. The IE settings are stored under your current windows profile. So if you, like me run your task in a scheduler on a server as the SYSTEM user, this will not work.
So here you will have to change your scripts and add the -UseBasicParsing argument, as ijn this example: $WebResponse = Invoke-WebRequest -Uri $url -TimeoutSec 1800 -ErrorAction:Stop -Method:Post -Headers $headers -UseBasicParsing
for (let [key, value] of map) {
console.log(key, value);
}
for (let entry of Array.from(map.entries())) {
let key = entry[0];
let value = entry[1];
}
Documenting in detail for future readers:
The short answer is you need to override both the methods. The shouldOverrideUrlLoading(WebView view, String url)
method is deprecated in API 24 and the shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
method is added in API 24. If you are targeting older versions of android, you need the former method, and if you are targeting 24 (or later, if someone is reading this in distant future) it's advisable to override the latter method as well.
The below is the skeleton on how you would accomplish this:
class CustomWebViewClient extends WebViewClient {
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
final Uri uri = Uri.parse(url);
return handleUri(uri);
}
@TargetApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
final Uri uri = request.getUrl();
return handleUri(uri);
}
private boolean handleUri(final Uri uri) {
Log.i(TAG, "Uri =" + uri);
final String host = uri.getHost();
final String scheme = uri.getScheme();
// Based on some condition you need to determine if you are going to load the url
// in your web view itself or in a browser.
// You can use `host` or `scheme` or any part of the `uri` to decide.
if (/* any condition */) {
// Returning false means that you are going to load this url in the webView itself
return false;
} else {
// Returning true means that you need to handle what to do with the url
// e.g. open web page in a Browser
final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
return true;
}
}
}
Just like shouldOverrideUrlLoading
, you can come up with a similar approach for shouldInterceptRequest
method.
You should be able to do the following:
$params = @{"@type"="login";
"username"="[email protected]";
"password"="yyy";
}
Invoke-WebRequest -Uri http://foobar.com/endpoint -Method POST -Body $params
This will send the post as the body. However - if you want to post this as a Json you might want to be explicit. To post this as a JSON you can specify the ContentType and convert the body to Json by using
Invoke-WebRequest -Uri http://foobar.com/endpoint -Method POST -Body ($params|ConvertTo-Json) -ContentType "application/json"
Extra: You can also use the Invoke-RestMethod for dealing with JSON and REST apis (which will save you some extra lines for de-serializing)
$Group
is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string")
.
Change $Group.StartsWith("S_G_")
to $Group.samaccountname.StartsWith("S_G_")
.
I had a similar challenge when writing a Powershell script to interact with AWS CLI using the AWS Powershell Tools
I ran the command:
Get-S3Bucket // List AWS S3 buckets
And then I got the error:
Get-S3Bucket : A positional parameter cannot be found that accepts argument list
Here's how I fixed it:
Get-S3Bucket
does not accept // List AWS S3 buckets
as an attribute.
I had put it there as a comment, but it's not acceptable by the AWS CLI as a comment. AWS CLI rather sees it as a parameter.
I had to do it this way:
#List AWS S3 buckets
Get-S3Bucket
That's all.
I hope this helps
The below is a compact script that will check if "running" and attempt start service until the service returns as running.
$Service = 'ServiceName'
If ((Get-Service $Service).Status -ne 'Running') {
do {
Start-Service $Service -ErrorAction SilentlyContinue
Start-Sleep 10
} until ((Get-Service $Service).Status -eq 'Running')
} Return "$($Service) has STARTED"
For using FusedLocationProviderClient with Google Play Services 11 and higher:
see here: How to get current Location in GoogleMap using FusedLocationProviderClient
For using (now deprecated) FusedLocationProviderApi:
If your project uses Google Play Services 10 or lower, using the FusedLocationProviderApi is the optimal choice.
The FusedLocationProviderApi offers less battery drain than the old open source LocationManager API. Also, if you're already using Google Play Services for Google Maps, there's no reason not to use it.
Here is a full Activity class that places a Marker at the current location, and also moves the camera to the current position.
It also checks for the Location permission at runtime for Android 6 and later (Marshmallow, Nougat, Oreo).
In order to properly handle the Location permission runtime check that is necessary on Android M/Android 6 and later, you need to ensure that the user has granted your app the Location permission before calling mGoogleMap.setMyLocationEnabled(true)
and also before requesting location updates.
public class MapLocationActivity extends AppCompatActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("Map Location Activity");
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
@Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
@Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int i) {}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
@Override
public void onLocationChanged(Location location)
{
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MapLocationActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/map"
tools:context=".MapLocationActivity"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
</LinearLayout>
Result:
Show permission explanation if needed using an AlertDialog (this happens if the user denies a permission request, or grants the permission and then later revokes it in the settings):
Prompt the user for Location permission by calling ActivityCompat.requestPermissions()
:
Move camera to current location and place Marker when the Location permission is granted:
Example:
2.032 MB (2,131,022 bytes)
$u=($mbox.TotalItemSize.value).tostring()
$u=$u.trimend(" bytes)") #yields 2.032 MB (2,131,022
$u=$u.Split("(") #yields `$u[1]` as 2,131,022
$uI=[int]$u[1]
The result is 2131022 in integer form.
Android-M ie, API 23 introduced Runtime Permissions for reducing security flaws in android device, where users can now directly manage app permissions at runtime.so if the user denies a particular permission of your application you have to obtain it by asking the permission dialog that you mentioned in your query.
So check before action ie, check you have permission to access the resource link and if your application doesn't have that particular permission you can request the permission link and handle the the permissions request response like below.
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
So finally, It's a good practice to go through behavior changes if you are planning to work with new versions to avoid force closes :)
You can go through the official sample app here.
Load names with tf.train.match_filenames_once get the number of files to iterate over with tf.size open session and enjoy ;-)
import tensorflow as tf
import numpy as np
import matplotlib;
from PIL import Image
matplotlib.use('Agg')
import matplotlib.pyplot as plt
filenames = tf.train.match_filenames_once('./images/*.jpg')
count_num_files = tf.size(filenames)
filename_queue = tf.train.string_input_producer(filenames)
reader=tf.WholeFileReader()
key,value=reader.read(filename_queue)
img = tf.image.decode_jpeg(value)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
num_files = sess.run(count_num_files)
for i in range(num_files):
image=img.eval()
print(image.shape)
Image.fromarray(np.asarray(image)).save('te.jpeg')
I think you need to get some fundamentals right. With the examples above you have created tensors (multi dimensional array). But for tensor flow to really work you have to initiate a "session" and run your "operation" in the session. Notice the word "session" and "operation". You need to know 4 things to work with tensorflow:
Now from what you wrote out you have given the tensor, and the operation but you have no session running nor a graph. Tensor (edges of the graph) flow through graphs and are manipulated by operations (nodes of the graph). There is default graph but you can initiate yours in a session.
When you say print , you only access the shape of the variable or constant you defined.
So you can see what you are missing :
with tf.Session() as sess:
print(sess.run(product))
print (product.eval())
Hope it helps!
Get-Content
has bad performance; it tries to read the file into memory all at once.
C# (.NET) file reader reads each line one by one
Best Performace
foreach($line in [System.IO.File]::ReadLines("C:\path\to\file.txt"))
{
$line
}
Or slightly less performant
[System.IO.File]::ReadLines("C:\path\to\file.txt") | ForEach-Object {
$_
}
The foreach
statement will likely be slightly faster than ForEach-Object
(see comments below for more information).
It is simple. take a look at this
https://codepen.io/anon/pen/mepogj?editors=001
basically you want to deal with states of your component so you check the currently active one. you will need to include
getInitialState: function(){}
//and
isActive: function(){}
check out the code on the link
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Log.d(TAG, "Permission granted");
} else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
100);
}
fab.setOnClickListener(v -> {
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.refer_pic);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(requireActivity().getContentResolver(),
b, "Title", null);
Uri imageUri = Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
share.putExtra(Intent.EXTRA_TEXT, "Here is text");
startActivity(Intent.createChooser(share, "Share via"));
});
Android changed how permissions work with Android 6.0 that's the reason for your errors. You have to actually request and check if the permission was granted by user to use. So permissions in manifest file will only work for api below 21. Check this link for a snippet of how permissions are requested in api23 http://android-developers.blogspot.nl/2015/09/google-play-services-81-and-android-60.html?m=1
Code:-
If (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_RC);
return;
}`
` @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == STORAGE_PERMISSION_RC) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permission granted start reading
} else {
Toast.makeText(this, "No permission to read external storage.", Toast.LENGTH_SHORT).show();
}
}
}
}
Starting with Android 11, you can directly bring up the app-specific settings page for the location permission only using code like this: requestPermissions(arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION), PERMISSION_REQUEST_BACKGROUND_LOCATION)
However, the above will only work one time. If the user denies the permission or even accidentally dismisses the screen, the app can never trigger this to come up again.
Other than the above, the answer remains the same as prior to Android 11 -- the best you can do is bring up the app-specific settings page and ask the user to drill down two levels manually to enable the proper permission.
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
val uri: Uri = Uri.fromParts("package", packageName, null)
intent.data = uri
// This will take the user to a page where they have to click twice to drill down to grant the permission
startActivity(intent)
See my related question here: Android 11 users can’t grant background location permission?
2 workarounds, rather than a solution: In my Git Bash, following command hangs and I don't get the prompt back:
% python
So I just use:
% winpty python
As some people have noted above, you can also use:
% python -i
2020-07-14: Git 2.27.0 has added optional experimental support for pseudo consoles, which allow running Python from the command line:
The easiest way to open an admin Powershell window in Windows 10 (and Windows 8) is to add a "Windows Powershell (Admin)" option to the "Power User Menu". Once this is done, you can open an admin powershell window via Win+X,A or by right-clicking on the start button and selecting "Windows Powershell (Admin)":
[
Here's where you replace the "Command Prompt" option with a "Windows Powershell" option:
[
Add the following aliases. I think these should be made available in PowerShell by default:
function not-exist { -not (Test-Path $args) }
Set-Alias !exist not-exist -Option "Constant, AllScope"
Set-Alias exist Test-Path -Option "Constant, AllScope"
With that, the conditional statements will change to:
if (exist $path) { ... }
and
if (not-exist $path) { ... }
if (!exist $path) { ... }
You can use the Test-Path
cmd-let. So something like...
if(!(Test-Path [oldLocation]) -and !(Test-Path [newLocation]))
{
Write-Host "$file doesn't exist in both locations."
}
You may use this package renderer, I have written to solve this kind of problem, it's a wrapper to serve JSON, JSONP, XML, HTML etc.
I don't want to include the Support library just for getColor, so I'm using something like
public static int getColorWrapper(Context context, int id) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return context.getColor(id);
} else {
//noinspection deprecation
return context.getResources().getColor(id);
}
}
I guess the code should work just fine, and the deprecated getColor
cannot disappear from API < 23.
And this is what I'm using in Kotlin:
/**
* Returns a color associated with a particular resource ID.
*
* Wrapper around the deprecated [Resources.getColor][android.content.res.Resources.getColor].
*/
@Suppress("DEPRECATION")
@ColorInt
fun getColorHelper(context: Context, @ColorRes id: Int) =
if (Build.VERSION.SDK_INT >= 23) context.getColor(id) else context.resources.getColor(id);
The closest PowerShell construct I've been able to come up with to emulate that is:
@({'condition is false'},{'condition is true'})[$condition]
I met a similar problem.But the error report is about
[SSL: TLSV1_ALERT_ACCESS_DENIED] tlsv1 alert access denied (_ssl.c:777)
First I tried this https://python-forum.io/Thread-All-pip-install-attempts-are-met-with-SSL-error#pid_28035 ,but seems it couldn't solve my problems,and still repeat the same issue.
And Second if you are working on a business computer,generally it may exist a web content filter(but I can access https://pypi.python.org through browser directly).And solve this issue by adding a proxy server.
For windows,open the Internet properties
through IE or Chrome or whatsoever ,then set valid proxy address and port,and this way solve my problems
Or just adding the option pip --proxy [proxy-address]:port install mitmproxy
.But you always need to add this option while installing by pypi
The above two solution is alternative for you demand.
I found answer myself; and if someone will face same issue, i hope my solution will work for them as well.
It would be something like this
function CustomInputBox([string] $title, [string] $message, [string] $defaultText)
{
$inputObject = new-object -comobject MSScriptControl.ScriptControl
$inputObject.language = "vbscript"
$inputObject.addcode("function getInput() getInput = inputbox(`"$message`",`"$title`" , `"$defaultText`") end function" )
$_userInput = $inputObject.eval("getInput")
return $_userInput
}
Then you can call the function similar to this.
$userInput = CustomInputBox "User Name" "Please enter your name." ""
if ( $userInput -ne $null )
{
echo "Input was [$userInput]"
}
else
{
echo "User cancelled the form!"
}
This is the most simple way to do this that I can think of.
In windows server 2012 or 2016 you can search for Windows PowerShell and then "Pin to Start". After this you will see "Run as different user" option on a right click on the start page tiles.
try {
Import-Module SomeModule
Write-Host "Module exists"
}
catch {
Write-Host "Module does not exist"
}
It should be pointed out that your cmdlet Import-Module
has no terminating error, therefore the exception isnt being caught so no matter what your catch statement will never return the new statement you have written.
From The Above:
"A terminating error stops a statement from running. If PowerShell does not handle a terminating error in some way, PowerShell also stops running the function or script using the current pipeline. In other languages, such as C#, terminating errors are referred to as exceptions. For more information about errors, see about_Errors."
It should be written as:
Try {
Import-Module SomeModule -Force -Erroraction stop
Write-Host "yep"
}
Catch {
Write-Host "nope"
}
Which returns:
nope
And if you really wanted to be thorough you should add in the other suggested cmdlets Get-Module -ListAvailable -Name
and Get-Module -Name
to be extra cautious, before running other functions/cmdlets. And if its installed from psgallery or elsewhere you could also run a Find-Module
cmdlet to see if there is a new version available.
Use $dec = $null
From the documentation:
$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.
PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.
You are close, but the parameter you pass to SecureStringToBSTR
must be a SecureString
. You appear to be passing the result of ConvertFrom-SecureString
, which is an encrypted standard string. So call ConvertTo-SecureString
on this before passing to SecureStringToBSTR
.
$SecurePassword = ConvertTo-SecureString $PlainPassword -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
Some of the those leaving comments have noted that setting System.Net.ServicePointManager.SecurityProtocol
to specific values means that your app won't be able to take advantage of future TLS versions that may become the default values in future updates to .NET. Instead of specifying a fixed list of protocols, you can instead turn on or off protocols you know and care about, leaving any others as they are.
To turn on TLS 1.1 and 1.2 without affecting other protocols:
System.Net.ServicePointManager.SecurityProtocol |=
SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
Notice the use of |=
to turn on these flags without turning others off.
To turn off SSL3 without affecting other protocols:
System.Net.ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3;
another way is to use certutil.exe save your username and password in a file e.g. in.txt as username:password
certutil -encode in.txt out.txt
Now you should be able to use auth value from out.txt
$headers = @{ Authorization = "Basic $((get-content out.txt)[1])" }
Invoke-WebRequest -Uri 'https://whatever' -Headers $Headers
Use Expand-Archive
cmdlet with one of parameter set:
Expand-Archive -LiteralPath C:\source\file.Zip -DestinationPath C:\destination
Expand-Archive -Path file.Zip -DestinationPath C:\destination
The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5
. From the comment you put this needed to be declared elsewhere in your code
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
The error was because you are trying to execute a method that does not exist.
PS C:\Users\Matt> $md5 | gm
TypeName: System.Security.Cryptography.MD5CryptoServiceProvider
Name MemberType Definition
---- ---------- ----------
Clear Method void Clear()
ComputeHash Method byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...
The .ComputeHash()
of $md5.ComputeHash()
was the null valued expression. Typing in gibberish would create the same effect.
PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PowerShell by default allows this to happen as defined its StrictMode
When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.
Out-File
defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii
to change this behavior. In your case
Out-File -Encoding Ascii -append textfile.txt.
Add-Content
uses Ascii and also appends by default.
"This is a test" | Add-Content textfile.txt.
As for the lack of newline: You did not send a newline so it will not write one to file.
This one liner gives you the IP address:
(Test-Connection -ComputerName $env:computername -count 1).ipv4address.IPAddressToString
Include it in a Variable?
$IPV4=(Test-Connection -ComputerName $env:computername -count 1).ipv4address.IPAddressToString
easy way to do it: To get the actual user count:
$ADInfo = Get-ADGroup -Identity '<groupname>' -Properties Members
$AdInfo.Members.Count
and you get the count easily, it is pretty fast as well for 20k+ users too
Using ByteArrayOutputStream
public static String printObjectToXML(final Object object) throws TransformerFactoryConfigurationError,
TransformerConfigurationException, SOAPException, TransformerException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
XMLEncoder xmlEncoder = new XMLEncoder(baos);
xmlEncoder.writeObject(object);
xmlEncoder.close();
String xml = baos.toString();
System.out.println(xml);
return xml.toString();
}
I struggled with this as well and found a simple pattern to isolate the test context after a cursory read of the @ComponentScan docs.
/**
* Type-safe alternative to {@link #basePackages} for specifying the packages
* to scan for annotated components. The package of each class specified will be scanned.
* Consider creating a special no-op marker class or interface in each package
* that serves no purpose other than being referenced by this attribute.
*/
Class<?>[] basePackageClasses() default {};
("com.example.test")
.Example
IsolatedTest.java
package com.example.test;
@RunWith(SpringJUnit4ClassRunner.class)
@ComponentScan(basePackageClasses = {TestDomain.class})
@SpringApplicationConfiguration(classes = IsolatedTest.Config.class)
public class IsolatedTest {
String expected = "Read the documentation on @ComponentScan";
String actual = "Too lazy when I can just search on Stack Overflow.";
@Test
public void testSomething() throws Exception {
assertEquals(expected, actual);
}
@ComponentScan(basePackageClasses = {TestDomain.class})
public static class Config {
public static void main(String[] args) {
SpringApplication.run(Config.class, args);
}
}
}
...
TestDomain.java
package com.example.test;
public interface TestDomain {
//noop marker
}
I think the correct solution with support library 21 is the following
// action_bar is def resource of appcompat;
// if you have not provided your own toolbar I mean
Toolbar toolbar = (Toolbar) findViewById(R.id.action_bar);
if (toolbar != null) {
// change home icon if you wish
toolbar.setLogo(this.getResValues().homeIconDrawable());
toolbar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//catch here title and home icon click
}
});
}
We can use elasticdump
or multielasticdump
to take the backup and restore it, We can move data from one server/cluster to another server/cluster.
Please find a detailed answer which I have provided here.
The solution posted by @Linga:
"Get-ChildItem -Recurse 'directory_path' | Measure-Object -Property Length -Sum"
is nice and short. However, it only computes the size of 'directory_path'
, without sub-directories.
Here is a simple solution for listing all sub-directory sizes. With a little pretty-printing added.
(Note: use the -File
option to avoid errors for empty sub-directories)
foreach ($d in gci -Directory -Force) {
'{0:N0}' -f ((gci $d -File -Recurse -Force | measure length -sum).sum) + "`t`t$d"
}
A simple way to get the tenantID is
Connect-MsolService -cred $LiveCred #sign in to tenant
(Get-MSOLCompanyInformation).objectid.guid #get tenantID
As I understand Copy-Item -Exclude
then you are doing it correct. What I usually do, get 1'st, and then do after, so what about using Get-Item
as in
Get-Item -Path $copyAdmin -Exclude $exclude |
Copy-Item -Path $copyAdmin -Destination $AdminPath -Recurse -force
You don't need quotes around the variable, so simply change this:
Get-ADComputer -Filter {name -like '$nameregex' -and Enabled -eq "true"}
into this:
Get-ADComputer -Filter {name -like $nameregex -and Enabled -eq "true"}
Note, however, that the scriptblock notation for filter statements is misleading, because the statement is actually a string, so it's better to write it as such:
Get-ADComputer -Filter "name -like '$nameregex' -and Enabled -eq 'true'"
And FTR: you're using wildcard matching here (operator -like
), not regular expressions (operator -match
).
You can use it this way:
$root = 'C:'
$folder1 = 'Program Files (x86)'
$folder2 = 'Microsoft.NET'
if (-Not(Test-Path $(Join-Path $root -ChildPath $folder1 | Join-Path -ChildPath $folder2)))
{
"Folder does not exist"
}
else
{
"Folder exist"
}
Referring to Gamaliel 's answer: $args is an array of the arguments that are passed into a script at runtime - as such cannot be used the way Gamaliel is using it. This is actually working:
$myPath = 'C:\whatever.file'
# get actual Acl entry
$myAcl = Get-Acl "$myPath"
$myAclEntry = "Domain\User","FullControl","Allow"
$myAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($myAclEntry)
# prepare new Acl
$myAcl.SetAccessRule($myAccessRule)
$myAcl | Set-Acl "$MyPath"
# check if added entry present
Get-Acl "$myPath" | fl
Assuming you can use integrated security, you can remove the user id and pass:
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"
You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.
You have two options:
Grant write permissions to the folder to the user or group you log in with (myuser
), or change the ownership of the folder to the user, or
Disable a transfer to temporary file.
In Preferences, go to Transfer > Endurance page and in Enable transfer resume/transfer to temporary file name for select Disable:
It seems the issue is in "-f ($_.Partition.Size/1GB)}}" If you want the value in MB then change the 1GB to 1MB.
Try quoting the argument list:
Start-Process -FilePath "C:\Program Files\MSBuild\test.exe" -ArgumentList "/genmsi/f $MySourceDirectory\src\Deployment\Installations.xml"
You can also provide the argument list as an array (comma separated args) but using a string is usually easier.
The includes
(formerly called contains
and include
) method compares objects by reference (or more precisely, with ===
). Because the two object literals of {"b": 2}
in your example represent different instances, they are not equal. Notice:
({"b": 2} === {"b": 2})
> false
However, this will work because there is only one instance of {"b": 2}
:
var a = {"a": 1}, b = {"b": 2};
_.includes([a, b], b);
> true
On the other hand, the where
(deprecated in v4) and find
methods compare objects by their properties, so they don't require reference equality. As an alternative to includes
, you might want to try some
(also aliased as any
):
_.some([{"a": 1}, {"b": 2}], {"b": 2})
> true
One solution would be to pipe your command from PowerShell to CMD. Running the following command will pipe the notepad.exe
command over to CMD, which will then open the Notepad application.
PS C:\> "notepad.exe" | cmd
Once the command has run in CMD, you will be returned to a PowerShell prompt, and can continue running your PowerShell script.
As mklement0 points out, this method shows CMD's startup message. If you were to copy the output using the method above into another terminal, the startup message will be copied along with it.
Just to add to this list of possible locations...
This didn't work for me:
\Users\{ME}\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
However this did:
\Users\{ME}\OneDrive\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
If you don't have a profile or you're looking to set one up, run the following command, it will create the folder/files necessary and even tell you where it lives!
New-Item -path $profile -type file -force
try put cd before the file path
example:
C:\Users\user>cd C:\Program Files\MongoDB\Server\4.4\bin
I found the solution here:
How to properly -filter multiple strings in a PowerShell copy script
You have to use -Include
flag for Get-ChildItem
My Example:
$Location = "C:\user\files"
$result = (Get-ChildItem $Location\* -Include *.png, *.gif, *.jpg)
Dont forget put "*" after path location.
If you had caught the error, you would have seen this:
jsonString, err := json.Marshal(datas)
fmt.Println(err)
// [] json: unsupported type: map[int]main.Foo
The thing is you cannot use integers as keys in JSON; it is forbidden. Instead, you can convert these values to strings beforehand, for instance using strconv.Itoa
.
See this post for more details: https://stackoverflow.com/a/24284721/2679935
A slightly prettier function based on Ansgar Wiechers's answer. Whether it's actually more useful is a matter of debate.
function Read-Choice(
[Parameter(Mandatory)][string]$Message,
[Parameter(Mandatory)][string[]]$Choices,
[Parameter(Mandatory)][string]$DefaultChoice,
[Parameter()][string]$Question='Are you sure you want to proceed?'
) {
$defaultIndex = $Choices.IndexOf($DefaultChoice)
if ($defaultIndex -lt 0) {
throw "$DefaultChoice not found in choices"
}
$choiceObj = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription]
foreach($c in $Choices) {
$choiceObj.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList $c))
}
$decision = $Host.UI.PromptForChoice($Message, $Question, $choiceObj, $defaultIndex)
return $Choices[$decision]
}
Example usage:
PS> $r = Read-Choice 'DANGER!!!!!!' '&apple','&blah','&car' '&blah'
DANGER!!!!!!
Are you sure you want to proceed?
[A] apple [B] blah [C] car [?] Help (default is "B"): c
PS> switch($r) { '&car' { Write-host 'caaaaars!!!!' } '&blah' { Write-Host "It's a blah day" } '&apple' { Write-Host "I'd like to eat some apples!" } }
caaaaars!!!!
You basically have 3 options to prevent the PowerShell Console window from closing, that I describe in more detail on my blog post.
PowerShell -NoExit "C:\SomeFolder\SomeScript.ps1"
Read-Host -Prompt "Press Enter to exit"
Global Fix: Change your registry key to always leave the PowerShell Console window open after the script finishes running. Here's the 2 registry keys that would need to be changed:
? Open With ? Windows PowerShell
When you right-click a .ps1 file and choose Open With
Registry Key: HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command
Default Value:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "%1"
Desired Value:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "& \"%1\""
? Run with PowerShell
When you right-click a .ps1 file and choose Run with PowerShell (shows up depending on which Windows OS and Updates you have installed).
Registry Key: HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\0\Command
Default Value:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"
Desired Value:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoExit "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & \"%1\""
You can download a .reg file from my blog to modify the registry keys for you if you don't want to do it manually.
It sounds like you likely want to use option #2. You could even wrap your whole script in a try block, and only prompt for input if an error occurred, like so:
try
{
# Do your script's stuff
}
catch
{
Write-Error $_.Exception.ToString()
Read-Host -Prompt "The above error occurred. Press Enter to exit."
}
you can just use post
to post your json.
values := map[string]string{"username": username, "password": password}
jsonValue, _ := json.Marshal(values)
resp, err := http.Post(authAuthenticatorUrl, "application/json", bytes.NewBuffer(jsonValue))
If the string is
$STR = 'HELLO WORLD'
and you want to remove the empty space between 'HELLO' and 'WORLD'
$STR.replace(' ','')
replace
takes the string and replaces white space with empty string (of length 0), in other words the white space is just deleted.
Escape the | character using a backtick
get-content c:\new\temp_*.txt | select-string -pattern 'H`|159' -notmatch | Out-File c:\new\newfile.txt
You first have to 'dot' source the script, so for you :
. .\Get-NetworkStatistics.ps1
The first 'dot' asks PowerShell to load the script file into your PowerShell environment, not to start it. You should also use set-ExecutionPolicy Unrestricted
or set-ExecutionPolicy AllSigned
see(the Execution Policy instructions).
rsync
transfers files as fast as it can over the network. For example, try using it to copy one large file that doesn't exist at all on the destination. That speed is the maximum speed rsync can transfer data. Compare it with the speed of scp
(for example). rsync
is even slower at raw transfer when the destination file exists, because both sides have to have a two-way chat about what parts of the file are changed, but pays for itself by identifying data that doesn't need to be transferred.
A simpler way to run rsync
in parallel would be to use parallel
. The command below would run up to 5 rsync
s in parallel, each one copying one directory. Be aware that the bottleneck might not be your network, but the speed of your CPUs and disks, and running things in parallel just makes them all slower, not faster.
run_rsync() {
# e.g. copies /main/files/blah to /main/filesTest/blah
rsync -av "$1" "/main/filesTest/${1#/main/files/}"
}
export -f run_rsync
parallel -j5 run_rsync ::: /main/files/*
You can use the Unblock-File cmdlet to unblock the execution of this specific script. This prevents you doing any permanent policy changes which you may not want due to security concerns.
Unblock-File path_to_your_script
Source: Unblock-File
Also, the long method - it was a last resort after trying all previous answers:
C:\python27\scripts\pip.exe install [package].whl
This after cd in directory where the wheel is located.
I got similar error after deleting a subproject, removed
"*compile project(path: ':MySubProject', configuration: 'android-endpoints')*"
in build.gradle
(dependencies) under Gradle Scripts
This issue is not always related to the PowerShell Execution Policy. My machine is configured as "Unrestricted" for both PowerShell x64 and x86, but I still get this error message from times to times in Visual Studio 2013.
When I try to open the Package Manager Console:
Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope. Due to the override, your shell will retain its current effective execution policy of Unrestricted. Type "Get-ExecutionPolicy -List" to view your execution policy settings. For more information please see "Get-Help Set-ExecutionPolicy".
This is not a valid error message.
Rebooting Visual Studio does not always resolve the problem.
Running the process as an admin never resolves the problem.
Like Declan, the latest update of the Package Manager plugin fixed the issue: 2.8.60723.765
So I have faced the same problem when trying to start apache service and I would like to share my solutions with you. Here is some notes about services or programs that may use port 80:
These options work great with me and I can start apache service without errors.
The other option is to change apache listen port from httpd.conf and set another port number.
Hope this solution helps anyone who face the same problem again.
In search of this same solution, I found what I needed under a different question in stackoverflow: Powershell-log-off-remote-session. The below one line will return a list of logged on users.
query user /server:$SERVER
You have to placed this code in application.rb
config.action_dispatch.default_headers = {
'Access-Control-Allow-Origin' => '*',
'Access-Control-Request-Method' => %w{GET POST OPTIONS}.join(",")
}
This is a bug in .NET. When PowerShell launches, it caches the output handle (Console.Out). The Encoding property of that text writer does not pick up the value StandardOutputEncoding property.
When you change it from within PowerShell, the Encoding property of the cached output writer returns the cached value, so the output is still encoded with the default encoding.
As a workaround, I would suggest not changing the encoding. It will be returned to you as a Unicode string, at which point you can manage the encoding yourself.
Caching example:
102 [C:\Users\leeholm]
>> $r1 = [Console]::Out
103 [C:\Users\leeholm]
>> $r1
Encoding FormatProvider
-------- --------------
System.Text.SBCSCodePageEncoding en-US
104 [C:\Users\leeholm]
>> [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
105 [C:\Users\leeholm]
>> $r1
Encoding FormatProvider
-------- --------------
System.Text.SBCSCodePageEncoding en-US
As my last resort with this error I created a fresh windows 10 virtual machine and installed the latest nodejs (v6). But there was a host of other "ERRs!" to work through.
I had to run npm cache clean --force
which ironically will give you a message that reads "I sure hope you know what you are doing". That seems to have worked.
It doesn't solve the issue on my main Dev machine. I'm canning nodejs as I found over the last few years that you spend more time on fixing it rather than on actual development. I had fewer issues with node on linux ubuntu 14.04 if that's any help.
Use chown
to change ownership and chmod
to change rights.
use the -R
option to apply the rights for all files inside of a directory too.
Note that both these commands just work for directories too. The -R
option makes them also change the permissions for all files and directories inside of the directory.
For example
sudo chown -R username:group directory
will change ownership (both user and group) of all files and directories inside of directory and directory itself.
sudo chown username:group directory
will only change the permission of the folder directory but will leave the files and folders inside the directory alone.
you need to use sudo to change the ownership from root to yourself.
Edit:
Note that if you use chown user: file
(Note the left-out group), it will use the default group for that user.
Also You can change the group ownership of a file or directory with the command:
chgrp group_name file/directory_name
You must be a member of the group to which you are changing ownership to.
You can find group of file as follows
# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file
# chown sujit:friends file
User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.
What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.
But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.
Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.
I don't have Python 2.7 installed, but in Python 3.3 calling Popen
with stdout
set to sys.stdout
worked just fine. Not before I had escaped the backslashes in the path, though.
>>> import subprocess
>>> import sys
>>> p = subprocess.Popen(['powershell.exe', 'C:\\Temp\\test.ps1'], stdout=sys.stdout)
>>> Hello World
_
Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:
json: cannot unmarshal object into Go struct field Comment.author of type string
The problem is that IE won't reset the proxy settings until it either
Below is the code that I've used to get this working:
function Refresh-System
{
$signature = @'
[DllImport("wininet.dll", SetLastError = true, CharSet=CharSet.Auto)]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
'@
$INTERNET_OPTION_SETTINGS_CHANGED = 39
$INTERNET_OPTION_REFRESH = 37
$type = Add-Type -MemberDefinition $signature -Name wininet -Namespace pinvoke -PassThru
$a = $type::InternetSetOption(0, $INTERNET_OPTION_SETTINGS_CHANGED, 0, 0)
$b = $type::InternetSetOption(0, $INTERNET_OPTION_REFRESH, 0, 0)
return $a -and $b
}
The suggested answer by Loïc MICHEL blindly writes a new value to the TrustedHosts entry.
I believe, a better way would be to first query TrustedHosts.
As Jeffery Hicks posted in 2010, first query the TrustedHosts entry:
PS C:\> $current=(get-item WSMan:\localhost\Client\TrustedHosts).value
PS C:\> $current+=",testdsk23,alpha123"
PS C:\> set-item WSMan:\localhost\Client\TrustedHosts –value $current
The good thing is, this one is really easily and deterministically to analyze: Either, the msi package is really not installed on the system or you're doing something wrong. Of course the correct call is:
msiexec /x {A4BFF20C-A21E-4720-88E5-79D5A5AEB2E8}
(Admin rights needed of course- With curly braces without any quotes here- quotes are only needed, if paths or values with blank are specified in the commandline.)
If the message is: "This action is only valid for products that are currently installed", then this is true. Either the package with this ProductCode is not installed or there is a typo.
To verify where the fault is:
First try to right click on the (probably) installed .msi file itself. You will see (besides "Install" and "Repair") an Uninstall entry. Click on that.
a) If that uninstall works, your msi has another ProductCode than you expect (maybe you have the wrong WiX source or your build has dynamic logging where the ProductCode changes).
b) If that uninstall gives the same "...only valid for products already installed" the package is not installed (which is obviously a precondition to be able to uninstall it).
If 1.a) was the case, you can look for the correct ProductCode of your package, if you open your msi file with Orca, Insted or another editor/tool. Just google for them. Look there in the table with the name "Property" and search for the string "ProductCode" in the first column. In the second column there is the correct value.
There are no other possibilities.
Just a suggestion for the used commandline: I would add at least the "/qb" for a simple progress bar or "/qn" parameter (the latter for complete silent uninstall, but makes only sense if you are sure it works).
Like what Volker mentioned, nested structs is the way to go. But if you really do not want nested structs, you can override the UnmarshalJSON func.
https://play.golang.org/p/dqn5UdqFfJt
type A struct {
FooBar string // takes foo.bar
FooBaz string // takes foo.baz
More string
}
func (a *A) UnmarshalJSON(b []byte) error {
var f interface{}
json.Unmarshal(b, &f)
m := f.(map[string]interface{})
foomap := m["foo"]
v := foomap.(map[string]interface{})
a.FooBar = v["bar"].(string)
a.FooBaz = v["baz"].(string)
a.More = m["more"].(string)
return nil
}
Please ignore the fact that I'm not returning a proper error. I left that out for simplicity.
UPDATE: Correctly retrieving "more" value.
First: As it currently stands, the $User
variable does not have a .Users
property. In your code, $User
simply represents one line (the "current" line in the foreach loop) from the text file.
$getmembership = Get-ADUser $User -Properties MemberOf | Select -ExpandProperty memberof
Secondly, I do not believe you can query an entire forest with one command. You will have to break it down into smaller chunks:
Get-ADUser
for each domain (you may have to specify alternate credentials via the -Credential
parameterThirdly, to get a list of groups that a user is a member of:
$User = Get-ADUser -Identity trevor -Properties *;
$GroupMembership = ($user.memberof | % { (Get-ADGroup $_).Name; }) -join ';';
# Result:
Orchestrator Users Group;ConfigMgr Administrators;Service Manager Admins;Domain Admins;Schema Admins
Fourthly: To get the final, desired string format, simply add the $User.Name
, a semicolon, and the $GroupMembership
string together:
$User.SamAccountName + ';' + $GroupMembership;
what you are searching for is the Export-Csv file.csv
try using Get-Help Export-Csv to see whats possible
also Out-File -FilePath "file.csv"
will work
variable=10
f=open("fileName.txt","w+") # file name and mode
for x in range(0,10):
f.writelines('your text')
f.writelines('if you want to add variable data'+str(variable))
# to add data you only add String data so you want to type cast variable
f.writelines("\n")
For MVC 5 just look inside the EnableTwoFactorAuthentication method of ManageController in WebApplication template scaffold, its being done there:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> EnableTwoFactorAuthentication()
{
await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true);
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", "Manage");
}
The answer is right there as suggested by Microsoft itself:
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
It will have all the additional properties you defined in ApplicationUser class.
Here is what I use.
Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
You can concatenate an array of values together using PowerShell's `-join' operator. Here is an example:
$FilePath = '{0}\temp\scripts\pshell\dump.txt' -f $env:SystemDrive;
$Computer = 'pc1';
$Speed = 9001;
$RegCheck = $true;
$Computer,$Speed,$RegCheck -join ',' | Out-File -FilePath $FilePath -Append -Width 200;
Output
pc1,9001,True
In my specific case of the same issue, it was caused by not having the Powershell script saved with an encoding of Windows-1252 or UFT-8 WITH BOM.
If it helps you can embed a tab character in a double quoted string:
PS> "`t hello"
This bug still exists in 0.8+/1.10
With Jackson
compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-csv:2.2.2'
I had to include as well as the above suggestion before it would compile
exclude 'META-INF/services/com.fasterxml.jackson.core.JsonFactory'
What about invoke-item script.bat
.
When you generate a JAXB model from an XML Schema, global elements that correspond to named complex types will have that metadata captured as an @XmlElementDecl
annotation on a create method in the ObjectFactory
class. Since you are creating the JAXBContext
on just the DocumentType
class this metadata isn't being processed. If you generated your JAXB model from an XML Schema then you should create the JAXBContext
on the generated package name or ObjectFactory
class to ensure all the necessary metadata is processed.
Example solution:
JAXBContext jaxbContext = JAXBContext.newInstance(my.generatedschema.dir.ObjectFactory.class);
DocumentType documentType = ((JAXBElement<DocumentType>) jaxbContext.createUnmarshaller().unmarshal(inputStream)).getValue();
Be sure, whenever you want PowerShell to run automatically / in the background / non-interactive, it’s a good idea to specify the parameters
-ExecutionPolicy Bypass
to PowerShell.exe
PowerShell.exe -ExecutionPolicy Bypass
I had this error and I found that the name of one of my connection strings was wrong. Check the names as well as the actual string.
You must update the Windows PowerShell to minimum of version 4.0 for the script below to work.
[array]$SiteLinks = "http://mypage.global/Chemical/test.html"
"http://maypage2:9080/portal/site/hotpot/test.json"
foreach($url in $SiteLinks) {
try {
Write-host "Verifying $url" -ForegroundColor Yellow
$checkConnection = Invoke-WebRequest -Uri $url
if ($checkConnection.StatusCode -eq 200) {
Write-Host "Connection Verified!" -ForegroundColor Green
}
}
catch [System.Net.WebException] {
$exceptionMessage = $Error[0].Exception
if ($exceptionMessage -match "503") {
Write-Host "Server Unavaiable" -ForegroundColor Red
}
elseif ($exceptionMessage -match "404") {
Write-Host "Page Not found" -ForegroundColor Red
}
}
}
You can find it in Nuget Package Microsoft ASP.NET Web Pages Version 3.2.0
If you have a reference to an earlier version than 3.0.0.0, Delete the reference, add the reference to the correct .dll in your packages folder and make sure "Copy Local" is set to "True" in the properties of the .dll.
Then in your web.config (as mentioned by @MichaelEvanchik)
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages.Razor" PublicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
Actually, the "Checkout to specific local branch"
from Claus's answer isn't needed as well.
You can just do changes, execute git commit -am "message"
and then use "Git Publisher" with "Branch to push" = /refs/heads/master
(or develop or whatever branch you need to push to), "Target remote name" = origin.
Use newtonsoft like so:
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
class Program
{
static void Main()
{
string json = "{'results':[{'SwiftCode':'','City':'','BankName':'Deutsche Bank','Bankkey':'10020030','Bankcountry':'DE'},{'SwiftCode':'','City':'10891 Berlin','BankName':'Commerzbank Berlin (West)','Bankkey':'10040000','Bankcountry':'DE'}]}";
var resultObjects = AllChildren(JObject.Parse(json))
.First(c => c.Type == JTokenType.Array && c.Path.Contains("results"))
.Children<JObject>();
foreach (JObject result in resultObjects) {
foreach (JProperty property in result.Properties()) {
// do something with the property belonging to result
}
}
}
// recursively yield all children of json
private static IEnumerable<JToken> AllChildren(JToken json)
{
foreach (var c in json.Children()) {
yield return c;
foreach (var cc in AllChildren(c)) {
yield return cc;
}
}
}
}
The latest PowerShell version as of Aug 2016 is PowerShell 5.1. It's bundled with Windows Management Framework 5.1.
Here's the download page for PowerShell 5.1 for all versions of Windows, including Windows 7 x64 and x86.
It is worth noting that PowerShell 5.1 is the first version available in two editions of "Desktop" and "Core". Powershell Core 6.x is cross-platform, its latest version for Jan 2019 is 6.1.2. It also works on Windows 7 SP1.
If you've got V3, you can take advantage of auto-enumeration, the -Raw switch in Get-Content, and some of the new line contiunation syntax to simply it to this, using the string .replace() method instead of the -replace operator:
(Get-ChildItem "[FILEPATH]" -recurse).FullName |
Foreach-Object {
(Get-Content $_ -Raw).
Replace('abt7d9epp4','w2svuzf54f').
Replace('AccountName=adtestnego','AccountName=zadtestnego').
Replace('AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','AccountKey=DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA==') |
Set-Content $_
}
Using the .replace() method uses literal strings for the replaced text argument (not regex), so you don't need to worry about escaping regex metacharacters in the text-to-replace argument.
You can try dirTimesJS.bat and fileTimesJS.bat
example:
C:\>dirTimesJS.bat %windir%
directory timestamps for C:\Windows :
Modified : 2020-11-22 22:12:55
Modified - milliseconds passed : 1604607175000
Modified day of the week : 4
Created : 2019-12-11 11:03:44
Created - milliseconds passed : 1575709424000
Created day of the week : 6
Accessed : 2020-11-16 16:39:22
Accessed - milliseconds passed : 1605019162000
Accessed day of the week : 2
C:\>fileTimesJS.bat %windir%\notepad.exe
file timestamps for C:\Windows\notepad.exe :
Modified : 2020-09-08 08:33:31
Modified - milliseconds passed : 1599629611000
Modified day of the week : 3
Created : 2020-09-08 08:33:31
Created - milliseconds passed : 1599629611000
Created day of the week : 3
Accessed : 2020-11-23 23:59:22
Accessed - milliseconds passed : 1604613562000
Accessed day of the week : 4
Windows PowerShell
Copyright (C) 2014 Microsoft Corporation. All rights reserved.
PS C:\Windows\system32> **$dte = Get-Date**
PS C:\Windows\system32> **$PastDueDate = $dte.AddDays(-45).Date**
PS C:\Windows\system32> **$PastDueDate**
Sunday, March 1, 2020 12:00:00 AM
PS C:\Windows\system32> **$NewDateFormat = Get-Date $PastDueDate -Format MMddyyyy**
PS C:\Windows\system32> **$NewDateFormat 03012020**
There're few additional methods available as well e.g.: $dte.AddDays(-45).Day
a simple way:
in view(pass the id value):
<td><?php echo anchor('textarea/delete_row?id='.$row->id, 'DELETE', 'id="$row->id"'); ?></td>
in controller(receive the id):
$id = $this->input->get('id');
$this->load->model('mod1');
$this->mod1->row_delete($id);
in model(get the passed args):
function row_delete($id){}
Actually, you should use the ajax to POST the id value to controller and delete the row, not the GET.
I had the same challenge. This is the solution I found to add users to roles.
internal class Security
{
ApplicationDbContext context = new ApplicationDbContext();
internal void AddUserToRole(string userName, string roleName)
{
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
try
{
var user = UserManager.FindByName(userName);
UserManager.AddToRole(user.Id, roleName);
context.SaveChanges();
}
catch
{
throw;
}
}
}
Go to Python Website/dowloads/windows. Download Windows x86-64 embeddable zip file. 2. Open Windows Explorer
open zipped folder python-3.7.0 In the windows toolbar with the Red flair saying “Compressed Folder Tool” Press “Extract” button on the tool bar with “File” “Home “Share” “View” Select Extract all Extraction process is not covered yet Once extracted save onto SDD or fastest memory device. Not usb. HDD is fine. SDD Users/butte/ProgramFiles blah blah ooooor D:\Python Or Hook up to your cloud 3. Click your User Icon in the Windows tool bar.
Search environment variable Proceed with progressing with “Environment Variables” button press Under the “user variables” table select “New..” After the Canvas of Information Add Python in Variable Name Select the “D:\Python\python-3.7.0-embed-amd64\python.exe;” click ok Under the “System Variables” label and in the Canvas the first row has a value marked “Path” Select “Edit” when “Path” is highlighted. Select “New” Enter D:\Python\python-3.7.0-embed-amd click ok Ok Save and double check Open Power Shell python --help
python --version
Source to tutorial https://thedishbunnybitch.com/2018/08/11/installing-python-on-windows-10-for-powershell/
Posted it also here: How to run powershell command in batch file
Following this thread:
https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/converting-powershell-to-batch
you can convert any PowerShell script into a batch file easily using this PowerShell function:
function Convert-PowerShellToBatch
{
param
(
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
[string]
[Alias("FullName")]
$Path
)
process
{
$encoded = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes((Get-Content -Path $Path -Raw -Encoding UTF8)))
$newPath = [Io.Path]::ChangeExtension($Path, ".bat")
"@echo off`npowershell.exe -NoExit -encodedCommand $encoded" | Set-Content -Path $newPath -Encoding Ascii
}
}
To convert all PowerShell scripts inside a directory, simply run the following command:
Get-ChildItem -Path <DIR-PATH> -Filter *.ps1 |
Convert-PowerShellToBatch
Where is the path to the desired folder. For instance:
Get-ChildItem -Path "C:\path\to\powershell\scripts" -Filter *.ps1 |
Convert-PowerShellToBatch
To convert a single PowerShell script, simply run this:
Get-ChildItem -Path <FILE-PATH> |
Convert-PowerShellToBatch
Where is the path to the desired file.
The converted files are located in the source directory. i.e., <FILE-PATH> or <DIR-PATH>.
Putting it all together:
create a .ps1 file (PowerShell script) with the following code in it:
function Convert-PowerShellToBatch
{
param
(
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
[string]
[Alias("FullName")]
$Path
)
process
{
$encoded = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes((Get-Content -Path $Path -Raw -Encoding UTF8)))
$newPath = [Io.Path]::ChangeExtension($Path, ".bat")
"@echo off`npowershell.exe -NoExit -encodedCommand $encoded" | Set-Content -Path $newPath -Encoding Ascii
}
}
# change <DIR> to the path of the folder in which the desired powershell scripts are.
# the converted files will be created in the destination path location (in <DIR>).
Get-ChildItem -Path <DIR> -Filter *.ps1 |
Convert-PowerShellToBatch
And don't forget, if you wanna convert only one file instead of many, you can replace the following
Get-ChildItem -Path <DIR> -Filter *.ps1 |
Convert-PowerShellToBatch
with this:
Get-ChildItem -Path <FILE-PATH> |
Convert-PowerShellToBatch
as I explained before.
This assumes that the content is in column B on each sheet (since it's not clear how you determine the column on each sheet.) and the last row of that column is also the last row of the sheet.
$xlCellTypeLastCell = 11
$startRow = 5
$col = 2
$excel = New-Object -Com Excel.Application
$wb = $excel.Workbooks.Open("C:\Users\Administrator\my_test.xls")
for ($i = 1; $i -le $wb.Sheets.Count; $i++)
{
$sh = $wb.Sheets.Item($i)
$endRow = $sh.UsedRange.SpecialCells($xlCellTypeLastCell).Row
$city = $sh.Cells.Item($startRow, $col).Value2
$rangeAddress = $sh.Cells.Item($startRow + 1, $col).Address() + ":" + $sh.Cells.Item($endRow, $col).Address()
$sh.Range($rangeAddress).Value2 | foreach
{
New-Object PSObject -Property @{ City = $city; Area = $_ }
}
}
$excel.Workbooks.Close()
In the code below, Class A
implements the interface IShow
and implements its method ShowData
. Class B
inherits Class A
. In order to use ShowData
method in Class B
, we have to use keyword new
in the ShowData
method in order to hide the base class Class A
method and use override
keyword in order to extend the method.
interface IShow
{
protected void ShowData();
}
class A : IShow
{
protected void ShowData()
{
Console.WriteLine("This is Class A");
}
}
class B : A
{
protected new void ShowData()
{
Console.WriteLine("This is Class B");
}
}
This may be an old post, but if anyone is still facing this issue after trying all the above mentioned steps, ensure whether the default path of PowerShell module is specified under the "PSModulePath" environment variable.
The default path should be "%SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\"
This is really old, but I wanted to add my slight variation for anyone else who may stumble across this. Regular expressions are powerful things.
To keep the text which falls between the equal sign and the comma:
-replace "^.*?=(.*?),.*?$",'$1'
This regular expression starts at the beginning of the line, wipes all characters until the first equal sign, captures every character until the next comma, then wipes every character until the end of the line. It then replaces the entire line with the capture group (anything within the parentheses). It will match any line that contains at least one equal sign followed by at least one comma. It is similar to the suggestion by Trix, but unlike that suggestion, this will not match lines which only contain either an equal sign or a comma, it must have both in order.
Use the same XML file format from Evan's answer, but one drawable file is all you need for formatting.
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/custom_button_background"
android:button="@android:color/transparent"
android:checked="true"
android:text="RadioButton1" />
And your separate drawable file:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" >
<shape android:shape="rectangle" >
<corners android:radius="3dip" />
<stroke android:width="1dip" android:color="#333333" />
<solid android:color="#cccccc" />
</shape>
</item>
<item android:state_checked="true">
<shape android:shape="rectangle" >
<corners android:radius="3dip" />
<stroke android:width="1dip" android:color="#333333" />
<solid android:color="#cccccc" />
</shape>
</item>
<item>
<shape android:shape="rectangle" >
<corners android:radius="3dip" />
<stroke android:width="1dip" android:color="#cccccc" />
<solid android:color="#ffffff" />
</shape>
</item>
</selector>
set datestr=%date%
set result=%datestr:/=-%
@echo %result%
pause
This is a state-of-the-union answer as of Windows PowerShell v5.1 / PowerShell Core v6.2.0:
Andrew Savinykh's ill-fated answer, despite being the accepted one, is, as of this writing, fundamentally flawed (I do hope it gets fixed - there's enough information in the comments - and in the edit history - to do so).
Ansgar Wiecher's helpful answer works well, but requires direct use of the .NET Framework (and reads the entire file into memory, though that could be changed). Direct use of the .NET Framework is not a problem per se, but is harder to master for novices and hard to remember in general.
A future version of PowerShell Core will have a
Convert-TextFile
cmdlet with a -LineEnding
parameter to allow in-place updating of text files with a specific newline style, as being discussed on GitHub.
In PSv5+, PowerShell-native solutions are now possible, because Set-Content
now supports the -NoNewline
switch, which prevents undesired appending of a platform-native newline[1]
:
# Convert CRLFs to LFs only.
# Note:
# * (...) around Get-Content ensures that $file is read *in full*
# up front, so that it is possible to write back the transformed content
# to the same file.
# * + "`n" ensures that the file has a *trailing LF*, which Unix platforms
# expect.
((Get-Content $file) -join "`n") + "`n" | Set-Content -NoNewline $file
The above relies on Get-Content
's ability to read a text file that uses any combination of CR-only, CRLF, and LF-only newlines line by line.
Caveats:
You need to specify the output encoding to match the input file's in order to recreate it with the same encoding. The command above does NOT specify an output encoding; to do so, use -Encoding
; without -Encoding
:
The input file's content as well as its transformed copy must fit into memory as a whole, which can be problematic with large input files.
There's a risk of file corruption, if the process of writing back to the input file gets interrupted.
[1] In fact, if there are multiple strings to write, -NoNewline
also doesn't place a newline between them; in the case at hand, however, this is irrelevant, because only one string is written.
Your sample code seems to be OK. Thus, the root problem needs to be dug up somehow. Let's eliminate chance for typos in the script. First off, make sure you put Set-Strictmode -Version 2.0
in the beginning of your script. This will help you to catch misspelled variable names. Like so,
# Test.ps1
set-strictmode -version 2.0 # Comment this line and no error will be reported.
$foo = "bar"
set-content -path ./test.txt -value $fo # Error! Should be "$foo"
PS C:\temp> .\test.ps1
The variable '$fo' cannot be retrieved because it has not been set.
At C:\temp\test.ps1:3 char:40
+ set-content -path ./test.txt -value $fo <<<<
+ CategoryInfo : InvalidOperation: (fo:Token) [], RuntimeException
+ FullyQualifiedErrorId : VariableIsUndefined
The next part about question marks sounds like you have a problem with Unicode. What's the output when you type the file with Powershell like so,
$file = "\\server\share\file.txt"
cat $file
Here is the full working code to download all files (with wildcard or file extension) from the FTP site to local directory. Set the variable values.
#FTP Server Information - SET VARIABLES
$ftp = "ftp://XXX.com/"
$user = 'UserName'
$pass = 'Password'
$folder = 'FTP_Folder'
$target = "C:\Folder\Folder1\"
#SET CREDENTIALS
$credentials = new-object System.Net.NetworkCredential($user, $pass)
function Get-FtpDir ($url,$credentials) {
$request = [Net.WebRequest]::Create($url)
$request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
if ($credentials) { $request.Credentials = $credentials }
$response = $request.GetResponse()
$reader = New-Object IO.StreamReader $response.GetResponseStream()
while(-not $reader.EndOfStream) {
$reader.ReadLine()
}
#$reader.ReadToEnd()
$reader.Close()
$response.Close()
}
#SET FOLDER PATH
$folderPath= $ftp + "/" + $folder + "/"
$files = Get-FTPDir -url $folderPath -credentials $credentials
$files
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
$counter = 0
foreach ($file in ($files | where {$_ -like "*.txt"})){
$source=$folderPath + $file
$destination = $target + $file
$webclient.DownloadFile($source, $target+$file)
#PRINT FILE NAME AND COUNTER
$counter++
$counter
$source
}
Here's what I use. If it fails to pretty print the JSON it just returns the original string. Useful for printing HTTP responses that should contain JSON.
import (
"encoding/json"
"bytes"
)
func jsonPrettyPrint(in string) string {
var out bytes.Buffer
err := json.Indent(&out, []byte(in), "", "\t")
if err != nil {
return in
}
return out.String()
}
The -Contains
operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections.
From the documentation you linked to:
-Contains Description: Containment operator. Tells whether a collection of reference values includes a single test value.
In the example you provided you're working with a collection containing just one string item.
If you read the documentation you linked to you'll see an example that demonstrates this behaviour:
Examples:
PS C:\> "abc", "def" -Contains "def"
True
PS C:\> "Windows", "PowerShell" -Contains "Shell"
False #Not an exact match
I think what you want is the -Match
operator:
"12-18" -Match "-"
Which returns True
.
Important: As pointed out in the comments and in the linked documentation, it should be noted that the -Match
operator uses regular expressions to perform text matching.
To get the content of a directory you can use
$files = Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files\"
Then you can loop over this variable as well:
for ($i=0; $i -lt $files.Count; $i++) {
$outfile = $files[$i].FullName + "out"
Get-Content $files[$i].FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}
An even easier way to put this is the foreach
loop (thanks to @Soapy and @MarkSchultheiss):
foreach ($f in $files){
$outfile = $f.FullName + "out"
Get-Content $f.FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}
Try redirecting the output like this:
$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose >$null 2>&1
You can do it in two different ways.
Option 1: The -eq
operator
>$a = "is"
>$b = "fission"
>$c = "is"
>$a -eq $c
True
>$a -eq $b
False
Option 2: The .Equals()
method of the string
object. Because strings in PowerShell are .Net System.String
objects, any method of that object can be called directly.
>$a.equals($b)
False
>$a.equals($c)
True
>$a|get-member -membertype method
List of System.String
methods follows.
You have to dot source
them:
. .\build_funtions.ps1
. .\build_builddefs.ps1
Note the extra .
This heyscriptingguy
article should be of help - How to Reuse Windows PowerShell Functions in Scripts
Something like this should work (it did for me). The reason for wanting to use -Filter
instead of -Include
is that include takes a huge performance hit compared to -Filter
.
Below just loops each file type and multiple servers/workstations specified in separate files.
##
## This script will pull from a list of workstations in a text file and search for the specified string
## Change the file path below to where your list of target workstations reside
## Change the file path below to where your list of filetypes reside
$filetypes = gc 'pathToListOffiletypes.txt'
$servers = gc 'pathToListOfWorkstations.txt'
##Set the scope of the variable so it has visibility
set-variable -Name searchString -Scope 0
$searchString = 'whatYouAreSearchingFor'
foreach ($server in $servers)
{
foreach ($filetype in $filetypes)
{
## below creates the search path. This could be further improved to exclude the windows directory
$serverString = "\\"+$server+"\c$\Program Files"
## Display the server being queried
write-host “Server:” $server "searching for " $filetype in $serverString
Get-ChildItem -Path $serverString -Recurse -Filter $filetype |
#-Include "*.xml","*.ps1","*.cnf","*.odf","*.conf","*.bat","*.cfg","*.ini","*.config","*.info","*.nfo","*.txt" |
Select-String -pattern $searchstring | group path | select name | out-file f:\DataCentre\String_Results.txt
$os = gwmi win32_operatingsystem -computer $server
$sp = $os | % {$_.servicepackmajorversion}
$a = $os | % {$_.caption}
## Below will list again the server name as well as its OS and SP
## Because the script may not be monitored, this helps confirm the machine has been successfully scanned
write-host $server “has completed its " $filetype "scan:” “|” “OS:” $a “SP:” “|” $sp
}
}
#end script
Would this do what you want?:
& "C:\Windows Services\MyService.exe"
Use &
, the call operator, to invoke commands whose names or paths are stored in quoted strings and/or are referenced via variables, as in the accepted answer. Invoke-Expression
is not only the wrong tool to use in this particular case, it should generally be avoided.
You can also do it without the [xml] cast. (Although xpath is a world unto itself. https://www.w3schools.com/xml/xml_xpath.asp)
$xml = (select-xml -xpath / -path stack.xml).node
$xml.objects.object.property
Or just this, xpath is case sensitive. Both have the same output:
$xml = (select-xml -xpath /Objects/Object/Property -path stack.xml).node
$xml
Name Type #text
---- ---- -----
DisplayName System.String SQL Server (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Running
DisplayName System.String SQL Server Agent (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Stopped
Here is a simple way to loop any number of times in PowerShell.
It is the same as the for
loop above, but much easier to understand for newer programmers and scripters. It uses a range, and foreach. A range is defined as:
range = lower..upper
or
$range = 1..10
A range can be used directly in a for
loop as well, although not the most optimal approach, any performance loss or additional instruction to process would be unnoticeable. The solution is below:
foreach($i in 1..10){
Write-Host $i
}
Or in your case:
$ActiveCampaigns = 10
foreach($i in 1..$ActiveCampaigns)
{
Write-Host $i
If($i==$ActiveCampaigns){
// Do your stuff on the last iteration here
}
}
Use the Out-File
cmdlet
Compare-Object ... | Out-File C:\filename.txt
Optionally, add -Encoding utf8
to Out-File
as the default encoding is not really ideal for many uses.
No need to update gradle for making release application in Android studio.If you were eclipse user then it will be so easy for you. If you are new then follow the steps
1: Go to the "Build" at the toolbar section. 2: Choose "Generate Signed APK..." option.
3:fill opened form and go next 4 :if you already have .keystore or .jks then choose that file enter your password and alias name and respective password. 5: Or don't have .keystore or .jks file then click on Create new... button as shown on pic 1 then fill the form.
Above process was to make build manually. If You want android studio to automatically Signing Your App
In Android Studio, you can configure your project to sign your release APK automatically during the build process:
On the project browser, right click on your app and select Open Module Settings. On the Project Structure window, select your app's module under Modules. Click on the Signing tab. Select your keystore file, enter a name for this signing configuration (as you may create more than one), and enter the required information. Figure 4. Create a signing configuration in Android Studio.
Click on the Build Types tab. Select the release build. Under Signing Config, select the signing configuration you just created. Figure 5. Select a signing configuration in Android Studio.
4:Most Important thing that make debuggable=false at gradle.
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard- android.txt'), 'proguard-rules.txt'
debuggable false
jniDebuggable false
renderscriptDebuggable false
zipAlignEnabled true
}
}
visit for more in info developer.android.com
Maybe powershell -Command "Get-AppLockerFileInformation....."
Take a look at powershell /?
string userName="";
string userId = "";
int uid = 0;
if (HttpContext.Current != null && HttpContext.Current.User != null
&& HttpContext.Current.User.Identity.Name != null)
{
userName = HttpContext.Current.User.Identity.Name;
}
using (DevEntities context = new DevEntities())
{
uid = context.Users.Where(x => x.UserName == userName).Select(x=>x.Id).FirstOrDefault();
return uid;
}
return uid;
By default Entity Framework uses lazy-loading for navigation properties. That's why these properties should be marked as virtual - EF creates proxy class for your entity and overrides navigation properties to allow lazy-loading. E.g. if you have this entity:
public class MemberLoan
{
public string LoandProviderCode { get; set; }
public virtual Membership Membership { get; set; }
}
Entity Framework will return proxy inherited from this entity and provide DbContext instance to this proxy in order to allow lazy loading of membership later:
public class MemberLoanProxy : MemberLoan
{
private CosisEntities db;
private int membershipId;
private Membership membership;
public override Membership Membership
{
get
{
if (membership == null)
membership = db.Memberships.Find(membershipId);
return membership;
}
set { membership = value; }
}
}
So, entity has instance of DbContext which was used for loading entity. That's your problem. You have using
block around CosisEntities usage. Which disposes context before entities are returned. When some code later tries to use lazy-loaded navigation property, it fails, because context is disposed at that moment.
To fix this behavior you can use eager loading of navigation properties which you will need later:
IQueryable<MemberLoan> query = db.MemberLoans.Include(m => m.Membership);
That will pre-load all memberships and lazy-loading will not be used. For details see Loading Related Entities article on MSDN.
An example is this: You have a string and the character $
String :
aaaaa$bbbbb$ccccc
Code:
SELECT SUBSTRING('aaaaa$bbbbb$ccccc',CHARINDEX('$','aaaaa$bbbbb$ccccc')+1, CHARINDEX('$','aaaaa$bbbbb$ccccc',CHARINDEX('$','aaaaa$bbbbb$ccccc')+1) -CHARINDEX('$','aaaaa$bbbbb$ccccc')-1) as My_String
Output:
bbbbb
Change your Action to:
powershell -noprofile -executionpolicy bypass -file C:\path\event4740.ps1
On a Windows 2008 server R2: In Task Scheduler under the General Tab - Make sure the 'Run As' user is set to an account with the right permissions it takes to execute the script.
Also, I believe you have the "Run only when user is logged on" Option checked off. Change that to "Run whether user is logged on or not". Leave the Do Not Store password option unchecked, and you'll probably need the "Run with Highest Privileges" option marked.
The issue here is your version of AngularJS; ng-attr
is not working due to the fact that it was introduced in version 1.1.4. I am unsure as to why title="{{product.shortDesc}}"
isn't working for you, but I imagine it is for similar reasons (old Angular version). I tested this on 1.2.9 and it is working for me.
As for the other answers here, this is NOT among the few use cases for ng-attr
! This is a simple double-curly-bracket situation:
<a title="{{product.shortDesc}}" ng-bind="product.shortDesc" />
One thing that I have observed is likely the email address you're providing is not a valid email address at the domain. like [email protected]. The email should be existing at Google Domain. I had alot of issues before figuring that out myself... Hope it helps.
You can use Invoke-RDUserLogoff
An example logging off Active Directory users of a specific Organizational Unit:
$users = Get-ADUser -filter * -SearchBase "ou=YOUR_OU_NAME,dc=contoso,dc=com"
Get-RDUserSession | where { $users.sAMAccountName -contains $_.UserName } | % { $_ | Invoke-RDUserLogoff -Force }
At the end of the pipe, if you try to use only foreach (%), it will log off only one user. But using this combination of foreach and pipe:
| % { $_ | command }
will work as expected.
Ps. Run as Adm.
Use mavenCentral()
or jcenter()
adding in the build.gradle
file the script:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
}
}
I also had the same problem. In starting, it was working fine then, but sometime later I uninstalled my application completely from my device (I was running it on my mobile) and ran it again, and it shows me the same error.
I had all lib and resources included as it was working, but still I was getting this error so I removed all references and lib from my project build, updated google service play to revision 10, uninstalled application completely from the device and then again added all resources and libs and ran it and it started working again.
One thing to note here is while running I am still seeing this error message in my LogCat, but on my device it is working fine now.
I whole-heartedly agree with zzzz's type assertion answer and I strongly prefer that way over others. That said, here's what I've had to do when the preferred method has not worked... (long story related to cross-serialization of data). You can even chain this into a switch
statement with case errInt == nil
and similar expressions.
package main
import "fmt"
import "strconv"
func main() {
var v interface{}
v = "4"
i, errInt := strconv.ParseInt(v.(string), 10, 64)
if errInt == nil {
fmt.Printf("%d is a int", i)
/* do what you wish with "i" here */
}
}
Like I said above, try type assertion first before trying this way.
First step is to load your xml string into an XmlDocument, using powershell's unique ability to cast strings to [xml]
$doc = [xml]@'
<xml>
<Section name="BackendStatus">
<BEName BE="crust" Status="1" />
<BEName BE="pizza" Status="1" />
<BEName BE="pie" Status="1" />
<BEName BE="bread" Status="1" />
<BEName BE="Kulcha" Status="1" />
<BEName BE="kulfi" Status="1" />
<BEName BE="cheese" Status="1" />
</Section>
</xml>
'@
Powershell makes it really easy to parse xml with the dot notation. This statement will produce a sequence of XmlElements for your BEName elements:
$doc.xml.Section.BEName
Then you can pipe these objects into the where-object cmdlet to filter down the results. You can use ? as a shortcut for where
$doc.xml.Section.BEName | ? { $_.Status -eq 1 }
The expression inside the braces will be evaluated for each XmlElement in the pipeline, and only those that have a Status of 1 will be returned. The $_ operator refers to the current object in the pipeline (an XmlElement).
If you need to do something for every object in your pipeline, you can pipe the objects into the foreach-object cmdlet, which executes a block for every object in the pipeline. % is a shortcut for foreach:
$doc.xml.Section.BEName | ? { $_.Status -eq 1 } | % { $_.BE + " is delicious" }
Powershell is great at this stuff. It's really easy to assemble pipelines of objects, filter pipelines, and do operations on each object in the pipeline.
You can remove the "bullets" by setting the "list-style-type: none;" Like
ul
{
list-style-type: none;
}
OR
<ul class="menu custompozition4" style="list-style-type: none;">
<li class="item-507"><a href=#">Strategic Recruitment Solutions</a>
</li>
<li class="item-508"><a href="#">Executive Recruitment</a>
</li>
<li class="item-509"><a href="#">Leadership Development</a>
</li>
<li class="item-510"><a href="#">Executive Capability Review</a>
</li>
<li class="item-511"><a href="#">Board and Executive Coaching</a>
</li>
<li class="item-512"><a href="#">Cross Cultutral Coaching</a>
</li>
<li class="item-513"><a href="#">Team Enhancement & Coaching</a>
</li>
<li class="item-514"><a href="#">Personnel Re-deployment</a>
</li>
</ul>
I had this problem because I tried to use both support library and appcompat:
dependencies {
compile fileTree(dir: 'libs', include: '*.jar')
compile 'com.android.support:support-v4:23.1.0'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.google.android.gms:play-services:8.3.0'
}
After I deleted support library and changed to older version, it compiled:
dependencies {
compile fileTree(dir: 'libs', include: '*.jar')
/*compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'*/
compile 'com.android.support:appcompat-v7:22.2.0'
compile 'com.android.support:design:22.2.0'
compile 'com.google.android.gms:play-services:8.3.0'
}
Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.
That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...
What version of the SQL Server engine do you get from SELECT @@VERSION
??
you are a PyCharm User, its good easy to install Flask First open the pycharm press Open Settings(Ctrl+Alt+s) Goto Project Interpreter
Double click pip>>
search bar (top of page) you search the flask and click install package
such Cases in which flask is not shown in pip: Open Manage Repository>> Add(+) >> Add this following url
https://www.palletsprojects.com/p/flask/
Now back to pip, it will show related packages of flask,
select flask>>
install package
For IntelliJ IDEA or Android Studio:
Add this to app.gradle build file
dependencies {
compile "com.android.support:appcompat-v7:21.0.+"
}
Replace -v:xx.0+
, with your build target, if you have 19 platform
then it must be like:
dependencies {
compile "com.android.support:appcompat-v7:19.0.+"
}
function Do-SendKeys {
param (
$SENDKEYS,
$WINDOWTITLE
)
$wshell = New-Object -ComObject wscript.shell;
IF ($WINDOWTITLE) {$wshell.AppActivate($WINDOWTITLE)}
Sleep 1
IF ($SENDKEYS) {$wshell.SendKeys($SENDKEYS)}
}
Do-SendKeys -WINDOWTITLE Print -SENDKEYS '{TAB}{TAB}'
Do-SendKeys -WINDOWTITLE Print
Do-SendKeys -SENDKEYS '%{f4}'
one time i found this script, this copy folder and files and keep the same structure of the source in the destination, you can make some tries with this.
# Find the source files
$sourceDir="X:\sourceFolder"
# Set the target file
$targetDir="Y:\Destfolder\"
Get-ChildItem $sourceDir -Include *.* -Recurse | foreach {
# Remove the original root folder
$split = $_.Fullname -split '\\'
$DestFile = $split[1..($split.Length - 1)] -join '\'
# Build the new destination file path
$DestFile = $targetDir+$DestFile
# Move-Item won't create the folder structure so we have to
# create a blank file and then overwrite it
$null = New-Item -Path $DestFile -Type File -Force
Move-Item -Path $_.FullName -Destination $DestFile -Force
}
Try this:
dir C:\PURGE -recurse |
where { ((get-date)-$_.creationTime).days -gt 15 } |
remove-item -force
You can use:
msiexec /i "c:\package.msi"
You can also add some more optional parameters. There are common msi parameters and parameters which are specific for your installer. For common parameters just call msiexec
This topic really helped me, so I'd like to share my improvements. All credits go to the nixda, this is based on his answer.
For those who need to convert multiple csv's in a folder, just modify the directory. Outputfilenames will be identical to input, just with another extension.
Take care of the cleanup in the end, if you like to keep the original csv's you might not want to remove these.
Can be easily modifed to save the xlsx in another directory.
$workingdir = "C:\data\*.csv"
$csv = dir -path $workingdir
foreach($inputCSV in $csv){
$outputXLSX = $inputCSV.DirectoryName + "\" + $inputCSV.Basename + ".xlsx"
### Create a new Excel Workbook with one empty sheet
$excel = New-Object -ComObject excel.application
$excel.DisplayAlerts = $False
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)
### Build the QueryTables.Add command
### QueryTables does the same as when clicking "Data » From Text" in Excel
$TxtConnector = ("TEXT;" + $inputCSV)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)
### Set the delimiter (, or ;) according to your regional settings
### $Excel.Application.International(3) = ,
### $Excel.Application.International(5) = ;
$query.TextFileOtherDelimiter = $Excel.Application.International(5)
### Set the format to delimited and text for every column
### A trick to create an array of 2s is used with the preceding comma
$query.TextFileParseType = 1
$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1
### Execute & delete the import query
$query.Refresh()
$query.Delete()
### Save & close the Workbook as XLSX. Change the output extension for Excel 2003
$Workbook.SaveAs($outputXLSX,51)
$excel.Quit()
}
## To exclude an item, use the '-exclude' parameter (wildcards if needed)
remove-item -path $workingdir -exclude *Crab4dq.csv
I'd like to make a note of this for people referencing in the future.
I wanted to avoid WMI because it uses a DCOM protocol, requiring the remote computer to have the necessary permissions, which could only be setup manually on that remote computer.
So, I wanted to avoid using WMI, but using get-counter often times didn't have the performance counter I wanted.
The solution I used was the Common Information Model (CIM). Unlike WMI, CIM doesn't use DCOM by default. Instead of returning WMI objects, CIM cmdlets return PowerShell objects.
CIM uses the Ws-MAN protocol by default, but it only works with computers that have access to Ws-Man 3.0 or later. So, earlier versions of PowerShell wouldn't be able to issue CIM cmdlets.
The cmdlet I ended up using to get total physical memory size was:
get-ciminstance -class "cim_physicalmemory" | % {$_.Capacity}
I wish the Lukas Olsen solution works for other scenarios, But in my case is quite different.
I faced the same while add ActionBarShelock to project, by comparing to the older library I found that application tag is missing in manifest. By adding one line I fixed my issue.
</application>
PowerShell 3 has the $PSScriptRoot
automatic variable:
Contains the directory from which a script is being run.
In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.
Don't be fooled by the poor wording. PSScriptRoot
is the directory of the current file.
In PowerShell 2, you can calculate the value of $PSScriptRoot
yourself:
# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
You can use the Environment class's static NewLine property to get the proper newline:
$errorMsg = "{0} Error {1}{2} key {3} expected: {4}{5} local value is: {6}" -f `
(Get-Date),$keyPath,$value,$key,$policyValue,([Environment]::NewLine),$localValue
Add-Content -Path $logpath $errorMsg
Bootstrap 3 dropped native support for nested collapsing menus, but there's a way to re-enable it with a 3rd party script. It's called SmartMenus. It means adding three new resources to your page, but it seamlessly supports Bootstrap 3.x with multiple levels of menus for nested <ul>/<li>
elements with class="dropdown-menu"
. It automatically displays the proper caret indicator as well.
<head>
...
<script src=".../jquery.smartmenus.min.js"></script>
<script src=".../jquery.smartmenus.bootstrap.min.js"></script>
...
<link rel="stylesheet" href=".../jquery.smartmenus.bootstrap.min.css"/>
...
</head>
Here's a demo page: http://vadikom.github.io/smartmenus/src/demo/bootstrap-navbar-fixed-top.html
I had to create an array of a predefined type, and I successfully did as follows:
[System.Data.DataColumn[]]$myitems = ([System.Data.DataColumn]("col1"),
[System.Data.DataColumn]("col2"), [System.Data.DataColumn]("col3"))
public static class HelperExtensions
{
//Convert Image to byte[] array:
public static byte[] ToByteArray(this Image imageIn)
{
var ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
//Convert byte[] array to Image:
public static Image ToImage(this byte[] byteArrayIn)
{
var ms = new MemoryStream(byteArrayIn);
var returnImage = Image.FromStream(ms);
return returnImage;
}
}
I was not even concentrating, here is how to do it
$DOCDIR = [Environment]::GetFolderPath("MyDocuments")
$TARGETDIR = '$DOCDIR\MatchedLog'
if(!(Test-Path -Path $TARGETDIR )){
New-Item -ItemType directory -Path $TARGETDIR
}
Get-ADGroupMember "Group1" -recursive | Select-Object Name | Export-Csv c:\path\Groups.csv
I got this to work for me... I would assume that you could put "Group1, Group2, etc." or try a wildcard. I did pre-load AD into PowerShell before hand:
Get-Module -ListAvailable | Import-Module
You need upper case property names in your structs in order to be used by the json packages.
Upper case property names are exported properties
. Lower case property names are not exported.
You also need to pass the your data object by reference (&data
).
package main
import "os"
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"
type tracks struct {
Toptracks []toptracks_info
}
type toptracks_info struct {
Track []track_info
Attr []attr_info
}
type track_info struct {
Name string
Duration string
Listeners string
Mbid string
Url string
Streamable []streamable_info
Artist []artist_info
Attr []track_attr_info
}
type attr_info struct {
Country string
Page string
PerPage string
TotalPages string
Total string
}
type streamable_info struct {
Text string
Fulltrack string
}
type artist_info struct {
Name string
Mbid string
Url string
}
type track_attr_info struct {
Rank string
}
func get_content() {
// json data
url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
res, err := http.Get(url)
if err != nil {
panic(err.Error())
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err.Error())
}
var data tracks
json.Unmarshal(body, &data)
fmt.Printf("Results: %v\n", data)
os.Exit(0)
}
func main() {
get_content()
}
(Get-Content file.txt) |
Foreach-Object {$_ -replace '\[MYID\]','MyValue'} |
Out-File file.txt
Note the parentheses around (Get-Content file.txt)
is required:
Without the parenthesis the content is read, one line at a time, and flows down the pipeline until it reaches out-file or set-content, which tries to write to the same file, but it's already open by get-content and you get an error. The parenthesis causes the operation of content reading to be performed once (open, read and close). Only then when all lines have been read, they are piped one at a time and when they reach the last command in the pipeline they can be written to the file. It's the same as $content=content; $content | where ...
As of PowerShell 2, simple:
$recipients = $addresses -split "; "
Note that the right hand side is actually a case-insensitive regular expression, not a simple match. Use csplit
to force case-sensitivity. See about_Split for more details.
Try the -Force
parameter:
New-Item -ItemType Directory -Force -Path C:\Path\That\May\Or\May\Not\Exist
You can use Test-Path -PathType Container
to check first.
See the New-Item MSDN help article for more details.
Just another performance imporvement tip:
Android Studio 3.0 includes new DEX compiler called D8.
"The dex compiler mostly works under the hood in your day-to-day app development, but it directly impacts your app's build time, .dex file size, and runtime performance."
"And when comparing the new D8 compiler with the current DX compiler, D8 compiles faster and outputs smaller .dex files, while having the same or better app runtime performance."
D8 is optional - do use it we have to put to project's gradle.properties
android.enableD8=true
More informations: https://android-developers.googleblog.com/2017/08/next-generation-dex-compiler-now-in.html
PS. It impove my build time by about 30%.
UPDATE ANDROID STUDIO 3.4
So I figured out what is wrong with this statement:
Import-Csv H:\Programs\scripts\SomeText.csv |`
(Original)
Import-Csv H:\Programs\scripts\SomeText.csv -Delimiter "|"
(Proposed, You must use quotations; otherwise, it will not work and ISE will give you an error)
It requires the -Delimiter "|"
, in order for the variable to be populated with an array of items. Otherwise, Powershell ISE does not display the list of items.
I cannot say that I would recommend the |
operator, since it is used to pipe cmdlets into one another.
I still cannot get the if statement to return true and output the values entered via the prompt.
If anyone else can help, it would be great. I still appreciate the post, it has been very helpful!
This also seems to do it. PS Example:
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
Here's the code with parameter labels
def draw_text(self, frame, text, x, y, color=BGR_COMMON['green'], thickness=1.3, size=0.3,):
if x is not None and y is not None:
cv2.putText(
frame, text, (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, size, color, thickness)
For font name please see another answer in this thread.
Excerpt from answer by @Roeffus
This is indeed a bit of an annoying problem. For python 2.x.x you use:
cv2.CV_FONT_HERSHEY_SIMPLEX and for Python 3.x.x:
cv2.FONT_HERSHEY_SIMPLEX
For more see this http://www.programcreek.com/python/example/83399/cv2.putText
Take your pick:
$ cat file
eth0 Link encap:Ethernet HWaddr 08:00:27:a3:e3:b0
inet addr:192.168.1.103 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::a00:27ff:fea3:e3b0/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1904 errors:0 dropped:0 overruns:0 frame:0
TX packets:2002 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1309425 (1.2 MiB) T
$ awk 'sub(/inet addr:/,""){print $1}' file
192.168.1.103
$ awk -F'[ :]+' '/inet addr/{print $4}' file
192.168.1.103
I'm facing same issue. Solved it using by http://
or https://
in react js.
Like as:
<a target="_blank" href="http://www.example.com/" title="example">See detail</a>
There are some great example already given here. Just adding a simple example to push associative array elements to root numeric index index.
`$intial_content = array();
if (true) {
$intial_content[] = array('name' => 'xyz', 'content' => 'other content');
}`
It sounds like you're doing something wrong to me - a whole lotta object creation going on.
How representative is that "test" file? What are you really doing with that data? If that's typical of what you really have, I'd say there's lots of repetition in that data.
If it's all going to be in Strings anyway, start with a BufferedReader to read each line. Pre-allocate that List to a size that's close to what you need so you don't waste resources adding to it each time. Split each of those lines at the comma; be sure to strip off the double quotes.
You might want to ask yourself: "Why do I need this whole file in memory all at once?" Can you read a little, process a little, and never have the whole thing in memory at once? Only you know your problem well enough to answer.
Maybe you can fire up jvisualvm if you have JDK 6 and see what's going on with memory. That would be a great clue.
I would recommend neXtep for version controlling the database it has got a good set of documentation and forums that explains how to install and the errors encountered. I have tested it for postgreSQL 9.1 and 9.3, i was able to get it working for 9.1 but for 9.3 it doesn't seems to work.
Angular is based on observable instead of promise base as of angularjs 1.x, so when we try to get data using http
it returns observable instead of promise, like you did
return this.http
.get(this.configEndPoint)
.map(res => res.json());
then to get data and show on view we have to convert it into desired form using RxJs functions like .map() function and .subscribe()
.map() is used to convert the observable (received from http request)to any form like .json(), .text()
as stated in Angular's official website,
.subscribe() is used to subscribe those observable response and ton put into some variable so from which we display it into the view
this.myService.getConfig().subscribe(res => {
console.log(res);
this.data = res;
});
The answer I want to give is "use collections.ChainMap", but I just discovered that it was only added in Python 3.3: https://docs.python.org/3.3/library/collections.html#chainmap-objects
You can try to crib the class from the 3.3 source though: http://hg.python.org/cpython/file/3.3/Lib/collections/init.py#l763
Here is a less feature-full Python 2.x compatible version (same author): http://code.activestate.com/recipes/305268-chained-map-lookups/
Instead of expanding/overwriting one dictionary with another using dict.merge, or creating an additional copy merging both, you create a lookup chain that searches both in order. Because it doesn't duplicate the mappings it wraps ChainMap uses very little memory, and sees later modifications to any sub-mapping. Because order matters you can also use the chain to layer defaults (i.e. user prefs > config > env).
You can try this, it is fully customizable.
ClipOval(
child: Material(
color: Colors.blue, // button color
child: InkWell(
splashColor: Colors.red, // inkwell color
child: SizedBox(width: 56, height: 56, child: Icon(Icons.menu)),
onTap: () {},
),
),
)
Output:
You need to use anaconda to manage python environment dependencies. MySQL connector can be installed using conda installer
conda install -c anaconda mysql-connector-python
You can also do like this by using sparkSession and implicit
import sparkSession.implicits._
val pagecount:DataFrame = sparkSession.read
.option("delimiter"," ")
.option("quote","")
.option("inferSchema","true")
.csv("dbfs:/databricks-datasets/wikipedia-datasets/data-001/pagecounts/sample/pagecounts-20151124-170000")
.toDF("project","article","requests","bytes_served")
When I find myself doing a lot of string concatenation in JavaScript, I start looking for templating. Handlebars.js works quite well keeping the HTML and JavaScript more readable. http://handlebarsjs.com
Or on OS-X the following works for me:
$ gsort --random-sort
You can filter your elment from all hovered elements. Problematic code:
element.filter(':hover')
Save code:
jQuery(':hover').filter(element)
To return boolean:
jQuery(':hover').filter(element).length===0
Also you will specify route on action for set route
[HttpGet]
[Route("api/customers/")]
public List<Customer> Get()
{
//gets all customer logic
}
[HttpGet]
[Route("api/customers/currentMonth")]
public List<Customer> GetCustomerByCurrentMonth()
{
//gets some customer
}
[HttpGet]
[Route("api/customers/{id}")]
public Customer GetCustomerById(string id)
{
//gets a single customer by specified id
}
[HttpGet]
[Route("api/customers/customerByUsername/{username}")]
public Customer GetCustomerByUsername(string username)
{
//gets customer by its username
}
To dump "myObject":
from bson import json_util
import json
print(json.dumps(myObject, default=json_util.default, sort_keys=True, indent=4, separators=(',', ': ')))
I tried vars() and dir(); both failed for what I was looking for. vars() didn't work because the object didn't have __dict__ (exceptions.TypeError: vars() argument must have __dict__ attribute). dir() wasn't what I was looking for: it's just a listing of field names, doesn't give the values or the object structure.
I think json.dumps() would work for most objects without the default=json_util.default, but I had a datetime field in the object so the standard json serializer failed. See How to overcome "datetime.datetime not JSON serializable" in python?
You have two options:
Option 1 (only works for bold, italic and underline):
String s = "<b>Bolded text</b>, <i>italic text</i>, even <u>underlined</u>!"
TextView tv = (TextView)findViewById(R.id.THE_TEXTVIEW_ID);
tv.setText(Html.fromHtml(s));
Option 2:
Use a Spannable; it is more complicated, but you can dynamically modify the text attributes (not only bold/italic, also colors).
No Dapper answer here. So I added one
using Dapper;
using System.Data.SqlClient;
using (var cn = new SqlConnection(@"Server=(local);DataBase=master;Integrated Security=SSPI"))
cn.Execute("dbo.test", commandType: CommandType.StoredProcedure);
this seems to be working nicely for me
$(window).bind('resize', function() {
jQuery("#grid").setGridWidth($('#parentDiv').width()-30, true);
}).trigger('resize');
Your path includes " at the beginning and at the end. Drop the quotes, and it'll be ok.
The \" at the beginning and end of what you see in VS Debugger is what tells us that the quotes are literally in the string.
In my humble experience with postgres 9.6, cascade delete doesn't work in practice for tables that grow above a trivial size.
Setting the line-height to the same height as it's containing div will also work
DEMO http://jsfiddle.net/kevinPHPkevin/gZXWC/7/
.inner {
line-height:72px;
border: 1px solid #000000;
}
We can cast an int
to a double
but we can't do the same with the wrapper classes Integer
and Double
:
int a = 1;
Integer b = 1; // inboxing, requires Java 1.5+
double c = (double) a; // OK
Double d = (Double) b; // No way.
This shows the compile time error that corresponds to your runtime exception.
You can't prevent the user from refreshing, nor should you really be trying. You should go back to why you need this solution, what's the root problem here?. Start there and find a different way to go about solving the problem. Perhaps is you elaborated on why you think you need to do this it would help in finding such a solution.
Breaking fundamental browser features is never a good idea, over 99.999999999% of the internet works and refreshes with F5, this is an expectation of the user, one you shouldn't break.
When dealing with C++ strings (std::string), you're looking for length() or size(). Both should provide you with the same value. However when dealing with C-Style strings, you would use strlen().
#include <iostream>
#include <string.h>
int main(int argc, char **argv)
{
std::string str = "Hello!";
const char *otherstr = "Hello!"; // C-Style string
std::cout << str.size() << std::endl;
std::cout << str.length() << std::endl;
std::cout << strlen(otherstr) << std::endl; // C way for string length
std::cout << strlen(str.c_str()) << std::endl; // convert C++ string to C-string then call strlen
return 0;
}
Output:
6
6
6
6
Well, this kind of depends how your Binary Tree is structured. Presumably you have some way of finding the desired leaf node given the root of the tree - simply apply that to both values until the branches you choose diverge.
If you don't have a way to find the desired leaf given the root, then your only solution - both in normal operation and to find the last common node - is a brute-force search of the tree.
If someone is still struggling to make predictions on images, here is the optimized code to load the saved model and make predictions:
# Modify 'test1.jpg' and 'test2.jpg' to the images you want to predict on
from keras.models import load_model
from keras.preprocessing import image
import numpy as np
# dimensions of our images
img_width, img_height = 320, 240
# load the model we saved
model = load_model('model.h5')
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
# predicting images
img = image.load_img('test1.jpg', target_size=(img_width, img_height))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
classes = model.predict_classes(images, batch_size=10)
print classes
# predicting multiple images at once
img = image.load_img('test2.jpg', target_size=(img_width, img_height))
y = image.img_to_array(img)
y = np.expand_dims(y, axis=0)
# pass the list of multiple images np.vstack()
images = np.vstack([x, y])
classes = model.predict_classes(images, batch_size=10)
# print the classes, the images belong to
print classes
print classes[0]
print classes[0][0]
Change the position
attribute to fixed
instead of absolute
.
You can use isin
method:
In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})
In [2]: df
Out[2]:
A B
0 5 1
1 6 2
2 3 3
3 4 5
In [3]: df[df['A'].isin([3, 6])]
Out[3]:
A B
1 6 2
2 3 3
And to get the opposite use ~
:
In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
A B
0 5 1
3 4 5
I know this questions has been answered, however the reason this is happening to you, was probably because you did not add your username to the docker group.
Here are the steps to do it:
Add the docker group if it doesn't already exist:
sudo groupadd docker
Add the connected user ${USER}
to the docker group. Change the user name to match your preferred user:
sudo gpasswd -a ${USER} docker
Restart the Docker daemon:
sudo service docker restart
If you are on Ubuntu 14.04-15.10* use docker.io instead:
sudo service docker.io restart
(If you are on Ubuntu 16.04 the service is named "docker" simply)
Either do a newgrp
docker or log out/in to activate the changes to groups.
You are testing if the values of the variables error
and Already
are present in RepoOutput[RepoName.index(repo)]
. If these variables don't exist then an undefined object is used.
Both of your if
and elif
tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].
I think you wanted to test if certain strings are in the value instead:
{% if "error" in RepoOutput[RepoName.index(repo)] %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
<td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>
Other corrections I made:
{% elif ... %}
instead of {$ elif ... %}
.</tr>
tag out of the if
conditional structure, it needs to be there always.id
attributeNote that most likely you want to use a class
attribute instead here, not an id
, the latter must have a value that must be unique across your HTML document.
Personally, I'd set the class value here and reduce the duplication a little:
{% if "Already" in RepoOutput[RepoName.index(repo)] %}
{% set row_class = "good" %}
{% else %}
{% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>
You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of
function email() {
// Opens SS by its ID
var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");
// Get the name of this SS
var name = ss.getName(); // Not necessary
// Read cell 1,1 * Line below does't work *
// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet
var range = sheet.getRange(1,1);
var data = range.getValue();
}
The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.
I faced the same problem once. In my case it was because of overridden equals
method. One values was coming null
.
Base on Francisco Daniel's answer I modified some of the Jquery code here's My version. I removed some excess code and use "fa" instead of "far" for the icon. I also remove the "far fa-minus-square" since I can't understand its purpose.
-- Edited --
I added the "draw" event for the button icon to update whenever the table is redrawn or reloaded. Because I noticed when I tried to reload the table using "myTable.ajax.reload()" the button icon is not changing.
https://codepen.io/john-kenneth-larbo/pen/zXeYpz
$(document).ready(function() {_x000D_
let myTable = $('#example').DataTable({_x000D_
columnDefs: [{_x000D_
orderable: false,_x000D_
className: 'select-checkbox',_x000D_
targets: 0,_x000D_
}],_x000D_
select: {_x000D_
style: 'os', // 'single', 'multi', 'os', 'multi+shift'_x000D_
selector: 'td:first-child',_x000D_
},_x000D_
order: [_x000D_
[1, 'asc'],_x000D_
],_x000D_
});_x000D_
_x000D_
myTable.on('select deselect draw', function () {_x000D_
var all = myTable.rows({ search: 'applied' }).count(); // get total count of rows_x000D_
var selectedRows = myTable.rows({ selected: true, search: 'applied' }).count(); // get total count of selected rows_x000D_
_x000D_
if (selectedRows < all) {_x000D_
$('#MyTableCheckAllButton i').attr('class', 'fa fa-square-o');_x000D_
} else {_x000D_
$('#MyTableCheckAllButton i').attr('class', 'fa fa-check-square-o');_x000D_
}_x000D_
_x000D_
});_x000D_
_x000D_
$('#MyTableCheckAllButton').click(function () {_x000D_
var all = myTable.rows({ search: 'applied' }).count(); // get total count of rows_x000D_
var selectedRows = myTable.rows({ selected: true, search: 'applied' }).count(); // get total count of selected rows_x000D_
_x000D_
_x000D_
if (selectedRows < all) {_x000D_
//Added search applied in case user wants the search items will be selected_x000D_
myTable.rows({ search: 'applied' }).deselect();_x000D_
myTable.rows({ search: 'applied' }).select();_x000D_
} else {_x000D_
myTable.rows({ search: 'applied' }).deselect();_x000D_
}_x000D_
});_x000D_
});
_x000D_
<table id="example" class="display" style="width:100%">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>_x000D_
<button style="border: none; background: transparent; font-size: 14px;" id="MyTableCheckAllButton">_x000D_
<i class="far fa-square"></i> _x000D_
</button>_x000D_
</th>_x000D_
<th>Name</th>_x000D_
<th>Position</th>_x000D_
<th>Office</th>_x000D_
<th>Age</th>_x000D_
<th>Salary</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Tiger Nixon</td>_x000D_
<td>System Architect</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>61</td>_x000D_
<td>$320,800</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Garrett Winters</td>_x000D_
<td>Accountant</td>_x000D_
<td>Tokyo</td>_x000D_
<td>63</td>_x000D_
<td>$170,750</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Ashton Cox</td>_x000D_
<td>Junior Technical Author</td>_x000D_
<td>San Francisco</td>_x000D_
<td>66</td>_x000D_
<td>$86,000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Cedric Kelly</td>_x000D_
<td>Senior Javascript Developer</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>22</td>_x000D_
<td>$433,060</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Airi Satou</td>_x000D_
<td>Accountant</td>_x000D_
<td>Tokyo</td>_x000D_
<td>33</td>_x000D_
<td>$162,700</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Brielle Williamson</td>_x000D_
<td>Integration Specialist</td>_x000D_
<td>New York</td>_x000D_
<td>61</td>_x000D_
<td>$372,000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Herrod Chandler</td>_x000D_
<td>Sales Assistant</td>_x000D_
<td>San Francisco</td>_x000D_
<td>59</td>_x000D_
<td>$137,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Rhona Davidson</td>_x000D_
<td>Integration Specialist</td>_x000D_
<td>Tokyo</td>_x000D_
<td>55</td>_x000D_
<td>$327,900</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Colleen Hurst</td>_x000D_
<td>Javascript Developer</td>_x000D_
<td>San Francisco</td>_x000D_
<td>39</td>_x000D_
<td>$205,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Sonya Frost</td>_x000D_
<td>Software Engineer</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>23</td>_x000D_
<td>$103,600</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Jena Gaines</td>_x000D_
<td>Office Manager</td>_x000D_
<td>London</td>_x000D_
<td>30</td>_x000D_
<td>$90,560</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
<tfoot>_x000D_
<tr>_x000D_
<th></th>_x000D_
<th>Name</th>_x000D_
<th>Position</th>_x000D_
<th>Office</th>_x000D_
<th>Age</th>_x000D_
<th>Salary</th>_x000D_
</tr>_x000D_
</tfoot>_x000D_
</table>
_x000D_
an alternative to using a proxy is to use SSH In the git configs, configure the origin remote on the ssh address.Then use the ssh-keygen command, which gives you a public key that you can set in your GitLab or Gitab account settings and login accordingly done...
1-verify which remotes are using by running git remote -v
in your Git client.
2-if this is http(s) url ,changed it to ssh address , run: git remote set-url <remote name, e.g. origin> <new SSH URL>
3-to generate ssh key for login ,run : ssh-keygen -o
, this command generate public(id_rsa.pub file) and private keys.
4-copy public key contents. (from id_rsa.pub file)
5-go to gitlab/githup/.... in profile in setting . create new ssh key and paste public key contents
All browsers, including Safari (+ mobile):
input[type=text] {
/* Remove */
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
/* Optional */
border: solid;
box-shadow: none;
/*etc.*/
}
An intuitive explanation to this is by simply analysing a single loop:
So the total time for a single loop is O(1)+O(e). Now sum it for each vertex as each vertex is visited once. This gives
For every V
=>
O(1)
+
O(e)
=> O(V) + O(E)
Hope the following demo can help you out.
$(function() {_x000D_
$("button").on('click', function() {_x000D_
var data = "";_x000D_
var tableData = [];_x000D_
var rows = $("table tr");_x000D_
rows.each(function(index, row) {_x000D_
var rowData = [];_x000D_
$(row).find("th, td").each(function(index, column) {_x000D_
rowData.push(column.innerText);_x000D_
});_x000D_
tableData.push(rowData.join(","));_x000D_
});_x000D_
data += tableData.join("\n");_x000D_
$(document.body).append('<a id="download-link" download="data.csv" href=' + URL.createObjectURL(new Blob([data], {_x000D_
type: "text/csv"_x000D_
})) + '/>');_x000D_
_x000D_
_x000D_
$('#download-link')[0].click();_x000D_
$('#download-link').remove();_x000D_
});_x000D_
});
_x000D_
table {_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td,_x000D_
th {_x000D_
border: 1px solid #aaa;_x000D_
padding: 0.5rem;_x000D_
text-align: left;_x000D_
}_x000D_
_x000D_
td {_x000D_
font-size: 0.875rem;_x000D_
}_x000D_
_x000D_
.btn-group {_x000D_
padding: 1rem 0;_x000D_
}_x000D_
_x000D_
button {_x000D_
background-color: #fff;_x000D_
border: 1px solid #000;_x000D_
margin-top: 0.5rem;_x000D_
border-radius: 3px;_x000D_
padding: 0.5rem 1rem;_x000D_
font-size: 1rem;_x000D_
}_x000D_
_x000D_
button:hover {_x000D_
cursor: pointer;_x000D_
background-color: #000;_x000D_
color: #fff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div id='PrintDiv'>_x000D_
<table id="mainTable">_x000D_
<tr>_x000D_
<td>Col1</td>_x000D_
<td>Col2</td>_x000D_
<td>Col3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Val1</td>_x000D_
<td>Val2</td>_x000D_
<td>Val3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Val11</td>_x000D_
<td>Val22</td>_x000D_
<td>Val33</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Val111</td>_x000D_
<td>Val222</td>_x000D_
<td>Val333</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
_x000D_
<div class="btn-group">_x000D_
<button>csv</button>_x000D_
</div>
_x000D_
Your error is also shown when trying to access the sizeof()
of an non-initialized extern array:
extern int a[];
sizeof(a);
>> error: invalid application of 'sizeof' to incomplete type 'int[]'
Note that you would get an array size missing
error without the extern
keyword.
For GlassFish Jersey JAX-RS implementation I have resolved this issue by common method is describing all common parameters. At least three of parameters have to be equal: name(="name"), path(="/") and domain(=null) :
public static NewCookie createDomainCookie(String value, int maxAgeInMinutes) {
ZonedDateTime time = ZonedDateTime.now().plusMinutes(maxAgeInMinutes);
Date expiry = time.toInstant().toEpochMilli();
NewCookie newCookie = new NewCookie("name", value, "/", null, Cookie.DEFAULT_VERSION,null, maxAgeInMinutes*60, expiry, false, false);
return newCookie;
}
And use it the common way to set cookie:
NewCookie domainNewCookie = RsCookieHelper.createDomainCookie(token, 60);
Response res = Response.status(Response.Status.OK).cookie(domainNewCookie).build();
and to delete the cookie:
NewCookie domainNewCookie = RsCookieHelper.createDomainCookie("", 0);
Response res = Response.status(Response.Status.OK).cookie(domainNewCookie).build();
Very similar to Marc, only difference I would make would be to spool to a parameter like so:
WHENEVER SQLERROR EXIT 1
SET LINES 32000
SET TERMOUT OFF ECHO OFF NEWP 0 SPA 0 PAGES 0 FEED OFF HEAD OFF TRIMS ON TAB OFF
SET SERVEROUTPUT ON
spool &1
-- Code
spool off
exit
And then to call the SQLPLUS as
sqlplus -s username/password@sid @tmp.sql /tmp/output.txt
In the 6.6.8 version I installed the NppAutoIndent plugin from Plugins > Plugin Manager > Show Plugin Manager. Then I selected the Smart Indent option in Plugin > NppAutoIndent. Hope this helps.
Any line starting with a "REM" is treated as a comment, nothing is executed including the redirection.
Also, the %date% variable may contain "/" characters which are treated as path separator characters, leading to the system being unable to create the desired log file.
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight)
{
//your code here
}
I too searched it and even after checking all comments here and more, this is the solution to check if reached the bottom or not.
the accepted answer is correct.. for mobile you can also use this (ng-touched rather ng-dirty)
input.ng-invalid.ng-touched{
border-bottom: 1px solid #e74c3c !important;
}
<script type="text/javascript">
$(function() {
$("#datepicker").datepicker({
onSelect: function(value, date) {
window.location = 'day.jsp' ;
}
});
});
</script>
<div id="datepicker"></div>
I think you can try this .It works fine .
I had the same issue too and this worked for me try:
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
subscribe((res) => {
let resSTR = JSON.stringify(res);
let resJSON = JSON.parse(resStr);
console.log(resJSON._body);
})
As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.
Because no one actually created an answer with using .on()
instead of bind()
i decided to create one.
$('div#dialog').on('dialogclose', function(event) {
//custom logic fired after dialog is closed.
});
Here is a script which generates grant queries for a particular table. It omits owner's privileges.
SELECT
format (
'GRANT %s ON TABLE %I.%I TO %I%s;',
string_agg(tg.privilege_type, ', '),
tg.table_schema,
tg.table_name,
tg.grantee,
CASE
WHEN tg.is_grantable = 'YES'
THEN ' WITH GRANT OPTION'
ELSE ''
END
)
FROM information_schema.role_table_grants tg
JOIN pg_tables t ON t.schemaname = tg.table_schema AND t.tablename = tg.table_name
WHERE
tg.table_schema = 'myschema' AND
tg.table_name='mytable' AND
t.tableowner <> tg.grantee
GROUP BY tg.table_schema, tg.table_name, tg.grantee, tg.is_grantable;
Say P7 is a Cell then you can use the following Syntex to check the value of the cell and assign appropriate value to another cell based on this following nested if:
=IF(P7=0,200,IF(P7=1,100,IF(P7=2,25,IF(P7=3,10,IF((P7=4),5,0)))))
in python .....intendation matters, e.g.:
if a==1:
print("hey")
if a==2:
print("bye")
print("all the best")
In this case "all the best" will be printed if either of the two conditions executes, but if it would have been like this
if a==2:
print("bye")
print("all the best")
then "all the best" will be printed only if a==2
I've settled on the following format for typing arrays that can have items of multiple types.
Array<ItemType1 | ItemType2 | ItemType3>
This works well with testing and type guards. https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types
This format doesn't work well with testing or type guards:
(ItemType1 | ItemType2 | ItemType3)[]
Where is the file that you're running? If it is in your public html folder, you can do echo dirname(__FILE__);
public class UploadToServer extends Activity {
TextView messageText;
Button uploadButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;
String upLoadServerUri = null;
/********** File Path *************/
final String uploadFilePath = "/mnt/sdcard/";
final String uploadFileName = "Quotes.jpg";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_to_server);
uploadButton = (Button) findViewById(R.id.uploadButton);
messageText = (TextView) findViewById(R.id.messageText);
messageText.setText("Uploading file path :- '/mnt/sdcard/"
+ uploadFileName + "'");
/************* Php script path ****************/
upLoadServerUri = "http://192.1.1.11/hhhh/UploadToServer.php";
uploadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(UploadToServer.this, "",
"Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("uploading started.....");
}
});
uploadFile(uploadFilePath + "" + uploadFileName);
}
}).start();
}
});
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection connection = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :" + uploadFilePath + ""
+ uploadFileName);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"
+ uploadFilePath + "" + uploadFileName);
}
});
return 0;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true); // Allow Inputs
connection.setDoOutput(true); // Allow Outputs
connection.setUseCaches(false); // Don't use a Cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(connection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
// dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
// + fileName + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
+ URLEncoder.encode(fileName, "UTF-8") + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+ " http://www.androidexample.com/media/uploads/"
+ uploadFileName;
messageText.setText(msg);
Toast.makeText(UploadToServer.this,
"File Upload Complete.", Toast.LENGTH_SHORT)
.show();
}
});
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText
.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadToServer.this,
"MalformedURLException", Toast.LENGTH_SHORT)
.show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploadToServer.this,
"Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
PHP FILE
<?php
$target_path = "./Upload/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
If you're using T-SQL
, the only thing wrong with your code is that you used braces {}
instead of parentheses ()
.
PS: Both IDENTITY
and PRIMARY KEY
imply NOT NULL
, so you can omit that if you wish.
A solution using flex box; fully responsive:
parent_div {
position: fixed;
width: 100%;
display: flex;
justify-content: center;
}
child_div {
/* whatever you want */
}
In pyspark 2.4.4
1) group_by_dataframe.count().filter("`count` >= 10").orderBy('count', ascending=False)
2) from pyspark.sql.functions import desc
group_by_dataframe.count().filter("`count` >= 10").orderBy('count').sort(desc('count'))
No need to import in 1) and 1) is short & easy to read,
So I prefer 1) over 2)
So, after After reviewing the code again, I found the error. I am wondering how no one notice that! In the above code I wrote
Post::create(request([ // <= the error is Here!!!
'body' => request('body'),
'title' => request('title'),
'user_id' => auth()->id()
]));
actually, there is no need for the request function warping the body of the create function.
// this is right
Post::create([
'body' => request('body'),
'title' => request('title'),
'user_id' => auth()->id()
]);
String str, str1;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a String : ");
str = sc.nextLine();
str1 = str.replaceAll("[aeiouAEIOU]", "");
System.out.print(str1);
For multiple lines the best way I find is to do this:
IEnumerable<string> lines = new List<string>
{
string.Format("{{ line with formatting... {0} }}", id),
"line 2",
"line 3"
};
StringBuilder sb = new StringBuilder();
foreach(var line in lines)
sb.AppendLine(line);
In this way you don't have to clutter the screen with the Environment.NewLine or AppendLine() repeated multiple times. It will also be less error prone than having to remember to type them.
in your device you want to run app on Go to settings About device >> Build number triple clicks or more and back to settings you will found "Developer options" appear go to and click on "USB debugging" Done
C++ has no built-in concepts of interfaces. You can implement it using abstract classes which contains only pure virtual functions. Since it allows multiple inheritance, you can inherit this class to create another class which will then contain this interface (I mean, object interface :) ) in it.
An example would be something like this -
class Interface
{
public:
Interface(){}
virtual ~Interface(){}
virtual void method1() = 0; // "= 0" part makes this method pure virtual, and
// also makes this class abstract.
virtual void method2() = 0;
};
class Concrete : public Interface
{
private:
int myMember;
public:
Concrete(){}
~Concrete(){}
void method1();
void method2();
};
// Provide implementation for the first method
void Concrete::method1()
{
// Your implementation
}
// Provide implementation for the second method
void Concrete::method2()
{
// Your implementation
}
int main(void)
{
Interface *f = new Concrete();
f->method1();
f->method2();
delete f;
return 0;
}
Seriously belated edit: If you're using .NET 4.0 or later
The File
class has a new ReadLines
method which lazily enumerates lines rather than greedily reading them all into an array like ReadAllLines
. So now you can have both efficiency and conciseness with:
var lineCount = File.ReadLines(@"C:\file.txt").Count();
Original Answer
If you're not too bothered about efficiency, you can simply write:
var lineCount = File.ReadAllLines(@"C:\file.txt").Length;
For a more efficient method you could do:
var lineCount = 0;
using (var reader = File.OpenText(@"C:\file.txt"))
{
while (reader.ReadLine() != null)
{
lineCount++;
}
}
Edit: In response to questions about efficiency
The reason I said the second was more efficient was regarding memory usage, not necessarily speed. The first one loads the entire contents of the file into an array which means it must allocate at least as much memory as the size of the file. The second merely loops one line at a time so it never has to allocate more than one line's worth of memory at a time. This isn't that important for small files, but for larger files it could be an issue (if you try and find the number of lines in a 4GB file on a 32-bit system, for example, where there simply isn't enough user-mode address space to allocate an array this large).
In terms of speed I wouldn't expect there to be a lot in it. It's possible that ReadAllLines has some internal optimisations, but on the other hand it may have to allocate a massive chunk of memory. I'd guess that ReadAllLines might be faster for small files, but significantly slower for large files; though the only way to tell would be to measure it with a Stopwatch or code profiler.
Download Handle.
https://technet.microsoft.com/en-us/sysinternals/bb896655.aspx
If you want to find what program has a handle on a certain file, run this from the directory that Handle.exe is extracted to. Unless you've added Handle.exe to the PATH
environment variable. And the file path is C:\path\path\file.txt", run this:
handle "C:\path\path\file.txt"
This will tell you what process(es) have the file (or folder) locked.
This problem can be caused also by jvm version used to compile the project and the jvm supported by the servlet container. Try to Fix the project build path. For example if you deploy on tomcat 9, use jvm 1.8.0 or lower.
After installing Anaconda3 on your system you need to add Anaconda to the PATH environment variable. This will allow you to access Anaconda with the 'conda' command from cmd.exe or PowerShell.
The link I provided below go through the three major issues with not recognized error. Which are:
My issue was resolved following the steps for issue #2 Environment PATH is incorrectly added. I did not have all three file paths in my variable environment.
This should work:
DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table;
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0
BEGIN
--Do stuff with scalar values
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;
I've tried all possible solutions offered but unluckly my vscode settings won't changed its linter path. So, I tride to explore vscode settings in settings > User Settings > python. Find Linting: Pylint Path and change it to "pylint_django". Don't forget to change the linter to "pylint_django" at settings > User Settings > python configuration from "pyLint" to "pylint_django".
Assuming that the length is same for each array in the second dimension, you can use
public class B {
public static void main(String [] main){
int [] [] nir= new int [2] [3];
System.out.println(nir[0].length);
}
}
Static methods are the methods in Java that can be called without creating an object of class. It is belong to the class.
We use static method when we no need to be invoked method using instance.
This statement will definitely help you:
env = env.OrderByDescending(c => c.ReportDate).ToList();
First you need to install Android Studio on your machine. Then simply follow these steps.
Try changing it to.
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "text/plain";
Response.Flush();
Response.TransmitFile(file.FullName);
Response.End();
I found this online java compiler and runner. It work also with threads and showing results immediately. http://www.browxy.com
Citing the official javadoc of List.addAll
:
Appends all of the elements in the specified collection to the end of
this list, in the order that they are returned by the specified
collection's iterator (optional operation). The behavior of this
operation is undefined if the specified collection is modified while
the operation is in progress. (Note that this will occur if the
specified collection is this list, and it's nonempty.)
So you will copy the references of the objects in list
to anotherList
. Any method that does not operate on the referenced objects of anotherList
(such as removal, addition, sorting) is local to it, and therefore will not influence list
.
If your array has static storage allocation, it is default initialized to zero. However, if the array has automatic storage allocation, then you can simply initialize all its elements to zero using an array initializer list which contains a zero.
// function scope
// this initializes all elements to 0
int arr[4] = {0};
// equivalent to
int arr[4] = {0, 0, 0, 0};
// file scope
int arr[4];
// equivalent to
int arr[4] = {0};
Please note that there is no standard way to initialize the elements of an array to a value other than zero using an initializer list which contains a single element (the value). You must explicitly initialize all elements of the array using the initializer list.
// initialize all elements to 4
int arr[4] = {4, 4, 4, 4};
// equivalent to
int arr[] = {4, 4, 4, 4};
def percentage_match(mainvalue,comparevalue):
if mainvalue >= comparevalue:
matched_less = mainvalue - comparevalue
no_percentage_matched = 100 - matched_less*100.0/mainvalue
no_percentage_matched = str(no_percentage_matched) + ' %'
return no_percentage_matched
else:
print('please checkout your value')
print percentage_match(100,10)
Ans = 10.0 %
You can delete it in the terminal via:
jupyter kernelspec uninstall yourKernel
where yourKernel
is the name of the kernel you want to delete.
Today we use many web apps and sites for our needs. Most of them are highly useful. I will show you some of them used by python or django.
The Washington Post’s website is a hugely popular online news source to accompany their daily paper. Its’ huge amount of views and traffic can be easily handled by the Django web framework.
Washington Post - 52.2 million unique visitors (March, 2015)
The National Aeronautics and Space Administration’s official website is the place to find news, pictures, and videos about their ongoing space exploration. This Django website can easily handle huge amounts of views and traffic.
2 million visitors monthly
The Guardian is a British news and media website owned by the Guardian Media Group. It contains nearly all of the content of the newspapers The Guardian and The Observer. This huge data is handled by Django.
The Guardian (commenting system) - 41,6 million unique visitors (October, 2014)
We all know YouTube as the place to upload cat videos and fails. As one of the most popular websites in existence, it provides us with endless hours of video entertainment. The Python programming language powers it and the features we love.
DropBox started the online document storing revolution that has become part of daily life. We now store almost everything in the cloud. Dropbox allows us to store, sync, and share almost anything using the power of Python.
Survey Monkey is the largest online survey company. They can handle over one million responses every day on their rewritten Python website.
Quora is the number one place online to ask a question and receive answers from a community of individuals. On their Python website relevant results are answered, edited, and organized by these community members.
A majority of the code for Bitly URL shortening services and analytics are all built with Python. Their service can handle hundreds of millions of events per day.
Reddit is known as the front page of the internet. It is the place online to find information or entertainment based on thousands of different categories. Posts and links are user generated and are promoted to the top through votes. Many of Reddit’s capabilities rely on Python for their functionality.
Hipmunk is an online consumer travel site that compares the top travel sites to find you the best deals. This Python website’s tools allow you to find the cheapest hotels and flights for your destination.
Click here for more: 25-of-the-most-popular-python-and-django-websites, What-are-some-well-known-sites-running-on-Django
If you prefer passing the arguments in a key-value pair you can use something like this:
@echo off
setlocal enableDelayedExpansion
::::: asigning arguments as a key-value pairs:::::::::::::
set counter=0
for %%# in (%*) do (
set /a counter=counter+1
set /a even=counter%%2
if !even! == 0 (
echo setting !prev! to %%#
set "!prev!=%%~#"
)
set "prev=%%~#"
)
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: showing the assignments
echo %one% %two% %three% %four% %five%
endlocal
And an example :
c:>argumentsDemo.bat one 1 "two" 2 three 3 four 4 "five" 5
1 2 3 4 5
You can also set some environment variables in advance. It can be done by setting them in the console or setting them from my computer:
@echo off
if defined variable1 (
echo %variable1%
)
if defined variable2 (
echo %variable2%
)
and calling it like:
c:\>set variable1=1
c:\>set variable2=2
c:\>argumentsTest.bat
1
2
You can also point to a file where the needed values are preset. If this is the script:
@echo off
setlocal
::::::::::
set "VALUES_FILE=E:\scripts\values.txt"
:::::::::::
for /f "usebackq eol=: tokens=* delims=" %%# in ("%VALUES_FILE%") do set "%%#"
echo %key1% %key2% %some_other_key%
endlocal
and values file is this:
:::: use EOL=: in the FOR loop to use it as a comment
key1=value1
key2=value2
:::: do not left spaces arround the =
:::: or at the begining of the line
some_other_key=something else
and_one_more=more
the output of calling it will be:
value1 value2 something else
Of course you can combine all approaches. Check also arguments syntax , shift
There are a couple of things to be aware of:
src/main/resources/public
will be served from the root of your application.
For example src/main/resources/public/hello.jpg
would be served from http://localhost:8080/hello.jpg
This is why your current matcher configuration hasn't permitted access to the static resources. For /resources/**
to work, you would have to place the resources in src/main/resources/public/resources
and access them at http://localhost:8080/resources/your-resource
.
As you're using Spring Boot, you may want to consider using its defaults rather than adding extra configuration. Spring Boot will, by default, permit access to /css/**
, /js/**
, /images/**
, and /**/favicon.ico
. You could, for example, have a file named src/main/resources/public/images/hello.jpg
and, without adding any extra configuration, it would be accessible at http://localhost:8080/images/hello.jpg
without having to log in. You can see this in action in the web method security smoke test where access is permitted to the Bootstrap CSS file without any special configuration.
this solved it for me, and is sure to work add this to ~/.zshrc
export PATH=path_to_anaconda_bin:$PATH
the answer
If its the case of the dll file missing you can download the dll file from this link http://en.osdn.jp/projects/sfnet_dose-grok/downloads/sqljdbc_auth.dll/
else you need to provide the username and password of the db you are trying to connect, and make the authentication as false
The default is height: auto
in browser, but height: X%
Defines the height in percentage of the containing block.
Actually what Luis proposed did not work for me. I had to figure out another way. This is what helped me. Might help you too. Links:
*.getEncoded(): https://docs.oracle.com/javase/7/docs/api/java/security/Key.html
Encoder information: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Encoder.html
Decoder information: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Decoder.html
Code snippets: For encoding:
String temp = new String(Base64.getEncoder().encode(key.getEncoded()));
For decoding:
byte[] encodedKey = Base64.getDecoder().decode(temp);
SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "DES");
You can use the .hide()
function bound to a click
handler:
$('#Comanda').click(function() {
$(this).hide();
});
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray()
According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.
This will work for you:
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
To apply font style to complete excel document:
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getDefaultStyle()
->applyFromArray($styleArray);
Take a look at the formats in ?strptime
R> foo <- factor("1/15/2006 0:00:00")
R> foo <- as.Date(foo, format = "%m/%d/%Y %H:%M:%S")
R> foo
[1] "2006-01-15"
R> class(foo)
[1] "Date"
Note that this will work even if foo
starts out as a character. It will also work if using other date formats (as.POSIXlt
, as.POSIXct
).
I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering
Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date
'You said time1 doesn't change, so I left it in a singe cell.
'If that is not correct, you will have to play with this some more.
time1 = Range("A6").Value
'Looping through each of our output cells.
For Each t In Range("B7:E9") 'Change these to match your real ranges.
'Looping through each departure date/time.
'(Only one row in your example. This can be adjusted if needed.)
For Each x In Range("B2:E2") 'Change these to match your real ranges.
'Check to see if our dep time corresponds to
'the matching column in our output
If t.Column = x.Column Then
'If it does, then check to see what our time value is
If x > 0 Then
time2 = x.Value
'Apply the change to the output cell.
t.Value = time1 - time2
'Exit out of this loop and move to the next output cell.
Exit For
End If
End If
'If the columns don't match, or the x value is not a time
'then we'll move to the next dep time (x)
Next x
Next t
End Sub
EDIT
I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).
A B C D E
1 LOAD_NUMBER 1 2 3 4
2 DEPARTURE_TIME_DATE 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 20:00
4 Dry_Refrig 7585.1 0 10099.8 16700
6 1/4/2012 19:30
Using the sub I got this output:
A B C D E
7 Friday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
8 Saturday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
9 Thursday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user
, picked from your example), then the syntax is quite simple:
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin('a.user', 'u')
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
Since you are applying a condition on the joined result here, using a LEFT JOIN
or simply JOIN
is the same.
If no association is available, then the query looks like following
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin(
'User\Entity\User',
'u',
\Doctrine\ORM\Query\Expr\Join::WITH,
'a.user = u.id'
)
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
This will produce a resultset that looks like following:
array(
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
// ...
)
You should be able to do this quite easily:
SELECT *
FROM WebPageContent
WHERE data.value('(/PageContent/Text)[1]', 'varchar(100)') LIKE 'XYZ%'
The .value
method gives you the actual value, and you can define that to be returned as a VARCHAR(), which you can then check with a LIKE statement.
Mind you, this isn't going to be awfully fast. So if you have certain fields in your XML that you need to inspect a lot, you could:
With this, you'd basically "extract" a certain portion of the XML into a computed field, make it persisted, and then you can search very efficiently on it (heck: you can even INDEX that field!).
Marc
I actually like MY JavaScript files to be validated, but I definitely don't want to validate and deal with trivial warnings with third party libraries.
That's why I think that turning off validation all together is too drastic. Fortunately with Eclipse, you can selectively remove some JavaScript sources from validation.
Excluded
pattern.Exclusion patterns
box.Browse
button to mention the JavaScript source by name.The information about JavaScript source inclusion/exclusion is saved into .settings/.jsdtscope
file. Do not forget to add it to your SCM.
Here is how configuration looks with jQuery files removed from validation:
--stdin
doesn't work on Debian. It says:
`passwd: unrecognized option '--stdin'`
This worked for me:
#useradd $USER
#echo "$USER:$SENHA" | chpasswd
Here we can find some other good ways:
SQL
SQL is used to communicate with a database, it is the standard language for relational database management systems.
In detail Structured Query Language is a special-purpose programming language designed for managing data held in a relational database management system (RDBMS), or for stream processing in a relational data stream management system (RDSMS).
Originally based upon relational algebra and tuple relational calculus, SQL consists of a data definition language and a data manipulation language. The scope of SQL includes data insert, query, update and delete, schema creation and modification, and data access control. Although SQL is often described as, and to a great extent is, a declarative language (4GL), it also includes procedural elements.
PL/SQL
PL/SQL is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle Corporation
Specialities of PL/SQL
T-SQL
Short for Transaction-SQL, an extended form of SQL that adds declared variables, transaction control, error and exceptionhandling and row processing to SQL
The Structured Query Language or SQL is a programming language that focuses on managing relational databases. SQL has its own limitations which spurred the software giant Microsoft to build on top of SQL with their own extensions to enhance the functionality of SQL. Microsoft added code to SQL and called it Transact-SQL or T-SQL. Keep in mind that T-SQL is proprietary and is under the control of Microsoft while SQL, although developed by IBM, is already an open format.
T-SQL adds a number of features that are not available in SQL.
This includes procedural programming elements and a local variable to provide more flexible control of how the application flows. A number of functions were also added to T-SQL to make it more powerful; functions for mathematical operations, string operations, date and time processing, and the like. These additions make T-SQL comply with the Turing completeness test, a test that determines the universality of a computing language. SQL is not Turing complete and is very limited in the scope of what it can do.
Another significant difference between T-SQL and SQL is the changes done to the DELETE and UPDATE commands that are already available in SQL. With T-SQL, the DELETE and UPDATE commands both allow the inclusion of a FROM clause which allows the use of JOINs. This simplifies the filtering of records to easily pick out the entries that match a certain criteria unlike with SQL where it can be a bit more complicated.
Choosing between T-SQL and SQL is all up to the user. Still, using T-SQL is still better when you are dealing with Microsoft SQL Server installations. This is because T-SQL is also from Microsoft, and using the two together maximizes compatibility. SQL is preferred by people who have multiple backends.
References , Wikipedea , Tutorial Points :www.differencebetween.com
this fails:
DECLARE @vPortalUID NVARCHAR(32)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
PRINT @nPortalUID
this works
DECLARE @vPortalUID NVARCHAR(36)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
PRINT @nPortalUID
the difference is NVARCHAR(36)
, your input parameter is too small!
there are some process which cannot be kill like this "kill %1" . if we have to terminate that process so special command is used to kill that process which is kill -9. eg open vim and stop if by using ctrl+z then see jobs and after apply kill process than this process will not terminated so here we use kill -9 command for terminating.
To quickly find a meaningful error message by inspecting the error during debugging:
Add a quick watch for:
((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors
Drill down into EntityValidationErrors like this:
(collection item e.g. [0]) > ValidationErrors > (collection item e.g. [0]) > ErrorMessage
If your test case runner returns a non-zero code for failed tests, you can simply write:
test_handler test_case_x; test_result=$?
if ((test_result != 0)); then
printf '%s\n' "Test case x failed" >&2 # write error message to stderr
exit 1 # or exit $test_result
fi
Or even shorter:
if ! test_handler test_case_x; then
printf '%s\n' "Test case x failed" >&2
exit 1
fi
Or the shortest:
test_handler test_case_x || { printf '%s\n' "Test case x failed" >&2; exit 1; }
To exit with test_handler's exit code:
test_handler test_case_x || { ec=$?; printf '%s\n' "Test case x failed" >&2; exit $ec; }
If you want to take a more comprehensive approach, you can have an error handler:
exit_if_error() {
local exit_code=$1
shift
[[ $exit_code ]] && # do nothing if no error code passed
((exit_code != 0)) && { # do nothing if error code is 0
printf 'ERROR: %s\n' "$@" >&2 # we can use better logging here
exit "$exit_code" # we could also check to make sure
# error code is numeric when passed
}
}
then invoke it after running your test case:
run_test_case test_case_x
exit_if_error $? "Test case x failed"
or
run_test_case test_case_x || exit_if_error $? "Test case x failed"
The advantages of having an error handler like exit_if_error
are:
if
blocks that test exit codes for errorsHere is a complete implementation of error handling and logging:
https://github.com/codeforester/base/blob/master/lib/stdlib.sh
__FILE__
, __LINE__
in BashAddition to @Binary Nerd
If you are using Spark, use the following to get the Spark version:
spark-submit --version
or
Login to the Cloudera Manager and goto Hosts page then run inspect hosts in cluster
You can get help from kubectl logs -h
and according the info,
kubectl logs -f deployment/myapp -c myapp --tail 100
-c
is the container name and --tail
will show the latest num lines,but this will choose one pod of the deployment, not all pods. This is something you have to bear in mind.
kubectl logs -l app=myapp -c myapp --tail 100
If you want to show logs of all pods, you can use -l
and specify a lable, but at the same time -f
won't be used.
This will automatically enable autocomplete and save password in browsers.
autocomplete="on"
(form)autocomplete="username"
(input, email/username)autocomplete="current-password"
(input, password)<form autocomplete="on">
<input id="user-text-field" type="email" autocomplete="username"/>
<input id="password-text-field" type="password" autocomplete="current-password"/>
</form>
Check out more at Apple's documentation: Enabling Password AutoFill on an HTML Input Element
A modification of previous answers using array_map
.
Blow up the CSV data with multiple lines.
$csv = array_map('str_getcsv', explode("\n", $csvData));
mvc:annotation-driven is a tag added in Spring 3.0 which does the following:
context:annotation-config Looks for annotations on beans in the same application context it is defined and declares support for all the general annotations like @Autowired, @Resource, @Required, @PostConstruct etc etc.
I tore my hair out over this one too. Your code only works if the user has granted an extended permission for that which is not ideal.
In a nutshell, if you turn on the OAuth 2.0
for Canvas advanced option, Facebook will send a $_REQUEST['signed_request']
along with every page requested within your tab app. If you parse that signed_request you can get some info about the user including if they've liked the page or not.
function parsePageSignedRequest() {
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
return $data;
}
return false;
}
if($signed_request = parsePageSignedRequest()) {
if($signed_request->page->liked) {
echo "This content is for Fans only!";
} else {
echo "Please click on the Like button to view this tab!";
}
}
If you disable asynchronous retrieval, your script will block until the request has been fulfilled. It's useful for performing some sequence of requests in a known order, though I find async callbacks to be cleaner.
Use this statement
SELECT TO_CHAR(current_date,'dd MONTH yyyy') FROM dual
this will convert the month number to month full string
This is a bug in the npm package regarding dependencies : https://askubuntu.com/questions/1088662/npm-depends-node-gyp-0-10-9-but-it-is-not-going-to-be-installed
Bugs have been reported. The above may not work depending what you have installed already, at least it didn't for me on an up to date Ubuntu 18.04 LTS.
I followed the suggested dependencies and installed them as the above link suggests:
sudo apt-get install nodejs-dev node-gyp libssl1.0-dev
and then
sudo apt-get install npm
Please subscribe to the bug if you're affected:
bugs.launchpad.net/ubuntu/+source/npm/+bug/1517491
bugs.launchpad.net/ubuntu/+source/npm/+bug/1809828
Guess you forgot to append the item to DOM.
Check it HERE.
Fedora/Cent Os same trouble when used yum install and interrupt it with Ctrl+Z.
Use this command:
sudo cat /var/cache/dnf/*pid
if there any pid, you can manually remove it:
sudo nano /var/cache/dnf/*pid
crtl+x followed by Y and Enter to exit nano editor (you can use any editor you want to open).
If after, delete some tmp files that may still be there:
sudo systemd-tmpfiles --remove dnf.conf
.
(dot) files are hidden by default on Unix/Linux systems. Most likely, if you know they are .htaccess
files, then they are probably in the root folder for the website.
If you are using a command line (terminal) to access, then they will only show up if you use:
ls -a
If you are using a GUI application, look for a setting to "show hidden files" or something similar.
If you still have no luck, and you are on a terminal, you can execute these commands to search the whole system (may take some time):
cd /
find . -name ".htaccess"
This will list out any files it finds with that name.
I used a Path to draw only corners on the image Canvas. (I needed solution with no bitmap memory allocation)
@Override
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
if (!hasRoundedCorners()) return;
mPaint.setStyle(Paint.Style.FILL);
mPaint.setStrokeWidth(0);
Path path = new Path();
path.setFillType(Path.FillType.INVERSE_WINDING);
path.addRoundRect(new RectF(0, 0, getWidth(), getHeight()), mRadius, mRadius, Path.Direction.CCW);
canvas.drawPath(path, mPaint);
}
Notice that you should not allocate any new object in onDraw method. This code is a proof of concept and should not be used like this in product code
See more: https://medium.com/@przemek.materna/rounded-image-view-no-bitmap-reallocation-11a8b163484d
Use the Git GUI in the Git plugin.
Clone your online repository with the URL which you have.
After cloning, make changes to the files. When you make changes, you can see the number changes. Commit those changes.
Fetch from the remote (to check if anything is updated while you are working).
If the fetch operation gives you an update about the changes in the remote repository, make a pull operation which will update your copy in Visual Studio Code. Otherwise, do not make a pull operation if there aren't any changes in the remote repository.
Push your changes to the upstream remote repository by making a push operation.
the_int=window.clearInterval(the_int);
Just /
refers to the root of your website from the public html folder. DOCUMENT_ROOT
refers to the local path to the folder on the server that contains your website.
For example, I have EasyPHP setup on a machine...
$_SERVER["DOCUMENT_ROOT"]
gives me file:///C:/Program%20Files%20(x86)/EasyPHP-5.3.9/www
but any file I link to with just /
will be relative to my www
folder.
If you want to give the absolute path to a file on your server (from the server's root) you can use DOCUMENT_ROOT
. if you want to give the absolute path to a file from your website's root, use just /
.
What is your PHP version? Extension "Mysql" was deprecated in PHP 5.5.0. Use extension Mysqli (like mysqli_query).
I was working on a nice defect last time and was wondering more about how to use properly hover property for A tag link and for IE browser. A strange thing for me was that IE was not able to capture A tag link element based on a simple A selector. So, I found out how to even force capturing A tag element and I spotted that we must use more specifc CSS selector. Here is an example below - It works perfect:
li a[href]:hover {...}
You can also use references on foreach
values:
foreach($array as $elementKey => &$element) {
// $element is the same than &$array[$elementKey]
if (isset($element['id']) and $element['id'] == 'searched_value') {
unset($element);
}
}
I remember from my student days that it was said it's mathematically provable that you can do anything in code without a goto (i.e. there is no situation where goto is the only answer). So, I never use goto's (just my personal preference, not suggesting that i'm right or wrong)
Anyways, to break out of nested loops I do something like this:
var isDone = false;
for (var x in collectionX) {
for (var y in collectionY) {
for (var z in collectionZ) {
if (conditionMet) {
// some code
isDone = true;
}
if (isDone)
break;
}
if (isDone)
break;
}
if (isDone)
break;
}
... i hope that helps for those who like me are anti-goto "fanboys" :)
diff -r dir1 dir2 | grep dir1 | awk '{print $4}' > difference1.txt
Explanation:
diff -r dir1 dir2
shows which files are only in dir1 and those only in dir2 and also the changes of the files present in both directories if any.
diff -r dir1 dir2 | grep dir1
shows which files are only in dir1
awk
to print only filename.
For the URI query use urlencode
/urldecode
; for anything else use rawurlencode
/rawurldecode
.
The difference between urlencode
and rawurlencode
is that
urlencode
encodes according to application/x-www-form-urlencoded (space is encoded with +
) whilerawurlencode
encodes according to the plain Percent-Encoding (space is encoded with %20
).Remove obj
and just do this inside your for loop:
arr.push(i);
Also, the i < yearEnd
condition will not include the final year, so change it to i <= yearEnd
.
Pretending you are displaying a list of customer objects with "customerName" and "customerId" properties:
listBox.DataSource = customerListObject;
listBox.DataTextField = "customerName";
listBox.DataValueField = "customerId";
listBox.DataBind();
Edit: I know this works in asp.net - if you are doing a winforms app, it should be pretty similar (I hope...)
You can get it with .outerHeight()
.
Sometimes, it will return 0
. For the best results, you can call it in your div
's ready event.
To be safe, you should not set the height of the div
to x
. You can keep its height auto
to get content populated properly with the correct height.
$('#x').ready( function(){
// alerts the height in pixels
alert($('#x').outerHeight());
})
You can find a detailed post here.
This seems to be already asked before:
This might help:
Twitter Bootstrap Use collapse.js on table cells [Almost Done]
UPDATE:
Your fiddle wasn't loading jQuery, so anything worked.
<table class="table table-hover">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr data-toggle="collapse" data-target="#accordion" class="clickable">
<td>Some Stuff</td>
<td>Some more stuff</td>
<td>And some more</td>
</tr>
<tr>
<td colspan="3">
<div id="accordion" class="collapse">Hidden by default</div>
</td>
</tr>
</tbody>
</table>
Try this one: http://jsfiddle.net/Nb7wy/2/
I also added colspan='2'
to the details row. But it's essentially your fiddle with jQuery loaded (in frameworks in the left column)
It means the text is stored as wchar_t
characters rather than plain old char
characters.
(I originally said it meant unicode. I was wrong about that. But it can be used for unicode.)
There is no difference in C++, but I believe in C it would allow you to declare instances of the struct Foo without explicitly doing:
struct Foo bar;
In addition to using an map-like object, there has been an actual Map
object for some time now, which is available in TypeScript when compiling to ES6, or when using a polyfill with the ES6 type-definitions:
let people = new Map<string, Person>();
It supports the same functionality as Object
, and more, with a slightly different syntax:
// Adding an item (a key-value pair):
people.set("John", { firstName: "John", lastName: "Doe" });
// Checking for the presence of a key:
people.has("John"); // true
// Retrieving a value by a key:
people.get("John").lastName; // "Doe"
// Deleting an item by a key:
people.delete("John");
This alone has several advantages over using a map-like object, such as:
Object
(no, Object
does not support numbers, it converts them to strings)--noImplicitAny
, as a Map
always has a key type and a value type, whereas an object might not have an index-signatureObject
Additionally, a Map
object provides a more powerful and elegant API for common tasks, most of which are not available through simple Object
s without hacking together helper functions (although some of these require a full ES6 iterator/iterable polyfill for ES5 targets or below):
// Iterate over Map entries:
people.forEach((person, key) => ...);
// Clear the Map:
people.clear();
// Get Map size:
people.size;
// Extract keys into array (in insertion order):
let keys = Array.from(people.keys());
// Extract values into array (in insertion order):
let values = Array.from(people.values());
Comparing websocket and webrtc is unfair.
Websocket is based on top of TCP. Packet's boundary can be detected from header information of a websocket packet unlike tcp.
Typically, webrtc makes use of websocket. The signalling for webrtc is not defined, it is upto the service provider what kind of signalling he wants to use. It may be SIP, HTTP, JSON or any text / binary message.
The signalling messages can be send / received using websocket.
I'm going to answer the literal question: no, there isn't a good reason you see VARCHAR(255) used so often (there are indeed reasons, as discussed in the other answers, just not good ones). You won't find many examples of projects that have failed catastrophically because the architect chose VARCHAR(300) instead of VARCHAR(255). This would be an issue of near-total insignificance even if you were talking about CHAR instead of VARCHAR.
Have a look and see if the the JDK is at:
Library/Java/JavaVirtualMachines/ Or /System/Library/Java/JavaVirtualMachines/
Check this earlier SO post: JDK on OSX 10.7 Lion
Not just tab icons, notification and launcher lives an app. I was confused about the sizes of the other icons used for different situations in the app.
I'm using 32px mdpi (Action Bar icons) dimensions and I cannot say if it would be correct.
I regularly use IntelliJ, PHPStorm and WebStorm. Would love to only use IntelliJ. As pointed out by the vendor the "Open Directory" functionality not being in IntelliJ is painful.
Now for the rub part; I have tried using IntelliJ as my single IDE and have found performance to be terrible compared to the lighter weight versions. Intellisense is almost useless in IntelliJ compared to WebStorm.
On IE7, IE8, and IE9 just go to Settings->Internet Options->Security->Custom Level and change security settings under "Miscellaneous" set "Access data sources across domains" to Enable.
You can also use,
parent.jQuery("#testdiv").attr("style", content from form);
Maybe I'm missing something, but a lot of these answers seem overly complicated. You should be able to just set the columns within a single list:
Column to the front:
df = df[ ['Mid'] + [ col for col in df.columns if col != 'Mid' ] ]
Or if instead, you want to move it to the back:
df = df[ [ col for col in df.columns if col != 'Mid' ] + ['Mid'] ]
Or if you wanted to move more than one column:
cols_to_move = ['Mid', 'Zsore']
df = df[ cols_to_move + [ col for col in df.columns if col not in cols_to_move ] ]
C++20 std::numbers::pi
At last, it has arrived: http://eel.is/c++draft/numbers
main.cpp
#include <numbers> // std::numbers
#include <iomanip>
#include <iostream>
int main() {
std::cout << std::fixed << std::setprecision(20);
std::cout << "float " << std::numbers::pi_v<float> << std::endl;
std::cout << "double " << std::numbers::pi << std::endl;
std::cout << "long double " << std::numbers::pi_v<long double> << std::endl;
std::cout << "exact " << "3.141592653589793238462643383279502884197169399375105820974944" << std::endl;
}
where the exact result was calculated with:
echo "scale=60; 4*a(1)" | BC_LINE_LENGTH=0 bc -l
as per: How can I calculate pi using Bash command
Compile and run:
g++-10 -ggdb3 -O0 -std=c++20 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
Output:
float 3.14159274101257324219
double 3.14159265358979311600
long double 3.14159265358979323851
exact 3.141592653589793238462643383279502884197169399375105820974944
Tested on Ubuntu 20.04 amd64, GCC 10.2.0
The accepted proposal describes:
5.0. “Headers” [headers] In the table [tab:cpp.library.headers], a new
<math>
header needs to be added.[...]
namespace std { namespace math { template<typename T > inline constexpr T pi_v = unspecified; inline constexpr double pi = pi_v<double>;
There is also a std::numbers::e
of course :-) How to calculate Euler constant or Euler powered in C++?
These constants use the C++14 variable template feature: C++14 Variable Templates: what is their purpose? Any usage example?
In earlier versions of the draft, the constant was under std::math::pi
: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0631r7.pdf
Because you want to set it when the form loads, you have to first .Show() the form before you can call the .Focus() method. The form cannot take focus in the Load event until you show the form
Private Sub RibbonForm1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.Show()
TextBox1.Select()
End Sub
You can do something like this to count from a list of things.
IList<String> names = new List<string>() { "ToString", "Format" };
IEnumerable<String> methodNames = typeof(String).GetMethods().Select(x => x.Name);
int count = methodNames.Where(x => names.Contains(x)).Count();
To count a single element
string occur = "Test1";
IList<String> words = new List<string>() {"Test1","Test2","Test3","Test1"};
int count = words.Where(x => x.Equals(occur)).Count();
Azure Data Studio with Postgres addin is the tool of choice to manage postgres databases for me. Check it out. https://docs.microsoft.com/en-us/sql/azure-data-studio/quickstart-postgres?view=sql-server-ver15
Python 3:
import itertools as it
for foo, bar in list(it.izip_longest(list1, list2)):
print(foo, bar)
...Just open this answer for edit to see it.
Nested lists, deeper levels: ---- leave here an empty row * first level A item - no space in front the bullet character * second level Aa item - 1 space is enough * third level Aaa item - 5 spaces min * second level Ab item - 4 spaces possible too * first level B item
Nested lists, deeper levels:
first level B item
Nested lists, deeper levels:
...Skip a line and indent eight spaces. (as said in the editor-help, just on this page)
* first level A item - no space in front the bullet character
* second level Aa item - 1 space is enough
* third level Aaa item - 5 spaces min
* second level Ab item - 4 spaces possible too
* first level B item
You can use ::after
to create a 0px
-height block after the <h4>
, which effectively moves anything after the <h4>
to the next line:
h4 {_x000D_
display: inline;_x000D_
}_x000D_
h4::after {_x000D_
content: "";_x000D_
display: block;_x000D_
}
_x000D_
<ul>_x000D_
<li>_x000D_
Text, text, text, text, text. <h4>Sub header</h4>_x000D_
Text, text, text, text, text._x000D_
</li>_x000D_
</ul>
_x000D_
This works for me :
<style>
.WidgetBody
{
background: #F0F0F0;
background-image:url('images/mini-loader.gif');
background-position: 50% 50%;
background-repeat:no-repeat;
}
</style>
You can also get this error message when you place an inline tag in your html but make the (common for me) typo that you forget to add the slash to the closing-script tag like this:
<script>
alert("I ran!");
<script> <!-- OOPS opened script tag again instead of closing it -->
The JS interpreter tries to "execute" the tag, which looks like an expression beginning with a less-than sign, hence the error: SyntaxError: expected expression, got '<'
I have slightly modified Emmanuel Touzery's implementation.
This version;
public static <T, K, U> Collector<T, ?, Map<K, U>> toMapOfNullables(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) {
return Collectors.collectingAndThen(
Collectors.toList(),
list -> {
Map<K, U> map = new LinkedHashMap<>();
list.forEach(item -> {
K key = keyMapper.apply(item);
if (map.containsKey(key)) {
throw new IllegalStateException(String.format("Duplicate key %s", key));
}
map.put(key, valueMapper.apply(item));
});
return map;
}
);
}
Unit tests:
@Test
public void toMapOfNullables_WhenHasNullKey() {
assertEquals(singletonMap(null, "value"),
Stream.of("ignored").collect(Utils.toMapOfNullables(i -> null, i -> "value"))
);
}
@Test
public void toMapOfNullables_WhenHasNullValue() {
assertEquals(singletonMap("key", null),
Stream.of("ignored").collect(Utils.toMapOfNullables(i -> "key", i -> null))
);
}
@Test
public void toMapOfNullables_WhenHasDuplicateNullKeys() {
assertThrows(new IllegalStateException("Duplicate key null"),
() -> Stream.of(1, 2, 3).collect(Utils.toMapOfNullables(i -> null, i -> i))
);
}
@Test
public void toMapOfNullables_WhenHasDuplicateKeys_NoneHasNullValue() {
assertThrows(new IllegalStateException("Duplicate key duplicated-key"),
() -> Stream.of(1, 2, 3).collect(Utils.toMapOfNullables(i -> "duplicated-key", i -> i))
);
}
@Test
public void toMapOfNullables_WhenHasDuplicateKeys_OneHasNullValue() {
assertThrows(new IllegalStateException("Duplicate key duplicated-key"),
() -> Stream.of(1, null, 3).collect(Utils.toMapOfNullables(i -> "duplicated-key", i -> i))
);
}
@Test
public void toMapOfNullables_WhenHasDuplicateKeys_AllHasNullValue() {
assertThrows(new IllegalStateException("Duplicate key duplicated-key"),
() -> Stream.of(null, null, null).collect(Utils.toMapOfNullables(i -> "duplicated-key", i -> i))
);
}
I had a similar thing happen to me. I didn't want to stage the files just yet so I added them with git add
and then just did git reset
. This basically just added and then unstaged my changes but cleared the unmerged paths.
Note The accepted is perfectly fine - but wanted to add a version4 example because they are different enough.
import React from 'react';
import { Link } from 'react-router';
export default class Nav extends React.Component {
render() {
return (
<nav className="Nav">
<div className="Nav__container">
<Link to="/" className="Nav__brand">
<img src="logo.svg" className="Nav__logo" />
</Link>
<div className="Nav__right">
<ul className="Nav__item-wrapper">
<li className="Nav__item">
<Link className="Nav__link" to="/path1">Link 1</Link>
</li>
<li className="Nav__item">
<Link className="Nav__link" to="/path2">Link 2</Link>
</li>
<li className="Nav__item">
<Link className="Nav__link" to="/path3">Link 3</Link>
</li>
</ul>
</div>
</div>
</nav>
);
}
}
import React from 'react';
import { Link, Switch, Route } from 'react-router';
import Nav from './nav';
import Page1 from './page1';
import Page2 from './page2';
import Page3 from './page3';
export default class App extends React.Component {
render() {
return (
<div className="App">
<Router>
<div>
<Nav />
<Switch>
<Route exactly component={Landing} pattern="/" />
<Route exactly component={Page1} pattern="/path1" />
<Route exactly component={Page2} pattern="/path2" />
<Route exactly component={Page3} pattern="/path3" />
<Route component={Page404} />
</Switch>
</div>
</Router>
</div>
);
}
}
Alternatively, if you want a more dynamic nav, you can look at the excellent v4 docs: https://reacttraining.com/react-router/web/example/sidebar
A few people have asked about a page without the Nav, such as a login page. I typically approach it with a wrapper Route component
import React from 'react';
import { Link, Switch, Route } from 'react-router';
import Nav from './nav';
import Page1 from './page1';
import Page2 from './page2';
import Page3 from './page3';
const NavRoute = ({exact, path, component: Component}) => (
<Route exact={exact} path={path} render={(props) => (
<div>
<Header/>
<Component {...props}/>
</div>
)}/>
)
export default class App extends React.Component {
render() {
return (
<div className="App">
<Router>
<Switch>
<NavRoute exactly component={Landing} pattern="/" />
<Route exactly component={Login} pattern="/login" />
<NavRoute exactly component={Page1} pattern="/path1" />
<NavRoute exactly component={Page2} pattern="/path2" />
<NavRoute component={Page404} />
</Switch>
</Router>
</div>
);
}
}
Use callbacks. Something like this should work based on your sample code.
function someFunc() {
callAjaxfunc(function() {
console.log('Pass2');
});
}
function callAjaxfunc(callback) {
//All ajax calls called here
onAjaxSuccess: function() {
callback();
};
console.log('Pass1');
}
This will print Pass1
immediately (assuming ajax request takes atleast a few microseconds), then print Pass2
when the onAjaxSuccess
is executed.
Why not just create a setup project? It's really easy.
Voila, and you're done.
See here for more: http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx
There is also a way to prompt the user for credentials (or supply your own).
Shell is an interface between a user and OS to access to an operating system's services. It can be either GUI or CLI (Command Line interface).
sh (Bourne shell) is a shell command-line interpreter, for Unix/Unix-like operating systems. It provides some built-in commands. In scripting language we denote interpreter as #!/bin/sh
. It was one most widely supported by other shells like bash (free/open), kash (not free).
Bash (Bourne again shell) is a shell replacement for the Bourne shell. Bash is superset of sh. Bash supports sh. POSIX is a set of standards defining how POSIX-compliant systems should work. Bash is not actually a POSIX compliant shell. In a scripting language we denote the interpreter as #!/bin/bash
.
Analogy:
Go to menu , search for Regional Settings. Switch to Keyboard layouts tab. Click Options button. Search for Key(s) to change layout. There isn't a default one so you have to tick the combination you like. Enjoy.
i think you can download the latest android SDK and use it.i do this and fixed the problem and work well. here is the link: http://developer.android.com/sdk/index.html#download
The error you're getting appears to be the result of the fact that there is no underscore between "chartered" and "flight" in the table name. I assume you want something like this where the name of the table is chartered_flight
.
CREATE TABLE chartered_flight(flight_no NUMBER(4) PRIMARY KEY
, customer_id NUMBER(6) REFERENCES customer(customer_id)
, aircraft_no NUMBER(4) REFERENCES aircraft(aircraft_no)
, flight_type VARCHAR2 (12)
, flight_date DATE NOT NULL
, flight_time INTERVAL DAY TO SECOND NOT NULL
, takeoff_at CHAR (3) NOT NULL
, destination CHAR (3) NOT NULL)
Generally, there is no benefit to declaring a column as CHAR(3)
rather than VARCHAR2(3)
. Declaring a column as CHAR(3)
doesn't force there to be three characters of (useful) data. It just tells Oracle to space-pad data with fewer than three characters to three characters. That is unlikely to be helpful if someone inadvertently enters an incorrect code. Potentially, you could declare the column as VARCHAR2(3)
and then add a CHECK
constraint that LENGTH(takeoff_at) = 3
.
CREATE TABLE chartered_flight(flight_no NUMBER(4) PRIMARY KEY
, customer_id NUMBER(6) REFERENCES customer(customer_id)
, aircraft_no NUMBER(4) REFERENCES aircraft(aircraft_no)
, flight_type VARCHAR2 (12)
, flight_date DATE NOT NULL
, flight_time INTERVAL DAY TO SECOND NOT NULL
, takeoff_at CHAR (3) NOT NULL CHECK( length( takeoff_at ) = 3 )
, destination CHAR (3) NOT NULL CHECK( length( destination ) = 3 )
)
Since both takeoff_at
and destination
are airport codes, you really ought to have a separate table of valid airport codes and define foreign key constraints between the chartered_flight
table and this new airport_code
table. That ensures that only valid airport codes are added and makes it much easier in the future if an airport code changes.
And from a naming convention standpoint, since both takeoff_at
and destination
are airport codes, I would suggest that the names be complementary and indicate that fact. Something like departure_airport_code
and arrival_airport_code
, for example, would be much more meaningful.
.so
files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.
.a
files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar
command -- a predecessor of tar
that's now just used for making libraries) of the original .o object files.
.la
files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?
Static and dynamic libraries each have pros and cons.
Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.
Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.
Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.
Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.
Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.
Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.
Dynamic libraries are especially useful for system libraries, like libc
. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.
These errors mean that the R code you are trying to run or source is not syntactically correct. That is, you have a typo.
To fix the problem, read the error message carefully. The code provided in the error message shows where R thinks that the problem is. Find that line in your original code, and look for the typo.
Prophylactic measures to prevent you getting the error again
The best way to avoid syntactic errors is to write stylish code. That way, when you mistype things, the problem will be easier to spot. There are many R style guides linked from the SO R tag info page. You can also use the formatR
package to automatically format your code into something more readable. In RStudio, the keyboard shortcut CTRL + SHIFT + A will reformat your code.
Consider using an IDE or text editor that highlights matching parentheses and braces, and shows strings and numbers in different colours.
Common syntactic mistakes that generate these errors
Mismatched parentheses, braces or brackets
If you have nested parentheses, braces or brackets it is very easy to close them one too many or too few times.
{}}
## Error: unexpected '}' in "{}}"
{{}} # OK
Missing *
when doing multiplication
This is a common mistake by mathematicians.
5x
Error: unexpected symbol in "5x"
5*x # OK
Not wrapping if, for, or return values in parentheses
This is a common mistake by MATLAB users. In R, if
, for
, return
, etc., are functions, so you need to wrap their contents in parentheses.
if x > 0 {}
## Error: unexpected symbol in "if x"
if(x > 0) {} # OK
Not using multiple lines for code
Trying to write multiple expressions on a single line, without separating them by semicolons causes R to fail, as well as making your code harder to read.
x + 2 y * 3
## Error: unexpected symbol in "x + 2 y"
x + 2; y * 3 # OK
else
starting on a new line
In an if
-else
statement, the keyword else
must appear on the same line as the end of the if
block.
if(TRUE) 1
else 2
## Error: unexpected 'else' in "else"
if(TRUE) 1 else 2 # OK
if(TRUE)
{
1
} else # also OK
{
2
}
=
instead of ==
=
is used for assignment and giving values to function arguments. ==
tests two values for equality.
if(x = 0) {}
## Error: unexpected '=' in "if(x ="
if(x == 0) {} # OK
Missing commas between arguments
When calling a function, each argument must be separated by a comma.
c(1 2)
## Error: unexpected numeric constant in "c(1 2"
c(1, 2) # OK
Not quoting file paths
File paths are just strings. They need to be wrapped in double or single quotes.
path.expand(~)
## Error: unexpected ')' in "path.expand(~)"
path.expand("~") # OK
Quotes inside strings
This is a common problem when trying to pass quoted values to the shell via system
, or creating quoted xPath
or sql
queries.
Double quotes inside a double quoted string need to be escaped. Likewise, single quotes inside a single quoted string need to be escaped. Alternatively, you can use single quotes inside a double quoted string without escaping, and vice versa.
"x"y"
## Error: unexpected symbol in ""x"y"
"x\"y" # OK
'x"y' # OK
Using curly quotes
So-called "smart" quotes are not so smart for R programming.
path.expand(“~”)
## Error: unexpected input in "path.expand(“"
path.expand("~") # OK
Using non-standard variable names without backquotes
?make.names
describes what constitutes a valid variable name. If you create a non-valid variable name (using assign
, perhaps), then you need to access it with backquotes,
assign("x y", 0)
x y
## Error: unexpected symbol in "x y"
`x y` # OK
This also applies to column names in data frames created with check.names = FALSE
.
dfr <- data.frame("x y" = 1:5, check.names = FALSE)
dfr$x y
## Error: unexpected symbol in "dfr$x y"
dfr[,"x y"] # OK
dfr$`x y` # also OK
It also applies when passing operators and other special values to functions. For example, looking up help on %in%
.
?%in%
## Error: unexpected SPECIAL in "?%in%"
?`%in%` # OK
Sourcing non-R code
The source
function runs R code from a file. It will break if you try to use it to read in your data. Probably you want read.table
.
source(textConnection("x y"))
## Error in source(textConnection("x y")) :
## textConnection("x y"):1:3: unexpected symbol
## 1: x y
## ^
Corrupted RStudio desktop file
RStudio users have reported erroneous source errors due to a corrupted .rstudio-desktop
file. These reports only occurred around March 2014, so it is possibly an issue with a specific version of the IDE. RStudio can be reset using the instructions on the support page.
Using expression without paste in mathematical plot annotations
When trying to create mathematical labels or titles in plots, the expression created must be a syntactically valid mathematical expression as described on the ?plotmath
page. Otherwise the contents should be contained inside a call to paste.
plot(rnorm(10), ylab = expression(alpha ^ *)))
## Error: unexpected '*' in "plot(rnorm(10), ylab = expression(alpha ^ *"
plot(rnorm(10), ylab = expression(paste(alpha ^ phantom(0), "*"))) # OK
Use the left
function:
QString yourString = "This is a string";
QString leftSide = yourString.left(5);
qDebug() << leftSide; // output "This "
Also have a look at mid()
if you want more control.
Bootstrapping something fast to chart multiple y-axes sharing an x-axis using @joe-kington's answer:
# d = Pandas Dataframe,
# ys = [ [cols in the same y], [cols in the same y], [cols in the same y], .. ]
def chart(d,ys):
from itertools import cycle
fig, ax = plt.subplots()
axes = [ax]
for y in ys[1:]:
# Twin the x-axis twice to make independent y-axes.
axes.append(ax.twinx())
extra_ys = len(axes[2:])
# Make some space on the right side for the extra y-axes.
if extra_ys>0:
temp = 0.85
if extra_ys<=2:
temp = 0.75
elif extra_ys<=4:
temp = 0.6
if extra_ys>5:
print 'you are being ridiculous'
fig.subplots_adjust(right=temp)
right_additive = (0.98-temp)/float(extra_ys)
# Move the last y-axis spine over to the right by x% of the width of the axes
i = 1.
for ax in axes[2:]:
ax.spines['right'].set_position(('axes', 1.+right_additive*i))
ax.set_frame_on(True)
ax.patch.set_visible(False)
ax.yaxis.set_major_formatter(matplotlib.ticker.OldScalarFormatter())
i +=1.
# To make the border of the right-most axis visible, we need to turn the frame
# on. This hides the other plots, however, so we need to turn its fill off.
cols = []
lines = []
line_styles = cycle(['-','-','-', '--', '-.', ':', '.', ',', 'o', 'v', '^', '<', '>',
'1', '2', '3', '4', 's', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd', '|', '_'])
colors = cycle(matplotlib.rcParams['axes.color_cycle'])
for ax,y in zip(axes,ys):
ls=line_styles.next()
if len(y)==1:
col = y[0]
cols.append(col)
color = colors.next()
lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
ax.set_ylabel(col,color=color)
#ax.tick_params(axis='y', colors=color)
ax.spines['right'].set_color(color)
else:
for col in y:
color = colors.next()
lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
cols.append(col)
ax.set_ylabel(', '.join(y))
#ax.tick_params(axis='y')
axes[0].set_xlabel(d.index.name)
lns = lines[0]
for l in lines[1:]:
lns +=l
labs = [l.get_label() for l in lns]
axes[0].legend(lns, labs, loc=0)
plt.show()
I've used CSS Grid to fix that. CSS Grid will make all the elements in the same row, all the same height.
I haven't looked into making all the elements in all the rows the same height though.
Anyway, here's how it can be done:
HTML:
<div class="grid-container">
<div class="card">...</div>
<div class="card">...</div>
</div>
CSS:
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}
Here's a complete JSFiddle. https://jsfiddle.net/bluegrounds/owjvhstq/4/
make sure you use the POST to insert the data. Actually you were using GET.
Assign something to your strings. This will definitely help.
Yes, I found MySQL also cannot edit result tables. Usually results tables joining other tables don't have primary keys. I heard other suggested put the result table in another table, but the better solution is to use Dbeaver which can edit result tables.
<graphics.h>
is very old library. It's better to use something that is new
Here are some 2D libraries (platform independent) for C/C++
Also there is a free very powerful 3D open source graphics library for C++
Bar
is guaranteed not to change the object it is being invoked on. See the section about const correctness in the C++ FAQ, for example.
password.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);
also you have to be careful that cursor moves to the starting point of the editText after this function is called, so make sure that you move cursor to the end point again.
public abstract class SingleFragmentActivity extends Activity {
public static final String FRAGMENT_TAG = "single";
private Fragment fragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
fragment = onCreateFragment();
getFragmentManager().beginTransaction()
.add(android.R.id.content, fragment, FRAGMENT_TAG)
.commit();
} else {
fragment = getFragmentManager().findFragmentByTag(FRAGMENT_TAG);
}
}
public abstract Fragment onCreateFragment();
public Fragment getFragment() {
return fragment;
}
}
use
public class ViewCatalogItemActivity extends SingleFragmentActivity {
@Override
public Fragment onCreateFragment() {
return new FragmentWorkShops();
}
}
As of 2019 there is a subcommand: vagrant box repackage
vagrant box repackage --help
Usage: vagrant box repackage <name> <provider> <version>
-h, --help Print this help
You can find name
provider
and version
by running vagrant box list
vagrant box list
macinbox (virtualbox, 10.14.5)
The ouput of vagrant box repackage
is a file called package.box
which is basically a tgz file which the content can be listed as below:
tar tzf package.box
./metadata.json
./box.ovf
./Vagrantfile
./box-disk001.vmdk
Here's another approach that runs slower (about 1000ms) than the above answer, but has an interesting idea :-)
Instead of iterating through each property chain, it just picks the last property and uses a look-up-table for the rest to store the intermediate results. This look-up-table will be iterated until there are no property chains left and all values reside on uncocatenated properties.
JSON.unflatten = function(data) {
"use strict";
if (Object(data) !== data || Array.isArray(data))
return data;
var regex = /\.?([^.\[\]]+)$|\[(\d+)\]$/,
props = Object.keys(data),
result, p;
while(p = props.shift()) {
var m = regex.exec(p),
target;
if (m.index) {
var rest = p.slice(0, m.index);
if (!(rest in data)) {
data[rest] = m[2] ? [] : {};
props.push(rest);
}
target = data[rest];
} else {
target = result || (result = (m[2] ? [] : {}));
}
target[m[2] || m[1]] = data[p];
}
return result;
};
It currently uses the data
input parameter for the table, and puts lots of properties on it - a non-destructive version should be possible as well. Maybe a clever lastIndexOf
usage performs better than the regex (depends on the regex engine).
Use this code
TextView textView = new TextView(YourActivity.this);
textView.setGravity(Gravity.CENTER | Gravity.TOP);
textView.setText("some text");
Sadly, it's not possible in Java. You'll have to resort to using if-else
statements.
I would use the well-tested (millions of downloads per week) pify and async modules. If you are unfamiliar with the async module, I highly recommend you check out its docs. I've seen multiple devs waste time recreating its methods, or worse, making difficult-to-maintain async code when higher-order async methods would simplify code.
const async = require('async')_x000D_
const fs = require('fs-promise')_x000D_
const pify = require('pify')_x000D_
_x000D_
async function getFilePaths() {_x000D_
return Promise.resolve([_x000D_
'./package.json',_x000D_
'./package-lock.json',_x000D_
]);_x000D_
}_x000D_
_x000D_
async function printFiles () {_x000D_
const files = await getFilePaths()_x000D_
_x000D_
await pify(async.eachSeries)(files, async (file) => { // <-- run in series_x000D_
// await pify(async.each)(files, async (file) => { // <-- run in parallel_x000D_
const contents = await fs.readFile(file, 'utf8')_x000D_
console.log(contents)_x000D_
})_x000D_
console.log('HAMBONE')_x000D_
}_x000D_
_x000D_
printFiles().then(() => {_x000D_
console.log('HAMBUNNY')_x000D_
})_x000D_
// ORDER OF LOGS:_x000D_
// package.json contents_x000D_
// package-lock.json contents_x000D_
// HAMBONE_x000D_
// HAMBUNNY_x000D_
```
_x000D_
For uploading Form-Encoded POST requests, I recommend using the FormData object.
Example code:
var params = {
userName: '[email protected]',
password: 'Password!',
grant_type: 'password'
};
var formData = new FormData();
for (var k in params) {
formData.append(k, params[k]);
}
var request = {
method: 'POST',
headers: headers,
body: formData
};
fetch(url, request);
You can do this
textView.text = "Name: \(string1) \n" + "Phone Number: \(string2)"
The output will be
Name: output of string1 Phone Number: output of string2
A POJO is a Plain Old Java Object.
From the wikipedia article I linked to:
In computing software, POJO is an acronym for Plain Old Java Object. The name is used to emphasize that a given object is an ordinary Java Object, not a special object, and in particular not an Enterprise JavaBean
Your class appears to already be a POJO.
To remove everything before a specific char, use below.
string1 = string1.Substring(string1.IndexOf('$') + 1);
What this does is, takes everything before the $ char and removes it. Now if you want to remove the items after a character, just change the +1 to a -1 and you are set!
But for a URL, I would use the built in .NET class to take of that.
use
Objective-C
[headingButton setTitleColor:[UIColor colorWithRed:36/255.0 green:71/255.0 blue:113/255.0 alpha:1.0] forState:UIControlStateNormal];
Swift
headingButton.setTitleColor(.black, for: .normal)
Swift 4 and Constraints
To your tableview add a bottom constraint relative to the bottom safe area. In my case the constraint is called tableViewBottomLayoutConstraint.
@IBOutlet weak var tableViewBottomLayoutConstraint: NSLayoutConstraint!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(notification:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear(notification:)), name: .UIKeyboardWillHide, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow , object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide , object: nil)
}
@objc
func keyboardWillAppear(notification: NSNotification?) {
guard let keyboardFrame = notification?.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue else {
return
}
let keyboardHeight: CGFloat
if #available(iOS 11.0, *) {
keyboardHeight = keyboardFrame.cgRectValue.height - self.view.safeAreaInsets.bottom
} else {
keyboardHeight = keyboardFrame.cgRectValue.height
}
tableViewBottomLayoutConstraint.constant = keyboardHeight
}
@objc
func keyboardWillDisappear(notification: NSNotification?) {
tableViewBottomLayoutConstraint.constant = 0.0
}
In the latest version of ggplot2, this can be more easy.
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p+ geom_point() + scale_x_continuous(expand = expansion(mult = c(0, 0))) + scale_y_continuous(expand = expansion(mult = c(0, 0)))
See ?expansion()
for more details.
I have fixed this in my matplotlib source, but it's not a pretty fix. However, if you, like me, are very particular about how the graph looks, it's worth it.
The issue seems to be in the rendering backends; they each get the correct values for linewidth, font size, etc., but that comes out slightly larger when rendered as a PDF or PNG than when rendered with show().
I added a few lines to the source for PNG generation, in the file matplotlib/backends/backend_agg.py. You could make similar changes for each backend you use, or find a way to make a more clever change in a single location ;)
Added to my matplotlib/backends/backend_agg.py file:
# The top of the file, added lines 42 - 44
42 # @warning: CHANGED FROM SOURCE to draw thinner lines
43 PATH_SCALAR = .8
44 FONT_SCALAR = .95
# In the draw_markers method, added lines 90 - 91
89 def draw_markers(self, *kl, **kw):
90 # @warning: CHANGED FROM SOURCE to draw thinner lines
91 kl[0].set_linewidth(kl[0].get_linewidth()*PATH_SCALAR)
92 return self._renderer.draw_markers(*kl, **kw)
# At the bottom of the draw_path method, added lines 131 - 132:
130 else:
131 # @warning: CHANGED FROM SOURCE to draw thinner lines
132 gc.set_linewidth(gc.get_linewidth()*PATH_SCALAR)
133 self._renderer.draw_path(gc, path, transform, rgbFace)
# At the bottom of the _get_agg_font method, added line 242 and the *FONT_SCALAR
241 font.clear()
242 # @warning: CHANGED FROM SOURCE to draw thinner lines
243 size = prop.get_size_in_points()*FONT_SCALAR
244 font.set_size(size, self.dpi)
So that suits my needs for now, but, depending on what you're doing, you may want to implement similar changes in other methods. Or find a better way to do the same without so many line changes!
Update: After posting an issue to the matplotlib project at Github, I was able to track down the source of my problem: I had changed the figure.dpi setting in the matplotlibrc file. If that value is different than the default, my savefig() images come out different, even if I set the savefig dpi to be the same as the figure dpi. So, instead of changing the source as above, I just kept the figure.dpi setting as the default 80, and was able to generate images with savefig() that looked like images from show().
Leon, had you also changed that setting?
Simply use min()
SELECT company, workflow, MIN(date)
FROM workflowTable
GROUP BY company, workflow
$("a > button").live('click', function() {
location.href = $(this).closest("a").attr("href");
}); // fixed
DPAPI is just for this purpose. Use DPAPI to encrypt the password the first time the user enters is, store it in a secure location (User's registry, User's application data directory, are some choices). Whenever the app is launched, check the location to see if your key exists, if it does use DPAPI to decrypt it and allow access, otherwise deny it.
In Excel, there is a way to embed relative reference to file or directory. You can try type in excel cell : =HYPERLINK("..\Name_of_file_or_folder\","DisplayLinkName")
I will submit the basis for an alternate solution. It is not specific to a Tk progress bar per se, but it can certainly be implemented very easily for that.
Here are some classes that allow you to run other tasks in the background of Tk, update the Tk controls when desired, and not lock up the gui!
Here's class TkRepeatingTask and BackgroundTask:
import threading
class TkRepeatingTask():
def __init__( self, tkRoot, taskFuncPointer, freqencyMillis ):
self.__tk_ = tkRoot
self.__func_ = taskFuncPointer
self.__freq_ = freqencyMillis
self.__isRunning_ = False
def isRunning( self ) : return self.__isRunning_
def start( self ) :
self.__isRunning_ = True
self.__onTimer()
def stop( self ) : self.__isRunning_ = False
def __onTimer( self ):
if self.__isRunning_ :
self.__func_()
self.__tk_.after( self.__freq_, self.__onTimer )
class BackgroundTask():
def __init__( self, taskFuncPointer ):
self.__taskFuncPointer_ = taskFuncPointer
self.__workerThread_ = None
self.__isRunning_ = False
def taskFuncPointer( self ) : return self.__taskFuncPointer_
def isRunning( self ) :
return self.__isRunning_ and self.__workerThread_.isAlive()
def start( self ):
if not self.__isRunning_ :
self.__isRunning_ = True
self.__workerThread_ = self.WorkerThread( self )
self.__workerThread_.start()
def stop( self ) : self.__isRunning_ = False
class WorkerThread( threading.Thread ):
def __init__( self, bgTask ):
threading.Thread.__init__( self )
self.__bgTask_ = bgTask
def run( self ):
try :
self.__bgTask_.taskFuncPointer()( self.__bgTask_.isRunning )
except Exception as e: print repr(e)
self.__bgTask_.stop()
Here's a Tk test which demos the use of these. Just append this to the bottom of the module with those classes in it if you want to see the demo in action:
def tkThreadingTest():
from tkinter import Tk, Label, Button, StringVar
from time import sleep
class UnitTestGUI:
def __init__( self, master ):
self.master = master
master.title( "Threading Test" )
self.testButton = Button(
self.master, text="Blocking", command=self.myLongProcess )
self.testButton.pack()
self.threadedButton = Button(
self.master, text="Threaded", command=self.onThreadedClicked )
self.threadedButton.pack()
self.cancelButton = Button(
self.master, text="Stop", command=self.onStopClicked )
self.cancelButton.pack()
self.statusLabelVar = StringVar()
self.statusLabel = Label( master, textvariable=self.statusLabelVar )
self.statusLabel.pack()
self.clickMeButton = Button(
self.master, text="Click Me", command=self.onClickMeClicked )
self.clickMeButton.pack()
self.clickCountLabelVar = StringVar()
self.clickCountLabel = Label( master, textvariable=self.clickCountLabelVar )
self.clickCountLabel.pack()
self.threadedButton = Button(
self.master, text="Timer", command=self.onTimerClicked )
self.threadedButton.pack()
self.timerCountLabelVar = StringVar()
self.timerCountLabel = Label( master, textvariable=self.timerCountLabelVar )
self.timerCountLabel.pack()
self.timerCounter_=0
self.clickCounter_=0
self.bgTask = BackgroundTask( self.myLongProcess )
self.timer = TkRepeatingTask( self.master, self.onTimer, 1 )
def close( self ) :
print "close"
try: self.bgTask.stop()
except: pass
try: self.timer.stop()
except: pass
self.master.quit()
def onThreadedClicked( self ):
print "onThreadedClicked"
try: self.bgTask.start()
except: pass
def onTimerClicked( self ) :
print "onTimerClicked"
self.timer.start()
def onStopClicked( self ) :
print "onStopClicked"
try: self.bgTask.stop()
except: pass
try: self.timer.stop()
except: pass
def onClickMeClicked( self ):
print "onClickMeClicked"
self.clickCounter_+=1
self.clickCountLabelVar.set( str(self.clickCounter_) )
def onTimer( self ) :
print "onTimer"
self.timerCounter_+=1
self.timerCountLabelVar.set( str(self.timerCounter_) )
def myLongProcess( self, isRunningFunc=None ) :
print "starting myLongProcess"
for i in range( 1, 10 ):
try:
if not isRunningFunc() :
self.onMyLongProcessUpdate( "Stopped!" )
return
except : pass
self.onMyLongProcessUpdate( i )
sleep( 1.5 ) # simulate doing work
self.onMyLongProcessUpdate( "Done!" )
def onMyLongProcessUpdate( self, status ) :
print "Process Update: %s" % (status,)
self.statusLabelVar.set( str(status) )
root = Tk()
gui = UnitTestGUI( root )
root.protocol( "WM_DELETE_WINDOW", gui.close )
root.mainloop()
if __name__ == "__main__":
tkThreadingTest()
Two import points I'll stress about BackgroundTask:
1) The function you run in the background task needs to take a function pointer it will both invoke and respect, which allows the task to be cancelled mid way through - if possible.
2) You need to make sure the background task is stopped when you exit your application. That thread will still run even if your gui is closed if you don't address that!
Andrew White's answer is sufficient to get you moving. Here's a step-by-step for beginners.
A simple get started:
Create test.cpp: (This will be built and run to verify you got things set up right.)
#include <X11/Xlib.h>
#include <unistd.h>
main()
{
// Open a display.
Display *d = XOpenDisplay(0);
if ( d )
{
// Create the window
Window w = XCreateWindow(d, DefaultRootWindow(d), 0, 0, 200,
100, 0, CopyFromParent, CopyFromParent,
CopyFromParent, 0, 0);
// Show the window
XMapWindow(d, w);
XFlush(d);
// Sleep long enough to see the window.
sleep(10);
}
return 0;
}
Try: g++ test.cpp -lX11
If it builds to a.out
, try running it.
If you see a simple window drawn, you have the necessary libraries, and some other root problem is afoot.
If your response is:
test.cpp:1:22: fatal error: X11/Xlib.h: No such file or directory
compilation terminated.
you need to install X11 development libraries.
sudo apt-get install libx11-dev
Retry g++ test.cpp -lX11
If it works, you're golden.
Tested using a fresh install of libX11-dev_2%3a1.5.0-1_i386.deb
No, it's not.
Attributes are meta-data and stored in binary-form in the compiled assembly (that's also why you can only use simple types in them).
None of the above worked for me. I spent too much time clearing other errors that came up. I found this to be the easiest and the best way.
This works for getting JavaFx on Jdk 11, 12 & on OpenJdk12 too!
module thisIsTheNameOfYourProject {
requires javafx.fxml;
requires javafx.controls;
requires javafx.graphics;
opens sample;
}
The entire thing took me only 5mins !!!
Use this example, you can split with the colspan
attribute
<TABLE BORDER>
<TR>
<TD>Item 1</TD>
<TD>Item 1</TD>
<TD COLSPAN=2>Item 2</TD>
</TR>
<TR>
<TD>Item 3</TD>
<TD>Item 3</TD>
<TD>Item 4</TD>
<TD>Item 5</TD>
</TR>
</TABLE>
More examples at http://hypermedia.univ-paris8.fr/jean/internet/ex_table.html.
if You are Using Toolbar the just Add
android:layout_gravity="center_horizontal"
Under the Toolbar Just like this snippet
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay">
<TextView
android:id="@+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" //Important
android:textColor="@color/whitecolor"
android:textSize="20sp"
android:textStyle="bold" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
This code work in IE7 and Chrome:
var hiddenInput = document.createElement("input");
hiddenInput.setAttribute("id", "uniqueIdentifier");
hiddenInput.setAttribute("type", "hidden");
hiddenInput.setAttribute("value", 'ID');
hiddenInput.setAttribute("class", "ListItem");
$('body').append(hiddenInput);
Maybe problem somewhere else ?
You can't.. You would have to know:
Maybe, just maybe if the object was optically tagged with for example a QR code, and you have a code-to-loc map...
The call to time(NULL)
returns the current calendar time (seconds since Jan 1, 1970). See this reference for details. Ordinarily, if you pass in a pointer to a time_t
variable, that pointer variable will point to the current time.
Hint: The STRINGIZE
macro above is cool, but if you make a mistake and its argument isn't a macro - you had a typo in the name, or forgot to #include
the header file - then the compiler will happily put the purported macro name into the string with no error.
If you intend that the argument to STRINGIZE
is always a macro with a normal C value, then
#define STRINGIZE(A) ((A),STRINGIZE_NX(A))
will expand it once and check it for validity, discard that, and then expand it again into a string.
It took me a while to figure out why STRINGIZE(ENOENT)
was ending up as "ENOENT"
instead of "2"
... I hadn't included errno.h
.
Never forget that offset() function is giving your element's position to document. So when you need scroll your element relative to its parent you should use this;
$('.a-parent-div').find('a').click(function(event){
event.preventDefault();
$('.scroll-div').animate({
scrollTop: $( $.attr(this, 'href') ).position().top + $('.scroll-div').scrollTop()
}, 500);
});
The key point is getting scrollTop of scroll-div and add it to scrollTop. If you won't do that position() function always gives you different position values.
Restart your wampServer... that should solve it. and if it doesn't.. Resta
list_of_e
that has relevant data. df['e'] = list_of_e
Webhook Tester is a great tool: https://webhook.site (GitHub)
Important for me, it showed the IP of the requester, which is helpful when you need to whitelist an IP address but aren't sure what it is.
This works for me:
window.addEventListener("beforeunload", function(event) {_x000D_
event.returnValue = "You may have unsaved Data";_x000D_
});
_x000D_