问:
Create table - Mysql
I'm looking for a little help with this table.  First:  The table isn't being accepted by mysql. I'm getting a 150 error, which doesn't tell me much.  Second, I'm very certain that I'm not using the best data types & way to go about things.... please give me a little input!  </p>

```<code>CREATE  TABLE IF NOT EXISTS `axis`.`Employee` (
`idEmployee` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT ,
`idAccount` INT(10) UNSIGNED NOT NULL ,
`user` VARCHAR(45) NULL DEFAULT NULL ,
`pass` VARCHAR(45) NULL DEFAULT NULL ,
`firstName` VARCHAR(45) NULL DEFAULT NULL ,
`lastName` VARCHAR(45) NULL DEFAULT NULL ,
`middleName` VARCHAR(45) NULL DEFAULT NULL ,
`idGrp` INT(10) UNSIGNED NULL DEFAULT NULL ,
`idCompany` INT(10) UNSIGNED NULL DEFAULT NULL ,
`idLocation` INT(10) UNSIGNED NULL DEFAULT NULL ,
`idUnit` INT(10) UNSIGNED NULL DEFAULT NULL ,
`idCrew` INT(10) UNSIGNED NULL DEFAULT NULL ,
`idPosition` INT(10) UNSIGNED NULL DEFAULT NULL ,
`officeLoc` VARCHAR(45) NULL DEFAULT NULL ,
`wPhone` VARCHAR(12) NULL DEFAULT NULL ,
`wCell` VARCHAR(12) NULL DEFAULT NULL ,
`wFax` VARCHAR(12) NULL DEFAULT NULL ,
`wEmail` VARCHAR(45) NULL DEFAULT NULL ,
`radio` VARCHAR(12) NULL DEFAULT NULL ,
`hPhone` VARCHAR(12) NULL DEFAULT NULL ,
`hCell` VARCHAR(12) NULL DEFAULT NULL ,
`hEmail` VARCHAR(45) NULL DEFAULT NULL ,
`addrOne` VARCHAR(45) NULL DEFAULT NULL ,
`addrTwo` VARCHAR(45) NULL DEFAULT NULL ,
`city` VARCHAR(45) NULL DEFAULT NULL ,
`state` VARCHAR(45) NULL DEFAULT NULL ,
`zip` VARCHAR(10) NULL DEFAULT NULL ,
`emergContact` VARCHAR(45) NULL DEFAULT NULL ,
`emergPhone` VARCHAR(12) NULL DEFAULT NULL ,
`gender` ENUM('male','female') NULL DEFAULT NULL ,
`birthDate` DATE NULL DEFAULT NULL ,
`ssn` VARCHAR(5) NULL DEFAULT NULL ,
`hireDate` DATE NULL DEFAULT NULL ,
`sepDate` DATE NULL DEFAULT NULL ,
`comment` VARCHAR(255) NULL DEFAULT NULL ,
`photo` MEDIUMBLOB NULL DEFAULT NULL ,
`isActive` BIT(1) NOT NULL DEFAULT 1 ,
`allowLogin` BIT(1) NOT NULL DEFAULT 0 ,
`trackTravel` BIT(1) NOT NULL DEFAULT 1 ,
`trackTimesheet` BIT(1) NOT NULL DEFAULT 1 ,
`defFltArr` VARCHAR(10) NULL DEFAULT NULL ,
`defFltDep` VARCHAR(10) NULL DEFAULT NULL ,
`defDayTimeStart` TIME NOT NULL DEFAULT '06:00:00' ,
`defHoursPerDay` DECIMAL(4,2) NOT NULL DEFAULT '11.50' ,
`userType` ENUM('root','admin','view','acl','report','employee') NOT NULL DEFAULT 'employee',
`created` DATETIME NOT NULL ,
`modified` TIMESTAMP NOT NULL ,
`modifiedBy` INT(10) UNSIGNED NULL DEFAULT NULL ,
PRIMARY KEY (`idEmployee`, `idAccount`, `idGrp`, `idCompany`, `idLocation`, `idUnit`, `idCrew`, `idPosition`, `modifiedBy`) ,
UNIQUE INDEX `UNIQUE` (`idEmployee` ASC) ,
INDEX `fk_Employee_Grp` (`idGrp` ASC) ,
INDEX `fk_Employee_Company` (`idCompany` ASC) ,
INDEX `fk_Employee_Unit` (`idUnit` ASC) ,
INDEX `fk_Employee_Location` (`idLocation` ASC) ,
INDEX `fk_Employee_Crew` (`idCrew` ASC) ,
INDEX `fk_Employee_Position` (`idPosition` ASC) ,
INDEX `fk_Employee_Employee` (`modifiedBy` ASC) ,
CONSTRAINT `fk_Employee_Grp`
FOREIGN KEY (`idGrp` )
REFERENCES `axis`.`Grp` (`idGrp` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Company`
FOREIGN KEY (`idCompany` )
REFERENCES `axis`.`Company` (`idCompany` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Unit`
FOREIGN KEY (`idUnit` )
REFERENCES `axis`.`Unit` (`idUnit` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Location`
FOREIGN KEY (`idLocation` )
REFERENCES `axis`.`Location` (`idLocation` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Crew`
FOREIGN KEY (`idCrew` )
REFERENCES `axis`.`Crew` (`idCrew` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Position`
FOREIGN KEY (`idPosition` )
REFERENCES `axis`.`Position` (`idPosition` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Employee`
FOREIGN KEY (`modifiedBy` )
REFERENCES `axis`.`Employee` (`idEmployee` )
ON DELETE SET NULL
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci
</code>```

答:
Adding to a1ex07's reply, see this thread:

http://forums.mysql.com/read.php?22,19755,259716#msg-259716

It might also be due to signed/unsigned integer-related problems.

Also, your primary key (a unique, not null (set of) field(s)) is, de facto, your employee ID, based on the table's definition.

Title: Create table - Mysql

Body:
I'm looking for a little help with this table.  First:  The table isn't being accepted by mysql. I'm getting a 150 error, which doesn't tell me much.  Second, I'm very certain that I'm not using the best data types & way to go about things.... please give me a little input!

CREATE  TABLE IF NOT EXISTS `axis`.`Employee` (
`idEmployee` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT ,
`idAccount` INT(10) UNSIGNED NOT NULL ,
`user` VARCHAR(45) NULL DEFAULT NULL ,
`pass` VARCHAR(45) NULL DEFAULT NULL ,
`firstName` VARCHAR(45) NULL DEFAULT NULL ,
`lastName` VARCHAR(45) NULL DEFAULT NULL ,
`middleName` VARCHAR(45) NULL DEFAULT NULL ,
`idGrp` INT(10) UNSIGNED NULL DEFAULT NULL ,
`idCompany` INT(10) UNSIGNED NULL DEFAULT NULL ,
`idLocation` INT(10) UNSIGNED NULL DEFAULT NULL ,
`idUnit` INT(10) UNSIGNED NULL DEFAULT NULL ,
`idCrew` INT(10) UNSIGNED NULL DEFAULT NULL ,
`idPosition` INT(10) UNSIGNED NULL DEFAULT NULL ,
`officeLoc` VARCHAR(45) NULL DEFAULT NULL ,
`wPhone` VARCHAR(12) NULL DEFAULT NULL ,
`wCell` VARCHAR(12) NULL DEFAULT NULL ,
`wFax` VARCHAR(12) NULL DEFAULT NULL ,
`wEmail` VARCHAR(45) NULL DEFAULT NULL ,
`radio` VARCHAR(12) NULL DEFAULT NULL ,
`hPhone` VARCHAR(12) NULL DEFAULT NULL ,
`hCell` VARCHAR(12) NULL DEFAULT NULL ,
`hEmail` VARCHAR(45) NULL DEFAULT NULL ,
`addrOne` VARCHAR(45) NULL DEFAULT NULL ,
`addrTwo` VARCHAR(45) NULL DEFAULT NULL ,
`city` VARCHAR(45) NULL DEFAULT NULL ,
`state` VARCHAR(45) NULL DEFAULT NULL ,
`zip` VARCHAR(10) NULL DEFAULT NULL ,
`emergContact` VARCHAR(45) NULL DEFAULT NULL ,
`emergPhone` VARCHAR(12) NULL DEFAULT NULL ,
`gender` ENUM('male','female') NULL DEFAULT NULL ,
`birthDate` DATE NULL DEFAULT NULL ,
`ssn` VARCHAR(5) NULL DEFAULT NULL ,
`hireDate` DATE NULL DEFAULT NULL ,
`sepDate` DATE NULL DEFAULT NULL ,
`comment` VARCHAR(255) NULL DEFAULT NULL ,
`photo` MEDIUMBLOB NULL DEFAULT NULL ,
`isActive` BIT(1) NOT NULL DEFAULT 1 ,
`allowLogin` BIT(1) NOT NULL DEFAULT 0 ,
`trackTravel` BIT(1) NOT NULL DEFAULT 1 ,
`trackTimesheet` BIT(1) NOT NULL DEFAULT 1 ,
`defFltArr` VARCHAR(10) NULL DEFAULT NULL ,
`defFltDep` VARCHAR(10) NULL DEFAULT NULL ,
`defDayTimeStart` TIME NOT NULL DEFAULT '06:00:00' ,
`defHoursPerDay` DECIMAL(4,2) NOT NULL DEFAULT '11.50' ,
`userType` ENUM('root','admin','view','acl','report','employee') NOT NULL DEFAULT 'employee',
`created` DATETIME NOT NULL ,
`modified` TIMESTAMP NOT NULL ,
`modifiedBy` INT(10) UNSIGNED NULL DEFAULT NULL ,
PRIMARY KEY (`idEmployee`, `idAccount`, `idGrp`, `idCompany`, `idLocation`, `idUnit`, `idCrew`, `idPosition`, `modifiedBy`) ,
UNIQUE INDEX `UNIQUE` (`idEmployee` ASC) ,
INDEX `fk_Employee_Grp` (`idGrp` ASC) ,
INDEX `fk_Employee_Company` (`idCompany` ASC) ,
INDEX `fk_Employee_Unit` (`idUnit` ASC) ,
INDEX `fk_Employee_Location` (`idLocation` ASC) ,
INDEX `fk_Employee_Crew` (`idCrew` ASC) ,
INDEX `fk_Employee_Position` (`idPosition` ASC) ,
INDEX `fk_Employee_Employee` (`modifiedBy` ASC) ,
CONSTRAINT `fk_Employee_Grp`
FOREIGN KEY (`idGrp` )
REFERENCES `axis`.`Grp` (`idGrp` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Company`
FOREIGN KEY (`idCompany` )
REFERENCES `axis`.`Company` (`idCompany` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Unit`
FOREIGN KEY (`idUnit` )
REFERENCES `axis`.`Unit` (`idUnit` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Location`
FOREIGN KEY (`idLocation` )
REFERENCES `axis`.`Location` (`idLocation` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Crew`
FOREIGN KEY (`idCrew` )
REFERENCES `axis`.`Crew` (`idCrew` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Position`
FOREIGN KEY (`idPosition` )
REFERENCES `axis`.`Position` (`idPosition` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Employee`
FOREIGN KEY (`modifiedBy` )
REFERENCES `axis`.`Employee` (`idEmployee` )
ON DELETE SET NULL
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci


来源: stackexchange

问:
How can we add Views dynamically androidx.constraintlayout.helper.widget.Flow and add reference Ids
How can we add Views dynamically in androidx.constraintlayout.helper.widget.Flow  and add reference Ids dynamically.

答:
```<code>view1.setId(View.generateViewId());
view2.setId(View.generateViewId());
view3.setId(View.generateViewId());
flow.setReferencedIds(new int[]{view1.getId(), view2.getId(), view3.getId()});
</code>```

ContentLicense: CC BY-SA 4.0


问:
How to ensure load time weaving takes place for Eclipselink when using SpringBootTest with other tests running beforethe Spring one
I'm using Spring Rest Docs to generate documentation for my REST services. This involves running unit(strictly integration) tests that run against a live Spring Boot Container that is kicked off by the test. The test class looks like this:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MySpringConfiguration.class)
@WebAppConfiguration
public class ApiDocumentation {

  private MockMvc mockMvc;

  @Rule
  public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("target/generated-snippets");

  @Autowired
  private WebApplicationContext context;

  @Autowired
  private ObjectMapper objectMapper;

  @Before
  public void setUp() {
      this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
            .apply(documentationConfiguration(this.restDocumentation))
            .build();
  }

  @Test
  public void testSomething() throws Exception {
  }
}
</code>```

The application uses JPA with EclipseLink for the EntityManager implementation.

When I run the test standalone in my IDE or as the only test present when I run a Maven build using the maven-surefire-plugin everything works fine.

However it's not the only test I want to run in the suite. As soon as I run other tests in the suite I come across the issue mentioned here, namely

"Spring's agent does not initialize the persistence context until the application accesses the Spring context. If the application has already triggered the loading of the persistent class before accessing the Spring context, weaving will not occur."

and get errors like this:

Exception Description: The method [_persistence_set_someField_vh] or [_persistence_get_someField_vh] is not defined in the object [mypackage.MyEntity].

So what do people normally do to get around this ? Run SpringBootTest classes in a different module to unit tests that access entities ?

答:
Another solution could be to disable dynamic weaving in that particular test using eclipselink.weaving JPA property.

See this question and its answers: @SpringBootTest interferes with EclipseLink dynamic weaving

ContentLicense: CC BY-SA 3.0

Body:
I'm using Spring Rest Docs to generate documentation for my REST services. This involves running unit(strictly integration) tests that run against a live Spring Boot Container that is kicked off by the test. The test class looks like this:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MySpringConfiguration.class)
@WebAppConfiguration
public class ApiDocumentation {

  private MockMvc mockMvc;

  @Rule
  public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("target/generated-snippets");

  @Autowired
  private WebApplicationContext context;

  @Autowired
  private ObjectMapper objectMapper;

  @Before
  public void setUp() {
      this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
            .apply(documentationConfiguration(this.restDocumentation))
            .build();
  }

  @Test
  public void testSomething() throws Exception {
  }
}

The application uses JPA with EclipseLink for the EntityManager implementation.

When I run the test standalone in my IDE or as the only test present when I run a Maven build using the maven-surefire-plugin everything works fine.

However it's not the only test I want to run in the suite. As soon as I run other tests in the suite I come across the issue mentioned here, namely

"Spring's agent does not initialize the persistence context until the application accesses the Spring context. If the application has already triggered the loading of the persistent class before accessing the Spring context, weaving will not occur."

and get errors like this:

Exception Description: The method [_persistence_set_someField_vh] or [_persistence_get_someField_vh] is not defined in the object [mypackage.MyEntity].

So what do people normally do to get around this ? Run SpringBootTest classes in a different module to unit tests that access entities ?


问:
How i can remove duplicates array in object value?
Js Object, ReactJs</p>

```<code>{userId:1, userName:mahadi},
{userId:2,userName:hasan},
{userId:1, userName:mahadi}
]
</code>```

答:
const origin = [{
    userId: 1,
    userName: "mahadi"
  },
  {
    userId: 2,
    userName: "hasan"
  },
  {
    userId: 1,
    userName: "mahadi"
  }
];

const result = origin.filter(function(element, index, arr) {
  return index === arr.findIndex(e => e.userId == element.userId);
});

const repeat = origin.filter(function(element, index, arr) {
  return index !== arr.findIndex(e => e.userId == element.userId);
});

console.log("result", result);
console.log("repeat", repeat);```

Body:
Js Object, ReactJs

{userId:1, userName:mahadi},
{userId:2,userName:hasan},
{userId:1, userName:mahadi}
]


问:
How to issue notification/alert from JavaScript when application in background - PhoneGap iPhone/iOS
I want to issue a notification/alert to the user - based on a timed event emanating from a stop watch. The logic is in JavaScript, the application runs in PhoneGap on iPhone.

Problem: iPhone pauses JavaScript execution in the webview on iPhone/iOs when the application is in the background.

Triggering a native alert dialogs, using e.g. PhoneGap's navigator.notification.alert(), fails because the alert is simply not invoked while in the background.

How can I efficiently combine this with, e.g., UILocalNotification? - Any examples / samples / plugins available?

答:
In general, iOS doesn't allow long-running background tasks, unless you're doing background audio, location services, or VOIP.

You could use Task Completion (beginBackgroundTaskWithExpirationHandler) to keep your logic running for a little while once you app goes into the background. However iOS will still terminate your task after about 10 minutes.

Another option is to pre-schedule all your timed events using UILocalNotification. You can schedule as many as 128 events, each with an optional repeat interval. Here's the sample code from Apple's documentation:

```<code>// Create a new notification.
UILocalNotification* alarm = [[[UILocalNotification alloc] init] autorelease];
if (alarm)
{
    alarm.fireDate = theDate;
    alarm.timeZone = [NSTimeZone defaultTimeZone];
    alarm.repeatInterval = 0;
    alarm.soundName = @"alarmsound.caf";
    alarm.alertBody = @"Time to wake up!";

    [app scheduleLocalNotification:alarm];
}
</code>```

http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

Body:
In general, iOS doesn't allow long-running background tasks, unless you're doing background audio, location services, or VOIP.

You could use Task Completion (beginBackgroundTaskWithExpirationHandler) to keep your logic running for a little while once you app goes into the background. However iOS will still terminate your task after about 10 minutes.

Another option is to pre-schedule all your timed events using UILocalNotification. You can schedule as many as 128 events, each with an optional repeat interval. Here's the sample code from Apple's documentation:

// Create a new notification.
UILocalNotification* alarm = [[[UILocalNotification alloc] init] autorelease];
if (alarm)
{
    alarm.fireDate = theDate;
    alarm.timeZone = [NSTimeZone defaultTimeZone];
    alarm.repeatInterval = 0;
    alarm.soundName = @"alarmsound.caf";
    alarm.alertBody = @"Time to wake up!";

    [app scheduleLocalNotification:alarm];
}

http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html


问:
python script to paste rows from 1 excel sheet to another. Paste should be "paste by value"
I am writing a python script to copy rows and columns from source to destination excel sheet.
Source excel sheet has rows that have formulas. I just want to copy and paste values instead of the formula. Is there some way to do that in python?
I have written the below code (it copies and paste the formulas instead of the actual value)</p>

```<code>file_src="C:\\Users\\final_excel1.xlsx"
wb1 = openpyxl.load_workbook(file_src)
ws1 = wb1.worksheets[2] # index=n-1

file_dest = "C:\\Users\\final_excel2.xlsx"
wb2 = openpyxl.load_workbook(file_dest)
ws2 = wb2.active

r_ws1=ws1.max_row
c_ws1=ws1.max_column

## copying values from source to dest.
for i in range  (1, req_r_ws1+1):
    for j in range (1, req_c_ws1+1):
        cell=ws1.cell(row=i, column=j)
        ws2.cell(row=i, column=j).value=cell.value

wb2.save(file_dest)
</code>```

答:
add data_only=True to wb1

```<code>wb1 = openpyxl.load_workbook(file_src, data_only=True)
</code>```

also see, Read Excel cell value and not the formula computing it -openpyxl

Body:
I am writing a python script to copy rows and columns from source to destination excel sheet.
Source excel sheet has rows that have formulas. I just want to copy and paste values instead of the formula. Is there some way to do that in python?
I have written the below code (it copies and paste the formulas instead of the actual value)

file_src="C:\\Users\\final_excel1.xlsx"
wb1 = openpyxl.load_workbook(file_src)
ws1 = wb1.worksheets[2] # index=n-1

file_dest = "C:\\Users\\final_excel2.xlsx"
wb2 = openpyxl.load_workbook(file_dest)
ws2 = wb2.active

r_ws1=ws1.max_row
c_ws1=ws1.max_column

## copying values from source to dest.
for i in range  (1, req_r_ws1+1):
    for j in range (1, req_c_ws1+1):
        cell=ws1.cell(row=i, column=j)
        ws2.cell(row=i, column=j).value=cell.value

wb2.save(file_dest)

Body:
add data_only=True to wb1

wb1 = openpyxl.load_workbook(file_src, data_only=True)

also see, Read Excel cell value and not the formula computing it -openpyxl


问:
Cannot delete a file from s3 with boto3
I am trying to permanently delete a file from S3, using boto3. My buckets are not using versioning.

I have tried two ways:

def remove_aws_object(bucket_name, item_key):
    ''' Provide bucket name and item key, remove from S3
    '''
    s3_client = boto3.client('s3',
                             aws_access_key_id=AWS_ACCESS_KEY,
                             aws_secret_access_key=AWS_SECRET)
    delete = s3_client.delete_object(Bucket=bucket_name, Key=item_key)
    print(delete)
{'ResponseMetadata': {'RequestId': '61F3C195D373B0C5', 'HostId': 'pigcx1wtIN+Y8RU3zJKliWXcXrHXHzpdAOuGBL64x3V9YefQbWXPZi9B/9F', 'HTTPStatusCode': 204, 'HTTPHeaders': {'x-amz-id-2': 'pigcx1wtIN+Y8RU3zJKliWXcXrHXHzpdAOuGBL64x3V9YefQbWXPZi9B/9FLazUSsCds8f4=', 'x-amz-request-id': '61F3C195D373B0C5', 'date': 'Thu, 13 Feb 2020 09:07:50 GMT', 'server': 'AmazonS3'}, 'RetryAttempts': 0}}
```

<p>As well as via the Object:</p>

<pre class="lang-python prettyprint-override"><code>def remove_aws_object(bucket_name, item_key):
    ''' Provide bucket name and item key, remove from S3
    '''
    s3_client = boto3.resource('s3',
                             aws_access_key_id=AWS_ACCESS_KEY,
                             aws_secret_access_key=AWS_SECRET)

    my_object = s3_client.Object(bucket_name, item_key)
    a = my_object.delete()
    print(a)
    {'ResponseMetadata': {'RequestId': '6074B9CA870773CE', 'HostId': 'rQoK+x+xcjAw2T3DpTHMWQb4Gq6DzPJy2qFoFHQCYoGwb8/p7700+Nk+6gBIERN', 'HTTPStatusCode': 204, 'HTTPHeaders': {'x-amz-id-2': 'rQoK+x+xcjAw2TKK833DpTHMWQb4Gq6DzPJy2qFoFHQCYoGwb8/p7700+Nk+6gBIE', 'x-amz-request-id': '6074B9CA870773CE', 'date': 'Thu, 13 Feb 2020 12:02:36 GMT', 'x-amz-version-id': 'null', 'x-amz-delete-marker': 'true', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'DeleteMarker': True, 'VersionId': 'null'}
</code>```

Both methods work without error, but do not remove the file, I can still see it in the S3 console and I then have to manually delete it. Am I doing something wrong?

答:
It was a fairly simple solution, my items are stored within a folder structure, and I needed to pass the folder location, along with the item key.

def remove_aws_object(bucket_name, item_key):
    ''' Provide bucket name and item key, remove from S3
    '''
    folder = "foo/bar/"
    delete_key = folder + item_key
    s3_client = boto3.client('s3',
                             aws_access_key_id=AWS_ACCESS_KEY,
                             aws_secret_access_key=AWS_SECRET)
    delete = s3_client.delete_object(Bucket=bucket_name, Key=delete_key)
```

Title: Cannot delete a file from s3 with boto3

Body:
I am trying to permanently delete a file from S3, using boto3. My buckets are not using versioning.

I have tried two ways:

def remove_aws_object(bucket_name, item_key):
    ''' Provide bucket name and item key, remove from S3
    '''
    s3_client = boto3.client('s3',
                             aws_access_key_id=AWS_ACCESS_KEY,
                             aws_secret_access_key=AWS_SECRET)
    delete = s3_client.delete_object(Bucket=bucket_name, Key=item_key)
    print(delete)
{'ResponseMetadata': {'RequestId': '61F3C195D373B0C5', 'HostId': 'pigcx1wtIN+Y8RU3zJKliWXcXrHXHzpdAOuGBL64x3V9YefQbWXPZi9B/9F', 'HTTPStatusCode': 204, 'HTTPHeaders': {'x-amz-id-2': 'pigcx1wtIN+Y8RU3zJKliWXcXrHXHzpdAOuGBL64x3V9YefQbWXPZi9B/9FLazUSsCds8f4=', 'x-amz-request-id': '61F3C195D373B0C5', 'date': 'Thu, 13 Feb 2020 09:07:50 GMT', 'server': 'AmazonS3'}, 'RetryAttempts': 0}}

As well as via the Object:

def remove_aws_object(bucket_name, item_key):
    ''' Provide bucket name and item key, remove from S3
    '''
    s3_client = boto3.resource('s3',
                             aws_access_key_id=AWS_ACCESS_KEY,
                             aws_secret_access_key=AWS_SECRET)

    my_object = s3_client.Object(bucket_name, item_key)
    a = my_object.delete()
    print(a)
    {'ResponseMetadata': {'RequestId': '6074B9CA870773CE', 'HostId': 'rQoK+x+xcjAw2T3DpTHMWQb4Gq6DzPJy2qFoFHQCYoGwb8/p7700+Nk+6gBIERN', 'HTTPStatusCode': 204, 'HTTPHeaders': {'x-amz-id-2': 'rQoK+x+xcjAw2TKK833DpTHMWQb4Gq6DzPJy2qFoFHQCYoGwb8/p7700+Nk+6gBIE', 'x-amz-request-id': '6074B9CA870773CE', 'date': 'Thu, 13 Feb 2020 12:02:36 GMT', 'x-amz-version-id': 'null', 'x-amz-delete-marker': 'true', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'DeleteMarker': True, 'VersionId': 'null'}

Both methods work without error, but do not remove the file, I can still see it in the S3 console and I then have to manually delete it. Am I doing something wrong?


问:
React Native: Can't see changes to my code
I'm a beginner with React Native. I've followed the simple tutorial from the offical doc, but I have a problem when I try to see my code changes. The doc says:

For Android, you can edit index.android.js to make changes to the app
  and press Reload JS from the rage shake menu to see the changes

I'm developing directly on my Nexus 6, not on the simulator, I did as it tells but I can't see any changes for my Android sample app, I've tried only to edit the text but without success. I've also tried to rebuild after any changes but no result, I'm sure it's a simple thing but what am I missing?

答:
Clear watchman watches: watchman watch-del-all.

Delete the node_modules folder: rm -rf node_modules && npm install.

Reset Metro Bundler cache: rm -rf /tmp/metro-bundler-cache-* or npm start -- --reset-cache.

Remove haste cache: rm -rf /tmp/haste-map-react-native-packager-*.


问:
Semantic-UI / ReactJS | Use DropDown as group
I'm using Semantic-UI/ReactJS and want to use DropDown component as group but there is not such option, but I googled, and find a fiddle that provide this but in standalone semantic ui not for reactjs, how can I use dropdown as group?

```<code><Dropdown
    id="Province"
    search selection clearable
    options={this.state.ProvinceData && this.state.ProvinceData.map(v => {
        return {
            key: v.id,
            text: v.name,
            value: v.id
        }
    })}
    onChange={this.getProvince}
    placeholder="-- Choose --"
    value={this.state.provinceValue}
    noResultsMessage={'Not Found!'}
/>
</code>```

答:
Use <Dropdown.Header /> and <Dropdown.Divider />

```<code><Dropdown
    id="Province"
    search selection clearable
    onChange={this.getProvince}
    placeholder="-- Choose --"
    value={this.state.provinceValue}
    noResultsMessage={'Not Found!'}
    <Dropdown.Menu>
        <Dropdown.Divider />
        <Dropdown.Header icon='tags' content='Group 1' />
        <Dropdown.Item text='Text 1' />
        <Dropdown.Item text='Text 2' />
        <Dropdown.Item text='Text 3' />
        <Dropdown.Divider />
        <Dropdown.Header icon='tags' content='Group 2' />
        <Dropdown.Item text='Text 4' />
        <Dropdown.Item text='Text 5' />
        <Dropdown.Item text='Text 6' />
    </Dropdown.Menu>
</Dropdown>
</code>```

Just iterate your options as above jsx

Body:
I'm using Semantic-UI/ReactJS and want to use DropDown component as group but there is not such option, but I googled, and find a fiddle that provide this but in standalone semantic ui not for reactjs, how can I use dropdown as group?

<Dropdown
    id="Province"
    search selection clearable
    options={this.state.ProvinceData && this.state.ProvinceData.map(v => {
        return {
            key: v.id,
            text: v.name,
            value: v.id
        }
    })}
    onChange={this.getProvince}
    placeholder="-- Choose --"
    value={this.state.provinceValue}
    noResultsMessage={'Not Found!'}
/>

Body:
Use <Dropdown.Header /> and <Dropdown.Divider />

<Dropdown
    id="Province"
    search selection clearable
    onChange={this.getProvince}
    placeholder="-- Choose --"
    value={this.state.provinceValue}
    noResultsMessage={'Not Found!'}
    <Dropdown.Menu>
        <Dropdown.Divider />
        <Dropdown.Header icon='tags' content='Group 1' />
        <Dropdown.Item text='Text 1' />
        <Dropdown.Item text='Text 2' />
        <Dropdown.Item text='Text 3' />
        <Dropdown.Divider />
        <Dropdown.Header icon='tags' content='Group 2' />
        <Dropdown.Item text='Text 4' />
        <Dropdown.Item text='Text 5' />
        <Dropdown.Item text='Text 6' />
    </Dropdown.Menu>
</Dropdown>

Just iterate your options as above jsx


问:
Attaching a remote host process in ByteBuddy
I am new to ByteBuddy and trying to setup instrumentation for a process running on a remote process.

My remote process is started with -XX:+StartAttachListener.

Created a simple Maven project with the following in the pom.

```<code> <dependency>
     <groupId>net.bytebuddy</groupId>
     <artifactId>byte-buddy-agent</artifactId>
     <version>1.10.7</version>
 </dependency>
 <!-- https://mvnrepository.com/artifact/net.bytebuddy/byte-buddy -->
 <dependency>
     <groupId>net.bytebuddy</groupId>
     <artifactId>byte-buddy</artifactId>
     <version>1.10.7</version>
 </dependency>
</code>```

Created an agent class with a premain method.

```<code> public class Agent {

      public static void premain(String args, Instrumentation instrumentation) {

             System.out.println("Premain");
             File file ;
             try {

                     file = (new File("Agent.jar"));
                     ByteBuddyAgent.attach(file,"18467");
                 }
                 catch (Exception e)
                 {
                     e.printStackTrace();
                 }

         }
     }
</code>```

Questions:-

Do I need to generate Agent.jar here? Or else, it comes with byte-buddy?

ByteBuddyAgent.attach doesn't take the remote hostname. How can I define the remote host process to attach? Or else, byte buddy should be running in the same host where the Java process in running.

The below example to run the agent along with the jar under test.

```<code> java -javaagent:/path/to/agent.jar -cp jar-under-test.jar Foo.Main
</code>```

How to run the agent attacher as a separate process to attach the java agent to a java process running on a remote host?

答:
Remote attachment in Java is only possible not only from the same host but also only from the same OS user. This is meant as a security mechanism as it would otherwise be fairly simple to take over any Java process from a remote location.

Byte Buddy simply provides wrappers around it. You can use byte-buddy-agent.jar as your agent and attach it either to your own process (ByteBuddyAgent.install()) or to a remote one ByteBuddyAgent.attach(pid, new File("byte-buddy-agent.jar")). An instance of Instrumentation is then available via Installer class to the entire Java process. Adding byte-buddy-agent.jar to the command line has the same effect for that process.

Body:
I am new to ByteBuddy and trying to setup instrumentation for a process running on a remote process.

My remote process is started with -XX:+StartAttachListener.

Created a simple Maven project with the following in the pom.

 <dependency>
     <groupId>net.bytebuddy</groupId>
     <artifactId>byte-buddy-agent</artifactId>
     <version>1.10.7</version>
 </dependency>

 <dependency>
     <groupId>net.bytebuddy</groupId>
     <artifactId>byte-buddy</artifactId>
     <version>1.10.7</version>
 </dependency>

Created an agent class with a premain method.

 public class Agent {

      public static void premain(String args, Instrumentation instrumentation) {

             System.out.println("Premain");
             File file ;
             try {

                     file = (new File("Agent.jar"));
                     ByteBuddyAgent.attach(file,"18467");
                 }
                 catch (Exception e)
                 {
                     e.printStackTrace();
                 }

         }
     }

Questions:-

Do I need to generate Agent.jar here? Or else, it comes with byte-buddy?

ByteBuddyAgent.attach doesn't take the remote hostname. How can I define the remote host process to attach? Or else, byte buddy should be running in the same host where the Java process in running.

The below example to run the agent along with the jar under test.

 java -javaagent:/path/to/agent.jar -cp jar-under-test.jar Foo.Main

How to run the agent attacher as a separate process to attach the java agent to a java process running on a remote host?


问:
Debugging Drupal's White Screen of Death?
I have a Drupal installation that previously worked perfectly on my localhost. However, now, after a formatted my computer, it just shows a blank screen (completely white).

So my question is, how can I see where things are going wrong, if I can't even log into the sever?

The only errors I can find are (taken from the Apache Error Logs):

```<code>[Tue May 17 05:05:04 2011] [notice] Parent: child process exited with status 255 -- Restarting.
[Tue May 17 05:05:04 2011] [notice] Digest: generating secret for digest authentication ...
[Tue May 17 05:05:04 2011] [notice] Digest: done
[Tue May 17 05:05:07 2011] [notice] Apache/2.2.11 (Win32) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i PHP/5.2.9 configured -- resuming normal operations
[Tue May 17 05:05:07 2011] [notice] Server built: Dec 10 2008 00:10:06
[Tue May 17 05:05:07 2011] [notice] Parent: Created child process 6992
</code>```

There are no errors in Watchdog...

I am using Xamp 1.7.1 (PHP 5.2) and Drupal 6.

I just also need to mention that once I try and load the site on my local machine, apache also crashes! I added this:

```<code>error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
</code>```

And it still just shows the screen of death? Where can I actually see errors?

I also found this in apache access.log:

```<code>127.0.0.1 - - [17/May/2011:05:22:14 +0200] "GET /greekmerchant/src/ HTTP/1.1" 200 3
127.0.0.1 - - [17/May/2011:05:25:45 +0200] "GET /greekmerchant/src/update.php HTTP/1.1" 302 -
127.0.0.1 - - [17/May/2011:05:25:46 +0200] "GET /greekmerchant/src/update.php?op=info HTTP/1.1" 200 -
</code>```

... after trying to access update.php. It also just goes to a white screen.

I have this in my sql config file:

```<code>[mysqld]
port= 3306
socket= "C:/xampp/mysql/mysql.sock"
basedir="C:/xampp/mysql"
tmpdir="C:/xampp/tmp"
datadir="C:/xampp/mysql/data"
skip-locking
key_buffer = 16M
max_allowed_packet = 128M
table_cache = 64
sort_buffer_size = 512K
net_buffer_length = 8K
read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 8M
log_error="mysql_error.log"
</code>```

And...

```<code>[mysqldump]
quick
max_allowed_packet = 128M
</code>```

Also, my PHP memory is set to 1024MB.

Anyone got any idea why this is just dying? Is it really a memory problem? What else can I do to get errors shown to me? I still see nothing even after enabling error logging.

Update:

The website runs on my local machine if I delete the files folder. So, for some reason, when it has to access files in the files folder, it runs out of memory. Why? Or better yet, what could be causing this excessive use of memory?

答:
Check your error reporting settings for PHP. You may need to enable error reporting.

This may help: http://drupal.org/node/158043

Body:
I have a Drupal installation that previously worked perfectly on my localhost. However, now, after a formatted my computer, it just shows a blank screen (completely white).

So my question is, how can I see where things are going wrong, if I can't even log into the sever?

The only errors I can find are (taken from the Apache Error Logs):

[Tue May 17 05:05:04 2011] [notice] Parent: child process exited with status 255 -- Restarting.
[Tue May 17 05:05:04 2011] [notice] Digest: generating secret for digest authentication ...
[Tue May 17 05:05:04 2011] [notice] Digest: done
[Tue May 17 05:05:07 2011] [notice] Apache/2.2.11 (Win32) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i PHP/5.2.9 configured -- resuming normal operations
[Tue May 17 05:05:07 2011] [notice] Server built: Dec 10 2008 00:10:06
[Tue May 17 05:05:07 2011] [notice] Parent: Created child process 6992

There are no errors in Watchdog...

I am using Xamp 1.7.1 (PHP 5.2) and Drupal 6.

I just also need to mention that once I try and load the site on my local machine, apache also crashes! I added this:

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

And it still just shows the screen of death? Where can I actually see errors?

I also found this in apache access.log:

127.0.0.1 - - [17/May/2011:05:22:14 +0200] "GET /greekmerchant/src/ HTTP/1.1" 200 3
127.0.0.1 - - [17/May/2011:05:25:45 +0200] "GET /greekmerchant/src/update.php HTTP/1.1" 302 -
127.0.0.1 - - [17/May/2011:05:25:46 +0200] "GET /greekmerchant/src/update.php?op=info HTTP/1.1" 200 -

... after trying to access update.php. It also just goes to a white screen.

I have this in my sql config file:

[mysqld]
port= 3306
socket= "C:/xampp/mysql/mysql.sock"
basedir="C:/xampp/mysql"
tmpdir="C:/xampp/tmp"
datadir="C:/xampp/mysql/data"
skip-locking
key_buffer = 16M
max_allowed_packet = 128M
table_cache = 64
sort_buffer_size = 512K
net_buffer_length = 8K
read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 8M
log_error="mysql_error.log"

And...

[mysqldump]
quick
max_allowed_packet = 128M

Also, my PHP memory is set to 1024MB.

Anyone got any idea why this is just dying? Is it really a memory problem? What else can I do to get errors shown to me? I still see nothing even after enabling error logging.

Update:

The website runs on my local machine if I delete the files folder. So, for some reason, when it has to access files in the files folder, it runs out of memory. Why? Or better yet, what could be causing this excessive use of memory?


问:
How to add Jquery cdn in ScriptManager and if the load fail then load from local file
In asp:ScriptManager i load jquery like this.

```<code><asp:ScriptManager ID="ScriptManagerMasterPage" runat="server">
    <Scripts>
        <asp:ScriptReference Path="~/Scripts/jquery-1.6.4.min.js" />
        <asp:ScriptReference Path="~/Scripts/jquery-ui-1.8.16.min.js" />
        <asp:ScriptReference Path="~/Scripts/tag-it.js" />
        <asp:ScriptReference Path="~/Scripts/MosJScript.js" />
        <asp:ScriptReference Path="~/Scripts/jquery.tools.min.js" />
        <asp:ScriptReference Path="~/Scripts/jquery.dragsort.js" />
        <asp:ScriptReference Path="~/Scripts/jquery.ad-gallery.pack.js" />
    </Scripts>
</asp:ScriptManager>
</code>```

Suppose that i would like to use jquery cdn from google but if the cdn file fail to load then i would load from local machine instead. how to do this.

答:
You have to add a Script Resource Mapping Definition. See the document below for example:

https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.scriptmanager.scriptresourcemapping

Then you have to set EnableCdn property of ScriptManager to true, to enable the usage of CDN.

Body:
In asp:ScriptManager i load jquery like this.

<asp:ScriptManager ID="ScriptManagerMasterPage" runat="server">

</asp:ScriptManager>

Suppose that i would like to use jquery cdn from google but if the cdn file fail to load then i would load from local machine instead. how to do this.


问:
Push to Laravel queue from outside Laravel (NodeJS)
I have a Laravel 5.3 installation running as a pure API application and need to connect from several different applications.

Everything is working fine (after all it's Laravel we're talking about :P), except I can't figure out one thing:

I have a MQTT server that is listening for messages from several devices (doesn't matter what). These messages contain information about a Job Class and method that need to be called on the backend.

I can't call the API directly, the devices simply don't support this (they do, but it's a lot more effort than using MQTT to transmit data). My thought was to push a new job onto the queue defining which Laravel Job Class to call (and which method). The problem is the JSON serialization...

The MQTT server is running on NodeJS, my queues are running on Redis. I remember a Tweet from Taylor where he mentioned that theoretically it could be possible to serialize the JSON needed and push to the queue from outside Laravel, and have the job processed by Laravel.

Anyone any idea how to approach this? Is there a documentation available about the structure of the JSON?

I should also mention that this solution NodeJS push queue, consumed by Laravel worker did not work for me. Same result as above, the job is placed on the queue but discarded without being processed or any errors thrown.

The sample data structure for a queued Event in Redis looks like this:

"{\"job\":\"Illuminate\\\\Broadcasting\\\\BroadcastEvent\",\"data\":{\"event\":\"O:28:\\\"App\\\\Events\\\\NotificationEvent\\\":5:{s:7:\\\"\\u0000*\\u0000name\\\";s:12:\\\"notification\\\";s:4:\\\"data\\\";a:4:{s:4:\\\"testkey\\\";s:14:\\\"testval\\\";s:9:\\\"timestamp\\\";s:19:\\\"2017-02-24 11:07:48\\\";s:5:\\\"event\\\";s:12:\\\"notification\\\";s:5:\\\"class\\\";s:28:\\\"App\\\\Events\\\\NotificationEvent\\\";}s:10:\\\"\\u0000*\\u0000channel\\\";N;s:7:\\\"\\u0000*\\u0000user\\\";O:45:\\\"Illuminate\\\\Contracts\\\\Database\\\\ModelIdentifier\\\":2:{s:5:\\\"class\\\";s:8:\\\"App\\\\User\\\";s:2:\\\"id\\\";i:2;}s:6:\\\"socket\\\";N;}\"},\"id\":\"XuUKRTf8CTSdzaVgp2gRcvmxQqLcpBUG\",\"attempts\":1}"

Based on that structure, I would think the object (that needs to be serialized) should look similar to this:

```<code>{
"job":"EventClass@method", //<-- Just a name
"data":{
    "event":"EventClass", //<-- Just a name
    "name":"EventName", //<-- Just a name
    "data":{
    "key":"value"
    "event":"EventName" //<-- Same as data.name
    "class":"EventClass@method" //<-- This is actually being called
    }
}
</code>```

There is additional information included in what Laravel actually puts on the queue (like a timestamp, user model identifier, etc), but I don't think that's necessary to trigger the job.

The data needs to be serialized in JS to achieve a similar output than with php serialize() (or better, to get a string that can be unserialized by php's unserialize().

I achieved to do so with the php-serialization NPM module (Thanks to Simon Svensson), but the job still isn't being consumed by Laravel (discarded but not executed)

Thanks in advance for any help :)

EDIT SOLUTION

Thanks to Simon's answer, here's the solution on how to serialize job data in Javascript and push onto a Laravel queue (and have Laravel process the whole thing automatically).

Note that this is an example for using queues with Redis. When using Beanstalkd or Database based queues, this might look different (or not).

This is the code I successfully used:

```<code>var serialize,Class,job,jobUser,jobData,serialized,result;

serialize = require('php-serialization').serialize;
Class = require('php-serialization').Class;

job = new Class("App\\Events\\NotificationEvent");

job.__addAttr__("name","string","notification","string","protected");

jobData = new Class();
jobData.__addAttr__("testkey","string","testval","string");
jobData.__addAttr__("timestamp","string","2017-02-24 11:07:48","string");
jobData.__addAttr__("event","string","notification","string");
jobData.__addAttr__("class","string","App\\Events\\NotificationEvent","string");
job.__addAttr__("data","string",jobData,"array","public");

job.__addAttr__("channel","string",null,"null","protected");

jobUser = new Class("Illuminate\\Contracts\\Database\\ModelIdentifier")
jobUser.__addAttr__("class","string","App\\User","string","public");
jobUser.__addAttr__("id","string",2,"integer","public");
job.__addAttr__("user","string",jobUser,"object","protected");

job.__addAttr__("socket","string",null,"null","public");

serialized = serialize(job,"object");

result = {
    job:"Illuminate\\Broadcasting\\BroadcastEvent",
    data:{
        event:serialized
    },
    id:"XuUKRTf8CTSdzaVgp2gRcvmxQqLcpBUG",
    attempts:1
};

queue.rpush('queues:default',JSON.stringify(result));
</code>```

I haven't figured out yet what the ID is exactly for, I successfully pushed jobs onto the queue with always the same Id. I guess if you're pushing jobs at a fast pace and they are stored at the same time it could be a problem. Since it's a string you could substitute it with any random ID you like (the random ID generated by Laravel is 32 characters, I think it's a good idea to keep this length).

Attempts should be set to 1 when initially pushing the job. If Laravel can't process the job, it will push it back onto the queue and increase the attempts value.

答:
simply expose an API where the job processor is written.
If we are talking about the node js and laravel. An API needs to be exposed which will accept the HTTP request and place the job and return to node js server.

Later on, if you have to execute the job with a different server which has different language installed the solution given by others will not work and will be restricted to a specific framework.

Body:
I have a Laravel 5.3 installation running as a pure API application and need to connect from several different applications.

Everything is working fine (after all it's Laravel we're talking about :P), except I can't figure out one thing:

I have a MQTT server that is listening for messages from several devices (doesn't matter what). These messages contain information about a Job Class and method that need to be called on the backend.

I can't call the API directly, the devices simply don't support this (they do, but it's a lot more effort than using MQTT to transmit data). My thought was to push a new job onto the queue defining which Laravel Job Class to call (and which method). The problem is the JSON serialization...

The MQTT server is running on NodeJS, my queues are running on Redis. I remember a Tweet from Taylor where he mentioned that theoretically it could be possible to serialize the JSON needed and push to the queue from outside Laravel, and have the job processed by Laravel.

Anyone any idea how to approach this? Is there a documentation available about the structure of the JSON?

I should also mention that this solution NodeJS push queue, consumed by Laravel worker did not work for me. Same result as above, the job is placed on the queue but discarded without being processed or any errors thrown.

The sample data structure for a queued Event in Redis looks like this:

"{\"job\":\"Illuminate\\\\Broadcasting\\\\BroadcastEvent\",\"data\":{\"event\":\"O:28:\\\"App\\\\Events\\\\NotificationEvent\\\":5:{s:7:\\\"\\u0000*\\u0000name\\\";s:12:\\\"notification\\\";s:4:\\\"data\\\";a:4:{s:4:\\\"testkey\\\";s:14:\\\"testval\\\";s:9:\\\"timestamp\\\";s:19:\\\"2017-02-24 11:07:48\\\";s:5:\\\"event\\\";s:12:\\\"notification\\\";s:5:\\\"class\\\";s:28:\\\"App\\\\Events\\\\NotificationEvent\\\";}s:10:\\\"\\u0000*\\u0000channel\\\";N;s:7:\\\"\\u0000*\\u0000user\\\";O:45:\\\"Illuminate\\\\Contracts\\\\Database\\\\ModelIdentifier\\\":2:{s:5:\\\"class\\\";s:8:\\\"App\\\\User\\\";s:2:\\\"id\\\";i:2;}s:6:\\\"socket\\\";N;}\"},\"id\":\"XuUKRTf8CTSdzaVgp2gRcvmxQqLcpBUG\",\"attempts\":1}"

Based on that structure, I would think the object (that needs to be serialized) should look similar to this:

{
"job":"EventClass@method", //<-- Just a name
"data":{
    "event":"EventClass", //<-- Just a name
    "name":"EventName", //<-- Just a name
    "data":{
    "key":"value"
    "event":"EventName" //<-- Same as data.name
    "class":"EventClass@method" //<-- This is actually being called
    }
}

There is additional information included in what Laravel actually puts on the queue (like a timestamp, user model identifier, etc), but I don't think that's necessary to trigger the job.

The data needs to be serialized in JS to achieve a similar output than with php serialize() (or better, to get a string that can be unserialized by php's unserialize().

I achieved to do so with the php-serialization NPM module (Thanks to Simon Svensson), but the job still isn't being consumed by Laravel (discarded but not executed)

Thanks in advance for any help :)

EDIT SOLUTION

Thanks to Simon's answer, here's the solution on how to serialize job data in Javascript and push onto a Laravel queue (and have Laravel process the whole thing automatically).

Note that this is an example for using queues with Redis. When using Beanstalkd or Database based queues, this might look different (or not).

This is the code I successfully used:

var serialize,Class,job,jobUser,jobData,serialized,result;

serialize = require('php-serialization').serialize;
Class = require('php-serialization').Class;

job = new Class("App\\Events\\NotificationEvent");

job.__addAttr__("name","string","notification","string","protected");

jobData = new Class();
jobData.__addAttr__("testkey","string","testval","string");
jobData.__addAttr__("timestamp","string","2017-02-24 11:07:48","string");
jobData.__addAttr__("event","string","notification","string");
jobData.__addAttr__("class","string","App\\Events\\NotificationEvent","string");
job.__addAttr__("data","string",jobData,"array","public");

job.__addAttr__("channel","string",null,"null","protected");

jobUser = new Class("Illuminate\\Contracts\\Database\\ModelIdentifier")
jobUser.__addAttr__("class","string","App\\User","string","public");
jobUser.__addAttr__("id","string",2,"integer","public");
job.__addAttr__("user","string",jobUser,"object","protected");

job.__addAttr__("socket","string",null,"null","public");

serialized = serialize(job,"object");

result = {
    job:"Illuminate\\Broadcasting\\BroadcastEvent",
    data:{
        event:serialized
    },
    id:"XuUKRTf8CTSdzaVgp2gRcvmxQqLcpBUG",
    attempts:1
};

queue.rpush('queues:default',JSON.stringify(result));

I haven't figured out yet what the ID is exactly for, I successfully pushed jobs onto the queue with always the same Id. I guess if you're pushing jobs at a fast pace and they are stored at the same time it could be a problem. Since it's a string you could substitute it with any random ID you like (the random ID generated by Laravel is 32 characters, I think it's a good idea to keep this length).

Attempts should be set to 1 when initially pushing the job. If Laravel can't process the job, it will push it back onto the queue and increase the attempts value.


问:
How can I make this statement converted to eloquent?
How can I make this statement converted to eloquent?

(SELECT conversations_id
FROM conversation_users
WHERE users_id = $myid)
INTERSECT
(SELECT conversations_id
FROM conversation_users
WHERE users_id = $recipientid)
```

The result should be this:

答:
I haven't tested it yet. But you can try something like this. This query may be needed some adjustment. </p>

```<code>$q1 = DB::table('conversation_users')->where('users_id', $myid);
$q2 = DB::table('conversation_users')->where('users_id', $recipientid);

DB::select($q1->toSql().' intersect '.$q2->toSql(), array_merge($q1->getBindings(), $q2->getBindings()));
</code>```

Body:
How can I make this statement converted to eloquent?

(SELECT conversations_id
FROM conversation_users
WHERE users_id = $myid)
INTERSECT
(SELECT conversations_id
FROM conversation_users
WHERE users_id = $recipientid)

The result should be this:

Body:
I haven't tested it yet. But you can try something like this. This query may be needed some adjustment.

$q1 = DB::table('conversation_users')->where('users_id', $myid);
$q2 = DB::table('conversation_users')->where('users_id', $recipientid);

DB::select($q1->toSql().' intersect '.$q2->toSql(), array_merge($q1->getBindings(), $q2->getBindings()));


问:
Based on navigaton ,show/hide few controls in Angular
I am going to Component X from two components A,B. If I go from Component A to Component X then I need to show/hide different set of controls whereas If  I go from Component B to Component X then I need to show/hide a different set of controls.
How can I achieve this,I can pass the query string parameter but it can be changed by the user in the browser.

How can I achieve this functionality in Angular 6?

I am setting a navigation link in component dynamically inside kendo grid

```<code>editHandler(dataItem) {

        this.router.navigate(['/A', dataItem.ID]);

  }
</code>```

答:
You can do this:

From your componentA and componentB you can pass parameter to determine from which component it's coming like :

```<code><a [routerLink]="['/Linkx', {state: "A"}]">Componenta </a>
<a [routerLink]="['/Linkx', {state: "B"}]">Componenta </a>
</code>```

and in your x .ts you do:

```<code>constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       this.state = params['state']; // take the state
           // check the state and do your controls
    });
</code>```

Body:
I am going to Component X from two components A,B. If I go from Component A to Component X then I need to show/hide different set of controls whereas If  I go from Component B to Component X then I need to show/hide a different set of controls.
How can I achieve this,I can pass the query string parameter but it can be changed by the user in the browser.

How can I achieve this functionality in Angular 6?

I am setting a navigation link in component dynamically inside kendo grid

editHandler(dataItem) {

        this.router.navigate(['/A', dataItem.ID]);

  }

Body:
You can do this:

From your componentA and componentB you can pass parameter to determine from which component it's coming like :

<a [routerLink]="['/Linkx', {state: "A"}]">Componenta </a>
<a [routerLink]="['/Linkx', {state: "B"}]">Componenta </a>

and in your x .ts you do:

constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       this.state = params['state']; // take the state
           // check the state and do your controls
    });


问:
unable to install flask-mysqldb
I cant install flask-mysqldb

```<code>_mysql.c:37:20: fatal error: Python.h: No such file or directory
</code>```

compilation terminated.
  error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

i can't resolve

答:
First create path as below by running into terminal

```<code>export PATH=/usr/local/mysql/bin:$PATH
</code>```

After doing this run following command to terminal

```<code>sudo pip3 install flask-mysqldb
</code>```

It worked for me.

Title: unable to install flask-mysqldb

Body:
I cant install flask-mysqldb

_mysql.c:37:20: fatal error: Python.h: No such file or directory

compilation terminated.
  error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

i can't resolve

Body:
First create path as below by running into terminal

export PATH=/usr/local/mysql/bin:$PATH

After doing this run following command to terminal

sudo pip3 install flask-mysqldb

It worked for me.


问:
SwiftUI: Programmatically setting value for Picker
All of the examples on the Internet show the following type of code for implementing pickers:

```<code>struct MyView: View
{
   var colours = ["Red", "Green", "Blue"]
   @State private var myColourIndex = 1
   @State private var myColour = "Green"
   var body: some View
   {
       VStack
       {
           Picker(selection: $myColourIndex, label: Text("Choose a colour"))
           {
               ForEach(0 ..< colours.count)
               {
                   Text(self.colours[$0])
               }
           }
       }
   }
}
</code>```

This is probably very obvious but my question is how do you set the section based on the string value stored in myColour rather than the index?

答:
Actually, almost the same (tested & works with Xcode 11.2 / iOS 13.2):</p>

```<code>struct MyView: View
{
   var colours = ["Red", "Green", "Blue"]
   @State private var myColourIndex = 1
   @State private var myColour = "Green"

   var body: some View {
       VStack {
           Picker("Choose a colour", selection: $myColour) {
               ForEach(colours, id: \.self) { colour in
                   Text(colour)
               }
           }
       }
   }
}
</code>```

Body:
All of the examples on the Internet show the following type of code for implementing pickers:

struct MyView: View
{
   var colours = ["Red", "Green", "Blue"]
   @State private var myColourIndex = 1
   @State private var myColour = "Green"
   var body: some View
   {
       VStack
       {
           Picker(selection: $myColourIndex, label: Text("Choose a colour"))
           {
               ForEach(0 ..< colours.count)
               {
                   Text(self.colours[$0])
               }
           }
       }
   }
}

This is probably very obvious but my question is how do you set the section based on the string value stored in myColour rather than the index?

Body:
Actually, almost the same (tested & works with Xcode 11.2 / iOS 13.2):

struct MyView: View
{
   var colours = ["Red", "Green", "Blue"]
   @State private var myColourIndex = 1
   @State private var myColour = "Green"

   var body: some View {
       VStack {
           Picker("Choose a colour", selection: $myColour) {
               ForEach(colours, id: \.self) { colour in
                   Text(colour)
               }
           }
       }
   }
}


问:
How to remove React Auth in Laravel 6.0 in CMD?
Sorry, I've tried to search on the answer for the command on CLI to remove the react auth that I downloaded.

I also tried looking in the documentation on "Laravel 6.0.", then look for similar keywords on searching such as reset, remove, react yet, seems there is no relative solution, or probably my fault to not find the right solution.

Can someone help me solve this problem?
Thank you.

答:
From the 5.8 Laravel documentation: laravel.com/docs/5.8/frontend

Removing The Frontend Scaffolding

If you would like to remove the frontend scaffolding from your
  application, you may use the preset Artisan command. This command,
  when combined with the none option, will remove the Bootstrap and Vue
  scaffolding from your application, leaving only a blank SASS file and
  a few common JavaScript utility libraries:

php artisan preset none
```

<p>So try with laravel 6.x:</p>

<pre class="lang-sh prettyprint-override"><code>php artisan ui none
</code>```

Body:
From the 5.8 Laravel documentation: laravel.com/docs/5.8/frontend

Removing The Frontend Scaffolding

If you would like to remove the frontend scaffolding from your
  application, you may use the preset Artisan command. This command,
  when combined with the none option, will remove the Bootstrap and Vue
  scaffolding from your application, leaving only a blank SASS file and
  a few common JavaScript utility libraries:

php artisan preset none

So try with laravel 6.x:

php artisan ui none


问:
Learning WPF without success
Hello developers and designers,

I am very willing to learn WPF in which i use C# as the logic code.
Or i 'try' to anyway.

I have written a 2-page long code-behind in Forms-style though, so i know some syntaxes.
But that was a really cumbersome way of doing it.

The problem is that i am still lingering around the area of understanding at least the basic concept of object oriented programming. But 9 out of 10 times i am not getting the example-codes entirely because of that '1 little thing of which i don't even know what it's called'.
How do you even know if there is a command for the function you want to express and more importantly.... how it's called and where it located in what namespace?

Even the best video-examples aren't doing it for me, because when any code is typed, they never explain how the code exactly works. And most of the times it just doesn't even add up to what i know of logic code (of course i'm wrong).

In the early days i learned the Commodore64's Basic no problem.
Learning and writing Actionscript (Flash), within 2 months creating a 2D-shoot'em up
Learning and writing CMD, within 3 months writing 5000+ lines of code for all sorts of functions.

Why in Merlin's beard is WPF so hard?
Watching the "simplest" tutorial-video's are becoming more and more de-motivational.

Anyone recognizes this?

Thanks for reading,
Danny

答:
I figured I'd add my $.02 since I've recently started using WPF.  First off, you'll need to read that MVVM article mentioned by Fëanor, and DEAR GOD, download the sample code and learn what every line in that program does!  Reading the article is great, but seeing the code, running it, changing it, etc, is INVALUABLE.  I also echo the comments about the MSDN overviews, and the one about creating a side project rather than learning WPF via an existing project.

Other than that, don't expect to get WPF in a day, or even in a week.  I've been using it for about a month now, and I've still got a ways to go.  I had my "AHA!" moment about a week ago where everything started to click and it became apparent to me what I DIDN'T know which is important.  A good strategy would be for you to pick a single concept such as Data Binding, or Data Templates, or Styles, and explore each in depth.  It's a lot to chew on, so just remember that Rome wasn't built in a day.  And if you're not already comfortable with data binding, I'd pick that up early on since it's pretty crucial.

Lastly, once you learn WPF, it's going to be REALLY hard to go back to using Windows Forms :)

Have Fun!
Q

Title: Learning WPF without success


问:
Getting Selenium to Work with Firefox Driver on C# Latest 3.9.0
I Cannot get Selenium to work with the Firefox Driver on c#.
Chrome works perfectly but not Firefox.

Using:

Netframework 4.6.1

Latest version of selenium 3.9.0

Gecko-driver Downloaded from (manage Nuget packages) 0.19.1

Using the MSTest.TestAdapater which should work perfectly as it did with Chrome.

I have already set the path variable in Windows.

GeckoDriver is already installed in the Bin folder in sources.

The Firefoxdriverservice does not exist so cannot use that command.

The error im getting is "threw exception:
System.ComponentModel.Win32Exception: The system cannot find the file specified"

```<code>using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System.Windows.Forms;

 namespace BeatRecaptcha
{
[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {

        IWebDriver driver = new FirefoxDriver();
        driver.Manage().Window.Maximize();

        //Go to Google
        driver.Navigate().GoToUrl("www.google.co.uk");

    }
}
</code>```

}

答:
Install Selenium.WebDriver.GeckoDriver via nuget package. (1) Right click project and select manage nuget package)

After installation your references in the project look like

After this you will not get the error

Body:
I Cannot get Selenium to work with the Firefox Driver on c#.
Chrome works perfectly but not Firefox.

Using:

Netframework 4.6.1

Latest version of selenium 3.9.0

Gecko-driver Downloaded from (manage Nuget packages) 0.19.1

Using the MSTest.TestAdapater which should work perfectly as it did with Chrome.

I have already set the path variable in Windows.

GeckoDriver is already installed in the Bin folder in sources.

The Firefoxdriverservice does not exist so cannot use that command.

The error im getting is "threw exception:
System.ComponentModel.Win32Exception: The system cannot find the file specified"

using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System.Windows.Forms;

 namespace BeatRecaptcha
{
[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {

        IWebDriver driver = new FirefoxDriver();
        driver.Manage().Window.Maximize();

        //Go to Google
        driver.Navigate().GoToUrl("www.google.co.uk");

    }
}

}


问:
How to use media query and selectors at the same time using scss?
So I am creating a web app that supports dark mode.

If the device prefers dark mode by default, it will use the dark mode by the media query @media (prefers-color-scheme: dark).

But I also want to have a feature that users can manually switch to dark mode by adding an attribute to the body: data-theme="dark".

So I tried this:

// ...

.ChatScreen {
    background-color: #eee;
}

@media (prefers-color-scheme: dark), body[data-theme="dark"] {
    .ChatScreen {
        background-color: #000;
    }
}
```

<p>It gives me this error while compiling:</p>

```Failed to compile.

./src/scss/app.scss (./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-5-1!./node_modules/postcss-loader/src??postcss!./node_modules/resolve-url-loader??ref--6-oneOf-5-3!./node_modules/sass-loader/dist/cjs.js??ref--6-oneOf-5-4!./src/scss/app.scss)
SassError: Invalid CSS after "...me: dark), body": expected "{", was '[data-theme="dark"]'
        on line 107 of src/scss/screens/_chat.scss
        from line 6 of /Users/****/src/scss/app.scss
>> @media (prefers-color-scheme: dark), body[data-theme="dark"] {

   -------------------------------------^
```

How can I achieve this without duplicate these codes?

答:
```<code>@media (prefers-color-scheme: dark) {
  body {
    &[data-theme="dark"] {
   .ChatScreen {
        background-color: #000;
    }
   }
  }
}
</code>```

You can look at sass mixins and define your dark styling and then include that rule wherever you need.

Edit

```<code>@mixin dark-theme {
  .ChatScreen {
        background-color: #000;
    }
}

@media (prefers-color-scheme: dark) {
    @include dark-theme;
}

body {
    &[data-theme="dark"] {
        @include dark-theme;
   }
}
</code>```

Body:
So I am creating a web app that supports dark mode.

If the device prefers dark mode by default, it will use the dark mode by the media query @media (prefers-color-scheme: dark).

But I also want to have a feature that users can manually switch to dark mode by adding an attribute to the body: data-theme="dark".

So I tried this:

// ...

.ChatScreen {
    background-color: #eee;
}

@media (prefers-color-scheme: dark), body[data-theme="dark"] {
    .ChatScreen {
        background-color: #000;
    }
}

It gives me this error while compiling:

Failed to compile.

./src/scss/app.scss (./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-5-1!./node_modules/postcss-loader/src??postcss!./node_modules/resolve-url-loader??ref--6-oneOf-5-3!./node_modules/sass-loader/dist/cjs.js??ref--6-oneOf-5-4!./src/scss/app.scss)
SassError: Invalid CSS after "...me: dark), body": expected "{", was '[data-theme="dark"]'
        on line 107 of src/scss/screens/_chat.scss
        from line 6 of /Users/****/src/scss/app.scss
>> @media (prefers-color-scheme: dark), body[data-theme="dark"] {

   -------------------------------------^

How can I achieve this without duplicate these codes?

Body:
@media (prefers-color-scheme: dark) {
  body {
    &[data-theme="dark"] {
   .ChatScreen {
        background-color: #000;
    }
   }
  }
}

You can look at sass mixins and define your dark styling and then include that rule wherever you need.

Edit

@mixin dark-theme {
  .ChatScreen {
        background-color: #000;
    }
}

@media (prefers-color-scheme: dark) {
    @include dark-theme;
}

body {
    &[data-theme="dark"] {
        @include dark-theme;
   }
}


问:
Scraping Data from the List java
I have a list which looks like below:

```<code>[
  StartingNmap7.60(https: //nmap.org)at2020-02-1713: 32IST,
  Nmapscanreportfor192.168.1.1(192.168.1.1),
  Hostisup(0.0012slatency).,
  Nmapscanreportforbevywise_37e0(192.168.1.4),
  Hostisup(0.14slatency).,
  Nmapscanreportforshiv-thinkpad-t420(192.168.1.5),
  Hostisup(0.0072slatency).,
  Nmapscanreportforvivo-1726(192.168.1.12),
  Hostisup(0.028slatency).,
  Nmapscanreportforrealme-5(192.168.1.13),
  Hostisup(0.13slatency).,
  Nmapdone: 256IPaddresses(5hostsup)scannedin21.02seconds
]
</code>```

It looks like messy. I want to get some data from that list.I want the required output to be like below:

```<code>[{"host name":"192.168.1.1","IP address":192.168.1.1"},
{"host name":"bevywise_37e0","IP address:"192.168.1.4"},
{"host name":"shiv-thinkpad-t420","IP address":"192.168.1.5"},
{"host name":"vivo-1726","IP address":"192.168.1.12"},
{"host name":"realme-5","IP address":"192.168.1.13"}]
</code>```

Since I am new to java, I can't figure out how to make it. Help me with some solutions.

答:
If this list is  list/array of strings you can do the folowing

Filter your list by string prefix, in your case it will be

```<code>String prefix = "Nmapscanreportfor";
</code>```

Create formating template where you will put parsed data

String template = "{\"host name\":\"%s\",\"IP address\":%s\"}";

Then iterate over your list and parse host name and ip address. String.indexOf() will be usefull. E.g. to get hostname, you can do

```<code>listEntry.substring(prefix.length(), entry.indexOf("("))
</code>```

For ip it wil be similar, just find first "(" and last ")". String between is your ip address.

And when you will have hostname and ip address you can use String.format() method to fill template string placeholders.

To iterate over the list you can use for loop or streams. With streams it will look pretty nice

```<code>        List<String> newList = Arrays.stream(array) //if it's array of list.stream() if it's list
            .filter(entry -> entry.startsWith(prefix))
            .map(entry -> String.format(template, %your hostname%, %your ip address%))
            .collect(Collectors.toList());
</code>```

Title: Scraping Data from the List java

Body:
I have a list which looks like below:

[
  StartingNmap7.60(https: //nmap.org)at2020-02-1713: 32IST,
  Nmapscanreportfor192.168.1.1(192.168.1.1),
  Hostisup(0.0012slatency).,
  Nmapscanreportforbevywise_37e0(192.168.1.4),
  Hostisup(0.14slatency).,
  Nmapscanreportforshiv-thinkpad-t420(192.168.1.5),
  Hostisup(0.0072slatency).,
  Nmapscanreportforvivo-1726(192.168.1.12),
  Hostisup(0.028slatency).,
  Nmapscanreportforrealme-5(192.168.1.13),
  Hostisup(0.13slatency).,
  Nmapdone: 256IPaddresses(5hostsup)scannedin21.02seconds
]

It looks like messy. I want to get some data from that list.I want the required output to be like below:

[{"host name":"192.168.1.1","IP address":192.168.1.1"},
{"host name":"bevywise_37e0","IP address:"192.168.1.4"},
{"host name":"shiv-thinkpad-t420","IP address":"192.168.1.5"},
{"host name":"vivo-1726","IP address":"192.168.1.12"},
{"host name":"realme-5","IP address":"192.168.1.13"}]

Since I am new to java, I can't figure out how to make it. Help me with some solutions.

Body:
If this list is  list/array of strings you can do the folowing

Filter your list by string prefix, in your case it will be

String prefix = "Nmapscanreportfor";

Create formating template where you will put parsed data

String template = "{\"host name\":\"%s\",\"IP address\":%s\"}";

Then iterate over your list and parse host name and ip address. String.indexOf() will be usefull. E.g. to get hostname, you can do

listEntry.substring(prefix.length(), entry.indexOf("("))

For ip it wil be similar, just find first "(" and last ")". String between is your ip address.

And when you will have hostname and ip address you can use String.format() method to fill template string placeholders.

To iterate over the list you can use for loop or streams. With streams it will look pretty nice

        List<String> newList = Arrays.stream(array) //if it's array of list.stream() if it's list
            .filter(entry -> entry.startsWith(prefix))
            .map(entry -> String.format(template, %your hostname%, %your ip address%))
            .collect(Collectors.toList());


问:
Bytebuddy - Arguments for agent premain
I have a premain as below for attaching an agent to a remote process.

```<code>public static void premain(String args, Instrumentation instrumentation) {

    System.out.println("Premain");
    File file ;
    try {

            file = (new File("Agent.jar"));
            ByteBuddyAgent.attach(file,"18467");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

}
</code>```

Here, I want to pass the process id and couple of other arguments. Is there anyway to do this. Looks like it takes one single argument.

java -javaagent:/path/to/agent.jar -cp jar-under-test.jar Foo.Main

How can i pass the argument here?

答: You would need to encode the argument in any manner you find appropriate. Instead of spaces as used for the arguments to main, use commas for example but escape all existing commas, for example by doubling them. In the agent, split by single commas and reverse the escaping for the resulting segments.

Title: Bytebuddy - Arguments for agent premain

Body:
I have a premain as below for attaching an agent to a remote process.

public static void premain(String args, Instrumentation instrumentation) {

    System.out.println("Premain");
    File file ;
    try {

            file = (new File("Agent.jar"));
            ByteBuddyAgent.attach(file,"18467");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

}

Here, I want to pass the process id and couple of other arguments. Is there anyway to do this. Looks like it takes one single argument.

java -javaagent:/path/to/agent.jar -cp jar-under-test.jar Foo.Main

How can i pass the argument here?


问:
Migrate legacy database to cqrs/event sourcing view
We got old legacy application with complex business logic which we need to rewrite. We consider to use cqrs and event sourcing. But it's not clear how to migrate data from the old database. Probable we need migrate it to the read database only, as we can't reproduce all the events to populate event store. But we atleast need to create some initial records in event store for each aggregate, like AggregateCreated? Or we need write a scripts and to use all the commands one by one to recreate aggregates in same way we will normally with event sourcing?

答:
Probable we need migrate it to the read database only

No, your read model db can be dropped and recreated any time based on write side, only write side is your source of truth.

But we atleast need to create some initial records in event store for
  each aggregate, like AggregateCreated?

Of course, and having ONLY the initial event could be not enough. If your current OrderAggregate has reservations, you must create ItemReservedEvent for-each reservation it has.

Or we need write a scripts and to use all the commands one by one to
  recreate aggregates in same way we will normally with event sourcing?

Feels like that's the way you should go. Read old aggregate/entity from db and try to map it to a new one.


问:
Load dynamic library and use functions inside the library
In C#, I am using an external dll, using loadLibrary, like this:

```<code>public class Utilities
    [DllImport("kernel32", CharSet= CharSet.Auto, SetLastError=true)]
    private static extern IntPtr LoadLibrary(string librayName);
    [DllImport("kernel32", CharSet= CharSet.Auto, SetLastError=true)]
    private static extern IntPtr GetProcAddress(intPtr hwnd, string procedureName);

    public static LoadAssembliesAndMethods() {
        string mainPath = AppDomain.CurrentDomain.BaseDirectory;
        string path = Path.Combine(mainPath, "MyAssembly.dll");

        IntPtr ptr = LoadLibrary(path);

        // What to do next in order to get all the list of functions/methods/class in the library and use them?

    }
</code>```

The dll has no signature of Assembly (it's a 3rd party), so I cannot do

```<code>Assebly.LoadFile(path);
</code>```

I need to get all of the functions/methods/class of the dll, and use some of them, using C#.

How can I do that.

答:
There is no common way to get the export list of a unmanaged library programatically.

See Is there a way to find all the functions exposed by a dll for more info

Body:
In C#, I am using an external dll, using loadLibrary, like this:

public class Utilities
    [DllImport("kernel32", CharSet= CharSet.Auto, SetLastError=true)]
    private static extern IntPtr LoadLibrary(string librayName);
    [DllImport("kernel32", CharSet= CharSet.Auto, SetLastError=true)]
    private static extern IntPtr GetProcAddress(intPtr hwnd, string procedureName);

    public static LoadAssembliesAndMethods() {
        string mainPath = AppDomain.CurrentDomain.BaseDirectory;
        string path = Path.Combine(mainPath, "MyAssembly.dll");

        IntPtr ptr = LoadLibrary(path);

        // What to do next in order to get all the list of functions/methods/class in the library and use them?

    }

The dll has no signature of Assembly (it's a 3rd party), so I cannot do

Assebly.LoadFile(path);

I need to get all of the functions/methods/class of the dll, and use some of them, using C#.

How can I do that.


问:
How can I use BigQuery's dataset in Data Lab
I have some datasets in BigQuery, I wonder if there is a way to use the same datasets in Data Lab? As the datasets are big, I can't download it and reload it in Data Lab.

Thank you very much.

答:
The BigQuery Python client library support querying data stored in BigQuery. To load the commands from the client library, paste the following code into the first cell of the notebook:

```<code>%load_ext google.cloud.bigquery
</code>```

%load_ext is one of the many Jupyter built-in magic commands.

The BigQuery client library provides a %%bigquery cell, which runs a SQL query and returns the results as a Pandas DataFrame.

You can query data from a public dataset or from the datasets in your project:

```<code>%%bigquery

SELECT *

FROM `MY_PROJECT.MY_DATASET.MY_TABLE`

LIMIT 50
</code>```

I was able to successfully get data from the dataset without any issues.

You can follow this tutorial. I hope it helps.

Body:
The BigQuery Python client library support querying data stored in BigQuery. To load the commands from the client library, paste the following code into the first cell of the notebook:

%load_ext google.cloud.bigquery

%load_ext is one of the many Jupyter built-in magic commands.

The BigQuery client library provides a %%bigquery cell, which runs a SQL query and returns the results as a Pandas DataFrame.

You can query data from a public dataset or from the datasets in your project:

%%bigquery

SELECT *

FROM `MY_PROJECT.MY_DATASET.MY_TABLE`

LIMIT 50

I was able to successfully get data from the dataset without any issues.

You can follow this tutorial. I hope it helps.


问:
How to change supervisor name on Horizon dashboard?
I've checked the source code and it seems that the name is determined from the server hostname and some random 4 characters string. What's the proper way to set it programmatically?
Here's a sample: myserver-UME9

答:
You can define a custom nameResolver on app/Providers/HorizonServiceProvider.php as shown below:

<?php

namespace App\Providers;

...
use Laravel\Horizon\MasterSupervisor;
...

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();

        ...

        MasterSupervisor::determineNameUsing(function() {
          return "my_fancy_name";
          // return "my_fancy_name" . config('horizon.supervision_name');
        });
    }
}
```


问:
How to open react select menu pragmatically
I want to open react select menu on click of a button.

here is the link of code sand box

https://codesandbox.io/s/material-demo-kssrb

I know a react select property 'menuIsOpen', Drawback of this prop is menu is always open and default close behaviour is lost because of this.

Any help appreciated.

答:
Along with menuIsOpen prop, you are also going to need the onBlur event to make it mork.

As menuIsOpen prop does reset all the on-* events for the Select component.

Additionally for onBlur to work, you need to  set the focus to the dropdown element using setFocus.

You can check this out over here.
https://codesandbox.io/s/material-demo-gxvxr


问:
Issue using node-sass after updating NodeJS
I get an issue using node-sass after updating my NodeJS version.

Issue :

```<code>(node:472) fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version.
C:\aglqng\src\main\webapp\node_modules\node-sass\lib\index.js:15
    throw new Error(errors.missingBinary());
    ^

Error: Missing binding C:\aglqng\src\main\webapp\node_modules\node-sass\vendor\win32-x64-48\binding.node
Node Sass could not find a binding for your current environment: Windows 64-bit with Node.js 6.x

Found bindings for the following environments:
  - Windows 64-bit with Node 0.12.x

This usually happens because your environment has changed since running `npm install`.
Run `npm rebuild node-sass` to build the binding for your current environment.
    at Object.<anonymous> (C:\aglqng\src\main\webapp\node_modules\node-sass\lib\index.js:15:11)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
    at Module.require (module.js:468:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\aglqng\src\main\webapp\node_modules\gulp-sass\index.js:187:21)
    at Module._compile (module.js:541:32)
</code>```

Versions :

```<code>node-sass 3.8.0 (Wrapper) [JavaScript]
libsass 3.3.6 (Sass Compiler) [C/C++]
nodejs v6.3.1
</code>```

Platform : Windows 10 x64

I tried this and it doesn't work :

1)

```<code>node rebuild node-sass
</code>```

2)

```<code>npm uninstall node-sass
npm i node-sass
</code>```

答:
Some versions of node-sass are not compatible with certain versions of Node. After I upgraded my Node to version 12, I had to upgrade the version of node-sass in my project to 4.12 using this command:

npm install node-sass@4.12.0

This page shows the version compatibilities:

https://www.npmjs.com/package/node-sass

Body:
I get an issue using node-sass after updating my NodeJS version.

Issue :

(node:472) fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version.
C:\aglqng\src\main\webapp\node_modules\node-sass\lib\index.js:15
    throw new Error(errors.missingBinary());
    ^

Error: Missing binding C:\aglqng\src\main\webapp\node_modules\node-sass\vendor\win32-x64-48\binding.node
Node Sass could not find a binding for your current environment: Windows 64-bit with Node.js 6.x

Found bindings for the following environments:
  - Windows 64-bit with Node 0.12.x

This usually happens because your environment has changed since running `npm install`.
Run `npm rebuild node-sass` to build the binding for your current environment.
    at Object.<anonymous> (C:\aglqng\src\main\webapp\node_modules\node-sass\lib\index.js:15:11)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
    at Module.require (module.js:468:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\aglqng\src\main\webapp\node_modules\gulp-sass\index.js:187:21)
    at Module._compile (module.js:541:32)

Versions :

node-sass 3.8.0 (Wrapper) [JavaScript]
libsass 3.3.6 (Sass Compiler) [C/C++]
nodejs v6.3.1

Platform : Windows 10 x64

I tried this and it doesn't work :

1)

node rebuild node-sass

2)

npm uninstall node-sass
npm i node-sass


问:
QueryDSL 4.x subqueries in the FROM clause
Are subqueries in the from clause supported in the latest QueryDSL version? I tried my best but could not find a solution for now.</p>

答:
This is not a QueryDSL issue, but a JPQL limitation. Support for subqueries exists only for Select and Where clauses. From the Hibernate documentation:

Note that HQL subqueries can occur only in the select or where clauses.

You need to use native queries if you wish to utilize subqueries in that fashion. For example, see JPA subquery in from clause for query migration. QueryDSL supports native queries, so the principles should be translatable.


问:
creating s3 bucket and folders inside it using node js in aws lambda function
I am both new to Node js and AWS. I am trying to create a bucket in S3 using node js in lambda function. Consequently, I am trying to create folders inside this S3 bucket.

I followed all the questions answered before and tried different iterations of code, but none of them seem to be working. Following is my code which is executing without giving any issues, yet the bucket and the folders are not getting created.

```<code>const AWS = require('aws-sdk');

let s3Client = new AWS.S3({
  accessKeyId: '<access_key_id>',
  secretAccessKey: '<secret_access_key>'
});

var params = {
  Bucket : 'pshycology06'
};

exports.handler = async (event, context, callback) => {

// call spaces to create the bucket
    s3Client.createBucket(params, function(err, data) {
      if (err) {
        console.log("\r\n[ERROR] : ", err);
      } else {
        console.log("\r\n[SUCCESS] : data = ",data);
      }
    });
};
</code>```

The code for creating folders inside the Lambda function is as following --

```<code>var AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
var s3Client = new AWS.S3({apiVersion: '2006-03-01'});

exports.handler = async (event, context) => {

    let params1 = { Bucket: 'travasko', Key: '2/dir1/dir2', Body:'body does not matter' };

    s3Client.putObject(params1, function (err, data) {
        if (err) {
            console.log("Error creating the folder: ", err);
        } else {
            console.log("Successfully created a folder on S3");
        }
    });
</code>```

Both of them doesn't work. I read a lot of documents on this issue and answers previously asked, but none of them are working for me.

The lambda function has a timeout of 1 minute. It has following policies for the IAM role -
1. AmazonRDSFullAccess
2. AmazonS3FullAccess
3. AWSLambdaVPCExecutionRole

The VPC security group is the default one.

Also, when I am trying to create the same bucket using the following AWS CLI command, it creates the bucket.

```<code>aws s3api create-bucket --bucket psychology06 --region us-east-1

</code>```

I am not sure, where am i making a mistake.

答:
You need to chain the .promise() method to your aws-sdk calls and await on them because you are creating async functions.

await s3Client.createBucket(params).promise();
```

<pre class="lang-js prettyprint-override"><code>await s3Client.putObject(params1).promise();
</code>```

Furthermore, S3 doesn't work with directories although you may be thrown over by the way the S3 console looks like when you add / to your filenames. You can read more about it here

Body:
I am both new to Node js and AWS. I am trying to create a bucket in S3 using node js in lambda function. Consequently, I am trying to create folders inside this S3 bucket.

I followed all the questions answered before and tried different iterations of code, but none of them seem to be working. Following is my code which is executing without giving any issues, yet the bucket and the folders are not getting created.

const AWS = require('aws-sdk');

let s3Client = new AWS.S3({
  accessKeyId: '<access_key_id>',
  secretAccessKey: '<secret_access_key>'
});

var params = {
  Bucket : 'pshycology06'
};

exports.handler = async (event, context, callback) => {

// call spaces to create the bucket
    s3Client.createBucket(params, function(err, data) {
      if (err) {
        console.log("\r\n[ERROR] : ", err);
      } else {
        console.log("\r\n[SUCCESS] : data = ",data);
      }
    });
};

The code for creating folders inside the Lambda function is as following --

var AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
var s3Client = new AWS.S3({apiVersion: '2006-03-01'});

exports.handler = async (event, context) => {

    let params1 = { Bucket: 'travasko', Key: '2/dir1/dir2', Body:'body does not matter' };

    s3Client.putObject(params1, function (err, data) {
        if (err) {
            console.log("Error creating the folder: ", err);
        } else {
            console.log("Successfully created a folder on S3");
        }
    });

Both of them doesn't work. I read a lot of documents on this issue and answers previously asked, but none of them are working for me.

The lambda function has a timeout of 1 minute. It has following policies for the IAM role -
1. AmazonRDSFullAccess
2. AmazonS3FullAccess
3. AWSLambdaVPCExecutionRole

The VPC security group is the default one.

Also, when I am trying to create the same bucket using the following AWS CLI command, it creates the bucket.

aws s3api create-bucket --bucket psychology06 --region us-east-1

I am not sure, where am i making a mistake.

Body:
You need to chain the .promise() method to your aws-sdk calls and await on them because you are creating async functions.

await s3Client.createBucket(params).promise();

await s3Client.putObject(params1).promise();

Furthermore, S3 doesn't work with directories although you may be thrown over by the way the S3 console looks like when you add / to your filenames. You can read more about it here


问:
Prevent redirect WooCommerce checkout form after complete
Just trying to stop checkout form stay still after checkout form submit complete. As we know WooCommerce checkout form submission done by ajax ?wc-ajax=checkout. As default after successfully complete an order checkout form redirect to thankyou page but that not what I want to do.

I want after successfully complete an order checkout form stay still. I will redirect later after done some my own ajax or coding.

I look WooCommerce checkout.js didn't find any hook or anything to do that, So here I am to ask you guys to know anyone how to do this?

NOTE: My main reason to do this, after order status and payment status before checkout gone to thankyou page but for that I need order id and that's why it need to complete first. hope it make sense.

答:
The woocommerce_payment_complete hook is fired when the payment is completed. The only variable passed is the order id, though from that you can get the order object, and ultimately the user.</p>

```<code>add_action( 'woocommerce_payment_complete', 'so_payment_complete' );
function so_payment_complete( $order_id ){
    $order = wc_get_order( $order_id );
    $order->update_status( 'pending' );
    $user = $order->get_user();
    if( $user ){
        // do something with the user
    }
}
</code>```

Body:
The woocommerce_payment_complete hook is fired when the payment is completed. The only variable passed is the order id, though from that you can get the order object, and ultimately the user.

add_action( 'woocommerce_payment_complete', 'so_payment_complete' );
function so_payment_complete( $order_id ){
    $order = wc_get_order( $order_id );
    $order->update_status( 'pending' );
    $user = $order->get_user();
    if( $user ){
        // do something with the user
    }
}


问:
How to script out stored procedures to files?
Is there a way that I can find where stored procedures are saved so that I can just copy the files to my desktop? </p>

答:
I recently came across an issue with programmatically extracting Stored Procedure scripts to file. I started off using the routine_definition approach, but quickly realised that I hit the 4000 character limit... No matter what I tried, I couldn't find a way to get over that hump. (Still interested to know if there's a way around this!)

Instead, I stumbled across a powerful built-in helper; sp_helptext

In short, for the purposes of extracting Stored Procedure Scripts, specifically, sp_helptext extracts each line to a row in the output. ie, 2000 lines of code = 2000 rows in a returned dataset. As long as your individual lines don't exceed the 4000 character limit, nothing will be clipped.

Of course, you can then write the entire table contents to file pretty easily either in SQL, or in my case SSIS.


问:
npm ERR! Unexpected end of JSON input while parsing near '.../openpgpjs.org\r\n\r\'
I am a newbie to React and trying to start a project

npm version: 6.4.1

create-react-app version: 2.1.8

node version: 10.15.0

I run create-react-app newApp , And got error:

npm ERR! Unexpected end of JSON input while parsing near '.../openpgpjs.org\r\n\r\'

npm ERR! A complete log of this run can be found in:

npm ERR! C:\Users\ThunderF\AppData\Roaming\npm-cache_logs\2019-04-> 06T18_16_37_841Z-debug.log

Aborting installation.

npm install --save --save-exact --loglevel error react react-dom react-scripts has failed.

答:
I got the same problem and I ran these commands

1) npm cache clean --force

2) restart your machine

3) npx create-react-app my-app

           (or)

npm install create-react-app enter and then npm init react-app my-app

cd my-app

npm start


问:
Java's Optional Forces Itself or else I get an error
Why do I get an error if I don't use Optional (the IDE suggested I use Optional) as oppose to just using DemographicEntity demoEntity?</p>

```<code>@Test
public void testFindDemographicsById() {
    DemographicEntity demoEntity = demoRepo.findById(1l); /////Gives Error
}

@Test
public void testFindDemographicsById() {
    /////forced to use Optional
    Optional<DemographicEntity> demoEntity = demoRepo.findById(1l); /////No Error
}
</code>```

答:
In your demoRepo you must have had declared method

```<code>Optional<DemographicEntity> findById
</code>```

You can fix in two ways.

First one is to change method in repository to return DemographicEntity:

```<code>DemographicEntity findById
</code>```

The other and better solution is to call

```<code>demoRepo.findById(1l).get();
</code>```

Body:
Why do I get an error if I don't use Optional (the IDE suggested I use Optional) as oppose to just using DemographicEntity demoEntity?

@Test
public void testFindDemographicsById() {
    DemographicEntity demoEntity = demoRepo.findById(1l); /////Gives Error
}

@Test
public void testFindDemographicsById() {
    /////forced to use Optional
    Optional<DemographicEntity> demoEntity = demoRepo.findById(1l); /////No Error
}

Body:
In your demoRepo you must have had declared method

Optional<DemographicEntity> findById

You can fix in two ways.

First one is to change method in repository to return DemographicEntity:

DemographicEntity findById

The other and better solution is to call

demoRepo.findById(1l).get();