问:
Get path of process without Admin privileges in C#
I am trying to get the path of a running process without admin privileges. There is lots of tutorials online, but i can't get them to work. This is the basic premise that works great when running as administrator:

// main

```<code>   Process pname = Process.GetProcessesByName(processName)[0];
   string path = GetExecutablePath(pname);
</code>```

// api

```<code>    private static string GetExecutablePath(Process process) {
        //If running on Vista or later use the new function
        if (Environment.OSVersion.Version.Major >= 6) {
            return GetExecutablePathAboveVista(process.Id);
        }

        return process.MainModule.FileName;
    }

    private static string GetExecutablePathAboveVista(int ProcessId) {
        var buffer = new StringBuilder(1024);
        IntPtr hprocess = OpenProcess(ProcessAccessFlags.QueryLimitedInformation,
                                      false, ProcessId);
        if (hprocess != IntPtr.Zero) {
            try {
                int size = buffer.Capacity;
                if (QueryFullProcessImageName(hprocess, 0, buffer, out size)) {
                    return buffer.ToString();
                }
            } finally {
                CloseHandle(hprocess);
            }
        }
        throw new Win32Exception(Marshal.GetLastWin32Error()); //always throws error
    }

    [DllImport("kernel32.dll")]
    private static extern bool QueryFullProcessImageName(IntPtr hprocess, int dwFlags,
                   StringBuilder lpExeName, out int size);
    [DllImport("kernel32.dll")]
    private static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess,
                   bool bInheritHandle, int dwProcessId);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool CloseHandle(IntPtr hHandle);

    [Flags]
    public enum ProcessAccessFlags : uint {
        All = 0x001F0FFF,
        Terminate = 0x00000001,
        CreateThread = 0x00000002,
        VirtualMemoryOperation = 0x00000008,
        VirtualMemoryRead = 0x00000010,
        VirtualMemoryWrite = 0x00000020,
        DuplicateHandle = 0x00000040,
        CreateProcess = 0x000000080,
        SetQuota = 0x00000100,
        SetInformation = 0x00000200,
        QueryInformation = 0x00000400,
        QueryLimitedInformation = 0x1000,
        Synchronize = 0x00100000
    }
</code>```

Unfortunately, the line

```<code>throw new Win32Exception(Marshal.GetLastWin32Error());
</code>```

always executes with an error message

```<code>System.ComponentModel.Win32Exception: 'Not all privileges or groups referenced are assigned to the caller'
</code>```

Is it possible to find the path of an exe without running as administrator? What solution do you recommend?

Update:

I think admin priviligies are needed because the program that I am inspecting has been run with admin priviliges. So the question could be rephrased to: how to find the executable path of a running process that is started as administrator?

In broader context.. I've been trying to determine if process A, that I installed, is already running on the machine. Process A requirs admin priviliges and it is usually starter as a service. There are many processes on the machines, that are named A. To find out, if this is my process, I inspected the path to exe file. Is there another way to determine if the process is indeed the one you are looking for? What else can be checked beside path to executable?

答:
You can't.  You must run as admin to get the process's path.

You don't need all that excess code you can just use this, as long as you run as admin:

```<code>string path = Process.GetProcessesByName("processfilename")[0].MainModule.FileName;
</code>```

Body:
I am trying to get the path of a running process without admin privileges. There is lots of tutorials online, but i can't get them to work. This is the basic premise that works great when running as administrator:

// main

   Process pname = Process.GetProcessesByName(processName)[0];
   string path = GetExecutablePath(pname);

// api

    private static string GetExecutablePath(Process process) {
        //If running on Vista or later use the new function
        if (Environment.OSVersion.Version.Major >= 6) {
            return GetExecutablePathAboveVista(process.Id);
        }

        return process.MainModule.FileName;
    }

    private static string GetExecutablePathAboveVista(int ProcessId) {
        var buffer = new StringBuilder(1024);
        IntPtr hprocess = OpenProcess(ProcessAccessFlags.QueryLimitedInformation,
                                      false, ProcessId);
        if (hprocess != IntPtr.Zero) {
            try {
                int size = buffer.Capacity;
                if (QueryFullProcessImageName(hprocess, 0, buffer, out size)) {
                    return buffer.ToString();
                }
            } finally {
                CloseHandle(hprocess);
            }
        }
        throw new Win32Exception(Marshal.GetLastWin32Error()); //always throws error
    }

    [DllImport("kernel32.dll")]
    private static extern bool QueryFullProcessImageName(IntPtr hprocess, int dwFlags,
                   StringBuilder lpExeName, out int size);
    [DllImport("kernel32.dll")]
    private static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess,
                   bool bInheritHandle, int dwProcessId);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool CloseHandle(IntPtr hHandle);

    [Flags]
    public enum ProcessAccessFlags : uint {
        All = 0x001F0FFF,
        Terminate = 0x00000001,
        CreateThread = 0x00000002,
        VirtualMemoryOperation = 0x00000008,
        VirtualMemoryRead = 0x00000010,
        VirtualMemoryWrite = 0x00000020,
        DuplicateHandle = 0x00000040,
        CreateProcess = 0x000000080,
        SetQuota = 0x00000100,
        SetInformation = 0x00000200,
        QueryInformation = 0x00000400,
        QueryLimitedInformation = 0x1000,
        Synchronize = 0x00100000
    }

Unfortunately, the line

throw new Win32Exception(Marshal.GetLastWin32Error());

always executes with an error message

System.ComponentModel.Win32Exception: 'Not all privileges or groups referenced are assigned to the caller'

Is it possible to find the path of an exe without running as administrator? What solution do you recommend?

Update:

I think admin priviligies are needed because the program that I am inspecting has been run with admin priviliges. So the question could be rephrased to: how to find the executable path of a running process that is started as administrator?

In broader context.. I've been trying to determine if process A, that I installed, is already running on the machine. Process A requirs admin priviliges and it is usually starter as a service. There are many processes on the machines, that are named A. To find out, if this is my process, I inspected the path to exe file. Is there another way to determine if the process is indeed the one you are looking for? What else can be checked beside path to executable?

Body:
You can't.  You must run as admin to get the process's path.

You don't need all that excess code you can just use this, as long as you run as admin:

string path = Process.GetProcessesByName("processfilename")[0].MainModule.FileName;


来源: stackexchange

问:
How to detect if multiple keys are pressed at once using JavaScript?
I'm trying to develop a JavaScript game engine and I've came across this problem:

When I press SPACE the character jumps.

When I press → the character moves right.

The problem is that when I'm pressing right and then press space, the character jumps and then stops moving.

I use the keydown function to get the key pressed. How can I check if there are multiple keys pressed at once?

答:
```<code>Easiest, and most Effective Method
</code>```

```<code>//check key press
    function loop(){
        //>>key<< can be any string representing a letter eg: "a", "b", "ctrl",
        if(map[*key*]==true){
         //do something
        }
        //multiple keys
        if(map["x"]==true&&map["ctrl"]==true){
         console.log("x, and ctrl are being held down together")
        }
    }
</code>```

```<code>//>>>variable which will hold all key information<<
    var map={}

//Key Event Listeners
    window.addEventListener("keydown", btnd, true);
    window.addEventListener("keyup", btnu, true);

    //Handle button down
      function btnd(e) {
      map[e.key] = true;
      }

    //Handle Button up
      function btnu(e) {
      map[e.key] = false;
      }
</code>```

```<code>//>>>If you want to see the state of every Key on the Keybaord<<<
    setInterval(() => {
                for (var x in map) {
                    log += "|" + x + "=" + map[x];
                }
                console.log(log);
                log = "";
            }, 300);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Easiest, and most Effective Method

//check key press
    function loop(){
        //>>key<< can be any string representing a letter eg: "a", "b", "ctrl",
        if(map[*key*]==true){
         //do something
        }
        //multiple keys
        if(map["x"]==true&&map["ctrl"]==true){
         console.log("x, and ctrl are being held down together")
        }
    }

//>>>variable which will hold all key information<<
    var map={}

//Key Event Listeners
    window.addEventListener("keydown", btnd, true);
    window.addEventListener("keyup", btnu, true);

    //Handle button down
      function btnd(e) {
      map[e.key] = true;
      }

    //Handle Button up
      function btnu(e) {
      map[e.key] = false;
      }

//>>>If you want to see the state of every Key on the Keybaord<<<
    setInterval(() => {
                for (var x in map) {
                    log += "|" + x + "=" + map[x];
                }
                console.log(log);
                log = "";
            }, 300);


问:
Distorted video output from CGBitmapContext and CVPixelBuffer
I've been trying to debug (for days now) this code to produce a video from CGImages.  The CGImages actually get created from CGBitMapContext's I draw into in the app code.  I've simplified here to simply draw a diagonal yellow line and draw a number of frames of that static image.  However, here is a frame (every frame is the same) fo the distorted video I find at the written to path.

```<code>import Foundation
import CoreGraphics
import CoreMedia
import QuartzCore
import AVFoundation

func exportVideo(
    width: Int = 500,
    height: Int = 500,
    numberOfFrames: Int = 100
) {
    let vidURL = NSURL.fileURL(withPath: "/Users/me/Desktop/testVideo.mp4")

    try? FileManager.default.removeItem(at: vidURL)

    let settings: [String: Any] = [
        AVVideoCodecKey: AVVideoCodecType.h264,
        AVVideoWidthKey: width,
        AVVideoHeightKey: height
    ]

    let assetWriter = try! AVAssetWriter(url: vidURL, fileType: .m4v)
    let writerInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: settings)
    assetWriter.add(writerInput)

    let queue = DispatchQueue.global(qos: .background)

    writerInput.expectsMediaDataInRealTime = false

    let inputAdaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: writerInput, sourcePixelBufferAttributes: nil)

    assetWriter.startWriting()

    assetWriter.startSession(atSourceTime: CMTime.zero)

    writerInput.requestMediaDataWhenReady(on: queue) {

        for i in 0..<numberOfFrames where writerInput.isReadyForMoreMediaData {

            guard let buffer = newPixelBufferFrom(width: width, height: height) else {
                fatalError()
            }

            inputAdaptor.append(
                buffer,
                withPresentationTime: CMTime(seconds: Double(i), preferredTimescale: CMTimeScale(10))
            )
        }

        writerInput.markAsFinished()

        assetWriter.finishWriting { }
    }
}

private func newPixelBufferFrom(
    width: Int,
    height: Int
) -> CVPixelBuffer? {

    let options:[String: Any] = [
        kCVPixelBufferCGImageCompatibilityKey as String: true,
        kCVPixelBufferCGBitmapContextCompatibilityKey as String: true
    ]

    var pxbuffer: CVPixelBuffer?
    let status = CVPixelBufferCreate(kCFAllocatorDefault,
                                     width,
                                     height,
                                     kCVPixelFormatType_32ARGB,
                                     options as CFDictionary?,
                                     &pxbuffer)

    assert(status == kCVReturnSuccess && pxbuffer != nil, "newPixelBuffer failed")

    CVPixelBufferLockBaseAddress(pxbuffer!, CVPixelBufferLockFlags(rawValue: 0))

    let pxdata = CVPixelBufferGetBaseAddress(pxbuffer!)

    let rgbColorSpace = CGColorSpaceCreateDeviceRGB()

    guard let context = CGContext(
        data: pxdata,
        width: width,
        height: height,
        bitsPerComponent: 8,
        bytesPerRow: 4 * width,
        space: rgbColorSpace,
        bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue
        ) else {
            fatalError()
    }

    context.setStrokeColor(UIColor.yellow.cgColor)
    context.setLineWidth(5)
    context.move(to: .init(x: 0, y: 0))
    context.addLine(to: .init(x: width, y: height))
    context.strokePath()

    CVPixelBufferUnlockBaseAddress(pxbuffer!, CVPixelBufferLockFlags(rawValue: 0))
    return pxbuffer
}
</code>```

答:
so i stumbled across "the answer" to my problem here.

It turns out that the width and height needs to be a multiple of 4.  I'll only say that I hope this post helps a future poor soul as the error codes, warnings, API members, and docs totally failed to help me.

Body:
I've been trying to debug (for days now) this code to produce a video from CGImages.  The CGImages actually get created from CGBitMapContext's I draw into in the app code.  I've simplified here to simply draw a diagonal yellow line and draw a number of frames of that static image.  However, here is a frame (every frame is the same) fo the distorted video I find at the written to path.

import Foundation
import CoreGraphics
import CoreMedia
import QuartzCore
import AVFoundation

func exportVideo(
    width: Int = 500,
    height: Int = 500,
    numberOfFrames: Int = 100
) {
    let vidURL = NSURL.fileURL(withPath: "/Users/me/Desktop/testVideo.mp4")

    try? FileManager.default.removeItem(at: vidURL)

    let settings: [String: Any] = [
        AVVideoCodecKey: AVVideoCodecType.h264,
        AVVideoWidthKey: width,
        AVVideoHeightKey: height
    ]

    let assetWriter = try! AVAssetWriter(url: vidURL, fileType: .m4v)
    let writerInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: settings)
    assetWriter.add(writerInput)

    let queue = DispatchQueue.global(qos: .background)

    writerInput.expectsMediaDataInRealTime = false

    let inputAdaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: writerInput, sourcePixelBufferAttributes: nil)

    assetWriter.startWriting()

    assetWriter.startSession(atSourceTime: CMTime.zero)

    writerInput.requestMediaDataWhenReady(on: queue) {

        for i in 0..<numberOfFrames where writerInput.isReadyForMoreMediaData {

            guard let buffer = newPixelBufferFrom(width: width, height: height) else {
                fatalError()
            }

            inputAdaptor.append(
                buffer,
                withPresentationTime: CMTime(seconds: Double(i), preferredTimescale: CMTimeScale(10))
            )
        }

        writerInput.markAsFinished()

        assetWriter.finishWriting { }
    }
}

private func newPixelBufferFrom(
    width: Int,
    height: Int
) -> CVPixelBuffer? {

    let options:[String: Any] = [
        kCVPixelBufferCGImageCompatibilityKey as String: true,
        kCVPixelBufferCGBitmapContextCompatibilityKey as String: true
    ]

    var pxbuffer: CVPixelBuffer?
    let status = CVPixelBufferCreate(kCFAllocatorDefault,
                                     width,
                                     height,
                                     kCVPixelFormatType_32ARGB,
                                     options as CFDictionary?,
                                     &pxbuffer)

    assert(status == kCVReturnSuccess && pxbuffer != nil, "newPixelBuffer failed")

    CVPixelBufferLockBaseAddress(pxbuffer!, CVPixelBufferLockFlags(rawValue: 0))

    let pxdata = CVPixelBufferGetBaseAddress(pxbuffer!)

    let rgbColorSpace = CGColorSpaceCreateDeviceRGB()

    guard let context = CGContext(
        data: pxdata,
        width: width,
        height: height,
        bitsPerComponent: 8,
        bytesPerRow: 4 * width,
        space: rgbColorSpace,
        bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue
        ) else {
            fatalError()
    }

    context.setStrokeColor(UIColor.yellow.cgColor)
    context.setLineWidth(5)
    context.move(to: .init(x: 0, y: 0))
    context.addLine(to: .init(x: width, y: height))
    context.strokePath()

    CVPixelBufferUnlockBaseAddress(pxbuffer!, CVPixelBufferLockFlags(rawValue: 0))
    return pxbuffer
}


问:
Uploading and viewing pdf in django
I am making a Webapp using django. In the app, users can login and upload one pdf file. Then others users can visit their profile and view/download the uploaded pdf file. I know how to upload the pdf. But how do I make it viewable and downloadable from the site??</p>

答:
To view you could use the below code.

```<code>with open('file.pdf', 'r') as pdf_document:
        response = HttpResponse(pdf_document.read(),contenttype ='application/pdf')
</code>```

To add download functionality, you can set 'Content-Disposition' property as shown below.

```<code>response['Content-Disposition'] = 'inline;filename=pdf_file.pdf'
</code>```

Title: Uploading and viewing pdf in django

Body:
To view you could use the below code.

with open('file.pdf', 'r') as pdf_document:
        response = HttpResponse(pdf_document.read(),contenttype ='application/pdf')

To add download functionality, you can set 'Content-Disposition' property as shown below.

response['Content-Disposition'] = 'inline;filename=pdf_file.pdf'


问:
How to add custom svg icon and regular angular material icons to same mat-icon tag
Using Angular 8 material design, I am stuck at a point where I need to use both custom svg icons and built-in/regular material icons to the same mat-icon tag.

I am running a loop to display the menu with these icons, where-in for some menu items. I am using regular material and for some menu items, I have to use custom icons (svg).

Need something like:

<mat-icon svgIcon="menuIcon">{{menuIcon}}</mat-icon>
```

答:
Typically, I would have 2 properties that represent a menu item's icon:

svgIcon which is the name of the SVG icon

icon which is the name of the CSS font icon

A menu item would be represented with the following interface:

export interface MenuItem {
  /** The menu item's title. */
  title: string;
  /** The menu item's SVG icon. Either this or the `icon` property should be used. */
  svgIcon?: string;
  /** The menu item's icon. Either this or the `svgIcon` property should be used. */
  icon?: string;
  // Other properties
}
```

<p>Then I would conditionally show the appropriate <code><mat-icon></code> based on whether the <code>svgIcon</code> or <code>icon</code> properties are set:</p>

<pre class="lang-html prettyprint-override"><code><mat-icon *ngIf="item?.icon && !item?.svgIcon">{{ item.icon }}</mat-icon>
<mat-icon *ngIf="!item?.icon && item?.svgIcon" [svgIcon]="item.svgIcon"></mat-icon>
</code>```

Alternatively, you could have an isSvgIcon property in your interface which represents whether the icon specified is an SVG icon:

<mat-icon *ngIf="item.isSvgIcon" [svgIcon]="item.icon"></mat-icon>
<mat-icon *ngIf="!item.isSvgIcon">{{ item.icon }}</mat-icon>
```

Body:
Typically, I would have 2 properties that represent a menu item's icon:

svgIcon which is the name of the SVG icon

icon which is the name of the CSS font icon

A menu item would be represented with the following interface:

export interface MenuItem {
  /** The menu item's title. */
  title: string;
  /** The menu item's SVG icon. Either this or the `icon` property should be used. */
  svgIcon?: string;
  /** The menu item's icon. Either this or the `svgIcon` property should be used. */
  icon?: string;
  // Other properties
}

Then I would conditionally show the appropriate <mat-icon> based on whether the svgIcon or icon properties are set:

<mat-icon *ngIf="item?.icon && !item?.svgIcon">{{ item.icon }}</mat-icon>
<mat-icon *ngIf="!item?.icon && item?.svgIcon" [svgIcon]="item.svgIcon"></mat-icon>

Alternatively, you could have an isSvgIcon property in your interface which represents whether the icon specified is an SVG icon:

<mat-icon *ngIf="item.isSvgIcon" [svgIcon]="item.icon"></mat-icon>
<mat-icon *ngIf="!item.isSvgIcon">{{ item.icon }}</mat-icon>


问:
How to implement "Distributed cache clearing" in Ofbiz?
We have multiple instances of Ofbiz/Opentaps running. All the instances talk to the same database. There are many tables that are rarely updated hence they are cached and all the instances maintain their individual copies of cache as a standard Ofbiz cache mechanism. But in rare situations when we update some entity using one of many instances then all other instances keep showing dirty cache data. So it requires a manual action to go and clear all the cache copies on other instances as well.

I want this cache clearing operation on all the instances to happen automatically. On Ofbiz confluence page here there is a very brief mention of "Distributed cache clearing". It relies on JMS it seems so whenever an instance's cache is cleared it sends notification over JMS to a topic and other instances subscribing to the same JMS topic clear their corresponding copies of cache upon this notification. But I could not find any other reference or documentation on how to do that? What are the files that need to be updated to set it all up in Ofbiz? An example page/link is what I'm looking for.

答:
Yes, I fixed this behaviour sometimes ago at http://svn.apache.org/viewvc?rev=1090961&view=rev. But it still needs another fix related to https://issues.apache.org/jira/browse/OFBIZ-4296.

The patch below fixes this issue locally, but still creates 2 listeners on clusters, not sure why... Still investigating (not a priority)...

```<code>Index: framework/entity/src/org/ofbiz/entity/DelegatorFactory.java
===================================================================
--- framework/entity/src/org/ofbiz/entity/DelegatorFactory.java (revision 1879)
+++ framework/entity/src/org/ofbiz/entity/DelegatorFactory.java (revision 2615)
@@ -39,10 +39,10 @@

             if (delegator != null) {
+                // setup the distributed CacheClear
+                delegator.initDistributedCacheClear();
+
                 // setup the Entity ECA Handler
                 delegator.initEntityEcaHandler();
                 //Debug.logInfo("got delegator(" + delegatorName + ") from cache", module);
-
-                // setup the distributed CacheClear
-                delegator.initDistributedCacheClear();

             return delegator;
</code>```

Please notify me using @JacquesLeRoux in your post, if ever you have something new to share.

Body:
Yes, I fixed this behaviour sometimes ago at http://svn.apache.org/viewvc?rev=1090961&view=rev. But it still needs another fix related to https://issues.apache.org/jira/browse/OFBIZ-4296.

The patch below fixes this issue locally, but still creates 2 listeners on clusters, not sure why... Still investigating (not a priority)...

Index: framework/entity/src/org/ofbiz/entity/DelegatorFactory.java
===================================================================
--- framework/entity/src/org/ofbiz/entity/DelegatorFactory.java (revision 1879)
+++ framework/entity/src/org/ofbiz/entity/DelegatorFactory.java (revision 2615)
@@ -39,10 +39,10 @@

             if (delegator != null) {
+                // setup the distributed CacheClear
+                delegator.initDistributedCacheClear();
+
                 // setup the Entity ECA Handler
                 delegator.initEntityEcaHandler();
                 //Debug.logInfo("got delegator(" + delegatorName + ") from cache", module);
-
-                // setup the distributed CacheClear
-                delegator.initDistributedCacheClear();

             return delegator;

Please notify me using @JacquesLeRoux in your post, if ever you have something new to share.

ContentLicense: CC BY-SA 3.0


问:
JDBC - select query from a materialized view does not work
I'm trying to create a select query from a materialized view using jdbc. Here is my actuall code:

```<code>Query q = entityManager.createNativeQuery("SELECT v.name FROM my_materialized_view v");
List<Object[]> authors = q.getResultList();
</code>```

But when I run this code I get the following error:

```<code>javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not prepare statement
</code>```

There's an specific to select materialized views in this context? Because if I use that code querying from a normal table it works perfect...

答:
dont use SQL ALIAS

try

```<code>"SELECT name FROM my_materialized_view"
</code>```

Body:
I'm trying to create a select query from a materialized view using jdbc. Here is my actuall code:

Query q = entityManager.createNativeQuery("SELECT v.name FROM my_materialized_view v");
List<Object[]> authors = q.getResultList();

But when I run this code I get the following error:

javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not prepare statement

There's an specific to select materialized views in this context? Because if I use that code querying from a normal table it works perfect...

Body:
dont use SQL ALIAS

try

"SELECT name FROM my_materialized_view"


问:
Why does the terminal keep printing a question mark when I'm trying to print a different character?
this is a first-time question from a beginner who's learning c#. I had just learned about how you can "convert numbers to characters" by explicitly typecasting an integer into the char method, therefore being able to print the character it shares binary with (sorry about my sucky terminology). But when I try to do this, all the terminal prints is a question mark. Here's the code:
 char a = (char)977;

Console.WriteLine(a);
When I run this, all I get is
?
Thanks for taking the time to help out a beginner.

答:
You're trying to print a character in your terminal or console, but the font that your console is using might not have a glyph for that character, or it might not be configured with the correct character encoding.

The character in question is the Greek theta symbol (ϑ), unicode character U+03D1 (note here how 03D1 is the hexadecimal representation of decimal 977).

Running the code in an environment with a font that does have this character, will successfully print it. (I tried on https://dotnetfiddle.net/ and got the character to print, but even there it will depend on the fonts installed on your system.)


问:
Oracle: Why do I have to use TO_DATE to pull my data?
When trying to filter on EXPIRE_DATE, it seems I have to use TO_DATE. Why do I have to use TO_DATE? The EXPIRE_DATE data type in the database is ALREADY set to date. Here is the code that works.

```<code>SELECT * FROM MY_TABLE
  WHERE EXPIRE_DATE >= TO_DATE('2020/01/13','yyyy/mm/dd')
  AND EXPIRE_DATE <= TO_DATE('2020/04/19','yyyy/mm/dd')
</code>```

I tried to use BETWEEN without TO_DATE and just use my dates but I received an error.

To recap, even though the data type for this is ALREADY date, it seems I have to use TO_DATE to pull my data when I want to filter. Is there something I am missing? Here is my error when I try filter my data without using TO_DATE.

答:
You can use BETWEEN:

Warning: it's  better to use always TO_DATE function with proper format string and avoid implicit conversions that in some occasions produces strange behaviors in the results.

Warning: all columns of type DATE have always the hour-minute-second component.
if you forget this you may have fewer records in the result.

Example:

```<code>create table my_table
(id          number,
 expire_date date
);
</code>```

Some data:

```<code>insert into my_table values ( 4,to_date('2011-06-17 10:07:18','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (12,to_date('2010-10-01 17:43:30','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (13,to_date('2011-07-30 08:38:34','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (21,to_date('2010-04-22 07:03:35','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (26,to_date('2011-03-26 02:07:57','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (35,to_date('2010-09-16 17:40:01','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (38,to_date('2011-11-05 17:27:45','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (44,to_date('2011-12-25 04:51:24','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (45,to_date('2011-11-05 03:08:51','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (54,to_date('2011-09-22 18:29:14','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (78,to_date('2010-03-12 20:23:21','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (79,to_date('2011-05-19 17:30:15','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (83,to_date('2011-11-15 10:04:58','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (96,to_date('2011-03-11 20:14:30','yyyy-mm-dd hh24:mi:ss'));
</code>```

Set default date format to ISO-8601 international format:

```<code>alter session set nls_date_format='YYYY-MM-DD HH24:MI:SS';
</code>```

Query using implicit conversion:

```<code>SELECT a.*
fROM my_table a
where expire_date between '2010-01-01 00:00:00'
                      and '2010-12-31 23:59:59';
</code>```

Answer:

```<code>ID EXPIRE_DATE
12 2010-10-01 17:43:30
21 2010-04-22 07:03:35
35 2010-09-16 17:40:01
78 2010-03-12 20:23:21
</code>```

but using US date format month-day-year:

```<code>SELECT a.*
fROM my_table a
where expire_date between '01/01/2010 00:00:00'
                      and '12/31/2010 23:59:59';
</code>```

You got error:

```<code>ORA-01861: literal does not match format string
</code>```

Change session date format to US format:

```<code>alter session set nls_date_format='MM-DD-YYYY HH24:MI:SS';
</code>```

you can write dates in US format:

```<code>SELECT a.*
fROM my_table a
where expire_date between '01/01/2010 00:00:00'
                      and '12/31/2010 23:59:59';
</code>```

And the answer is:

```<code>        ID EXPIRE_DATE
---------- -------------------
        12 10-01-2010 17:43:30
        21 04-22-2010 07:03:35
        35 09-16-2010 17:40:01
        78 03-12-2010 20:23:21
</code>```

Body:
When trying to filter on EXPIRE_DATE, it seems I have to use TO_DATE. Why do I have to use TO_DATE? The EXPIRE_DATE data type in the database is ALREADY set to date. Here is the code that works.

SELECT * FROM MY_TABLE
  WHERE EXPIRE_DATE >= TO_DATE('2020/01/13','yyyy/mm/dd')
  AND EXPIRE_DATE <= TO_DATE('2020/04/19','yyyy/mm/dd')

I tried to use BETWEEN without TO_DATE and just use my dates but I received an error.

To recap, even though the data type for this is ALREADY date, it seems I have to use TO_DATE to pull my data when I want to filter. Is there something I am missing? Here is my error when I try filter my data without using TO_DATE.

Body:
You can use BETWEEN:

Warning: it's  better to use always TO_DATE function with proper format string and avoid implicit conversions that in some occasions produces strange behaviors in the results.

Warning: all columns of type DATE have always the hour-minute-second component.
if you forget this you may have fewer records in the result.

Example:

create table my_table
(id          number,
 expire_date date
);

Some data:

insert into my_table values ( 4,to_date('2011-06-17 10:07:18','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (12,to_date('2010-10-01 17:43:30','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (13,to_date('2011-07-30 08:38:34','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (21,to_date('2010-04-22 07:03:35','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (26,to_date('2011-03-26 02:07:57','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (35,to_date('2010-09-16 17:40:01','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (38,to_date('2011-11-05 17:27:45','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (44,to_date('2011-12-25 04:51:24','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (45,to_date('2011-11-05 03:08:51','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (54,to_date('2011-09-22 18:29:14','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (78,to_date('2010-03-12 20:23:21','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (79,to_date('2011-05-19 17:30:15','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (83,to_date('2011-11-15 10:04:58','yyyy-mm-dd hh24:mi:ss'));
insert into my_table values (96,to_date('2011-03-11 20:14:30','yyyy-mm-dd hh24:mi:ss'));

Set default date format to ISO-8601 international format:

alter session set nls_date_format='YYYY-MM-DD HH24:MI:SS';

Query using implicit conversion:

SELECT a.*
fROM my_table a
where expire_date between '2010-01-01 00:00:00'
                      and '2010-12-31 23:59:59';

Answer:

ID EXPIRE_DATE
12 2010-10-01 17:43:30
21 2010-04-22 07:03:35
35 2010-09-16 17:40:01
78 2010-03-12 20:23:21

but using US date format month-day-year:

SELECT a.*
fROM my_table a
where expire_date between '01/01/2010 00:00:00'
                      and '12/31/2010 23:59:59';

You got error:

ORA-01861: literal does not match format string

Change session date format to US format:

alter session set nls_date_format='MM-DD-YYYY HH24:MI:SS';

you can write dates in US format:

SELECT a.*
fROM my_table a
where expire_date between '01/01/2010 00:00:00'
                      and '12/31/2010 23:59:59';

And the answer is:

        ID EXPIRE_DATE
---------- -------------------
        12 10-01-2010 17:43:30
        21 04-22-2010 07:03:35
        35 09-16-2010 17:40:01
        78 03-12-2010 20:23:21


问:
How to publish build output to network share with Azure Devops
I have modified my Build Pipeline to run jobs in parallel using multiple agents hosted on different build servers (VMs hosted in Azure).

The problem is that now I cannot use "Container" as the publishLocation value, because each build server should publish to the same drop folder.

So I would like to start using filePath. However what is the typical approach to this in Azure ? Is it possible to publish to the storage  ? Or do I have to create another dedicated VM to which I would publish the build outputs of each build machine ?  How to specify a VM in the filePath ?

答:
As a workaround ,you can switch Artifact publish location to A file share in Publish Pipeline Artifacts
task then specify your network drive folder path.

Specifying the path to the file share where you want to copy the files. The path must be a fully-qualified path or a valid path relative to the root directory of your repository. Publishing artifacts from a Linux or macOS agent to a file share is not supported.


问:
Continue in while inside foreach
In the following C# code snippet

I have a 'while' loop inside a 'foreach' loop and I wish to jump to the next item in 'foreach' when a certain condition occurs.

```<code>foreach (string objectName in this.ObjectNames)
{
    // Line to jump to when this.MoveToNextObject is true.
    this.ExecuteSomeCode();
    while (this.boolValue)
    {
        // 'continue' would jump to here.
        this.ExecuteSomeMoreCode();
        if (this.MoveToNextObject())
        {
            // What should go here to jump to next object.
        }
        this.ExecuteEvenMoreCode();
        this.boolValue = this.ResumeWhileLoop();
    }
    this.ExecuteSomeOtherCode();
}
</code>```

'continue' would jump to the beginning of the 'while' loop not the 'foreach' loop.
Is there's a keyword to use here, or should I just use goto which I don't really like.

答:
The following should do the trick</p>

```<code>foreach (string objectName in this.ObjectNames)
{
    // Line to jump to when this.MoveToNextObject is true.
    this.ExecuteSomeCode();
    while (this.boolValue)
    {
        if (this.MoveToNextObject())
        {
            // What should go here to jump to next object.
            break;
        }
    }
    if (! this.boolValue) continue; // continue foreach

    this.ExecuteSomeOtherCode();
}
</code>```

OwnerDisplayName: Amr

ContentLicense: CC BY-SA 2.5

Title: Continue in while inside foreach

Body:
In the following C# code snippet

I have a 'while' loop inside a 'foreach' loop and I wish to jump to the next item in 'foreach' when a certain condition occurs.

foreach (string objectName in this.ObjectNames)
{
    // Line to jump to when this.MoveToNextObject is true.
    this.ExecuteSomeCode();
    while (this.boolValue)
    {
        // 'continue' would jump to here.
        this.ExecuteSomeMoreCode();
        if (this.MoveToNextObject())
        {
            // What should go here to jump to next object.
        }
        this.ExecuteEvenMoreCode();
        this.boolValue = this.ResumeWhileLoop();
    }
    this.ExecuteSomeOtherCode();
}

'continue' would jump to the beginning of the 'while' loop not the 'foreach' loop.
Is there's a keyword to use here, or should I just use goto which I don't really like.

LastEditorDisplayName: configurator

Body:
The following should do the trick

foreach (string objectName in this.ObjectNames)
{
    // Line to jump to when this.MoveToNextObject is true.
    this.ExecuteSomeCode();
    while (this.boolValue)
    {
        if (this.MoveToNextObject())
        {
            // What should go here to jump to next object.
            break;
        }
    }
    if (! this.boolValue) continue; // continue foreach

    this.ExecuteSomeOtherCode();
}

OwnerDisplayName: Henk Holterman


问:
Most efficient way in Python to iterate over a large file (10GB+)
I'm working on a Python script to go through two files - one containing a list of UUIDs, the other containing a large amount of log entries - each line containing one of the UUIDs from the other file. The purpose of the program is to create a list of the UUIDS from file1, then for each time that UUID is found in the log file, increment the associated value for each time a match is found.

So long story short, count how many times each UUID appears in the log file.
At the moment, I have a list which is populated with UUID as the key, and 'hits' as the value. Then another loop which iterates over each line of the log file, and checking if the UUID in the log matches a UUID in the UUID list. If it matches, it increments the value.

```<code>    for i, logLine in enumerate(logHandle):         #start matching UUID entries in log file to UUID from rulebase
        if logFunc.progress(lineCount, logSize):    #check progress
            print logFunc.progress(lineCount, logSize)  #print progress in 10% intervals
        for uid in uidHits:
            if logLine.count(uid) == 1:             #for each UUID, check the current line of the log for a match in the UUID list
                uidHits[uid] += 1                   #if matched, increment the relevant value in the uidHits list
                break                                #as we've already found the match, don't process the rest
        lineCount += 1
</code>```

It works as it should - but I'm sure there is a more efficient way of processing the file. I've been through a few guides and found that using 'count' is faster than using a compiled regex. I thought reading files in chunks rather than line by line would improve performance by reducing the amount of disk I/O time but the performance difference on a test file ~200MB was neglible. If anyone has any other methods I would be very grateful :)

答:
Like folks above have said, with a 10GB file you'll probably hit the limits of your disk pretty quickly. For code-only improvements, the generator advice is great. In python 2.x it'll look something like

```<code>uuid_generator = (line.split(SPLIT_CHAR)[UUID_FIELD] for line in file)
</code>```

It sounds like this doesn't actually have to be a python problem. If you're not doing anything more complex than counting UUIDs, Unix might be able to solve your problems faster than python can.

```<code>cut -d${SPLIT_CHAR} -f${UUID_FIELD} log_file.txt | sort | uniq -c
</code>```

Body:
I'm working on a Python script to go through two files - one containing a list of UUIDs, the other containing a large amount of log entries - each line containing one of the UUIDs from the other file. The purpose of the program is to create a list of the UUIDS from file1, then for each time that UUID is found in the log file, increment the associated value for each time a match is found.

So long story short, count how many times each UUID appears in the log file.
At the moment, I have a list which is populated with UUID as the key, and 'hits' as the value. Then another loop which iterates over each line of the log file, and checking if the UUID in the log matches a UUID in the UUID list. If it matches, it increments the value.

    for i, logLine in enumerate(logHandle):         #start matching UUID entries in log file to UUID from rulebase
        if logFunc.progress(lineCount, logSize):    #check progress
            print logFunc.progress(lineCount, logSize)  #print progress in 10% intervals
        for uid in uidHits:
            if logLine.count(uid) == 1:             #for each UUID, check the current line of the log for a match in the UUID list
                uidHits[uid] += 1                   #if matched, increment the relevant value in the uidHits list
                break                                #as we've already found the match, don't process the rest
        lineCount += 1

It works as it should - but I'm sure there is a more efficient way of processing the file. I've been through a few guides and found that using 'count' is faster than using a compiled regex. I thought reading files in chunks rather than line by line would improve performance by reducing the amount of disk I/O time but the performance difference on a test file ~200MB was neglible. If anyone has any other methods I would be very grateful :)

Body:
Like folks above have said, with a 10GB file you'll probably hit the limits of your disk pretty quickly. For code-only improvements, the generator advice is great. In python 2.x it'll look something like

uuid_generator = (line.split(SPLIT_CHAR)[UUID_FIELD] for line in file)

It sounds like this doesn't actually have to be a python problem. If you're not doing anything more complex than counting UUIDs, Unix might be able to solve your problems faster than python can.

cut -d${SPLIT_CHAR} -f${UUID_FIELD} log_file.txt | sort | uniq -c


问:
Flutter Firebase - Get a specific field from document
I'm trying to get a specific field called "specie" from a document in a Firebase collection. I am trying as follows but I have an error of type 'Future ' is not a subtype of type 'String'. What am I doing wrong?

Repository method:

```<code>getSpecie(String petId) {
    Future<DocumentSnapshot> snapshot = petCollection.document(petId).get();
    return snapshot.then((value) => Pet.fromSnapshot(value).specie);
  }
</code>```

Entity method:

```<code> factory Pet.fromSnapshot(DocumentSnapshot snapshot) {
    Pet newPet = Pet.fromJson(snapshot.data);
    newPet.reference = snapshot.reference;
    return newPet;
  }

 factory Pet.fromJson(Map<String, dynamic> json) => _PetFromJson(json);

Pet _PetFromJson(Map<String, dynamic> json) {
  return Pet(json['name'] as String,
      specie: json['specie'] as String);
}
</code>```

答:
I found a solution. No needed fromJson() method, I only changed the repository method:</p>

```<code>Future<String> getSpecie(String petId) async {
    DocumentReference documentReference = petCollection.document(petId);
    String specie;
    await documentReference.get().then((snapshot) {
      specie = snapshot.data['specie'].toString();
    });
    return specie;
  }
</code>```

Body:
I'm trying to get a specific field called "specie" from a document in a Firebase collection. I am trying as follows but I have an error of type 'Future ' is not a subtype of type 'String'. What am I doing wrong?

Repository method:

getSpecie(String petId) {
    Future<DocumentSnapshot> snapshot = petCollection.document(petId).get();
    return snapshot.then((value) => Pet.fromSnapshot(value).specie);
  }

Entity method:

 factory Pet.fromSnapshot(DocumentSnapshot snapshot) {
    Pet newPet = Pet.fromJson(snapshot.data);
    newPet.reference = snapshot.reference;
    return newPet;
  }

 factory Pet.fromJson(Map<String, dynamic> json) => _PetFromJson(json);

Pet _PetFromJson(Map<String, dynamic> json) {
  return Pet(json['name'] as String,
      specie: json['specie'] as String);
}

Body:
I found a solution. No needed fromJson() method, I only changed the repository method:

Future<String> getSpecie(String petId) async {
    DocumentReference documentReference = petCollection.document(petId);
    String specie;
    await documentReference.get().then((snapshot) {
      specie = snapshot.data['specie'].toString();
    });
    return specie;
  }


问:
Risks involved with publicly accessible AWS RDS databases
I've come across multiple guidelines stating that AWS RDS instances should not be configured to be publicly accessible, because it is a major security risk. Example:RDS Publicly Accessible - RDS best practice

If the RDS instance is configured with a sufficiently strong and unique password which is practically impossible to brute-force, is it still a security risk? Wouldn't a strong and unique password make the instance reasonably safe, even if it is publicly accessible?

答:
You would still be open to brute force and other denial of service attacks.

The best practice is to have the DB server on a private subnet, and only allow known IP from the local subnet to have access, via security groups.

Some go further, and secure the VPC with network access control lists.

Its pretty easy to set up up a properly secured RDS server in this way. I would not rely on a single layer of defense if you really want to protect sensitive data.


问:
Need help scaling and rotating an image in a viewport
I have the code in this JSFidle - https://jsfiddle.net/pmi2018/smewua0k/211/

Javascript

```<code>$('#rotate').click(function(e) {
  updateImage(90, 0)
  console.log("rotation");
});

$('#zoom-in').click(function() {
  updateImage(0, 0.1);
  console.log("Zoomed in");
});

$('#zoom-out').click(function() {
  updateImage(0, -0.1);
  console.log("Zoomed out");
});

var zoomLevel = 1;
var rotation = 0;

var updateImage = function(angle, zoom) {
  zoomLevel += zoom;
  var img_scale = ' scale(' + zoomLevel + ') ';

  rotation += angle;
  if (rotation == 360) {
    rotation = 0;
  }
  var str_rotation = ' rotate(' + rotation + 'deg) ';
  console.log("rotation=" + str_rotation + " scale=" + img_scale);
  var img = document.getElementById('sam');
  img.style.transform = img_scale + str_rotation
  //if (angle == 0) {
  //   img.style.transformOrigin = '0 0';
  //   img.style.transform = img_scale;
  // }
  // else {
  //   img.style.transformOrigin = 'center center';
  //   img.style.transform = str_rotation;
  // }
}
</code>```

HTML

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button type="button" id="zoom-in">zoom in</button> <button type="button" id="zoom-out">zoom out</button>

<div id=imageblock>
  <img  id="sam" src="http://placekitten.com/g/250/250" />
</div>
<div>
  <a id="rotate" href="#">Rotate 90 degrees</a>
</div>
</code>```

CSS

```<code>#imageblock {
  width: 300px;
  height: 300px;
  border: 1px solid #000000;
  overflow: auto;
  display: block;
}

#sam {
  transform-origin: center, center;
}
</code>```

The problem is I need the have the origin be upper left corner when I scale the image to keep the scaled image in the box; but the origin has to be center, center when I rotate the image to keep the image in the box. However the CSS articles I have read say when rotating and scaling an image, they have to be done together.

I tried applying the rotation and scale separately so I could set the origin correctly (the commented out code), but only the first transform fires, and not the second.

How can I rotate and scale the image in the #imagebox?

Thanks!

Mark

答:
The reason why it "goes together" is because the transform property can only have one origin. So if you apply multiple transformations on a single object, they will all use the same origin.

An easy solution would be to put the image in a div. Then, use the zoom on the div, and the rotate on the image for exemple so that both can have different origins.

$('#rotate').click(function(e) {
  updateImage(90, 0)
});

$('#zoom-in').click(function() {
  updateImage(0, 0.1);
});

$('#zoom-out').click(function() {
  updateImage(0, -0.1);
});

var zoomLevel = 1;
var rotation = 0;

var updateImage = function(angle, zoom) {
  zoomLevel += zoom;
  var img_scale = ' scale(' + zoomLevel + ') ';

  rotation += angle;
  if (rotation == 360) {
    rotation = 0;
  }
  var str_rotation = ' rotate(' + rotation + 'deg) ';

  // Here I modified the syntax just a bit, to use JQuery methods instead of pur Javascript. I hope you are ok with it
  // I modify the image rotate property, and then the div scale property
  $('#sam').css('transform',str_rotation)
  $('#zoom').css('transform', img_scale);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#imageblock {
  width: 300px;
  height: 300px;
  border: 1px solid #000000;
  overflow: auto;
  display: block;
  overflow: hidden; /* To hide the scrollbar when you zoom in */
}

#zoom {
  transform:scale(1);
  transform-origin:top left;
}

#sam {
  transform: rotate(0deg)
  transform-origin: center center;
}</code>```

<button type="button" id="zoom-in">zoom in</button> <button type="button" id="zoom-out">zoom out</button>

  Rotate 90 degrees

```

Also, please note that there is no coma in transform-origin: center center;.

Ask them if you have any questions. I hope it helped !

Body:
I have the code in this JSFidle - https://jsfiddle.net/pmi2018/smewua0k/211/

Javascript

$('#rotate').click(function(e) {
  updateImage(90, 0)
  console.log("rotation");
});

$('#zoom-in').click(function() {
  updateImage(0, 0.1);
  console.log("Zoomed in");
});

$('#zoom-out').click(function() {
  updateImage(0, -0.1);
  console.log("Zoomed out");
});

var zoomLevel = 1;
var rotation = 0;

var updateImage = function(angle, zoom) {
  zoomLevel += zoom;
  var img_scale = ' scale(' + zoomLevel + ') ';

  rotation += angle;
  if (rotation == 360) {
    rotation = 0;
  }
  var str_rotation = ' rotate(' + rotation + 'deg) ';
  console.log("rotation=" + str_rotation + " scale=" + img_scale);
  var img = document.getElementById('sam');
  img.style.transform = img_scale + str_rotation
  //if (angle == 0) {
  //   img.style.transformOrigin = '0 0';
  //   img.style.transform = img_scale;
  // }
  // else {
  //   img.style.transformOrigin = 'center center';
  //   img.style.transform = str_rotation;
  // }
}

HTML

<button type="button" id="zoom-in">zoom in</button> <button type="button" id="zoom-out">zoom out</button>

  Rotate 90 degrees

CSS

#imageblock {
  width: 300px;
  height: 300px;
  border: 1px solid #000000;
  overflow: auto;
  display: block;
}

#sam {
  transform-origin: center, center;
}

The problem is I need the have the origin be upper left corner when I scale the image to keep the scaled image in the box; but the origin has to be center, center when I rotate the image to keep the image in the box. However the CSS articles I have read say when rotating and scaling an image, they have to be done together.

I tried applying the rotation and scale separately so I could set the origin correctly (the commented out code), but only the first transform fires, and not the second.

How can I rotate and scale the image in the #imagebox?

Thanks!

Mark

Body:
The reason why it "goes together" is because the transform property can only have one origin. So if you apply multiple transformations on a single object, they will all use the same origin.

An easy solution would be to put the image in a div. Then, use the zoom on the div, and the rotate on the image for exemple so that both can have different origins.

$('#rotate').click(function(e) {
  updateImage(90, 0)
});

$('#zoom-in').click(function() {
  updateImage(0, 0.1);
});

$('#zoom-out').click(function() {
  updateImage(0, -0.1);
});

var zoomLevel = 1;
var rotation = 0;

var updateImage = function(angle, zoom) {
  zoomLevel += zoom;
  var img_scale = ' scale(' + zoomLevel + ') ';

  rotation += angle;
  if (rotation == 360) {
    rotation = 0;
  }
  var str_rotation = ' rotate(' + rotation + 'deg) ';

  // Here I modified the syntax just a bit, to use JQuery methods instead of pur Javascript. I hope you are ok with it
  // I modify the image rotate property, and then the div scale property
  $('#sam').css('transform',str_rotation)
  $('#zoom').css('transform', img_scale);
}

#imageblock {
  width: 300px;
  height: 300px;
  border: 1px solid #000000;
  overflow: auto;
  display: block;
  overflow: hidden; /* To hide the scrollbar when you zoom in */
}

#zoom {
  transform:scale(1);
  transform-origin:top left;
}

#sam {
  transform: rotate(0deg)
  transform-origin: center center;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button type="button" id="zoom-in">zoom in</button> <button type="button" id="zoom-out">zoom out</button>

<div id=imageblock>
  <div id="zoom"> <!-- I added this div -->
    <img  id="sam" src="http://placekitten.com/g/250/250" />
  </div>
</div>
<div>
  <a id="rotate" href="#">Rotate 90 degrees</a>
</div>

Also, please note that there is no coma in transform-origin: center center;.

Ask them if you have any questions. I hope it helped !


问:
react hooks - useEffect not called after action is dispatched
I have a button that can like/dislike a car.

The state stores usersLikedCars which is an array.

When the user clicks the like/dislike button (same button), an API call is made which is either a POST or DELETE which updates db and returns 1 more or 1 less row of usersLikedCars.

After this operation completes, I want to:

loop through the updated usersLikedCars array

check if the car has been liked/disliked

updated the button color to red=liked, blue=notLiked

Current behavior

The button color only updates when I leave the current page and come back to it

Inside the action, I can log the returned API data, and it updates correctly

Expected Behavior

I expect usersLikedCars to update in the component (it's count that is) and call the function that basically updates the button color by checking if the newly added car is part of the updated array.

Looking at answers in this link, I added useEffect where I dispatch the action which grabs the updated usersLikedCars - at least I thought it did. It is only called when the page first renders.

Also, useEffect forced me to wrap isCarLiked and setLikeButtonColor in useCallback which I am not 100% sure is correct..

Can someone point me in the right direction?

```<code>const CarScreen = ({ route }) => {
  // props
  const { params } = route;
  const { car } = params;
  // member variables
  const carTitle = `#${car.title}`;
  const carLikeCount = car.hit_count ? car.hit_count : 0;
  const carBirthday = moment(car.created_at).format('MMMM Do YYYY');
  const carLikeButtonColor = useRef('');
  // redux
  const dispatch = useDispatch();
  const user = useSelector((state) => state.user.user);
  const usersLikedCars = useSelector(
    (state) => state.usersLikedCars.items,
  );

  /**
   * Call this function when car is liked/unliked
   * and when like button color needs to be updated
   */
  useEffect(() => {
    dispatch(fetchUsersLikedCars());

    // set the like button's color: red - LIKED, blue - NOT LIKED
    setLikeButtonColor();
  }, [dispatch, setLikeButtonColor]);

  /**
   * Method for liking a car
   */
  const handleLikeOrUnlikeCar = async () => {
    // check if user already liked this car
    const carAlreadyLikedByUser = isCarLiked();

    if (carAlreadyLikedByUser) {
      // find the car in user's liked car state array to "unlike"
      const carToDelete = usersLikedCars.find(
        (usersLikedCar) => usersLikedCar.title === car.title,
      );
      // unlike it
      try {
        await console.log(
          'BEFORE remove usersLikedCars',
          usersLikedCars,
        );

        await remove({
          uid: carToDelete.uid,
        });
        await dispatch(fetchUsersLikedCars());
        await console.log(
          'AFTER remove usersLikedCars',
          usersLikedCars,
        );
      } catch (error) {
        console.error(error);
      }
    } else {
      // like it

      try {
        await console.log('BEFORE add usersLikedCars', usersLikedCars);
        await add({
          title: car.title,
          user_uid: user.uid,
          car_uid: car.uid,
        });
        await dispatch(fetchUsersLikedCars());
        await console.log('AFTER add usersLikedCars', usersLikedCars);
      } catch (error) {
        console.error(error);
      }
    }
  };

  const isCarLiked = useCallback(
    () =>
      usersLikedCars.some(
        (usersLikedCar) => usersLikedCar.title === car.title,
      ),
    [usersLikedCars, car.title],
  );

  /**
   * Set color of car like button
   */
  const setLikeButtonColor = useCallback(() => {
    // look through user's liked cars and see if the current one is in there already
    const carAlreadyLikedByUser = isCarLiked();

    // if user liked this car already, color = RED else BLUE
    carLikeButtonColor.current = carAlreadyLikedByUser
      ? Colors.loveRed
      : Colors.defaultColor;
  }, [isCarLiked]);

....
}
</code>```

action

```<code>export const fetchUsersLikedCars = () => async (dispatch) => {
  const usersLikedCars = await find();

  console.log('ACTION usersLikedCars', usersLikedCars); // value is correctly updated here
  return dispatch({
    type: FETCH_USERS_LIKED_CARS,
    payload: usersLikedCars,
  });
};
</code>```

答:
You need to put usersLikedCars in the dependency of useEffect so that whenever it changes, useEffect gets trigerred.

To accomplish that you can have another useEffect apart from the one you already have (it's pretty normal and legal to have multiple useEffects) which wouldn't trigger the dispatch again so it doesn't go into the infinite state

```<code> useEffect(() => {
    setLikeButtonColor();
  }, [usersLikedCars]);
</code>```

Body:
I have a button that can like/dislike a car.

The state stores usersLikedCars which is an array.

When the user clicks the like/dislike button (same button), an API call is made which is either a POST or DELETE which updates db and returns 1 more or 1 less row of usersLikedCars.

After this operation completes, I want to:

loop through the updated usersLikedCars array

check if the car has been liked/disliked

updated the button color to red=liked, blue=notLiked

Current behavior

The button color only updates when I leave the current page and come back to it

Inside the action, I can log the returned API data, and it updates correctly

Expected Behavior

I expect usersLikedCars to update in the component (it's count that is) and call the function that basically updates the button color by checking if the newly added car is part of the updated array.

Looking at answers in this link, I added useEffect where I dispatch the action which grabs the updated usersLikedCars - at least I thought it did. It is only called when the page first renders.

Also, useEffect forced me to wrap isCarLiked and setLikeButtonColor in useCallback which I am not 100% sure is correct..

Can someone point me in the right direction?

const CarScreen = ({ route }) => {
  // props
  const { params } = route;
  const { car } = params;
  // member variables
  const carTitle = `#${car.title}`;
  const carLikeCount = car.hit_count ? car.hit_count : 0;
  const carBirthday = moment(car.created_at).format('MMMM Do YYYY');
  const carLikeButtonColor = useRef('');
  // redux
  const dispatch = useDispatch();
  const user = useSelector((state) => state.user.user);
  const usersLikedCars = useSelector(
    (state) => state.usersLikedCars.items,
  );

  /**
   * Call this function when car is liked/unliked
   * and when like button color needs to be updated
   */
  useEffect(() => {
    dispatch(fetchUsersLikedCars());

    // set the like button's color: red - LIKED, blue - NOT LIKED
    setLikeButtonColor();
  }, [dispatch, setLikeButtonColor]);

  /**
   * Method for liking a car
   */
  const handleLikeOrUnlikeCar = async () => {
    // check if user already liked this car
    const carAlreadyLikedByUser = isCarLiked();

    if (carAlreadyLikedByUser) {
      // find the car in user's liked car state array to "unlike"
      const carToDelete = usersLikedCars.find(
        (usersLikedCar) => usersLikedCar.title === car.title,
      );
      // unlike it
      try {
        await console.log(
          'BEFORE remove usersLikedCars',
          usersLikedCars,
        );

        await remove({
          uid: carToDelete.uid,
        });
        await dispatch(fetchUsersLikedCars());
        await console.log(
          'AFTER remove usersLikedCars',
          usersLikedCars,
        );
      } catch (error) {
        console.error(error);
      }
    } else {
      // like it

      try {
        await console.log('BEFORE add usersLikedCars', usersLikedCars);
        await add({
          title: car.title,
          user_uid: user.uid,
          car_uid: car.uid,
        });
        await dispatch(fetchUsersLikedCars());
        await console.log('AFTER add usersLikedCars', usersLikedCars);
      } catch (error) {
        console.error(error);
      }
    }
  };

  const isCarLiked = useCallback(
    () =>
      usersLikedCars.some(
        (usersLikedCar) => usersLikedCar.title === car.title,
      ),
    [usersLikedCars, car.title],
  );

  /**
   * Set color of car like button
   */
  const setLikeButtonColor = useCallback(() => {
    // look through user's liked cars and see if the current one is in there already
    const carAlreadyLikedByUser = isCarLiked();

    // if user liked this car already, color = RED else BLUE
    carLikeButtonColor.current = carAlreadyLikedByUser
      ? Colors.loveRed
      : Colors.defaultColor;
  }, [isCarLiked]);

....
}

action

export const fetchUsersLikedCars = () => async (dispatch) => {
  const usersLikedCars = await find();

  console.log('ACTION usersLikedCars', usersLikedCars); // value is correctly updated here
  return dispatch({
    type: FETCH_USERS_LIKED_CARS,
    payload: usersLikedCars,
  });
};

Body:
You need to put usersLikedCars in the dependency of useEffect so that whenever it changes, useEffect gets trigerred.

To accomplish that you can have another useEffect apart from the one you already have (it's pretty normal and legal to have multiple useEffects) which wouldn't trigger the dispatch again so it doesn't go into the infinite state

 useEffect(() => {
    setLikeButtonColor();
  }, [usersLikedCars]);


问:
CSS selector when no sibling of certain type is present
Consider these scenarios:

Scenario 1:

```<code><div>
  <Button class="button"/>
  <div class="div1" />
  <div class="div2" />
  <div class="div3" />
</div>
</code>```

Scenario 2:

```<code><div>
  <div class="div1" />
  <div class="div2" />
  <div class="div3" />
</div>
</code>```

I want to write a css selector for div3 only when its <button>sibling is not present i.e. for Scenario 2.

Is that possible?

答:
```<code><!DOCTYPE html>
<html>
<head>
     <style>
         button ~ .div3 {
                background-color: yellow;
         }
     </style>
</head>
<body>
</html>

   <div>
      <Button class="button">vv</button>
      <div class="div1" >1</div>
      <div class="div2" >2</div>
      <div class="div3" >4</div>
  </div>

</body>
</code>```

Body:
Consider these scenarios:

Scenario 1:

  <Button class="button"/>

Scenario 2:

I want to write a css selector for div3 only when its <button>sibling is not present i.e. for Scenario 2.

Is that possible?


问:
PageMethods not working if the website is created as a Visual C# ASP.Net Web Application in VS2015
I am a newbie in web developing with VS (Visual Studio). I have the following problem and would appreciate it very much if you could share your view on this.

PROBLEM:
PageMethods works OK if I create a new website in VS via [File] - [New Web Site] - [ASP.NET Empty Web Site] as per the files given below.
But if I create a new website in VS via [File] - [New Project] - [Visual C# ASP.NET Web Application] then PageMethods do NOT work as per the files given below. Moreover, I can not run any method created in aspx.cs files!

Obviously, I am missing a basic step/concept but I can not see it unfortunately!

ASPX File:

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test4.aspx.cs" Inherits="ETDBWebApplication1.Content.Test.Test4" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="~/Scripts/jquery-3.5.1.js"></script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager runat="server" ID="sm1" EnablePageMethods="true" />
        <div>
            <script type="text/javascript">
                function getValues() {
                    var text1 = $('#txt1').val();
                    PageMethods.GetValues(text1, getValues_Success, getValues_Fail);
                }
                function getValues_Success(msg){
                    $('#div1').html(msg);
                }
                function getValues_Fail(msg) {
                    alert(msg.get_message());
                }
            </script>
            <input type="text" id="txt1" />
            <br />
            <input type="button" onclick="getValues();" value="get values"/>
            <br />
            <br />
            <div id="div1"></div>
        </div>
    </form></body>
</html>

</code>```

ASPX.CS FILE (CODEBEHIND):

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ETDBWebApplication1.Content.Test
{
    public partial class Test4 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static string GetValues(string value)
        {
            value = value + DateTime.UtcNow.ToLongTimeString();
            return value;
        }
    }
}
</code>```

Web.Config:

```<code><?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-ETDBWebApplication1-20200211070838.mdf;Initial Catalog=aspnet-ETDBWebApplication1-20200211070838;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <!--
    For a description of web.config changes see http://go.microsoft.com/fwlink/?LinkId=235367.

    The following attributes can be set on the <httpRuntime> tag.
      <system.Web>
        <httpRuntime targetFramework="4.5.2" />
      </system.Web>
  -->
  <system.web>
    <customErrors mode="Off"/>
    <authentication mode="None"/>
    <compilation debug="false" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
    <pages controlRenderingCompatibilityVersion="4.0">
      <namespaces>
        <add namespace="System.Web.Optimization"/>
        <add namespace="Microsoft.AspNet.Identity"/>
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt"/>
      </controls>
    </pages>
    <membership>
      <providers>
        <!--
        ASP.NET Membership is disabled in this template. Please visit the following link http://go.microsoft.com/fwlink/?LinkId=301889 to learn about the ASP.NET Membership support in this template
        -->
        <clear/>
      </providers>
    </membership>
    <profile>
      <providers>
        <!--
        ASP.NET Membership Profile is disabled in this template. Please visit the following link http://go.microsoft.com/fwlink/?LinkId=301889 to learn about the ASP.NET Membership support in this template
        -->
        <clear/>
      </providers>
    </profile>
    <roleManager>
      <!--
          ASP.NET Membership Role is disabled in this template. Please visit the following link http://go.microsoft.com/fwlink/?LinkId=301889 to learn about the ASP.NET Membership support in this template
        -->
      <providers>
        <clear/>
      </providers>
    </roleManager>
    <!--
            If you are deploying to a cloud environment that has multiple web server instances,
            you should change session state mode from "InProc" to "Custom". In addition,
            change the connection string named "DefaultConnection" to connect to an instance
            of SQL Server (including SQL Azure and SQL  Compact) instead of to SQL Server Express.
      -->
    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection"/>
      </providers>
    </sessionState>
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
    </httpModules>
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication"/>
      <remove name="ApplicationInsightsWebTracking"/>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler"/>
    </modules>
    <validation validateIntegratedModeConfiguration="false"/>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed"/>
        <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089"/>
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb"/>
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
    </providers>
  </entityFramework>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/>
    </compilers>
  </system.codedom>
</configuration>
</code>```

Many thanks in advance.
Cenk

答: Try using ScriptMethod instead of WebMethod attribute on the method GetValues and if it still fails, decorate the aspx.cs class with ScriptService attribute.

Body:
I am a newbie in web developing with VS (Visual Studio). I have the following problem and would appreciate it very much if you could share your view on this.

PROBLEM:
PageMethods works OK if I create a new website in VS via [File] - [New Web Site] - [ASP.NET Empty Web Site] as per the files given below.
But if I create a new website in VS via [File] - [New Project] - [Visual C# ASP.NET Web Application] then PageMethods do NOT work as per the files given below. Moreover, I can not run any method created in aspx.cs files!

Obviously, I am missing a basic step/concept but I can not see it unfortunately!

ASPX File:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test4.aspx.cs" Inherits="ETDBWebApplication1.Content.Test.Test4" %>

<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">
        <asp:ScriptManager runat="server" ID="sm1" EnablePageMethods="true" />

            <input type="text" id="txt1" />

            <input type="button" onclick="getValues();" value="get values"/>

    </form>

ASPX.CS FILE (CODEBEHIND):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ETDBWebApplication1.Content.Test
{
    public partial class Test4 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static string GetValues(string value)
        {
            value = value + DateTime.UtcNow.ToLongTimeString();
            return value;
        }
    }
}

Web.Config:

<?xml version="1.0"?>

<configuration>
  <configSections>

  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-ETDBWebApplication1-20200211070838.mdf;Initial Catalog=aspnet-ETDBWebApplication1-20200211070838;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>

  <system.web>
    <customErrors mode="Off"/>
    <authentication mode="None"/>
    <compilation debug="false" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
    <pages controlRenderingCompatibilityVersion="4.0">
      <namespaces>
        <add namespace="System.Web.Optimization"/>
        <add namespace="Microsoft.AspNet.Identity"/>
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt"/>
      </controls>
    </pages>
    <membership>
      <providers>

        <clear/>
      </providers>
    </membership>
    <profile>
      <providers>

        <clear/>
      </providers>
    </profile>
    <roleManager>

      <providers>
        <clear/>
      </providers>
    </roleManager>

    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection"/>
      </providers>
    </sessionState>
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
    </httpModules>
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication"/>
      <remove name="ApplicationInsightsWebTracking"/>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler"/>
    </modules>
    <validation validateIntegratedModeConfiguration="false"/>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed"/>
        <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089"/>
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb"/>
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
    </providers>
  </entityFramework>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/>
    </compilers>
  </system.codedom>
</configuration>

Many thanks in advance.
Cenk


问:
cant find file when using docker containers
I have an application which reads configuration file:

```<code>config.read('/data123/config/conf.ini')
</code>```

The file conf.ini exists in /data123/config/

When I'm running my application from command line, the application can find the conf.ini successfuly

I made a docker for my application, and when I run my docker, the application can't find the file.

My dockerfile:

```<code>FROM ubuntu:latest
RUN apt update -y
RUN apt install -y python3-pip
COPY . /app
WORKDIR /app
RUN pip3 install -r requirements.txt
ENTRYPOINT ["python3"]
CMD ["main.py"]
</code>```

Why is this ?

How can I read configurations files from applications when using containers ?

I don't want to create new docker each time the config file changes
and

I don't want to use environment variables, because I have a lot of values in the config file.

答:
run your docker with this command:

```<code>sudo docker run -it -v path_to_file_you_want_to_work_with:/app/data123/config/ your_docker_name
</code>```

and the container will run and load the config file you supply at run time

Body:
I have an application which reads configuration file:

config.read('/data123/config/conf.ini')

The file conf.ini exists in /data123/config/

When I'm running my application from command line, the application can find the conf.ini successfuly

I made a docker for my application, and when I run my docker, the application can't find the file.

My dockerfile:

FROM ubuntu:latest
RUN apt update -y
RUN apt install -y python3-pip
COPY . /app
WORKDIR /app
RUN pip3 install -r requirements.txt
ENTRYPOINT ["python3"]
CMD ["main.py"]

Why is this ?

How can I read configurations files from applications when using containers ?

I don't want to create new docker each time the config file changes
and

I don't want to use environment variables, because I have a lot of values in the config file.

Body:
run your docker with this command:

sudo docker run -it -v path_to_file_you_want_to_work_with:/app/data123/config/ your_docker_name

and the container will run and load the config file you supply at run time


问:
How can I change font size of the dates within the datepicker (SwiftUI)
How can I make the font of the dates smaller in the DatePicker using SwiftUI? </p>

```<code>struct TestView: View {
    @State private var eventDate = Date()

    var body: some View {
        ZStack {
            Color(.purple).edgesIgnoringSafeArea(.all)
            VStack {
                Section {
                    DatePicker("Event Date", selection: $eventDate, in: ...Date())
                    .labelsHidden()
                }
            }
        }
    }
}
</code>```

答:
You can apply a .transformEffect(.init(scaleX: 0.7, y: 0.7)):

```<code>var body: some View {
    ZStack {
        Color(.purple).edgesIgnoringSafeArea(.all)
        VStack {
            Section {
                DatePicker("Event Date", selection: $eventDate, in: ...Date())
                .labelsHidden()
                    .transformEffect(.init(scaleX: 0.7, y: 0.7))
            }
        }
    }
}
</code>```

Body:
How can I make the font of the dates smaller in the DatePicker using SwiftUI?

struct TestView: View {
    @State private var eventDate = Date()

    var body: some View {
        ZStack {
            Color(.purple).edgesIgnoringSafeArea(.all)
            VStack {
                Section {
                    DatePicker("Event Date", selection: $eventDate, in: ...Date())
                    .labelsHidden()
                }
            }
        }
    }
}

Body:
You can apply a .transformEffect(.init(scaleX: 0.7, y: 0.7)):

var body: some View {
    ZStack {
        Color(.purple).edgesIgnoringSafeArea(.all)
        VStack {
            Section {
                DatePicker("Event Date", selection: $eventDate, in: ...Date())
                .labelsHidden()
                    .transformEffect(.init(scaleX: 0.7, y: 0.7))
            }
        }
    }
}


问:
How to check language being used on a device?
I have android project as quiz app , I need to run some code if user system lang is English , and another code if user system lang Arabic or other , how can I do that. I mean , if the lang eng run sound right answer , and if the lang is other run another sound of different lang.</p>

```<code>public void checkAnswer(View view) {
    Button answerBtn = (Button) findViewById(view.getId());
    String btnText = answerBtn.getText().toString();
    String alerTitle;

    if (btnText.equals(rightAnswer)) {
        alertTitle=(getString(R.string.rightAnswer));
        rightAnswerCount++;
        score.setText(String.valueOf(rightAnswerCount));
        answerBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.c));
        mpright = MediaPlayer.create(MainActivity.this, R.raw.right_ans);
        mpright.start();
        Animation anm = AnimationUtils.loadAnimation(MainActivity.this, R.anim.abc_popup_exit);
        answerBtn.startAnimation(anm);
    } else {
        alertTitle =getString(R.string.wrongAnswer);
        wrongAnswerCount++;
        wrong.setText(String.valueOf(wrongAnswerCount));
        //  wrongBtn.setBackgroundColor(Color.RED);
        answerBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.d));
        mpwrong = MediaPlayer.create(MainActivity.this, R.raw.wronge_ans);
        mpwrong.start();
        Animation anm = AnimationUtils.loadAnimation(MainActivity.this, R.anim.abc_tooltip_enter);
        answerBtn.startAnimation(anm);
    }
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(alertTitle);
    builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface p1, int p2) {
                if (quizCount == Quiz_Count) {
                    Intent result = new Intent(getApplicationContext(), ResultActivity.class);
                    result.putExtra("Right_Answer_Count", rightAnswerCount);
                    startActivity(result);
                } else {
                    quizCount++;
                    ShowNextQuiz();
                }
            }
        });
    builder.setCancelable(false);
    builder.show();
</code>```

答:
try this code : </p>

```<code>if( Locale.getDefault().getLanguage().equalsIgnoreCase("en")) {
           // English
}else{
        //other
}
</code>```

Body:
I have android project as quiz app , I need to run some code if user system lang is English , and another code if user system lang Arabic or other , how can I do that. I mean , if the lang eng run sound right answer , and if the lang is other run another sound of different lang.

public void checkAnswer(View view) {
    Button answerBtn = (Button) findViewById(view.getId());
    String btnText = answerBtn.getText().toString();
    String alerTitle;

    if (btnText.equals(rightAnswer)) {
        alertTitle=(getString(R.string.rightAnswer));
        rightAnswerCount++;
        score.setText(String.valueOf(rightAnswerCount));
        answerBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.c));
        mpright = MediaPlayer.create(MainActivity.this, R.raw.right_ans);
        mpright.start();
        Animation anm = AnimationUtils.loadAnimation(MainActivity.this, R.anim.abc_popup_exit);
        answerBtn.startAnimation(anm);
    } else {
        alertTitle =getString(R.string.wrongAnswer);
        wrongAnswerCount++;
        wrong.setText(String.valueOf(wrongAnswerCount));
        //  wrongBtn.setBackgroundColor(Color.RED);
        answerBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.d));
        mpwrong = MediaPlayer.create(MainActivity.this, R.raw.wronge_ans);
        mpwrong.start();
        Animation anm = AnimationUtils.loadAnimation(MainActivity.this, R.anim.abc_tooltip_enter);
        answerBtn.startAnimation(anm);
    }
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(alertTitle);
    builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface p1, int p2) {
                if (quizCount == Quiz_Count) {
                    Intent result = new Intent(getApplicationContext(), ResultActivity.class);
                    result.putExtra("Right_Answer_Count", rightAnswerCount);
                    startActivity(result);
                } else {
                    quizCount++;
                    ShowNextQuiz();
                }
            }
        });
    builder.setCancelable(false);
    builder.show();

Body:
try this code :

if( Locale.getDefault().getLanguage().equalsIgnoreCase("en")) {
           // English
}else{
        //other
}


问:
TFS 2010 Change Log
Is there an automated way to create a change log using TFS 2010 and the version history of the files?  I'd like to pull in all the comments that were entered for each changeset either between a label (or a specific date) and the current version, or between two labels (or two specific dates).</p>

答:
Are you asking

Is there a tool already that does all of this for me?
OR

Can I automate this process?

If #1, my answer is "I don't know, but I would check CodePlex and the Microsoft TFS downloads on MSDN" for this type of tool.

If #2, there are web services you can use to query TFS. They don't have the "give me all changes between X and Y date or A and B release", but you can get information on changesets, work items, etc. As you would be creating a document, good check in note discipline is mandatory to get a coherent document, unless you just want to know what was actually changed in code, which I think is overkill.

Are the APIs mature enough to easily automate to create version 1.x changes are type of documents? My answer is no, but your mileage may vary.

Title: TFS 2010 Change Log


问:
How to display lines with Chinese letters on DevC++?
What I want is to display a line with a Chinese letter, entered by the user. Though the program DevC++.

This is my code:

```<code>#define UNICODE
#include <iostream>
#include <string>
    using namespace std;
    extern wostream wcout;
int main(int argc, char** argv) {
    std::wstring kanji = L"?";
    //std::wchar_t stop = L"0";
    std::wcout << L"\n\nWelcome to the Chinese letter program\n";
    std::wcout << L"The program will ask you for one Chinese letter\n";
    std::wcout << L"Then press enter, and a message will display.\n";
    std::wcout << L"Once you are done,you can enter another Chinese letter\n";
    std::wcout << L"To exit just close the Ubuntu's terminal'\n\n";
        for(int x = 0; x < 80; x++){
            std::wcout << L"Give me one Chinese letter...";
                wcin >> kanji;
                std::wcout << L"The Chinese letter is \"" << kanji << "\".\n\n";
        }
    return 0;
}
</code>```

What matters to me is the "The Chinese letter is "(kanji)"." line. When I do what the program says I get "The Chinese letter is "?".". So the problem is that DevC++ doesn't show the Chinese letters correctly, even when I using the wcin and wcout things.

Note I am using DevC++ on Ubuntu, through wine.

答:
Do your console support Chinese encoding? take a look at this post
How to print a Chinese character?</p>

Body:
What I want is to display a line with a Chinese letter, entered by the user. Though the program DevC++.

This is my code:

#define UNICODE
#include <iostream>
#include <string>
    using namespace std;
    extern wostream wcout;
int main(int argc, char** argv) {
    std::wstring kanji = L"?";
    //std::wchar_t stop = L"0";
    std::wcout << L"\n\nWelcome to the Chinese letter program\n";
    std::wcout << L"The program will ask you for one Chinese letter\n";
    std::wcout << L"Then press enter, and a message will display.\n";
    std::wcout << L"Once you are done,you can enter another Chinese letter\n";
    std::wcout << L"To exit just close the Ubuntu's terminal'\n\n";
        for(int x = 0; x < 80; x++){
            std::wcout << L"Give me one Chinese letter...";
                wcin >> kanji;
                std::wcout << L"The Chinese letter is \"" << kanji << "\".\n\n";
        }
    return 0;
}

What matters to me is the "The Chinese letter is "(kanji)"." line. When I do what the program says I get "The Chinese letter is "?".". So the problem is that DevC++ doesn't show the Chinese letters correctly, even when I using the wcin and wcout things.

Note I am using DevC++ on Ubuntu, through wine.


问:
C Windows: Enumerate *all* processes, including those started by the user
There is a lot of information on the interweb regarding the handling of processes on linux, not much on Windows.

I'm using C. I want to calculate the resource usage of all processes. Not just of the system processes, I want to include those who were opened by the user for exmaple.

This can be done using EnumProcesses(), OpenProcess() and GetProcessTimes(). However this does not include processes that are not system processes.

Any thoughts?

答:
This can be done using EnumProcesses(), OpenProcess() and GetProcessTimes(). However this does not include processes that are not system processes.

It still uses OpenProcess which from my understanding is only able to open system processes.

Still, EnumProcesses() for a fact lists only system processes.

These are all false.

CreateToolHelp32Snapshot() & EnumProcesses() will both list all running processes, make sure you run your application as an administrator to get access to all the information.

OpenProcess() works on all processes as well.


问:
python string split slice and into a list
I have a string for example "streemlocalbbv"

and I have my_function that takes this string and a string that I want to find ("loc") in the original string. And what I want to get returned is this;

```<code>my_function("streemlocalbbv", "loc")

output = ["streem","loc","albbv"]
</code>```

what I did so far is

```<code>def find_split(string,find_word):

    length = len(string)
    find_word_start_index = string.find(find_word)
    find_word_end_index = find_word_start_index + len(find_word)

    string[find_word_start_index:find_word_end_index]

    a = string[0:find_word_start_index]
    b = string[find_word_start_index:find_word_end_index]
    c = string[find_word_end_index:length]

    return [a,b,c]
</code>```

Trying to find the index of the string I am looking for in the original string, and then split the original string. But from here I am not sure how should I do it.

答:
Use the split, index and insert function to solve this

```<code>def my_function(word,split_by):
  l = word.split(split_by)
  l.insert(l.index(word[:word.find(split_by)])+1,split_by)
  return l
print(my_function("streemlocalbbv", "loc"))
#['str', 'eem', 'localbbv']
</code>```

Body:
I have a string for example "streemlocalbbv"

and I have my_function that takes this string and a string that I want to find ("loc") in the original string. And what I want to get returned is this;

my_function("streemlocalbbv", "loc")

output = ["streem","loc","albbv"]

what I did so far is

def find_split(string,find_word):

    length = len(string)
    find_word_start_index = string.find(find_word)
    find_word_end_index = find_word_start_index + len(find_word)

    string[find_word_start_index:find_word_end_index]

    a = string[0:find_word_start_index]
    b = string[find_word_start_index:find_word_end_index]
    c = string[find_word_end_index:length]

    return [a,b,c]

Trying to find the index of the string I am looking for in the original string, and then split the original string. But from here I am not sure how should I do it.

Body:
Use the split, index and insert function to solve this

def my_function(word,split_by):
  l = word.split(split_by)
  l.insert(l.index(word[:word.find(split_by)])+1,split_by)
  return l
print(my_function("streemlocalbbv", "loc"))
#['str', 'eem', 'localbbv']


问:
importerror : cannot import name 'secure_write' while updating python in conda evironment
I want to update my python version to python 3.6 ,
 I am using conda environment therefore used the following command on the terminal :

conda install python=3.6

while installation I'm encountered with this error : importerror : cannot import name 'secure_write'

Any help???

答:
First I did
pip uninstall jupyter_client
then
pip install jupyter_client
this helped me fix the error </p>